Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

fix(admin,vendor): rebuild product-create variants on every attribute change (#1650)

Viktor Holikf39d73965d26
diff --git a/packages/admin/src/pages/products/product-create/__tests__/variant-sync.spec.ts b/packages/admin/src/pages/products/product-create/__tests__/variant-sync.spec.ts
new file mode 100644
index 000000000..295073df2
--- /dev/null
+++ b/packages/admin/src/pages/products/product-create/__tests__/variant-sync.spec.ts
@@ -0,0 +1,84 @@
+import { createFormControl } from "react-hook-form"
+import { describe, expect, test } from "vitest"
+
+import { ProductCreateSchemaType } from "../types"
+import { subscribeVariantsToAttributes } from "../utils"
+
+const customAxis = (title: string, values: string[]) => ({
+ attribute_id: undefined,
+ title,
+ values,
+ is_custom: true,
+ use_for_variants: true,
+})
+
+const setup = () => {
+ const form = createFormControl<ProductCreateSchemaType>({
+ defaultValues: { attributes: [], variants: [] } as unknown as ProductCreateSchemaType,
+ })
+ const unsubscribe = subscribeVariantsToAttributes(form)
+ const titles = () => form.getValues("variants").map((v) => v.title)
+
+ return { form, unsubscribe, titles }
+}
+
+describe("subscribeVariantsToAttributes", () => {
+ test("seeds a default variant when no axis is set", () => {
+ const { titles } = setup()
+
+ expect(titles()).toEqual(["Default variant"])
+ })
+
+ test("rebuilds rows for every value added to an axis", () => {
+ const { form, titles } = setup()
+
+ form.setValue("attributes", [customAxis("Edition", ["Standard"])])
+ expect(titles()).toEqual(["Standard"])
+
+ form.setValue("attributes.0.values", ["Standard", "Deluxe"])
+ expect(titles()).toEqual(["Standard", "Deluxe"])
+ })
+
+ test("builds the full permutation table for a second axis", () => {
+ const { form, titles } = setup()
+
+ form.setValue("attributes", [
+ customAxis("Edition", ["Standard", "Deluxe"]),
+ customAxis("Platform", ["PC", "Xbox"]),
+ ])
+
+ expect(titles()).toEqual([
+ "Standard / PC",
+ "Standard / Xbox",
+ "Deluxe / PC",
+ "Deluxe / Xbox",
+ ])
+ expect(form.getValues("variants").map((v) => v.options)).toEqual([
+ { Edition: "Standard", Platform: "PC" },
+ { Edition: "Standard", Platform: "Xbox" },
+ { Edition: "Deluxe", Platform: "PC" },
+ { Edition: "Deluxe", Platform: "Xbox" },
+ ])
+ })
+
+ test("reacts to the use_for_variants switch on an existing row", () => {
+ const { form, titles } = setup()
+
+ form.setValue("attributes", [
+ { ...customAxis("Edition", ["Standard", "Deluxe"]), use_for_variants: false },
+ ])
+ expect(titles()).toEqual(["Default variant"])
+
+ form.setValue("attributes.0.use_for_variants", true)
+ expect(titles()).toEqual(["Standard", "Deluxe"])
+ })
+
+ test("stops syncing after unsubscribe", () => {
+ const { form, unsubscribe, titles } = setup()
+
+ unsubscribe()
+ form.setValue("attributes", [customAxis("Edition", ["Standard"])])
+
+ expect(titles()).toEqual(["Default variant"])
+ })
+})
diff --git a/packages/admin/src/pages/products/product-create/components/product-create-attributes-form/product-create-attributes-form.tsx b/packages/admin/src/pages/products/product-create/components/product-create-attributes-form/product-create-attributes-form.tsx
index 72ff1bd1b..92d12d017 100644
--- a/packages/admin/src/pages/products/product-create/components/product-create-attributes-form/product-create-attributes-form.tsx
+++ b/packages/admin/src/pages/products/product-create/components/product-create-attributes-form/product-create-attributes-form.tsx
@@ -20,6 +20,7 @@ import {
FieldArrayWithId,
UseFieldArrayRemove,
useFieldArray,
+ useWatch,
} from "react-hook-form"
import { useTranslation } from "react-i18next"
@@ -115,132 +116,15 @@ const Root = () => {
className="flex flex-col gap-y-4"
data-testid="product-create-attributes-list"
>
- {fields.map((field, index) => {
- if (!field.is_custom) return null
- const useForVariants = form.watch(
- `attributes.${index}.use_for_variants`
- )
-
- return (
- <li
- key={field.id}
- className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-start gap-1.5 rounded-xl p-1.5"
- data-testid={`product-create-attribute-row-${index}`}
- >
- <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
- <div className="flex items-center px-2 py-1.5">
- <Label
- size="xsmall"
- weight="plus"
- className="text-ui-fg-subtle"
- htmlFor={`attributes.${index}.title`}
- >
- {t("fields.title")}
- </Label>
- </div>
- <Input
- className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
- {...form.register(
- `attributes.${index}.title` as const
- )}
- placeholder={t(
- "products.create.attributes.titlePlaceholder"
- )}
- data-testid={`product-create-attribute-title-${index}`}
- />
- <div className="flex items-center px-2 py-1.5">
- <Label
- size="xsmall"
- weight="plus"
- className="text-ui-fg-subtle"
- htmlFor={`attributes.${index}.values`}
- >
- {t("fields.values")}
- </Label>
- </div>
- <Controller
- control={form.control}
- name={`attributes.${index}.values` as const}
- render={({ field: { onChange, value, ...field } }) =>
- useForVariants ? (
- <ChipInput
- {...field}
- variant="contrast"
- value={Array.isArray(value) ? value : []}
- onChange={onChange}
- placeholder={t(
- "products.create.attributes.valuePlaceholder"
- )}
- data-testid={`product-create-attribute-values-${index}`}
- />
- ) : (
- <Textarea
- {...field}
- className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
- value={
- Array.isArray(value)
- ? value[0] ?? ""
- : value ?? ""
- }
- onChange={(e) => onChange(e.target.value)}
- placeholder={t(
- "products.create.attributes.valuePlaceholder"
- )}
- data-testid={`product-create-attribute-values-${index}`}
- />
- )
- }
- />
- <div />
- <Form.Field
- control={form.control}
- name={`attributes.${index}.use_for_variants`}
- render={({
- field: { value, onChange, ref },
- }) => (
- <Form.Item>
- <div
- className="flex items-start gap-x-3 py-1.5"
- data-testid={`product-create-attribute-use-for-variants-${index}`}
- >
- <Form.Control>
- <Switch
- ref={ref}
- className="shrink-0 rtl:rotate-180"
- checked={value}
- onCheckedChange={onChange}
- />
- </Form.Control>
- <div className="flex flex-col">
- <Label size="xsmall" weight="plus">
- {t(
- "products.create.attributes.useForVariants"
- )}
- </Label>
- <Hint className="!txt-small">
- {t(
- "products.create.attributes.useForVariantsDescription"
- )}
- </Hint>
- </div>
- </div>
- </Form.Item>
- )}
- />
- </div>
- <IconButton
- type="button"
- size="small"
- variant="transparent"
- className="text-ui-fg-muted"
- onClick={() => remove(index)}
- data-testid={`product-create-attribute-remove-${index}`}
- >
- <XMarkMini />
- </IconButton>
- </li>
- )
- })}
+ {fields.map((field, index) =>
+ field.is_custom ? (
+ <CustomAttributeRow
+ key={field.id}
+ index={index}
+ remove={remove}
+ />
+ ) : null
+ )}
</ul>
)}
@@ -250,6 +134,140 @@ const Root = () => {
)
}
+const CustomAttributeRow = ({
+ index,
+ remove,
+}: {
+ index: number
+ remove: UseFieldArrayRemove
+}) => {
+ const { t } = useTranslation()
+ const form = useTabbedForm<ProductCreateSchemaType>()
+ const useForVariants = useWatch({
+ control: form.control,
+ name: `attributes.${index}.use_for_variants`,
+ })
+
+ return (
+ <li
+ className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-start gap-1.5 rounded-xl p-1.5"
+ data-testid={`product-create-attribute-row-${index}`}
+ >
+ <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`attributes.${index}.title`}
+ >
+ {t("fields.title")}
+ </Label>
+ </div>
+ <Input
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ {...form.register(
+ `attributes.${index}.title` as const
+ )}
+ placeholder={t(
+ "products.create.attributes.titlePlaceholder"
+ )}
+ data-testid={`product-create-attribute-title-${index}`}
+ />
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`attributes.${index}.values`}
+ >
+ {t("fields.values")}
+ </Label>
+ </div>
+ <Controller
+ control={form.control}
+ name={`attributes.${index}.values` as const}
+ render={({ field: { onChange, value, ...field } }) =>
+ useForVariants ? (
+ <ChipInput
+ {...field}
+ variant="contrast"
+ value={Array.isArray(value) ? value : []}
+ onChange={onChange}
+ placeholder={t(
+ "products.create.attributes.valuePlaceholder"
+ )}
+ data-testid={`product-create-attribute-values-${index}`}
+ />
+ ) : (
+ <Textarea
+ {...field}
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ value={
+ Array.isArray(value)
+ ? value[0] ?? ""
+ : value ?? ""
+ }
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={t(
+ "products.create.attributes.valuePlaceholder"
+ )}
+ data-testid={`product-create-attribute-values-${index}`}
+ />
+ )
+ }
+ />
+ <div />
+ <Form.Field
+ control={form.control}
+ name={`attributes.${index}.use_for_variants`}
+ render={({
+ field: { value, onChange, ref },
+ }) => (
+ <Form.Item>
+ <div
+ className="flex items-start gap-x-3 py-1.5"
+ data-testid={`product-create-attribute-use-for-variants-${index}`}
+ >
+ <Form.Control>
+ <Switch
+ ref={ref}
+ className="shrink-0 rtl:rotate-180"
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Form.Control>
+ <div className="flex flex-col">
+ <Label size="xsmall" weight="plus">
+ {t(
+ "products.create.attributes.useForVariants"
+ )}
+ </Label>
+ <Hint className="!txt-small">
+ {t(
+ "products.create.attributes.useForVariantsDescription"
+ )}
+ </Hint>
+ </div>
+ </div>
+ </Form.Item>
+ )}
+ />
+ </div>
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ onClick={() => remove(index)}
+ data-testid={`product-create-attribute-remove-${index}`}
+ >
+ <XMarkMini />
+ </IconButton>
+ </li>
+ )
+}
+
const SelectedAttributes = ({
fields,
remove,
diff --git a/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx b/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx
index 67547a770..83f887010 100644
--- a/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx
+++ b/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx
@@ -1,7 +1,7 @@
import { HttpTypes } from "@medusajs/types";
import { Button, toast } from "@medusajs/ui";
import { ReactNode, useEffect, useMemo, Children } from "react";
-import { useForm, useWatch } from "react-hook-form";
+import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { isForbidden, useCan } from "@mercurjs/dashboard-shared";
import {
@@ -18,8 +18,8 @@ import {
} from "../../constants";
import { ProductCreateSchemaType } from "../../types";
import {
- generateVariantsFromAttributes,
normalizeProductFormValues,
+ subscribeVariantsToAttributes,
} from "../../utils";
import { ProductCreateAttributesForm } from "../product-create-attributes-form";
import { ProductCreateDetailsForm } from "../product-create-details-form";
@@ -80,26 +80,7 @@ export const ProductCreateForm = ({
);
}, [regions]);
- const watchedAttributes = useWatch({
- control: form.control,
- name: "attributes",
- });
-
- // Generate variants from variant-axis attributes
- useEffect(() => {
- const currentVariants = form.getValues("variants") ?? [];
- const newVariants = generateVariantsFromAttributes(
- watchedAttributes ?? [],
- currentVariants,
- );
-
- if (
- JSON.stringify(newVariants.map((v) => v.options)) !==
- JSON.stringify(currentVariants.map((v) => v.options))
- ) {
- form.setValue("variants", newVariants);
- }
- }, [watchedAttributes, form]);
+ useEffect(() => subscribeVariantsToAttributes(form), [form]);
const handleSubmit = form.handleSubmit(async (values, e) => {
if (isRegionsPending) {
@@ -147,28 +128,28 @@ export const ProductCreateForm = ({
}
}
- await mutateAsync(
- normalizeProductFormValues({
- ...payload,
- media: uploadedMedia,
- status: (isDraftSubmission ? "draft" : "published") as any,
- regionsCurrencyMap,
- }) as any,
- {
- onSuccess: (data) => {
- toast.success(
- t("products.create.successToast", {
- title: data.product.title,
- }),
- );
-
- handleSuccess(`../${data.product.id}`);
- },
- onError: (error) => {
- toast.error(error.message);
- },
- },
- );
+ try {
+ const data = await mutateAsync(
+ normalizeProductFormValues({
+ ...payload,
+ media: uploadedMedia,
+ status: (isDraftSubmission ? "draft" : "published") as any,
+ regionsCurrencyMap,
+ }) as any,
+ );
+
+ toast.success(
+ t("products.create.successToast", {
+ title: data.product.title,
+ }),
+ );
+
+ handleSuccess(`../${data.product.id}`);
+ } catch (error) {
+ if (error instanceof Error) {
+ toast.error(error.message);
+ }
+ }
});
const defaultTabs = useMemo(
diff --git a/packages/admin/src/pages/products/product-create/utils.ts b/packages/admin/src/pages/products/product-create/utils.ts
index 271305f17..b353eedf2 100644
--- a/packages/admin/src/pages/products/product-create/utils.ts
+++ b/packages/admin/src/pages/products/product-create/utils.ts
@@ -1,5 +1,6 @@
import { HttpTypes } from "@medusajs/types"
import { AttributeType, ProductAttributeBatchAdd } from "@mercurjs/types"
+import { UseFormReturn } from "react-hook-form"
import { ProductCreateSchemaType } from "./types"
export const normalizeProductFormValues = (
@@ -258,3 +259,37 @@ export const generateVariantsFromAttributes = (
return newVariants
}
+
+type VariantSyncForm = Pick<
+ UseFormReturn<ProductCreateSchemaType>,
+ "getValues" | "setValue" | "subscribe"
+>
+
+export const syncVariantsWithAttributes = (form: VariantSyncForm) => {
+ const currentVariants = form.getValues("variants") ?? []
+ const nextVariants = generateVariantsFromAttributes(
+ form.getValues("attributes") ?? [],
+ currentVariants
+ )
+
+ const sameOptions =
+ JSON.stringify(nextVariants.map((v) => v.options)) ===
+ JSON.stringify(currentVariants.map((v) => v.options))
+
+ if (!sameOptions) {
+ form.setValue("variants", nextVariants)
+ }
+}
+
+// `useWatch({ name: "attributes" })` hands back the same array reference RHF
+// mutates in place, so a dependent effect only fires on the first change.
+// Subscribing by name fires for every nested update instead.
+export const subscribeVariantsToAttributes = (form: VariantSyncForm) => {
+ syncVariantsWithAttributes(form)
+
+ return form.subscribe({
+ name: "attributes",
+ formState: { values: true },
+ callback: () => syncVariantsWithAttributes(form),
+ })
+}
diff --git a/packages/vendor/src/pages/products/create/__tests__/variant-sync.spec.ts b/packages/vendor/src/pages/products/create/__tests__/variant-sync.spec.ts
new file mode 100644
index 000000000..295073df2
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/__tests__/variant-sync.spec.ts
@@ -0,0 +1,84 @@
+import { createFormControl } from "react-hook-form"
+import { describe, expect, test } from "vitest"
+
+import { ProductCreateSchemaType } from "../types"
+import { subscribeVariantsToAttributes } from "../utils"
+
+const customAxis = (title: string, values: string[]) => ({
+ attribute_id: undefined,
+ title,
+ values,
+ is_custom: true,
+ use_for_variants: true,
+})
+
+const setup = () => {
+ const form = createFormControl<ProductCreateSchemaType>({
+ defaultValues: { attributes: [], variants: [] } as unknown as ProductCreateSchemaType,
+ })
+ const unsubscribe = subscribeVariantsToAttributes(form)
+ const titles = () => form.getValues("variants").map((v) => v.title)
+
+ return { form, unsubscribe, titles }
+}
+
+describe("subscribeVariantsToAttributes", () => {
+ test("seeds a default variant when no axis is set", () => {
+ const { titles } = setup()
+
+ expect(titles()).toEqual(["Default variant"])
+ })
+
+ test("rebuilds rows for every value added to an axis", () => {
+ const { form, titles } = setup()
+
+ form.setValue("attributes", [customAxis("Edition", ["Standard"])])
+ expect(titles()).toEqual(["Standard"])
+
+ form.setValue("attributes.0.values", ["Standard", "Deluxe"])
+ expect(titles()).toEqual(["Standard", "Deluxe"])
+ })
+
+ test("builds the full permutation table for a second axis", () => {
+ const { form, titles } = setup()
+
+ form.setValue("attributes", [
+ customAxis("Edition", ["Standard", "Deluxe"]),
+ customAxis("Platform", ["PC", "Xbox"]),
+ ])
+
+ expect(titles()).toEqual([
+ "Standard / PC",
+ "Standard / Xbox",
+ "Deluxe / PC",
+ "Deluxe / Xbox",
+ ])
+ expect(form.getValues("variants").map((v) => v.options)).toEqual([
+ { Edition: "Standard", Platform: "PC" },
+ { Edition: "Standard", Platform: "Xbox" },
+ { Edition: "Deluxe", Platform: "PC" },
+ { Edition: "Deluxe", Platform: "Xbox" },
+ ])
+ })
+
+ test("reacts to the use_for_variants switch on an existing row", () => {
+ const { form, titles } = setup()
+
+ form.setValue("attributes", [
+ { ...customAxis("Edition", ["Standard", "Deluxe"]), use_for_variants: false },
+ ])
+ expect(titles()).toEqual(["Default variant"])
+
+ form.setValue("attributes.0.use_for_variants", true)
+ expect(titles()).toEqual(["Standard", "Deluxe"])
+ })
+
+ test("stops syncing after unsubscribe", () => {
+ const { form, unsubscribe, titles } = setup()
+
+ unsubscribe()
+ form.setValue("attributes", [customAxis("Edition", ["Standard"])])
+
+ expect(titles()).toEqual(["Default variant"])
+ })
+})
diff --git a/packages/vendor/src/pages/products/create/components/product-create-attributes-form/product-create-attributes-form.tsx b/packages/vendor/src/pages/products/create/components/product-create-attributes-form/product-create-attributes-form.tsx
index 504238d38..8ece26285 100644
--- a/packages/vendor/src/pages/products/create/components/product-create-attributes-form/product-create-attributes-form.tsx
+++ b/packages/vendor/src/pages/products/create/components/product-create-attributes-form/product-create-attributes-form.tsx
@@ -20,6 +20,7 @@ import {
FieldArrayWithId,
UseFieldArrayRemove,
useFieldArray,
+ useWatch,
} from "react-hook-form"
import { useTranslation } from "react-i18next"
@@ -113,132 +114,15 @@ const Root = () => {
className="flex flex-col gap-y-4"
data-testid="product-create-attributes-list"
>
- {fields.map((field, index) => {
- if (!field.is_custom) return null
- const useForVariants = form.watch(
- `attributes.${index}.use_for_variants`
- )
-
- return (
- <li
+ {fields.map((field, index) =>
+ field.is_custom ? (
+ <CustomAttributeRow
key={field.id}
- className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-start gap-1.5 rounded-xl p-1.5"
- data-testid={`product-create-attribute-row-${index}`}
- >
- <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
- <div className="flex items-center px-2 py-1.5">
- <Label
- size="xsmall"
- weight="plus"
- className="text-ui-fg-subtle"
- htmlFor={`attributes.${index}.title`}
- >
- {t("fields.title")}
- </Label>
- </div>
- <Input
- className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
- {...form.register(
- `attributes.${index}.title` as const
- )}
- placeholder={t(
- "products.create.attributes.titlePlaceholder"
- )}
- data-testid={`product-create-attribute-title-${index}`}
- />
- <div className="flex items-center px-2 py-1.5">
- <Label
- size="xsmall"
- weight="plus"
- className="text-ui-fg-subtle"
- htmlFor={`attributes.${index}.values`}
- >
- {t("fields.values")}
- </Label>
- </div>
- <Controller
- control={form.control}
- name={`attributes.${index}.values` as const}
- render={({ field: { onChange, value, ...field } }) =>
- useForVariants ? (
- <ChipInput
- {...field}
- variant="contrast"
- value={Array.isArray(value) ? value : []}
- onChange={onChange}
- placeholder={t(
- "products.create.attributes.valuePlaceholder"
- )}
- data-testid={`product-create-attribute-values-${index}`}
- />
- ) : (
- <Textarea
- {...field}
- className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
- value={
- Array.isArray(value)
- ? value[0] ?? ""
- : value ?? ""
- }
- onChange={(e) => onChange(e.target.value)}
- placeholder={t(
- "products.create.attributes.valuePlaceholder"
- )}
- data-testid={`product-create-attribute-values-${index}`}
- />
- )
- }
- />
- <div />
- <Form.Field
- control={form.control}
- name={`attributes.${index}.use_for_variants`}
- render={({
- field: { value, onChange, ref },
- }) => (
- <Form.Item>
- <div
- className="flex items-start gap-x-3 py-1.5"
- data-testid={`product-create-attribute-use-for-variants-${index}`}
- >
- <Form.Control>
- <Switch
- ref={ref}
- className="shrink-0 rtl:rotate-180"
- checked={value}
- onCheckedChange={onChange}
- />
- </Form.Control>
- <div className="flex flex-col">
- <Label size="xsmall" weight="plus">
- {t(
- "products.create.attributes.useForVariants"
- )}
- </Label>
- <Hint className="!txt-small">
- {t(
- "products.create.attributes.useForVariantsDescription"
- )}
- </Hint>
- </div>
- </div>
- </Form.Item>
- )}
- />
- </div>
- <IconButton
- type="button"
- size="small"
- variant="transparent"
- className="text-ui-fg-muted"
- onClick={() => remove(index)}
- data-testid={`product-create-attribute-remove-${index}`}
- >
- <XMarkMini />
- </IconButton>
- </li>
- )
- })}
+ index={index}
+ remove={remove}
+ />
+ ) : null
+ )}
</ul>
)}
@@ -248,6 +132,140 @@ const Root = () => {
)
}
+const CustomAttributeRow = ({
+ index,
+ remove,
+}: {
+ index: number
+ remove: UseFieldArrayRemove
+}) => {
+ const { t } = useTranslation()
+ const form = useTabbedForm<ProductCreateSchemaType>()
+ const useForVariants = useWatch({
+ control: form.control,
+ name: `attributes.${index}.use_for_variants`,
+ })
+
+ return (
+ <li
+ className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-start gap-1.5 rounded-xl p-1.5"
+ data-testid={`product-create-attribute-row-${index}`}
+ >
+ <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`attributes.${index}.title`}
+ >
+ {t("fields.title")}
+ </Label>
+ </div>
+ <Input
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ {...form.register(
+ `attributes.${index}.title` as const
+ )}
+ placeholder={t(
+ "products.create.attributes.titlePlaceholder"
+ )}
+ data-testid={`product-create-attribute-title-${index}`}
+ />
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`attributes.${index}.values`}
+ >
+ {t("fields.values")}
+ </Label>
+ </div>
+ <Controller
+ control={form.control}
+ name={`attributes.${index}.values` as const}
+ render={({ field: { onChange, value, ...field } }) =>
+ useForVariants ? (
+ <ChipInput
+ {...field}
+ variant="contrast"
+ value={Array.isArray(value) ? value : []}
+ onChange={onChange}
+ placeholder={t(
+ "products.create.attributes.valuePlaceholder"
+ )}
+ data-testid={`product-create-attribute-values-${index}`}
+ />
+ ) : (
+ <Textarea
+ {...field}
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ value={
+ Array.isArray(value)
+ ? value[0] ?? ""
+ : value ?? ""
+ }
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={t(
+ "products.create.attributes.valuePlaceholder"
+ )}
+ data-testid={`product-create-attribute-values-${index}`}
+ />
+ )
+ }
+ />
+ <div />
+ <Form.Field
+ control={form.control}
+ name={`attributes.${index}.use_for_variants`}
+ render={({
+ field: { value, onChange, ref },
+ }) => (
+ <Form.Item>
+ <div
+ className="flex items-start gap-x-3 py-1.5"
+ data-testid={`product-create-attribute-use-for-variants-${index}`}
+ >
+ <Form.Control>
+ <Switch
+ ref={ref}
+ className="shrink-0 rtl:rotate-180"
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Form.Control>
+ <div className="flex flex-col">
+ <Label size="xsmall" weight="plus">
+ {t(
+ "products.create.attributes.useForVariants"
+ )}
+ </Label>
+ <Hint className="!txt-small">
+ {t(
+ "products.create.attributes.useForVariantsDescription"
+ )}
+ </Hint>
+ </div>
+ </div>
+ </Form.Item>
+ )}
+ />
+ </div>
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ onClick={() => remove(index)}
+ data-testid={`product-create-attribute-remove-${index}`}
+ >
+ <XMarkMini />
+ </IconButton>
+ </li>
+ )
+}
+
const SelectedAttributes = ({
fields,
remove,
diff --git a/packages/vendor/src/pages/products/create/components/product-create-form/product-create-form.tsx b/packages/vendor/src/pages/products/create/components/product-create-form/product-create-form.tsx
index 8f160ad9d..4a6456fdf 100644
--- a/packages/vendor/src/pages/products/create/components/product-create-form/product-create-form.tsx
+++ b/packages/vendor/src/pages/products/create/components/product-create-form/product-create-form.tsx
@@ -1,7 +1,7 @@
import { MercurFeatureFlags } from "@mercurjs/types"
import { Button, toast } from "@medusajs/ui"
import { ReactNode, useEffect, useMemo, Children } from "react"
-import { useForm, useWatch, DeepPartial } from "react-hook-form"
+import { useForm, DeepPartial } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { zodResolver } from "@hookform/resolvers/zod"
@@ -13,7 +13,7 @@ import { sdk } from "@lib/client"
import { PRODUCT_CREATE_FORM_DEFAULTS, ProductCreateSchema } from "../../constants"
import { ProductCreateSchemaType } from "../../types"
import {
- generateVariantsFromAttributes,
+ subscribeVariantsToAttributes,
normalizeProductFormValues,
} from "../../utils"
import { ProductCreateAttributesForm } from "../product-create-attributes-form"
@@ -50,26 +50,7 @@ export const ProductCreateForm = ({
const productRequestEnabled =
!!feature_flags?.[MercurFeatureFlags.PRODUCT_REQUEST]
- const watchedAttributes = useWatch({
- control: form.control,
- name: "attributes",
- })
-
- // Generate variants from variant-axis attributes
- useEffect(() => {
- const currentVariants = form.getValues("variants") ?? []
- const newVariants = generateVariantsFromAttributes(
- watchedAttributes ?? [],
- currentVariants
- )
-
- if (
- JSON.stringify(newVariants.map((v) => v.options)) !==
- JSON.stringify(currentVariants.map((v) => v.options))
- ) {
- form.setValue("variants", newVariants)
- }
- }, [watchedAttributes, form])
+ useEffect(() => subscribeVariantsToAttributes(form), [form])
const submitProduct = async (
values: ProductCreateSchemaType,
@@ -106,31 +87,31 @@ export const ProductCreateForm = ({
? "proposed"
: "published"
- await mutateAsync(
- normalizeProductFormValues({
- ...payload,
- media: uploadedMedia,
- status: submittedStatus as any,
- }) as any,
- {
- onSuccess: (data: any) => {
- if (submittedStatus === "proposed") {
- toast.success(t("products.create.requestSuccessToast"))
- } else {
- toast.success(
- t("products.create.successToast", {
- title: data.product.title,
- })
- )
- }
-
- handleSuccess(`../${data.product.id}`)
- },
- onError: (error: any) => {
- toast.error(error.message)
- },
+ try {
+ const data = await mutateAsync(
+ normalizeProductFormValues({
+ ...payload,
+ media: uploadedMedia,
+ status: submittedStatus as any,
+ }) as any
+ )
+
+ if (submittedStatus === "proposed") {
+ toast.success(t("products.create.requestSuccessToast"))
+ } else {
+ toast.success(
+ t("products.create.successToast", {
+ title: data.product.title,
+ })
+ )
+ }
+
+ handleSuccess(`../${data.product.id}`)
+ } catch (error) {
+ if (error instanceof Error) {
+ toast.error(error.message)
}
- )
+ }
}
const handleSubmit = form.handleSubmit(async (values) => {
diff --git a/packages/vendor/src/pages/products/create/utils.ts b/packages/vendor/src/pages/products/create/utils.ts
index cbf2d62e5..3044862fa 100644
--- a/packages/vendor/src/pages/products/create/utils.ts
+++ b/packages/vendor/src/pages/products/create/utils.ts
@@ -1,5 +1,6 @@
import { HttpTypes } from "@medusajs/types"
import { AttributeType, ProductAttributeBatchAdd } from "@mercurjs/types"
+import { UseFormReturn } from "react-hook-form"
import { ProductCreateSchemaType } from "./types"
export const normalizeProductFormValues = (
@@ -248,3 +249,37 @@ export const generateVariantsFromAttributes = (
return newVariants
}
+
+type VariantSyncForm = Pick<
+ UseFormReturn<ProductCreateSchemaType>,
+ "getValues" | "setValue" | "subscribe"
+>
+
+export const syncVariantsWithAttributes = (form: VariantSyncForm) => {
+ const currentVariants = form.getValues("variants") ?? []
+ const nextVariants = generateVariantsFromAttributes(
+ form.getValues("attributes") ?? [],
+ currentVariants
+ )
+
+ const sameOptions =
+ JSON.stringify(nextVariants.map((v) => v.options)) ===
+ JSON.stringify(currentVariants.map((v) => v.options))
+
+ if (!sameOptions) {
+ form.setValue("variants", nextVariants)
+ }
+}
+
+// `useWatch({ name: "attributes" })` hands back the same array reference RHF
+// mutates in place, so a dependent effect only fires on the first change.
+// Subscribing by name fires for every nested update instead.
+export const subscribeVariantsToAttributes = (form: VariantSyncForm) => {
+ syncVariantsWithAttributes(form)
+
+ return form.subscribe({
+ name: "attributes",
+ formState: { values: true },
+ callback: () => syncVariantsWithAttributes(form),
+ })
+}