Extract product update form to separate component

This commit is contained in:
dominik-zeglen 2020-10-20 16:44:21 +02:00
parent d192bcac34
commit 374a072bf7
2 changed files with 454 additions and 318 deletions

View file

@ -3,7 +3,6 @@ import AvailabilityCard from "@saleor/components/AvailabilityCard";
import CardSpacer from "@saleor/components/CardSpacer"; import CardSpacer from "@saleor/components/CardSpacer";
import { ConfirmButtonTransitionState } from "@saleor/components/ConfirmButton"; import { ConfirmButtonTransitionState } from "@saleor/components/ConfirmButton";
import Container from "@saleor/components/Container"; import Container from "@saleor/components/Container";
import Form from "@saleor/components/Form";
import Grid from "@saleor/components/Grid"; import Grid from "@saleor/components/Grid";
import Metadata from "@saleor/components/Metadata/Metadata"; import Metadata from "@saleor/components/Metadata/Metadata";
import PageHeader from "@saleor/components/PageHeader"; import PageHeader from "@saleor/components/PageHeader";
@ -13,18 +12,13 @@ import { ProductErrorWithAttributesFragment } from "@saleor/fragments/types/Prod
import { TaxTypeFragment } from "@saleor/fragments/types/TaxTypeFragment"; import { TaxTypeFragment } from "@saleor/fragments/types/TaxTypeFragment";
import { WarehouseFragment } from "@saleor/fragments/types/WarehouseFragment"; import { WarehouseFragment } from "@saleor/fragments/types/WarehouseFragment";
import useDateLocalize from "@saleor/hooks/useDateLocalize"; import useDateLocalize from "@saleor/hooks/useDateLocalize";
import useFormset from "@saleor/hooks/useFormset";
import useStateFromProps from "@saleor/hooks/useStateFromProps"; import useStateFromProps from "@saleor/hooks/useStateFromProps";
import { sectionNames } from "@saleor/intl"; import { sectionNames } from "@saleor/intl";
import { maybe } from "@saleor/misc"; import { maybe } from "@saleor/misc";
import { SearchCategories_search_edges_node } from "@saleor/searches/types/SearchCategories"; import { SearchCategories_search_edges_node } from "@saleor/searches/types/SearchCategories";
import { SearchCollections_search_edges_node } from "@saleor/searches/types/SearchCollections"; import { SearchCollections_search_edges_node } from "@saleor/searches/types/SearchCollections";
import { FetchMoreProps, ListActions, ReorderAction } from "@saleor/types"; import { FetchMoreProps, ListActions, ReorderAction } from "@saleor/types";
import createMultiAutocompleteSelectHandler from "@saleor/utils/handlers/multiAutocompleteSelectChangeHandler";
import createSingleAutocompleteSelectHandler from "@saleor/utils/handlers/singleAutocompleteSelectChangeHandler";
import useMetadataChangeTrigger from "@saleor/utils/metadata/useMetadataChangeTrigger";
import { convertFromRaw, RawDraftContentState } from "draft-js"; import { convertFromRaw, RawDraftContentState } from "draft-js";
import { diff } from "fast-array-diff";
import React from "react"; import React from "react";
import { useIntl } from "react-intl"; import { useIntl } from "react-intl";
@ -33,17 +27,7 @@ import {
ProductDetails_product_images, ProductDetails_product_images,
ProductDetails_product_variants ProductDetails_product_variants
} from "../../types/ProductDetails"; } from "../../types/ProductDetails";
import { import { getChoices, ProductUpdatePageFormData } from "../../utils/data";
getAttributeInputFromProduct,
getChoices,
getProductUpdatePageFormData,
getStockInputFromProduct,
ProductUpdatePageFormData
} from "../../utils/data";
import {
createAttributeChangeHandler,
createAttributeMultiChangeHandler
} from "../../utils/handlers";
import ProductAttributes, { ProductAttributeInput } from "../ProductAttributes"; import ProductAttributes, { ProductAttributeInput } from "../ProductAttributes";
import ProductDetailsForm from "../ProductDetailsForm"; import ProductDetailsForm from "../ProductDetailsForm";
import ProductImages from "../ProductImages"; import ProductImages from "../ProductImages";
@ -53,6 +37,7 @@ import ProductShipping from "../ProductShipping/ProductShipping";
import ProductStocks, { ProductStockInput } from "../ProductStocks"; import ProductStocks, { ProductStockInput } from "../ProductStocks";
import ProductTaxes from "../ProductTaxes"; import ProductTaxes from "../ProductTaxes";
import ProductVariants from "../ProductVariants"; import ProductVariants from "../ProductVariants";
import ProductUpdateForm from "./form";
export interface ProductUpdatePageProps extends ListActions { export interface ProductUpdatePageProps extends ListActions {
defaultWeightUnit: string; defaultWeightUnit: string;
@ -136,25 +121,9 @@ export const ProductUpdatePage: React.FC<ProductUpdatePageProps> = ({
}) => { }) => {
const intl = useIntl(); const intl = useIntl();
const localizeDate = useDateLocalize(); const localizeDate = useDateLocalize();
const attributeInput = React.useMemo(
() => getAttributeInputFromProduct(product),
[product]
);
const stockInput = React.useMemo(() => getStockInputFromProduct(product), [
product
]);
const { change: changeAttributeData, data: attributes } = useFormset(
attributeInput
);
const {
add: addStock,
change: changeStockData,
data: stocks,
remove: removeStock
} = useFormset(stockInput);
const [selectedCategory, setSelectedCategory] = useStateFromProps( const [selectedCategory, setSelectedCategory] = useStateFromProps(
maybe(() => product.category.name, "") product?.category?.name || ""
); );
const [selectedCollections, setSelectedCollections] = useStateFromProps( const [selectedCollections, setSelectedCollections] = useStateFromProps(
@ -165,309 +134,217 @@ export const ProductUpdatePage: React.FC<ProductUpdatePageProps> = ({
product?.taxType.description product?.taxType.description
); );
const {
isMetadataModified,
isPrivateMetadataModified,
makeChangeHandler: makeMetadataChangeHandler
} = useMetadataChangeTrigger();
const initialData = getProductUpdatePageFormData(product, variants);
const initialDescription = maybe<RawDraftContentState>(() => const initialDescription = maybe<RawDraftContentState>(() =>
JSON.parse(product.descriptionJson) JSON.parse(product.descriptionJson)
); );
const categories = getChoices(categoryChoiceList); const categories = getChoices(categoryChoiceList);
const collections = getChoices(collectionChoiceList); const collections = getChoices(collectionChoiceList);
const currency = const currency = product?.variants[0]?.price.currency;
product?.variants?.length && product.variants[0].price.currency; const hasVariants = product?.productType?.hasVariants;
const hasVariants = maybe(() => product.productType.hasVariants, false);
const taxTypeChoices = const taxTypeChoices =
taxTypes?.map(taxType => ({ taxTypes?.map(taxType => ({
label: taxType.description, label: taxType.description,
value: taxType.taxCode value: taxType.taxCode
})) || []; })) || [];
const getAvailabilityData = ({
availableForPurchase,
isAvailableForPurchase,
isPublished,
publicationDate
}: ProductUpdatePageFormData) => ({
isAvailableForPurchase: isAvailableForPurchase || !!availableForPurchase,
isPublished: isPublished || !!publicationDate
});
const getStocksData = () => {
if (product.productType.hasVariants) {
return { addStocks: [], removeStocks: [], updateStocks: [] };
}
const dataStocks = stocks.map(stock => stock.id);
const variantStocks = product.variants[0]?.stocks.map(
stock => stock.warehouse.id
);
const stockDiff = diff(variantStocks, dataStocks);
return {
addStocks: stocks.filter(stock =>
stockDiff.added.some(addedStock => addedStock === stock.id)
),
removeStocks: stockDiff.removed,
updateStocks: stocks.filter(
stock => !stockDiff.added.some(addedStock => addedStock === stock.id)
)
};
};
const getMetadata = (data: ProductUpdatePageFormData) => ({
metadata: isMetadataModified ? data.metadata : undefined,
privateMetadata: isPrivateMetadataModified
? data.privateMetadata
: undefined
});
const getParsedData = (data: ProductUpdatePageFormData) => ({
...data,
...getAvailabilityData(data),
...getStocksData(),
...getMetadata(data),
attributes
});
const handleSubmit = (data: ProductUpdatePageFormData) =>
onSubmit(getParsedData(data));
return ( return (
<Form onSubmit={handleSubmit} initial={initialData} confirmLeave> <ProductUpdateForm
{({ change, data, hasChanged, submit, triggerChange, toggleValue }) => { onSubmit={onSubmit}
const handleCollectionSelect = createMultiAutocompleteSelectHandler( product={product}
toggleValue, categories={categories}
setSelectedCollections, collections={collections}
selectedCollections, selectedCollections={selectedCollections}
collections setSelectedCategory={setSelectedCategory}
); setSelectedCollections={setSelectedCollections}
const handleCategorySelect = createSingleAutocompleteSelectHandler( setSelectedTaxType={setSelectedTaxType}
change, taxTypes={taxTypeChoices}
setSelectedCategory, warehouses={warehouses}
categories >
); {({ change, data, handlers, hasChanged, submit }) => (
const handleAttributeChange = createAttributeChangeHandler( <>
changeAttributeData, <Container>
triggerChange <AppHeader onBack={onBack}>
); {intl.formatMessage(sectionNames.products)}
const handleAttributeMultiChange = createAttributeMultiChangeHandler( </AppHeader>
changeAttributeData, <PageHeader title={header} />
attributes, <Grid>
triggerChange <div>
); <ProductDetailsForm
const changeMetadata = makeMetadataChangeHandler(change); data={data}
const handleTaxTypeSelect = createSingleAutocompleteSelectHandler( disabled={disabled}
change, errors={errors}
setSelectedTaxType, initialDescription={initialDescription}
taxTypeChoices onChange={change}
); />
<CardSpacer />
return ( <ProductImages
<> images={images}
<Container> placeholderImage={placeholderImage}
<AppHeader onBack={onBack}> onImageDelete={onImageDelete}
{intl.formatMessage(sectionNames.products)} onImageReorder={onImageReorder}
</AppHeader> onImageEdit={onImageEdit}
<PageHeader title={header} /> onImageUpload={onImageUpload}
<Grid> />
<div> <CardSpacer />
<ProductDetailsForm {data.attributes.length > 0 && (
data={data} <ProductAttributes
disabled={disabled} attributes={data.attributes}
errors={errors} errors={errors}
initialDescription={initialDescription} disabled={disabled}
onChange={change} onChange={handlers.selectAttribute}
onMultiChange={handlers.selectAttributeMultiple}
/> />
<CardSpacer /> )}
<ProductImages <CardSpacer />
images={images} {!!product?.productType && !hasVariants && (
placeholderImage={placeholderImage} <>
onImageDelete={onImageDelete} <ProductPricing
onImageReorder={onImageReorder} currency={currency}
onImageEdit={onImageEdit} data={data}
onImageUpload={onImageUpload} disabled={disabled}
/>
<CardSpacer />
{attributes.length > 0 && (
<ProductAttributes
attributes={attributes}
errors={errors} errors={errors}
disabled={disabled} onChange={change}
onChange={handleAttributeChange}
onMultiChange={handleAttributeMultiChange}
/> />
)} <CardSpacer />
<CardSpacer /> </>
{!!product?.productType && !hasVariants && ( )}
<> {hasVariants ? (
<ProductPricing <ProductVariants
currency={currency} disabled={disabled}
data={data} variants={variants}
disabled={disabled} product={product}
errors={errors} fallbackPrice={
onChange={change} product?.variants?.length
/> ? product.variants[0].price
<CardSpacer /> : undefined
</> }
)} onRowClick={onVariantShow}
{hasVariants ? ( onVariantAdd={onVariantAdd}
<ProductVariants onVariantsAdd={onVariantsAdd}
onVariantReorder={onVariantReorder}
onSetDefaultVariant={onSetDefaultVariant}
toolbar={toolbar}
isChecked={isChecked}
selected={selected}
toggle={toggle}
toggleAll={toggleAll}
/>
) : (
<>
<ProductShipping
data={data}
disabled={disabled} disabled={disabled}
variants={variants} errors={errors}
product={product} weightUnit={product?.weight?.unit || defaultWeightUnit}
fallbackPrice={ onChange={change}
product?.variants?.length />
? product.variants[0].price <CardSpacer />
: undefined <ProductStocks
data={data}
disabled={disabled}
hasVariants={false}
errors={errors}
stocks={data.stocks}
warehouses={warehouses}
onChange={handlers.changeStock}
onFormDataChange={change}
onWarehouseStockAdd={handlers.addStock}
onWarehouseStockDelete={handlers.deleteStock}
onWarehouseConfigure={onWarehouseConfigure}
/>
</>
)}
<CardSpacer />
<SeoForm
errors={errors}
title={data.seoTitle}
titlePlaceholder={data.name}
description={data.seoDescription}
descriptionPlaceholder={maybe(() =>
convertFromRaw(data.description)
.getPlainText()
.slice(0, 300)
)}
slug={data.slug}
slugPlaceholder={data.name}
loading={disabled}
onClick={onSeoClick}
onChange={change}
helperText={intl.formatMessage({
defaultMessage:
"Add search engine title and description to make this product easier to find"
})}
/>
<CardSpacer />
<Metadata data={data} onChange={handlers.changeMetadata} />
</div>
<div>
<ProductOrganization
canChangeType={false}
categories={categories}
categoryInputDisplayValue={selectedCategory}
collections={collections}
collectionsInputDisplayValue={selectedCollections}
data={data}
disabled={disabled}
errors={errors}
fetchCategories={fetchCategories}
fetchCollections={fetchCollections}
fetchMoreCategories={fetchMoreCategories}
fetchMoreCollections={fetchMoreCollections}
productType={product?.productType}
onCategoryChange={handlers.selectCategory}
onCollectionChange={handlers.selectCollection}
/>
<CardSpacer />
<AvailabilityCard
data={data}
errors={errors}
disabled={disabled}
messages={{
hiddenLabel: intl.formatMessage({
defaultMessage: "Not published",
description: "product label"
}),
hiddenSecondLabel: intl.formatMessage(
{
defaultMessage: "will become published on {date}",
description: "product publication date label"
},
{
date: localizeDate(data.publicationDate, "L")
} }
onRowClick={onVariantShow} ),
onVariantAdd={onVariantAdd} visibleLabel: intl.formatMessage({
onVariantsAdd={onVariantsAdd} defaultMessage: "Published",
onVariantReorder={onVariantReorder} description: "product label"
onSetDefaultVariant={onSetDefaultVariant} })
toolbar={toolbar} }}
isChecked={isChecked} onChange={change}
selected={selected} />
toggle={toggle} <CardSpacer />
toggleAll={toggleAll} <ProductTaxes
/> data={data}
) : ( disabled={disabled}
<> selectedTaxTypeDisplayName={selectedTaxType}
<ProductShipping taxTypes={taxTypes}
data={data} onChange={change}
disabled={disabled} onTaxTypeChange={handlers.selectTaxRate}
errors={errors} />
weightUnit={product?.weight?.unit || defaultWeightUnit} </div>
onChange={change} </Grid>
/> <SaveButtonBar
<CardSpacer /> onCancel={onBack}
<ProductStocks onDelete={onDelete}
data={data} onSave={submit}
disabled={disabled} state={saveButtonBarState}
hasVariants={false} disabled={disabled || !hasChanged}
errors={errors} />
stocks={stocks} </Container>
warehouses={warehouses} </>
onChange={(id, value) => { )}
triggerChange(); </ProductUpdateForm>
changeStockData(id, value);
}}
onFormDataChange={change}
onWarehouseStockAdd={id => {
triggerChange();
addStock({
data: null,
id,
label: warehouses.find(
warehouse => warehouse.id === id
).name,
value: "0"
});
}}
onWarehouseStockDelete={id => {
triggerChange();
removeStock(id);
}}
onWarehouseConfigure={onWarehouseConfigure}
/>
</>
)}
<CardSpacer />
<SeoForm
errors={errors}
title={data.seoTitle}
titlePlaceholder={data.name}
description={data.seoDescription}
descriptionPlaceholder={maybe(() =>
convertFromRaw(data.description)
.getPlainText()
.slice(0, 300)
)}
slug={data.slug}
slugPlaceholder={data.name}
loading={disabled}
onClick={onSeoClick}
onChange={change}
helperText={intl.formatMessage({
defaultMessage:
"Add search engine title and description to make this product easier to find"
})}
/>
<CardSpacer />
<Metadata data={data} onChange={changeMetadata} />
</div>
<div>
<ProductOrganization
canChangeType={false}
categories={categories}
categoryInputDisplayValue={selectedCategory}
collections={collections}
collectionsInputDisplayValue={selectedCollections}
data={data}
disabled={disabled}
errors={errors}
fetchCategories={fetchCategories}
fetchCollections={fetchCollections}
fetchMoreCategories={fetchMoreCategories}
fetchMoreCollections={fetchMoreCollections}
productType={maybe(() => product.productType)}
onCategoryChange={handleCategorySelect}
onCollectionChange={handleCollectionSelect}
/>
<CardSpacer />
<AvailabilityCard
data={data}
errors={errors}
disabled={disabled}
messages={{
hiddenLabel: intl.formatMessage({
defaultMessage: "Not published",
description: "product label"
}),
hiddenSecondLabel: intl.formatMessage(
{
defaultMessage: "will become published on {date}",
description: "product publication date label"
},
{
date: localizeDate(data.publicationDate, "L")
}
),
visibleLabel: intl.formatMessage({
defaultMessage: "Published",
description: "product label"
})
}}
onChange={change}
/>
<CardSpacer />
<ProductTaxes
data={data}
disabled={disabled}
selectedTaxTypeDisplayName={selectedTaxType}
taxTypes={taxTypes}
onChange={change}
onTaxTypeChange={handleTaxTypeSelect}
/>
</div>
</Grid>
<SaveButtonBar
onCancel={onBack}
onDelete={onDelete}
onSave={submit}
state={saveButtonBarState}
disabled={disabled || !hasChanged}
/>
</Container>
</>
);
}}
</Form>
); );
}; };
ProductUpdatePage.displayName = "ProductUpdatePage"; ProductUpdatePage.displayName = "ProductUpdatePage";

View file

@ -0,0 +1,259 @@
import { MetadataFormData } from "@saleor/components/Metadata";
import { MultiAutocompleteChoiceType } from "@saleor/components/MultiAutocompleteSelectField";
import { SingleAutocompleteChoiceType } from "@saleor/components/SingleAutocompleteSelectField";
import useForm, { FormChange } from "@saleor/hooks/useForm";
import useFormset, {
FormsetChange,
FormsetData
} from "@saleor/hooks/useFormset";
import { ProductDetails_product } from "@saleor/products/types/ProductDetails";
import {
getAttributeInputFromProduct,
getProductUpdatePageFormData,
getStockInputFromProduct
} from "@saleor/products/utils/data";
import {
createAttributeChangeHandler,
createAttributeMultiChangeHandler
} from "@saleor/products/utils/handlers";
import { SearchWarehouses_search_edges_node } from "@saleor/searches/types/SearchWarehouses";
import createMultiAutocompleteSelectHandler from "@saleor/utils/handlers/multiAutocompleteSelectChangeHandler";
import createSingleAutocompleteSelectHandler from "@saleor/utils/handlers/singleAutocompleteSelectChangeHandler";
import useMetadataChangeTrigger from "@saleor/utils/metadata/useMetadataChangeTrigger";
import { RawDraftContentState } from "draft-js";
import { diff } from "fast-array-diff";
import React from "react";
import { ProductAttributeInput } from "../ProductAttributes";
import { ProductStockInput } from "../ProductStocks";
export interface ProductUpdateFormData extends MetadataFormData {
availableForPurchase: string;
basePrice: number;
category: string | null;
changeTaxCode: boolean;
chargeTaxes: boolean;
collections: string[];
description: RawDraftContentState;
isAvailable: boolean;
isAvailableForPurchase: boolean;
isPublished: boolean;
name: string;
slug: string;
publicationDate: string;
seoDescription: string;
seoTitle: string;
sku: string;
taxCode: string;
trackInventory: boolean;
visibleInListings: boolean;
weight: string;
}
export interface ProductUpdateData extends ProductUpdateFormData {
attributes: ProductAttributeInput[];
stocks: ProductStockInput[];
}
export interface ProductUpdateSubmitData extends ProductUpdateFormData {
attributes: ProductAttributeInput[];
collections: string[];
addStocks: ProductStockInput[];
updateStocks: ProductStockInput[];
removeStocks: string[];
}
export interface UseProductUpdateFormResult {
change: FormChange;
data: ProductUpdateData;
handlers: Record<
"changeMetadata" | "selectCategory" | "selectCollection" | "selectTaxRate",
FormChange
> &
Record<
"changeStock" | "selectAttribute" | "selectAttributeMultiple",
FormsetChange
> &
Record<"addStock" | "deleteStock", (id: string) => void>;
hasChanged: boolean;
submit: () => Promise<boolean>;
}
export interface UseProductUpdateFormOpts
extends Record<
"categories" | "collections" | "taxTypes",
SingleAutocompleteChoiceType[]
> {
setSelectedCategory: React.Dispatch<React.SetStateAction<string>>;
setSelectedCollections: React.Dispatch<
React.SetStateAction<MultiAutocompleteChoiceType[]>
>;
setSelectedTaxType: React.Dispatch<React.SetStateAction<string>>;
selectedCollections: MultiAutocompleteChoiceType[];
warehouses: SearchWarehouses_search_edges_node[];
}
export interface ProductUpdateFormProps extends UseProductUpdateFormOpts {
children: (props: UseProductUpdateFormResult) => React.ReactNode;
product: ProductDetails_product;
onSubmit: (data: ProductUpdateSubmitData) => Promise<boolean>;
}
const getAvailabilityData = ({
availableForPurchase,
isAvailableForPurchase,
isPublished,
publicationDate
}: ProductUpdateFormData) => ({
isAvailableForPurchase: isAvailableForPurchase || !!availableForPurchase,
isPublished: isPublished || !!publicationDate
});
const getStocksData = (
product: ProductDetails_product,
stocks: FormsetData<null, string>
) => {
if (product.productType.hasVariants) {
return { addStocks: [], removeStocks: [], updateStocks: [] };
}
const dataStocks = stocks.map(stock => stock.id);
const variantStocks = product.variants[0]?.stocks.map(
stock => stock.warehouse.id
);
const stockDiff = diff(variantStocks, dataStocks);
return {
addStocks: stocks.filter(stock =>
stockDiff.added.some(addedStock => addedStock === stock.id)
),
removeStocks: stockDiff.removed,
updateStocks: stocks.filter(
stock => !stockDiff.added.some(addedStock => addedStock === stock.id)
)
};
};
const getMetadata = (
data: ProductUpdateFormData,
isMetadataModified: boolean,
isPrivateMetadataModified: boolean
) => ({
metadata: isMetadataModified ? data.metadata : undefined,
privateMetadata: isPrivateMetadataModified ? data.privateMetadata : undefined
});
function useProductUpdateForm(
product: ProductDetails_product,
onSubmit: (data: ProductUpdateSubmitData) => Promise<boolean>,
opts: UseProductUpdateFormOpts
): UseProductUpdateFormResult {
const [changed, setChanged] = React.useState(false);
const triggerChange = () => setChanged(true);
const form = useForm(
getProductUpdatePageFormData(product, product?.variants)
);
const attributes = useFormset(getAttributeInputFromProduct(product));
const stocks = useFormset(getStockInputFromProduct(product));
const {
isMetadataModified,
isPrivateMetadataModified,
makeChangeHandler: makeMetadataChangeHandler
} = useMetadataChangeTrigger();
const handleChange: FormChange = (event, cb) => {
form.change(event, cb);
triggerChange();
};
const handleCollectionSelect = createMultiAutocompleteSelectHandler(
form.toggleValue,
opts.setSelectedCollections,
opts.selectedCollections,
opts.collections
);
const handleCategorySelect = createSingleAutocompleteSelectHandler(
handleChange,
opts.setSelectedCategory,
opts.categories
);
const handleAttributeChange = createAttributeChangeHandler(
attributes.change,
triggerChange
);
const handleAttributeMultiChange = createAttributeMultiChangeHandler(
attributes.change,
attributes.data,
triggerChange
);
const handleStockChange: FormsetChange = (id, value) => {
triggerChange();
stocks.change(id, value);
};
const handleStockAdd = (id: string) => {
triggerChange();
stocks.add({
data: null,
id,
label: opts.warehouses.find(warehouse => warehouse.id === id).name,
value: "0"
});
};
const handleStockDelete = (id: string) => {
triggerChange();
stocks.remove(id);
};
const handleTaxTypeSelect = createSingleAutocompleteSelectHandler(
handleChange,
opts.setSelectedTaxType,
opts.taxTypes
);
const changeMetadata = makeMetadataChangeHandler(handleChange);
const data: ProductUpdateData = {
...form.data,
attributes: attributes.data,
stocks: stocks.data
};
const submit = () =>
onSubmit({
...data,
...getAvailabilityData(data),
...getStocksData(product, stocks.data),
...getMetadata(data, isMetadataModified, isPrivateMetadataModified),
addStocks: [],
attributes: attributes.data
});
return {
change: handleChange,
data,
handlers: {
addStock: handleStockAdd,
changeMetadata,
changeStock: handleStockChange,
deleteStock: handleStockDelete,
selectAttribute: handleAttributeChange,
selectAttributeMultiple: handleAttributeMultiChange,
selectCategory: handleCategorySelect,
selectCollection: handleCollectionSelect,
selectTaxRate: handleTaxTypeSelect
},
hasChanged: changed,
submit
};
}
const ProductUpdateForm: React.FC<ProductUpdateFormProps> = ({
children,
product,
onSubmit,
...rest
}) => {
const props = useProductUpdateForm(product, onSubmit, rest);
return <form onSubmit={props.submit}>{children(props)}</form>;
};
ProductUpdateForm.displayName = "ProductUpdateForm";
export default ProductUpdateForm;