Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let extension fields join built-in forms' save cycle
Damian Legawiec5274ffbfe9e2
diff --git a/packages/dashboard-core/README.md b/packages/dashboard-core/README.mdindex 03bb8bf5bb..b2ff532926 100644--- a/packages/dashboard-core/README.md+++ b/packages/dashboard-core/README.md@@ -12,7 +12,7 @@ pnpm add @spree/dashboard-core @spree/dashboard-uiPeer dependencies that the consuming app provides: `react`, `react-dom`, `@spree/admin-sdk`, `@spree/dashboard-ui`, `@tanstack/react-query`, `@tanstack/react-router`, `@tanstack/react-hotkeys`, `react-hook-form`, `react-i18next`, `i18next`, `sonner`.-**Why peer deps:** the four registries (nav, slot, table, settings-nav) are module singletons. If your plugin bundles its own copy of `@spree/dashboard-core`, `registerSlot` writes to a different Map than the app's `<Slot>` reads — silent no-op. Same applies to React, the query client, the router instance, and the i18n singleton. pnpm dedupes these to a single instance as long as they're peers.+**Why peer deps:** the registries (nav, slot, table, settings-nav, form fields, custom field components) are module singletons. If your plugin bundles its own copy of `@spree/dashboard-core`, `registerSlot` writes to a different Map than the app's `<Slot>` reads — silent no-op. Same applies to React, the query client, the router instance, and the i18n singleton. pnpm dedupes these to a single instance as long as they're peers.## What's in the box@@ -294,7 +294,7 @@ i18n.addResourceBundle('fr', 'translation', fr, true, true)The framework currently ships English only; once Spree's locale list grows the same `addResourceBundle` pattern applies.-## Extension surface — the four registries+## Extension surface — the registries### `nav` — main sidebar items@@ -375,7 +375,7 @@ tables.products.updateColumn('total', { label: 'Net total' })## `defineDashboardPlugin` — one-call facade-All four registries in a single declarative config:+Every registry in a single declarative config:```tsimport { defineDashboardPlugin } from '@spree/dashboard-core/plugin'@@ -392,6 +392,14 @@ defineDashboardPlugin({update: { total: { label: 'Net total' } },},},+ // Extension fields on built-in forms — hydrate from the fetched resource,+ // persist through the form's own Save. Render the input from a slot widget+ // bound via useHostForm().+ formFields: {+ product: [{ name: 'tech_specs', from: (product) => product?.tech_specs ?? '' }],+ },+ // Replace the input widget for a specific custom field definition.+ customFieldComponents: { 'specs.color': ColorPicker },})```diff --git a/packages/dashboard-core/src/hooks/use-host-form.ts b/packages/dashboard-core/src/hooks/use-host-form.tsnew file mode 100644index 0000000000..12aba3a411--- /dev/null+++ b/packages/dashboard-core/src/hooks/use-host-form.ts@@ -0,0 +1,34 @@+import { type FieldValues, type UseFormReturn, useFormContext } from 'react-hook-form'++/**+ * The react-hook-form instance of the built-in resource form a slot widget is+ * rendered inside (e.g. the product detail form for `product.form_sidebar`).+ * Fields registered against it — `form.register(...)` or `<Controller>` —+ * hydrate, dirty-track, and persist through the host page's own Save button;+ * the widget ships no save logic of its own.+ *+ * Only forms that opt in provide a host form (they wrap themselves in RHF's+ * `FormProvider`). Slots on pages without a page-wide form (orders,+ * customers) have none — calling this there throws. Use+ * `useOptionalHostForm()` for widgets that render in both kinds of context.+ */+export function useHostForm<+ TFieldValues extends FieldValues = FieldValues,+>(): UseFormReturn<TFieldValues> {+ const form = useFormContext<TFieldValues>()+ if (!form) {+ throw new Error(+ 'useHostForm() must be rendered inside a resource form that exposes its form context ' ++ '(e.g. a product.form_sidebar slot widget). This page has no host form — ' ++ 'use useOptionalHostForm() and fall back to your own state + API save.',+ )+ }+ return form+}++/** Like {@link useHostForm}, but returns `null` when there is no host form. */+export function useOptionalHostForm<+ TFieldValues extends FieldValues = FieldValues,+>(): UseFormReturn<TFieldValues> | null {+ return useFormContext<TFieldValues>() ?? null+}diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex 1484715f38..103e81a034 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -54,24 +54,27 @@ export * from './hooks/use-direct-upload'export * from './hooks/use-display-name'export * from './hooks/use-export'export * from './hooks/use-global-search'+export * from './hooks/use-host-form'export * from './hooks/use-import'export * from './hooks/use-resource-mutation'export * from './hooks/use-switch-admin-locale'// ---------------------------------------------------------------------------+// Registries — pluggable extension points (nav, route, slot, table,+// settings-nav, form fields, custom field components)+// ---------------------------------------------------------------------------+export * from './lib/custom-field-components'+// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------export * from './lib/filters-to-ransack'export * from './lib/form-errors'+export * from './lib/form-fields-registry'export * from './lib/form-mappers'export * from './lib/formatters'// i18n side-effect import bootstraps i18next + React adapter on first import.// Consumers that need the singleton (e.g. plugin authors calling// `i18n.addResourceBundle`) get it via the named re-export.export * from './lib/i18n'-// ----------------------------------------------------------------------------// Registries — five pluggable extension points (nav, route, slot,-// table, settings-nav)-// ---------------------------------------------------------------------------export * from './lib/nav-registry'export * from './lib/permissions'export * from './lib/query-client'diff --git a/packages/dashboard-core/src/lib/custom-field-components.ts b/packages/dashboard-core/src/lib/custom-field-components.tsnew file mode 100644index 0000000000..260d5be361--- /dev/null+++ b/packages/dashboard-core/src/lib/custom-field-components.ts@@ -0,0 +1,56 @@+import type { CustomFieldDefinition } from '@spree/admin-sdk'+import type { ComponentType } from 'react'++/**+ * Props a custom field input component receives from the custom-fields card.+ * The component is a controlled input: render `value`, call `onChange` with+ * the next value — hydration and persistence are the card's concern (the+ * page form's Save for products/categories, the card's own Save elsewhere).+ */+export interface CustomFieldComponentProps {+ /** DOM id — wire it to your input for the card's `<label htmlFor>`. */+ id: string+ ariaLabel: string+ value: unknown+ onChange: (value: unknown) => void+ /** The full definition (field_type, config, namespace, key, …). */+ definition: CustomFieldDefinition+}++export type CustomFieldComponent = ComponentType<CustomFieldComponentProps>++const components = new Map<string, CustomFieldComponent>()++/**+ * Replace the input widget for a specific custom field definition, keyed by+ * its `namespace.key` identity (e.g. `'specs.color'`). When no component is+ * registered for a definition, the default widget for its `field_type`+ * renders — registering is purely additive.+ *+ * Keying by the definition's own identity (rather than a separate component+ * ID the definition would reference) means there's no stringly-typed+ * indirection to typo: the plugin that ships the definition registers the+ * component for it in the same breath.+ */+export const customFieldComponents = {+ register(namespaceDotKey: string, component: CustomFieldComponent): void {+ if (components.has(namespaceDotKey)) {+ throw new Error(`A custom field component is already registered for "${namespaceDotKey}".`)+ }+ components.set(namespaceDotKey, component)+ },++ get(namespaceDotKey: string): CustomFieldComponent | undefined {+ return components.get(namespaceDotKey)+ },++ /** Remove a registered component. No-op when absent. */+ remove(namespaceDotKey: string): void {+ components.delete(namespaceDotKey)+ },+}++/** Test-only: clear the registry. Not exported from the package index. */+export function __resetCustomFieldComponents(): void {+ components.clear()+}diff --git a/packages/dashboard-core/src/lib/form-fields-registry.ts b/packages/dashboard-core/src/lib/form-fields-registry.tsnew file mode 100644index 0000000000..de125a6947--- /dev/null+++ b/packages/dashboard-core/src/lib/form-fields-registry.ts@@ -0,0 +1,102 @@+// Extension form fields — let host-app code and plugins add fields to a+// built-in resource form (product, category, …) that hydrate from the fetched+// resource and persist through the form's own Save. The host form spreads its+// values into the update payload, so a registered field's value reaches the+// API without any save code on the extension side; the backend only needs to+// permit the attribute.+//+// The registry solves the hydration half: built-in forms reset their values+// from a mapper over the fetched resource (which knows nothing about+// extension fields), so each form merges `extensionFormValues(formKey,+// resource)` into every defaultValues/reset object. The rendering half is a+// slot widget binding an input via `useHostForm()`.++/** One extension field on a built-in resource form. */+export interface FormFieldRegistration<TResource = unknown> {+ /**+ * The form value key — also the API attribute name submitted on save+ * (read/write symmetry: whatever the serializer exposes is what the+ * controller permits).+ */+ name: string+ /**+ * Seed the field's form value from the fetched resource. Receives `null`+ * on create forms (no resource yet) — return the field's blank value.+ */+ from: (resource: TResource | null) => unknown+}++const registrations = new Map<string, FormFieldRegistration[]>()++/**+ * Registry of extension fields per built-in form. Form keys match the form's+ * slot prefix — `'product'` for the product detail form. Registered names+ * must be unique per form; duplicates throw so two plugins can't silently+ * fight over one attribute.+ */+export const formFields = {+ register<TResource = unknown>(+ formKey: string,+ registration: FormFieldRegistration<TResource>,+ ): void {+ const list = registrations.get(formKey) ?? []+ if (list.some((r) => r.name === registration.name)) {+ throw new Error(+ `Form field "${registration.name}" is already registered on the "${formKey}" form.`,+ )+ }+ registrations.set(formKey, [...list, registration as FormFieldRegistration])+ },++ /** Remove a registered field. No-op when absent. */+ remove(formKey: string, name: string): void {+ const list = registrations.get(formKey)+ if (!list) return+ registrations.set(+ formKey,+ list.filter((r) => r.name !== name),+ )+ },+}++/**+ * Values for every extension field registered on `formKey`, seeded from+ * `resource` (or blanks when `null`). Built-in forms merge this into their+ * defaultValues and every hydration `reset(...)` so extension fields survive+ * refetch-driven resets.+ */+export function extensionFormValues(+ formKey: string,+ resource: unknown | null,+): Record<string, unknown> {+ const out: Record<string, unknown> = {}+ for (const registration of registrations.get(formKey) ?? []) {+ out[registration.name] = registration.from(resource)+ }+ return out+}++/**+ * Current values of every extension field registered on `formKey`, read from+ * live form state. Host forms spread this into their submit payload: the+ * form's Zod schema only knows first-party fields (its parse strips unknown+ * keys from the submitted values), so extension values are collected from+ * `form.getValues(...)` instead — which also keeps them out of client-side+ * schema validation. Their validation is the server's; a 422 maps back onto+ * the field via `mapSpreeErrorsToForm`.+ */+export function extensionSubmitValues(+ formKey: string,+ form: { getValues: (name: string) => unknown },+): Record<string, unknown> {+ const out: Record<string, unknown> = {}+ for (const registration of registrations.get(formKey) ?? []) {+ out[registration.name] = form.getValues(registration.name)+ }+ return out+}++/** Test-only: clear the registry. Not exported from the package index. */+export function __resetFormFieldsRegistry(): void {+ registrations.clear()+}diff --git a/packages/dashboard-core/src/plugin.ts b/packages/dashboard-core/src/plugin.tsindex c3146922ca..12132ae65e 100644--- a/packages/dashboard-core/src/plugin.ts+++ b/packages/dashboard-core/src/plugin.ts@@ -31,6 +31,10 @@// ],// })+import type { CustomFieldComponent } from './lib/custom-field-components'+import { customFieldComponents } from './lib/custom-field-components'+import type { FormFieldRegistration } from './lib/form-fields-registry'+import { formFields } from './lib/form-fields-registry'import type { NavEntry } from './lib/nav-registry'import { nav } from './lib/nav-registry'import type { RouteEntry } from './lib/route-registry'@@ -108,6 +112,20 @@ export interface DashboardPluginConfig {* `useParams()` for path params.*/routes?: RouteEntry[]+ /**+ * Extension fields on built-in resource forms, keyed by form key (e.g.+ * `'product'`). Each field hydrates from the fetched resource via `from`+ * and persists through the form's own Save — render its input from a slot+ * widget bound via `useHostForm()`.+ */+ formFields?: Record<string, FormFieldRegistration[]>+ /**+ * Input components for specific custom field definitions, keyed by the+ * definition's `namespace.key` (e.g. `'specs.color'`). Replaces the+ * default widget for that definition's `field_type` wherever the+ * custom-fields card renders it.+ */+ customFieldComponents?: Record<string, CustomFieldComponent>}/**@@ -185,6 +203,18 @@ export function defineDashboardPlugin(config: DashboardPluginConfig): void {for (const entry of config.routes) safely(pluginRoutes.add, entry)}+ if (config.formFields) {+ for (const [formKey, fields] of Object.entries(config.formFields)) {+ for (const field of fields) safely(formFields.register, formKey, field)+ }+ }++ if (config.customFieldComponents) {+ for (const [key, component] of Object.entries(config.customFieldComponents)) {+ safely(customFieldComponents.register, key, component)+ }+ }+if (errors.length === 1) throw errors[0]if (errors.length > 1) {throw new AggregateError(errors, `${errors.length} registration(s) failed`)diff --git a/packages/dashboard-core/tests/custom-field-components.test.ts b/packages/dashboard-core/tests/custom-field-components.test.tsnew file mode 100644index 0000000000..df2fb73277--- /dev/null+++ b/packages/dashboard-core/tests/custom-field-components.test.ts@@ -0,0 +1,38 @@+import { beforeEach, describe, expect, it } from 'vitest'+import {+ __resetCustomFieldComponents,+ type CustomFieldComponent,+ customFieldComponents,+} from '../src/lib/custom-field-components'++const FakeComponent: CustomFieldComponent = () => null+const OtherComponent: CustomFieldComponent = () => null++describe('customFieldComponents registry', () => {+ beforeEach(() => {+ __resetCustomFieldComponents()+ })++ it('registers and resolves by namespace.key', () => {+ customFieldComponents.register('specs.color', FakeComponent)+ expect(customFieldComponents.get('specs.color')).toBe(FakeComponent)+ })++ it('returns undefined for unregistered definitions (default widget renders)', () => {+ expect(customFieldComponents.get('specs.unknown')).toBeUndefined()+ })++ it('throws on duplicate registration', () => {+ customFieldComponents.register('specs.color', FakeComponent)+ expect(() => customFieldComponents.register('specs.color', OtherComponent)).toThrow(+ /already registered/,+ )+ })++ it('remove() unregisters and is a no-op when absent', () => {+ customFieldComponents.register('specs.color', FakeComponent)+ customFieldComponents.remove('specs.color')+ expect(customFieldComponents.get('specs.color')).toBeUndefined()+ expect(() => customFieldComponents.remove('specs.color')).not.toThrow()+ })+})diff --git a/packages/dashboard-core/tests/form-fields-registry.test.ts b/packages/dashboard-core/tests/form-fields-registry.test.tsnew file mode 100644index 0000000000..54b0304c54--- /dev/null+++ b/packages/dashboard-core/tests/form-fields-registry.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it } from 'vitest'+import {+ __resetFormFieldsRegistry,+ extensionFormValues,+ extensionSubmitValues,+ formFields,+} from '../src/lib/form-fields-registry'++interface FakeProduct {+ tech_specs?: string+}++describe('formFields registry', () => {+ beforeEach(() => {+ __resetFormFieldsRegistry()+ })++ it('seeds registered fields from the resource', () => {+ formFields.register<FakeProduct>('product', {+ name: 'tech_specs',+ from: (p) => p?.tech_specs ?? '',+ })++ expect(extensionFormValues('product', { tech_specs: 'RAM: 16GB' })).toEqual({+ tech_specs: 'RAM: 16GB',+ })+ })++ it('passes null on create forms so fields seed their blank value', () => {+ formFields.register<FakeProduct>('product', {+ name: 'tech_specs',+ from: (p) => p?.tech_specs ?? '',+ })++ expect(extensionFormValues('product', null)).toEqual({ tech_specs: '' })+ })++ it('returns an empty object for forms with no registrations', () => {+ expect(extensionFormValues('category', { anything: true })).toEqual({})+ })++ it('scopes registrations per form key', () => {+ formFields.register('product', { name: 'a', from: () => 1 })+ formFields.register('category', { name: 'b', from: () => 2 })++ expect(extensionFormValues('product', {})).toEqual({ a: 1 })+ expect(extensionFormValues('category', {})).toEqual({ b: 2 })+ })++ it('throws on a duplicate name within one form', () => {+ formFields.register('product', { name: 'tech_specs', from: () => '' })+ expect(() => formFields.register('product', { name: 'tech_specs', from: () => '' })).toThrow(+ /already registered/,+ )+ })++ it('collects submit values from live form state', () => {+ formFields.register('product', { name: 'tech_specs', from: () => '' })+ formFields.register('product', { name: 'warranty_months', from: () => null })++ const fakeForm = {+ getValues: (name: string) => ({ tech_specs: 'RAM: 16GB', warranty_months: 24 })[name],+ }++ expect(extensionSubmitValues('product', fakeForm)).toEqual({+ tech_specs: 'RAM: 16GB',+ warranty_months: 24,+ })+ expect(extensionSubmitValues('category', fakeForm)).toEqual({})+ })++ it('remove() unregisters and is a no-op when absent', () => {+ formFields.register('product', { name: 'tech_specs', from: () => '' })+ formFields.remove('product', 'tech_specs')+ expect(extensionFormValues('product', {})).toEqual({})+ expect(() => formFields.remove('product', 'missing')).not.toThrow()+ })+})diff --git a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsxindex 50f516bb48..fd29a4a3e7 100644--- a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx+++ b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx@@ -24,6 +24,7 @@import { zodResolver } from '@hookform/resolvers/zod'import type { CustomField, CustomFieldDefinition, CustomFieldOwnerType } from '@spree/admin-sdk'import {+ customFieldComponents,mapSpreeErrorsToForm,useCreateCustomField,useCreateCustomFieldDefinition,@@ -743,7 +744,20 @@ function CustomFieldRow({ definition, value, onChange }: CustomFieldRowProps) {// label, not rendered as inline copy.const technicalKey = `${definition.namespace}.${definition.key}`- const widget = (+ // A plugin can replace the input for this specific definition+ // (customFieldComponents.register('specs.color', ColorPicker)); the default+ // field_type widget renders otherwise. Same controlled contract either way+ // — persistence stays with the card's provider.+ const CustomComponent = customFieldComponents.get(technicalKey)+ const widget = CustomComponent ? (+ <CustomComponent+ id={inputId}+ ariaLabel={friendlyLabel}+ value={value}+ onChange={onChange}+ definition={definition}+ />+ ) : (<CustomFieldWidgetid={inputId}ariaLabel={friendlyLabel}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex 6970d7dbfb..ed1a8cee2b 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -1,6 +1,13 @@import { zodResolver } from '@hookform/resolvers/zod'import { type Product, SpreeError, type Variant } from '@spree/admin-sdk'-import { adminClient, mapSpreeErrorsToForm, PageHeader, Slot } from '@spree/dashboard-core'+import {+ adminClient,+ extensionFormValues,+ extensionSubmitValues,+ mapSpreeErrorsToForm,+ PageHeader,+ Slot,+} from '@spree/dashboard-core'import {ErrorState,FormActions,@@ -14,7 +21,7 @@ import {import { createFileRoute, useRouter } from '@tanstack/react-router'import i18n from 'i18next'import { useEffect } from 'react'-import { useForm, useWatch } from 'react-hook-form'+import { FormProvider, useForm, useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import {@@ -250,7 +257,13 @@ function ProductForm({ product }: { product: Product }) {const form = useForm<ProductFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(productFormSchema) as any,- defaultValues: productToFormValues(product, mediaItems),+ // Extension form values ride along: fields registered via+ // `formFields.register('product', …)` hydrate from the fetched product+ // and flow into the PATCH payload through the loose schema.+ defaultValues: {+ ...productToFormValues(product, mediaItems),+ ...extensionFormValues('product', product),+ },})// Variants the MediaCard can assign uploaded images to. Only server-persisted@@ -276,7 +289,10 @@ function ProductForm({ product }: { product: Product }) {// already cleared isDirty, so the post-save refetch still re-hydrates.useEffect(() => {if (form.formState.isDirty) return- form.reset(productToFormValues(product, mediaItems))+ form.reset({+ ...productToFormValues(product, mediaItems),+ ...extensionFormValues('product', product),+ })}, [product, mediaItems, form])// Media-only hydration that bypasses the isDirty guard for the@@ -308,7 +324,10 @@ function ProductForm({ product }: { product: Product }) {const onSubmit = async (data: ProductFormValues) => {const { variants, media, ...rest } = data- const payload: Record<string, unknown> = { ...rest }+ // Extension fields come from live form state: the Zod parse behind+ // `data` strips keys the first-party schema doesn't know.+ const extensionValues = extensionSubmitValues('product', form)+ const payload: Record<string, unknown> = { ...rest, ...extensionValues }if (variants && variants.length > 0) {payload.variants = variants.map((v, i) => variantToWirePayload(v, i))@@ -339,6 +358,9 @@ function ProductForm({ product }: { product: Product }) {// ids will hydrate on the next refetch.const baseline: ProductFormValues = {...data,+ // `data` is the parsed (extension-stripped) shape — put extension+ // values back so the reset doesn't blank their inputs pre-refetch.+ ...extensionValues,media: (data.media ?? []).map(({ signed_id: _sid, previewUrl: _p, uploadId: _u, ...rest }) => rest,),@@ -375,61 +397,66 @@ function ProductForm({ product }: { product: Product }) {}return (- <form onSubmit={form.handleSubmit(onSubmit)}>- {form.formState.errors.root?.message && (- <p className="text-sm text-destructive" role="alert">- {form.formState.errors.root.message}- </p>- )}- <ResourceLayout- header={- <PageHeader- title={product.name}- backTo="products"- badges={<StatusBadge status={product.status} />}- actions={<FormActions form={form} saveLabel={t('admin.products.save_label')} />}- resource={{ id: product.id }}- onDelete={handleDelete}- deleteLabel={t('admin.products.delete_label')}- jsonPreview={{- title: `Product ${product.name}`,- fetch: () => adminClient.products.get(productId),- endpoint: `/api/v3/admin/products/${productId}`,- resolveLink: spreeJsonLinkResolver(storeId),- }}- />- }- main={- <>- <GeneralCard form={form} />- <VariantsCard form={form} />- <MediaCard productId={productId} variants={assignableVariants} form={form} />- <PricesCard form={form} productName={product.name} />- <InventoryCard form={form} storeId={storeId} />- <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Product">- <CustomFieldsInlineCard />- </FormBackedCustomFieldsProvider>- <ResourceTranslationsCard resourceType="product" resourceId={productId} />- <MetadataCard- metadata={product.metadata}- title={t('admin.components.metadata_card.title')}- emptyTitle={t('admin.components.metadata_card.empty_title')}- emptyDescription={t('admin.components.metadata_card.empty_description')}+ // FormProvider exposes the form to slot widgets: a `product.form_sidebar`+ // extension binds inputs via `useHostForm()` and they persist through+ // this form's Save — no widget-owned save cycle.+ <FormProvider {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ {form.formState.errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {form.formState.errors.root.message}+ </p>+ )}+ <ResourceLayout+ header={+ <PageHeader+ title={product.name}+ backTo="products"+ badges={<StatusBadge status={product.status} />}+ actions={<FormActions form={form} saveLabel={t('admin.products.save_label')} />}+ resource={{ id: product.id }}+ onDelete={handleDelete}+ deleteLabel={t('admin.products.delete_label')}+ jsonPreview={{+ title: `Product ${product.name}`,+ fetch: () => adminClient.products.get(productId),+ endpoint: `/api/v3/admin/products/${productId}`,+ resolveLink: spreeJsonLinkResolver(storeId),+ }}/>- </>- }- sidebar={- <>- <StatusCard form={form} />- <PublishingCard form={form} />- <CategorizationCard form={form} />- <TaxCard form={form} />- <SEOCard form={form} product={product} />- <Slot name="product.form_sidebar" context={{ product }} />- </>- }- />- </form>+ }+ main={+ <>+ <GeneralCard form={form} />+ <VariantsCard form={form} />+ <MediaCard productId={productId} variants={assignableVariants} form={form} />+ <PricesCard form={form} productName={product.name} />+ <InventoryCard form={form} storeId={storeId} />+ <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Product">+ <CustomFieldsInlineCard />+ </FormBackedCustomFieldsProvider>+ <ResourceTranslationsCard resourceType="product" resourceId={productId} />+ <MetadataCard+ metadata={product.metadata}+ title={t('admin.components.metadata_card.title')}+ emptyTitle={t('admin.components.metadata_card.empty_title')}+ emptyDescription={t('admin.components.metadata_card.empty_description')}+ />+ </>+ }+ sidebar={+ <>+ <StatusCard form={form} />+ <PublishingCard form={form} />+ <CategorizationCard form={form} />+ <TaxCard form={form} />+ <SEOCard form={form} product={product} />+ <Slot name="product.form_sidebar" context={{ product }} />+ </>+ }+ />+ </form>+ </FormProvider>)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsxindex 09f133ce77..f004431233 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx@@ -1,6 +1,13 @@import { zodResolver } from '@hookform/resolvers/zod'import { SpreeError } from '@spree/admin-sdk'-import { adminClient, mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'+import {+ adminClient,+ extensionFormValues,+ extensionSubmitValues,+ mapSpreeErrorsToForm,+ PageHeader,+ Slot,+} from '@spree/dashboard-core'import {ErrorState,FormActions,@@ -11,7 +18,7 @@ import {} from '@spree/dashboard-ui'import { createFileRoute, useRouter } from '@tanstack/react-router'import { useEffect } from 'react'-import { useForm } from 'react-hook-form'+import { FormProvider, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import {@@ -64,24 +71,28 @@ function CategoryDetail({ categoryId, storeId }: { categoryId: string; storeId:const form = useForm<CategoryFormValues>({resolver: zodResolver(categoryFormSchema),- defaultValues: CATEGORY_DEFAULTS,+ defaultValues: { ...CATEGORY_DEFAULTS, ...extensionFormValues('category', null) },})// Hydrate (and re-baseline after save) from the source row, unless the// merchant has unsaved edits in flight.useEffect(() => {if (!category || form.formState.isDirty) return- form.reset(categoryToForm(category))+ form.reset({ ...categoryToForm(category), ...extensionFormValues('category', category) })}, [category, form])const onSubmit = async (values: CategoryFormValues) => {+ // Read before any reset — extension values live in raw form state (the+ // Zod parse behind `values` strips keys the schema doesn't know).+ const extensionValues = extensionSubmitValues('category', form)try {- await updateCategory.mutateAsync(categoryToParams(values))+ await updateCategory.mutateAsync({ ...categoryToParams(values), ...extensionValues })// Re-baseline so isDirty flips false before the refetch lands; drop the// consumed signed_ids + clear flags so a second save can't re-send a// stale upload/purge (the refetch hydrates the persisted image state).form.reset({...values,+ ...extensionValues,image_signed_id: null,image_cleared: false,square_image_signed_id: null,@@ -112,32 +123,39 @@ function CategoryDetail({ categoryId, storeId }: { categoryId: string; storeId:}return (- <form onSubmit={form.handleSubmit(onSubmit)}>- {form.formState.errors.root?.message && (- <p className="text-sm text-destructive" role="alert">- {form.formState.errors.root.message}- </p>- )}- <ResourceLayout- header={- <PageHeader- title={category?.name ?? ''}- backTo="products/categories"- actions={<FormActions form={form} saveLabel={t('admin.actions.save')} />}- resource={category ? { id: category.id } : undefined}- onDelete={handleDelete}- deleteLabel={t('admin.categories.delete_label')}- jsonPreview={{- title: `Category ${category?.name ?? ''}`,- fetch: () => adminClient.categories.get(categoryId),- endpoint: `/api/v3/admin/categories/${categoryId}`,- }}- />- }- main={<CategoryMain form={form} category={category} />}- sidebar={<CategorySidebar form={form} category={category} />}- />- </form>+ <FormProvider {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ {form.formState.errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {form.formState.errors.root.message}+ </p>+ )}+ <ResourceLayout+ header={+ <PageHeader+ title={category?.name ?? ''}+ backTo="products/categories"+ actions={<FormActions form={form} saveLabel={t('admin.actions.save')} />}+ resource={category ? { id: category.id } : undefined}+ onDelete={handleDelete}+ deleteLabel={t('admin.categories.delete_label')}+ jsonPreview={{+ title: `Category ${category?.name ?? ''}`,+ fetch: () => adminClient.categories.get(categoryId),+ endpoint: `/api/v3/admin/categories/${categoryId}`,+ }}+ />+ }+ main={<CategoryMain form={form} category={category} />}+ sidebar={+ <>+ <CategorySidebar form={form} category={category} />+ <Slot name="category.form_sidebar" context={{ category }} />+ </>+ }+ />+ </form>+ </FormProvider>)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsxindex 1f5d014f22..ad62304de2 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsx@@ -1,9 +1,14 @@import { zodResolver } from '@hookform/resolvers/zod'import { SpreeError } from '@spree/admin-sdk'-import { mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'+import {+ extensionFormValues,+ extensionSubmitValues,+ mapSpreeErrorsToForm,+ PageHeader,+} from '@spree/dashboard-core'import { FormActions, ResourceLayout, useFormSubmitShortcut } from '@spree/dashboard-ui'import { createFileRoute, useNavigate } from '@tanstack/react-router'-import { useForm } from 'react-hook-form'+import { FormProvider, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import {@@ -30,12 +35,18 @@ function NewCategoryPage() {const form = useForm<CategoryFormValues>({resolver: zodResolver(categoryFormSchema),- defaultValues: CATEGORY_DEFAULTS,+ // Extension fields seed their blank value (`from(null)`) on create.+ defaultValues: { ...CATEGORY_DEFAULTS, ...extensionFormValues('category', null) },})const onSubmit = async (values: CategoryFormValues) => {try {- const created = await createCategory.mutateAsync(categoryToParams(values))+ const created = await createCategory.mutateAsync({+ ...categoryToParams(values),+ // Extension fields come from live form state — the Zod parse behind+ // `values` strips keys the first-party schema doesn't know.+ ...extensionSubmitValues('category', form),+ })form.reset(values)// Land on the edit page so images + products can be managed next.await navigate({@@ -52,23 +63,25 @@ function NewCategoryPage() {useFormSubmitShortcut(form, onSubmit)return (- <form onSubmit={form.handleSubmit(onSubmit)}>- {form.formState.errors.root?.message && (- <p className="text-sm text-destructive" role="alert">- {form.formState.errors.root.message}- </p>- )}- <ResourceLayout- header={- <PageHeader- title={t('admin.categories.new_title')}- backTo="products/categories"- actions={<FormActions form={form} saveLabel={t('admin.actions.save')} />}- />- }- main={<CategoryMain form={form} />}- sidebar={<CategorySidebar form={form} />}- />- </form>+ <FormProvider {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ {form.formState.errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {form.formState.errors.root.message}+ </p>+ )}+ <ResourceLayout+ header={+ <PageHeader+ title={t('admin.categories.new_title')}+ backTo="products/categories"+ actions={<FormActions form={form} saveLabel={t('admin.actions.save')} />}+ />+ }+ main={<CategoryMain form={form} />}+ sidebar={<CategorySidebar form={form} />}+ />+ </form>+ </FormProvider>)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex 1e1f10c84b..187d00f3b9 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -1,9 +1,14 @@import { zodResolver } from '@hookform/resolvers/zod'import { type ProductCreateParams, SpreeError } from '@spree/admin-sdk'-import { mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'+import {+ extensionFormValues,+ extensionSubmitValues,+ mapSpreeErrorsToForm,+ PageHeader,+} from '@spree/dashboard-core'import { FormActions, ResourceLayout, useFormSubmitShortcut } from '@spree/dashboard-ui'import { createFileRoute, useNavigate } from '@tanstack/react-router'-import { useForm } from 'react-hook-form'+import { FormProvider, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import {@@ -44,7 +49,8 @@ function NewProductPage() {const form = useForm<ProductFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(productFormSchema) as any,- defaultValues: newProductFormDefaults(),+ // Extension fields seed their blank value (`from(null)`) on create.+ defaultValues: { ...newProductFormDefaults(), ...extensionFormValues('product', null) },})const onSubmit = async (data: ProductFormValues) => {@@ -58,6 +64,9 @@ function NewProductPage() {const payload: ProductCreateParams = {...(rest as ProductCreateParams),+ // Extension fields come from live form state — the Zod parse behind+ // `data` strips keys the first-party schema doesn't know.+ ...extensionSubmitValues('product', form),}// Only ship custom_fields when there are some — empty arrays are noise// and Spree::Metafields#custom_fields= already no-ops on empty input.@@ -148,50 +157,52 @@ function NewProductPage() {useFormSubmitShortcut(form, onSubmit)return (- <form onSubmit={form.handleSubmit(onSubmit)}>- {form.formState.errors.root?.message && (- <p className="text-sm text-destructive" role="alert">- {form.formState.errors.root.message}- </p>- )}- <ResourceLayout- header={- <PageHeader- title={t('admin.pages.products.new.title')}- subtitle={t('admin.pages.products.new.description')}- backTo="products"- actions={- <FormActions form={form} saveLabel={t('admin.pages.products.new.save_label')} />- }- />- }- main={- <>- <GeneralCard form={form} />- <VariantsCard form={form} />- {/* Form-backed media uploader — files are uploaded to ActiveStorage- pre-save and their signed_ids ride the product POST. */}- <MediaCard form={form} />- <PricesCard- form={form}- productName={form.watch('name') || t('admin.pages.products.new.title')}+ <FormProvider {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ {form.formState.errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {form.formState.errors.root.message}+ </p>+ )}+ <ResourceLayout+ header={+ <PageHeader+ title={t('admin.pages.products.new.title')}+ subtitle={t('admin.pages.products.new.description')}+ backTo="products"+ actions={+ <FormActions form={form} saveLabel={t('admin.pages.products.new.save_label')} />+ }/>- <InventoryCard form={form} storeId={storeId} />- <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Product">- <CustomFieldsInlineCard />- </FormBackedCustomFieldsProvider>- </>- }- sidebar={- <>- <StatusCard form={form} />- <PublishingCard form={form} seedDefaultChannel />- <CategorizationCard form={form} />- <TaxCard form={form} />- <SEOCard form={form} />- </>- }- />- </form>+ }+ main={+ <>+ <GeneralCard form={form} />+ <VariantsCard form={form} />+ {/* Form-backed media uploader — files are uploaded to ActiveStorage+ pre-save and their signed_ids ride the product POST. */}+ <MediaCard form={form} />+ <PricesCard+ form={form}+ productName={form.watch('name') || t('admin.pages.products.new.title')}+ />+ <InventoryCard form={form} storeId={storeId} />+ <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Product">+ <CustomFieldsInlineCard />+ </FormBackedCustomFieldsProvider>+ </>+ }+ sidebar={+ <>+ <StatusCard form={form} />+ <PublishingCard form={form} seedDefaultChannel />+ <CategorizationCard form={form} />+ <TaxCard form={form} />+ <SEOCard form={form} />+ </>+ }+ />+ </form>+ </FormProvider>)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsxindex 52d590b5f4..d3f681779f 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx@@ -1,9 +1,12 @@import { zodResolver } from '@hookform/resolvers/zod'import { SpreeError, type Store } from '@spree/admin-sdk'import {+ extensionFormValues,+ extensionSubmitValues,mapSpreeErrorsToForm,PageHeader,reconcileStoreDefaultLocale,+ Slot,useAuth,useStore,useSwitchAdminLocale,@@ -37,6 +40,7 @@ import {Controller,type FieldPath,type FieldValues,+ FormProvider,useForm,} from 'react-hook-form'import { useTranslation } from 'react-i18next'@@ -128,7 +132,7 @@ function StoreSettingsForm({ store }: { store: Store }) {const form = useForm<StoreSettingsFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(storeSettingsFormSchema) as any,- defaultValues: storeToFormValues(store),+ defaultValues: { ...storeToFormValues(store), ...extensionFormValues('store', store) },})// When unit_system flips, reset weight_unit to the first valid option for@@ -149,6 +153,9 @@ function StoreSettingsForm({ store }: { store: Store }) {// (name, timezone, units) must not touch the admin's UI language.const code = values.preferred_admin_localeconst localeChanged = (code ?? '') !== (store.preferred_admin_locale ?? '')+ // Extension fields come from live form state — the Zod parse behind+ // `values` strips keys the first-party schema doesn't know.+ const extensionValues = extensionSubmitValues('store', form)try {await updateMutation.mutateAsync({name: values.name,@@ -158,12 +165,13 @@ function StoreSettingsForm({ store }: { store: Store }) {preferred_weight_unit: values.preferred_weight_unit,preferred_storefront_access: values.preferred_storefront_access,preferred_guest_checkout: values.preferred_guest_checkout,+ ...extensionValues,})toast.success(t('admin.messages.store_settings_updated'))// Reset FIRST so the form is no longer dirty — otherwise the language// switch below reloads the page while the `beforeunload` dirty-guard is// still armed, triggering the browser's "unsaved changes" prompt.- form.reset(values)+ form.reset({ ...values, ...extensionValues })// When the admin language was actually changed:// - a concrete value → adopt it as this admin's own UI language and switch// the dashboard into it immediately (same as the profile / top-bar);@@ -230,127 +238,130 @@ function StoreSettingsForm({ store }: { store: Store }) {const { errors } = form.formStatereturn (- <form onSubmit={form.handleSubmit(onSubmit)}>- <ResourceLayout- header={- <PageHeader- title={t('admin.pages.settings.store.title')}- subtitle={t('admin.pages.settings.store.subtitle')}- actions={<FormActions form={form} />}- />- }- main={- <>- {errors.root?.message && (- <p className="text-sm text-destructive" role="alert">- {errors.root.message}- </p>- )}- <Card>- <CardHeader>- <CardTitle>{t('admin.pages.settings.store.tab_general')}</CardTitle>- </CardHeader>- <CardContent>- <FieldGroup>- <Field>- <FieldLabel htmlFor="store-name">- {t('admin.fields.store.name.label')}- </FieldLabel>- <Input- id="store-name"- aria-invalid={!!errors.name || undefined}- {...form.register('name')}- />- <FieldError errors={[errors.name]} />- </Field>- </FieldGroup>- </CardContent>- </Card>+ <FormProvider {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <ResourceLayout+ header={+ <PageHeader+ title={t('admin.pages.settings.store.title')}+ subtitle={t('admin.pages.settings.store.subtitle')}+ actions={<FormActions form={form} />}+ />+ }+ main={+ <>+ {errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {errors.root.message}+ </p>+ )}+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_general')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="store-name">+ {t('admin.fields.store.name.label')}+ </FieldLabel>+ <Input+ id="store-name"+ aria-invalid={!!errors.name || undefined}+ {...form.register('name')}+ />+ <FieldError errors={[errors.name]} />+ </Field>+ </FieldGroup>+ </CardContent>+ </Card>- <Card>- <CardHeader>- <CardTitle>{t('admin.pages.settings.store.tab_standards')}</CardTitle>- </CardHeader>- <CardContent>- <FieldGroup>- <SelectField- id="store-admin-locale"- label={t('admin.fields.store.preferred_admin_locale.label')}- placeholder={t('admin.fields.store.preferred_admin_locale.placeholder')}- name="preferred_admin_locale"- control={form.control}- options={adminLocaleOptions}- />- <SelectField- id="store-timezone"- label={t('admin.fields.store.preferred_timezone.label')}- placeholder={t('admin.fields.store.preferred_timezone.placeholder')}- name="preferred_timezone"- control={form.control}- options={timezoneOptions}- />- <SelectField- id="store-unit-system"- label={t('admin.fields.store.preferred_unit_system.label')}- name="preferred_unit_system"- control={form.control}- options={unitSystemOptions}- />- <SelectField- id="store-weight-unit"- label={t('admin.fields.store.preferred_weight_unit.label')}- name="preferred_weight_unit"- control={form.control}- options={weightOptions}- />- </FieldGroup>- </CardContent>- </Card>+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_standards')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SelectField+ id="store-admin-locale"+ label={t('admin.fields.store.preferred_admin_locale.label')}+ placeholder={t('admin.fields.store.preferred_admin_locale.placeholder')}+ name="preferred_admin_locale"+ control={form.control}+ options={adminLocaleOptions}+ />+ <SelectField+ id="store-timezone"+ label={t('admin.fields.store.preferred_timezone.label')}+ placeholder={t('admin.fields.store.preferred_timezone.placeholder')}+ name="preferred_timezone"+ control={form.control}+ options={timezoneOptions}+ />+ <SelectField+ id="store-unit-system"+ label={t('admin.fields.store.preferred_unit_system.label')}+ name="preferred_unit_system"+ control={form.control}+ options={unitSystemOptions}+ />+ <SelectField+ id="store-weight-unit"+ label={t('admin.fields.store.preferred_weight_unit.label')}+ name="preferred_weight_unit"+ control={form.control}+ options={weightOptions}+ />+ </FieldGroup>+ </CardContent>+ </Card>- <Card>- <CardHeader>- <CardTitle>{t('admin.pages.settings.store.tab_storefront_access')}</CardTitle>- </CardHeader>- <CardContent>- <FieldGroup>- <SelectField- id="store-storefront-access"- label={t('admin.fields.store.storefront_access.label')}- name="preferred_storefront_access"- control={form.control}- options={storefrontAccessOptions}- help={t('admin.fields.store.storefront_access.help')}- />- <Field>- <div className="flex items-start justify-between gap-4">- <div className="flex flex-col">- <FieldLabel htmlFor="store-guest-checkout" className="cursor-pointer">- {t('admin.fields.store.guest_checkout.label')}- </FieldLabel>- <span className="text-xs text-muted-foreground">- {t('admin.fields.store.guest_checkout.help')}- </span>+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_storefront_access')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SelectField+ id="store-storefront-access"+ label={t('admin.fields.store.storefront_access.label')}+ name="preferred_storefront_access"+ control={form.control}+ options={storefrontAccessOptions}+ help={t('admin.fields.store.storefront_access.help')}+ />+ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel htmlFor="store-guest-checkout" className="cursor-pointer">+ {t('admin.fields.store.guest_checkout.label')}+ </FieldLabel>+ <span className="text-xs text-muted-foreground">+ {t('admin.fields.store.guest_checkout.help')}+ </span>+ </div>+ <Controller+ name="preferred_guest_checkout"+ control={form.control}+ render={({ field }) => (+ <Switch+ id="store-guest-checkout"+ checked={!!field.value}+ onCheckedChange={field.onChange}+ />+ )}+ /></div>- <Controller- name="preferred_guest_checkout"- control={form.control}- render={({ field }) => (- <Switch- id="store-guest-checkout"- checked={!!field.value}- onCheckedChange={field.onChange}- />- )}- />- </div>- </Field>- </FieldGroup>- </CardContent>- </Card>- </>- }- />- </form>+ </Field>+ </FieldGroup>+ </CardContent>+ </Card>+ <Slot name="store.form_main" context={{ store }} />+ </>+ }+ />+ </form>+ </FormProvider>)}