saleor-dashboard/src/products/utils/handlers.ts

72 lines
2.1 KiB
TypeScript
Raw Normal View History

2019-08-09 10:17:04 +00:00
import { FormChange } from "@saleor/hooks/useForm";
import { FormsetChange, FormsetData } from "@saleor/hooks/useFormset";
import { toggle } from "@saleor/utils/lists";
2019-08-09 10:17:04 +00:00
import { ProductAttributeInputData } from "../components/ProductAttributes";
2020-10-15 11:56:22 +00:00
import { getAttributeInputFromProductType, ProductType } from "./data";
2019-08-09 10:17:04 +00:00
export function createAttributeChangeHandler(
changeAttributeData: FormsetChange<string[]>,
triggerChange: () => void
): FormsetChange {
return (attributeId: string, value: string) => {
triggerChange();
2020-10-12 10:45:07 +00:00
changeAttributeData(attributeId, value === "" ? [] : [value]);
2019-08-09 10:17:04 +00:00
};
}
export function createAttributeMultiChangeHandler(
changeAttributeData: FormsetChange<string[]>,
2020-10-19 09:33:51 +00:00
attributes: FormsetData<ProductAttributeInputData, string[]>,
2019-08-09 10:17:04 +00:00
triggerChange: () => void
): FormsetChange {
return (attributeId: string, value: string) => {
2020-10-19 09:33:51 +00:00
const attribute = attributes.find(
attribute => attribute.id === attributeId
);
2019-08-09 10:17:04 +00:00
const newAttributeValues = toggle(
2020-10-19 09:33:51 +00:00
value,
attribute.value,
(a, b) => a === b
2019-08-09 10:17:04 +00:00
);
triggerChange();
2020-10-19 09:33:51 +00:00
changeAttributeData(attributeId, newAttributeValues);
2019-08-09 10:17:04 +00:00
};
}
export function createProductTypeSelectHandler(
change: FormChange,
setAttributes: (data: FormsetData<ProductAttributeInputData>) => void,
setProductType: (productType: ProductType) => void,
productTypeChoiceList: ProductType[]
): FormChange {
return (event: React.ChangeEvent<any>) => {
const id = event.target.value;
const selectedProductType = productTypeChoiceList.find(
productType => productType.id === id
);
setProductType(selectedProductType);
change(event);
setAttributes(getAttributeInputFromProductType(selectedProductType));
};
}
interface ProductAvailabilityArgs {
availableForPurchase: string | null;
isAvailableForPurchase: boolean;
productId: string;
}
2020-10-19 10:59:43 +00:00
export const getProductAvailabilityVariables = ({
isAvailableForPurchase,
availableForPurchase,
productId
2020-10-19 10:59:43 +00:00
}: ProductAvailabilityArgs) => ({
isAvailable: isAvailableForPurchase,
productId,
2020-10-22 09:15:49 +00:00
startDate: availableForPurchase || null
2020-10-19 10:59:43 +00:00
});