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
Added extension slots to the dashboard's forms and sheets (#14940)
Damian Legawiec44b1933854a8
diff --git a/.changeset/detail-page-main-slots.md b/.changeset/detail-page-main-slots.mdnew file mode 100644index 0000000000..a24f7435a5--- /dev/null+++ b/.changeset/detail-page-main-slots.md@@ -0,0 +1,5 @@+---+"@spree/dashboard": minor+---++Added main-column slots to the order, customer, category, collection, purchase order and stock transfer pages (`<resource>.form_main`), and `delivery_profile.form_main` and `delivery_profile.form_sidebar` to the delivery profile page. The category and collection slots also render on the new category and new collection pages, and receive `mode`.diff --git a/.changeset/media-library-slots.md b/.changeset/media-library-slots.mdnew file mode 100644index 0000000000..c449179356--- /dev/null+++ b/.changeset/media-library-slots.md@@ -0,0 +1,5 @@+---+"@spree/dashboard": minor+---++Added media library slots for plugins: `media.form_fields` in a file's detail sheet, saved with its Save button, and `media.context_menu` in the grid's right-click menu. Enter in any field of the sheet now saves it.diff --git a/.changeset/product-form-slots.md b/.changeset/product-form-slots.mdnew file mode 100644index 0000000000..0c87990d82--- /dev/null+++ b/.changeset/product-form-slots.md@@ -0,0 +1,7 @@+---+"@spree/dashboard": minor+"@spree/dashboard-core": minor+"@spree/seller-dashboard": minor+---++Added product page slots for plugins: `product.form_main` at the end of the main column, `product.media.form_fields` in the media editor, `product.media.actions` in the Media card, and `product.variant.form_fields` in the variant editor, with `seller.product.*` counterparts in the seller panel. `product.form_sidebar` now also renders on the new product page, and both column slots receive `mode`. Fields on a media or variant row register under the `product.media` and `product.variant` form keys and save with the product.diff --git a/.changeset/sheet-form-slots.md b/.changeset/sheet-form-slots.mdnew file mode 100644index 0000000000..c75f2ba2ec--- /dev/null+++ b/.changeset/sheet-form-slots.md@@ -0,0 +1,7 @@+---+"@spree/dashboard": minor+"@spree/dashboard-core": minor+"@spree/seller-dashboard": minor+---++Added `<resource>.form_fields` slots to the create and edit sheets for markets, stock locations, tax rates, tax categories, sales channels, policies, package types, product types, delivery zones, delivery methods, option types and customer groups. Fields a widget binds there save with the sheet. The seller panel's stock location and package type sheets use `seller.stock_location.form_fields` and `seller.package_type.form_fields`. `HostFormSlot` renders a slot that exposes a form which isn't wrapped in `FormProvider`.diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.ymlindex e2269b1a81..34d2ddaa4e 100644--- a/.github/workflows/packages.yml+++ b/.github/workflows/packages.yml@@ -298,7 +298,12 @@ jobs:# invitation happens there rather than in the dashboard. Its starter's# vite config imports `@spree/seller-dashboard/vite`, which resolves to# that package's `dist/`, so it must be built even to load the config.+ #+ # VITE_E2E_SLOT_PROBES builds in the slot probes the E2E specs assert+ # against (packages/dashboard/src/testing/slot-probes.tsx).- name: Build dashboard packages+ env:+ VITE_E2E_SLOT_PROBES: "1"run: pnpm turbo build --filter=@spree/dashboard --filter=@spree/seller-dashboard-starter --cache-dir=.turbo- name: Setup dummy Rails appdiff --git a/docs/developer/customization/api.mdx b/docs/developer/customization/api.mdxindex a65b520996..a399e4cdf6 100644--- a/docs/developer/customization/api.mdx+++ b/docs/developer/customization/api.mdx@@ -297,6 +297,15 @@ Spree::Product.additional_permitted_attributes += [:brand_id]Standard resource endpoints append these to their own allowlist, so onedeclaration covers the model's create and update endpoints.+A product write also carries its media and variants as nested lists, and those+lists take what `Spree::Media` and `Spree::Variant` declare. One line makes a+media column writable both through the media endpoints and as part of a product+save:++```ruby config/initializers/spree.rb+Spree::Media.additional_permitted_attributes += [:photo_credit]+```+Use `+=`, never `=` — assigning replaces what another extension added — anddeclare only attributes of your own, since redeclaring a key the controlleralready permits replaces its filter rather than widening it.@@ -318,6 +327,9 @@ seller panel's product page, declare it again on the seller list:Spree::Product.additional_seller_permitted_attributes += [:brand_id]```+The seller product endpoint's nested media and variant lists read the same+seller lists on `Spree::Media` and `Spree::Variant`.+Only declare attributes a seller may safely set on their own records.Two endpoints deliberately ignore this hook because their parameters arediff --git a/docs/developer/dashboard/recipes/custom-form-field.mdx b/docs/developer/dashboard/recipes/custom-form-field.mdxindex 4c2e08e04a..792be7f92a 100644--- a/docs/developer/dashboard/recipes/custom-form-field.mdx+++ b/docs/developer/dashboard/recipes/custom-form-field.mdx@@ -151,13 +151,55 @@ defineDashboardPlugin({Done. The field hydrates when the page loads, participates in the form's dirty state (Save enables when it changes), ships in the same PATCH as every core field, and re-baselines after save.+### A field on a media or variant row++The product page's media and variant editors are sheets over one row of the product form — the row the merchant opened. They render their own slots (`product.media.form_fields`, `product.variant.form_fields`), and a field there saves with the product just like one in the sidebar. Two things differ:++- Register the field under the row's form key, `product.media` or `product.variant`. `from` receives the media or variant record.+- Bind the input under the row's path. The slot passes it as `fieldPrefix` (`media.2`, `variants.0`).++```tsx+// src/slots/photo-credit-field.tsx+import { Field, FieldLabel, Input, useHostForm } from '@spree/dashboard'+import { useTranslation } from 'react-i18next'++export function PhotoCreditField({ fieldPrefix }: { fieldPrefix: string }) {+ const { t } = useTranslation()+ const form = useHostForm()+ const id = `${fieldPrefix}-photo-credit`++ return (+ <Field>+ <FieldLabel htmlFor={id}>{t('admin.fields.media.photo_credit.label')}</FieldLabel>+ <Input id={id} {...form.register(`${fieldPrefix}.photo_credit`)} />+ </Field>+ )+}+```++```tsx+// src/plugins.ts+defineDashboardPlugin({+ formFields: {+ 'product.media': [{ name: 'photo_credit', from: (media) => media?.photo_credit ?? '' }],+ },+ slots: {+ 'product.media.form_fields': [{ id: 'photo-credit', component: PhotoCreditField as never }],+ },+})+```++On the backend, declare the column on the row's own model — `Spree::Media` or `Spree::Variant` — and the product endpoint accepts it in its nested list (see [Adding an Attribute to a Core Resource](/developer/customization/api#adding-an-attribute-to-a-core-resource)). A row added after the page loaded, such as a fresh upload, starts without the field, so treat an empty value as blank. Cancel in the sheet restores the field along with the built-in ones.++In the seller panel the same slots and form keys start with `seller.` — `seller.product.media.form_fields` and the `seller.product.media` form key.+### ValidationExtension fields are validated by the **server** — a Rails validation failing returns a 422, and the host form's error mapping puts the message inline on your field (that's the `errors.tech_specs` read in the component). This mirrors how Vendure and Saleor treat extension-field validation: the backend is authoritative; the client renders what it says.### Which forms support this-`useHostForm()` works wherever a built-in form exposes its form context — currently the **product** (edit + new), **category** (edit + new), **collection**, **catalog**, **price list** (edit + new), **promotion** (edit + new), and **store settings** forms, with matching slots (`product.form_sidebar`, `category.form_sidebar`, `collection.form_sidebar`, `catalog.form_sidebar`, `price_list.form_sidebar`, `promotion.form_sidebar`, `store.form_main`) and form keys (`product`, `category`, `collection`, `catalog`, `price_list`, `promotion`, `store`). The [slots catalog](/developer/dashboard/slots-catalog#detail-page-slots) marks which pages have a host form. Orders and customers have no page-wide form — their sheets own their edits — so slot widgets there manage their own persistence; use `useOptionalHostForm()` to write a widget that adapts to both contexts.+`useHostForm()` works wherever a built-in form exposes its form context — currently the **product** (edit + new), **category** (edit + new), **collection** (edit + new), **catalog**, **price list** (edit + new), **promotion** (edit + new), and **store settings** forms, with matching slots (`product.form_sidebar`, `product.form_main`, `product.media.form_fields`, `product.variant.form_fields`, `category.form_main`, `category.form_sidebar`, `collection.form_main`, `collection.form_sidebar`, `catalog.form_sidebar`, `price_list.form_sidebar`, `promotion.form_sidebar`, `store.form_main`) and form keys (`product`, `category`, `collection`, `catalog`, `price_list`, `promotion`, `store`). The settings create and edit sheets are host forms too, each with a `<resource>.form_fields` slot and the matching form key (`market`, `tax_rate`, `stock_location`, …) — see [Sheet slots](/developer/dashboard/slots-catalog#sheet-slots). The [slots catalog](/developer/dashboard/slots-catalog#detail-page-slots) marks which pages have a host form. Orders and customers have no page-wide form — their sheets own their edits — so slot widgets there manage their own persistence; use `useOptionalHostForm()` to write a widget that adapts to both contexts.## Which path should I pick?diff --git a/docs/developer/dashboard/slots-catalog.mdx b/docs/developer/dashboard/slots-catalog.mdxindex 7796dd34cf..bfada25196 100644--- a/docs/developer/dashboard/slots-catalog.mdx+++ b/docs/developer/dashboard/slots-catalog.mdx@@ -14,20 +14,23 @@ If you need a new injection point in a built-in page, open a PR adding `<Slot na|---|---|---|| Every page | Page header | `page.actions`, `page.actions_dropdown` || Every page | Tabbed sub-navigation | `page.tabs` |-| Products | Product | `product.form_sidebar` |-| Products | Category | `category.form_sidebar` |-| Products | Collection | `collection.form_sidebar` |+| Products | Product | `product.form_main`, `product.form_sidebar`, `product.media.*`, `product.variant.form_fields` |+| Products | Media library | `media.form_fields`, `media.context_menu` |+| Products | Category | `category.form_main`, `category.form_sidebar` |+| Products | Collection | `collection.form_main`, `collection.form_sidebar` || Products | Catalog | `catalog.form_sidebar` || Products | Price list | `price_list.form_sidebar`, `price_list.rule_form.<type>` |-| Orders | Order | `order.form_sidebar` |-| Customers | Customer | `customer.form_sidebar` |+| Orders | Order | `order.form_main`, `order.form_sidebar` |+| Customers | Customer | `customer.form_main`, `customer.form_sidebar` || Customers | Company | `company.form_main`, `company.form_sidebar`, `company_membership.*` || Promotions | Promotion | `promotion.form_sidebar`, `promotion.rule_form.<type>`, `promotion.action_form.<type>` |-| Inventory | Purchase order | `purchase_order.form_sidebar` |-| Inventory | Stock transfer | `stock_transfer.form_sidebar` |+| Inventory | Purchase order | `purchase_order.form_main`, `purchase_order.form_sidebar` |+| Inventory | Stock transfer | `stock_transfer.form_main`, `stock_transfer.form_sidebar` || Sellers | Seller | `seller.form_main`, `seller.form_sidebar` || Sellers | Seller payout | `seller_payout.form_main`, `seller_payout.form_sidebar` || Settings | Store | `store.form_main` |+| Settings | Delivery profile | `delivery_profile.form_main`, `delivery_profile.form_sidebar` |+| Settings, options, customer groups | Create and edit sheets | `<resource>.form_fields` — see [Sheet slots](#sheet-slots) || Settings | Payment method | `payment_method.*.<provider>` || Settings | Webhook endpoint | `webhook_endpoint.form_sidebar` || Onboarding | Getting started | `getting-started.task.<name>` |@@ -96,28 +99,91 @@ On host-form pages your widget renders inside the page's `<form>` element, so a### Products+#### `product.form_main`++| Where | Product create and edit pages (`products/new`, `products/$productId`), end of the main column |+|---|---|+| Use | Wide cards that belong with the product's content — size charts, bundle contents, a feed preview |+| Context | `{ product, mode }` — `mode` is `'new'` or `'edit'`; `product` is `undefined` while creating |+| Host form | **Yes** — form key `product` |+#### `product.form_sidebar`-| Where | Product detail page (`products/$productId`), end of the sidebar column |+| Where | Product create and edit pages (`products/new`, `products/$productId`), end of the sidebar column ||---|---|| Use | Add a card scoped to the product being edited (e.g., a "Brand" picker, wishlist stats, sync status from an external system) |-| Context | `{ product }` — the full `Product` record from the Admin API |+| Context | `{ product, mode }` — the full `Product` record from the Admin API; `mode` is `'new'` or `'edit'`, and `product` is `undefined` while creating |+| Host form | **Yes** — form key `product` |++#### `product.media.form_fields`++| Where | The media editor sheet on the product create and edit pages, below the built-in fields |+|---|---|+| Use | Fields stored on one media file — a photo credit, a license, a usage restriction |+| Context | `{ productId, media, mediaIndex, fieldPrefix }` — `media` is the row's form values, `fieldPrefix` the row's path (`media.2`); `productId` is `undefined` while creating |+| Host form | **Yes** — form key `product.media`. Bind inputs under `fieldPrefix` and register fields under `product.media` ([recipe](/developer/dashboard/recipes/custom-form-field#a-field-on-a-media-or-variant-row)) |++#### `product.media.actions`++| Where | The product page's Media card, after the "Add video link" button |+|---|---|+| Use | More ways to add media — import from a digital asset manager, generate an image |+| Context | `{ productId, addMedia }` — `addMedia(entries)` appends entries to the gallery and they save with the product. Each entry carries a `signed_id` (from a finished upload), a library `source_media_id`, or `media_type: 'external_video'` with an `external_video_url`, plus an optional `previewUrl` for the tile || Host form | **Yes** — form key `product` |+#### `product.variant.form_fields`++| Where | The variant editor sheet on the product create and edit pages, after the Tax section |+|---|---|+| Use | Fields stored on one variant — a supplier code, a fulfillment flag, a per-variant certification |+| Context | `{ variant, variantIndex, fieldPrefix }` — `variant` is the row's form values, `fieldPrefix` the row's path (`variants.0`) |+| Host form | **Yes** — form key `product.variant`. Bind inputs under `fieldPrefix` and register fields under `product.variant` |++#### `media.form_fields`++| Where | Media library (`products/media`), the file's detail sheet, below "Alt text" |+|---|---|+| Use | Fields stored on the file itself — a photo credit, a license, an expiry date for the rights to use it |+| Context | `{ media, canWrite }` — the `Media` record from the Admin API; `canWrite` is whether the admin may edit it |+| Host form | **Yes** — form key `media`. The sheet's Save sends the fields to the media endpoint, which accepts what `Spree::Media.additional_permitted_attributes` declares |++#### `media.context_menu`++| Where | Media library, the right-click menu on a file in the grid, above Delete |+|---|---|+| Use | Actions on one file — open it in a digital asset manager, remove its background, copy a public link |+| Context | `{ media, canWrite }` — render `<ContextMenuItem>`s |++#### `category.form_main`++| Where | Category create and edit pages (`products/categories/new`, `products/categories/$categoryId`), end of the main column |+|---|---|+| Use | Wide category cards — a landing-page banner, a curated content block |+| Context | `{ category, mode }` — `mode` is `'new'` or `'edit'`; `category` is `undefined` while creating (and briefly while refetching) |+| Host form | **Yes** — form key `category` |+#### `category.form_sidebar`-| Where | Category detail page (`products/categories/$categoryId`), end of the sidebar column |+| Where | Category create and edit pages, end of the sidebar column ||---|---|| Use | Category-scoped cards — merchandising rules, feed settings, external sync state |-| Context | `{ category }` — the `Category` record (may be briefly `undefined` while refetching) |+| Context | `{ category, mode }` — as for `category.form_main` || Host form | **Yes** — form key `category` |+#### `collection.form_main`++| Where | Collection create and edit pages (`products/collections/new`, `products/collections/$collectionId`), end of the main column |+|---|---|+| Use | Wide collection cards — a campaign banner, a schedule |+| Context | `{ collection, mode }` — `mode` is `'new'` or `'edit'`; `collection` is `undefined` while creating |+| Host form | **Yes** — form key `collection` |+#### `collection.form_sidebar`-| Where | Collection detail page (`products/collections/$collectionId`), end of the sidebar column |+| Where | Collection create and edit pages, end of the sidebar column ||---|---|| Use | Collection-scoped cards — merchandising rules, feed settings, external sync state |-| Context | `{ collection }` — the `Collection` record |+| Context | `{ collection, mode }` — as for `collection.form_main` || Host form | **Yes** — form key `collection` |#### `catalog.form_sidebar`@@ -138,6 +204,14 @@ On host-form pages your widget renders inside the page's `<form>` element, so a### Orders and customers+#### `order.form_main`++| Where | Order detail page (`orders/$orderId`), end of the main column |+|---|---|+| Use | Wide order cards — a shipment timeline from a carrier, a support conversation, a fraud report |+| Context | `{ order }` — the full `Order` record |+| Host form | No — widgets save via their own API calls |+#### `order.form_sidebar`| Where | Order detail page (`orders/$orderId`), end of the sidebar column |@@ -146,6 +220,14 @@ On host-form pages your widget renders inside the page's `<form>` element, so a| Context | `{ order }` — the full `Order` record || Host form | No — widgets save via their own API calls |+#### `customer.form_main`++| Where | Customer detail page (`customers/$customerId`), end of the main column |+|---|---|+| Use | Wide customer cards — subscriptions, reviews the customer wrote, a support history |+| Context | `{ customer }` — the full `Customer` record |+| Host form | No — the page edits through sheets; widgets save via their own API calls |+#### `customer.form_sidebar`| Where | Customer detail page (`customers/$customerId`), end of the sidebar column |@@ -192,6 +274,14 @@ The company's member list and its "Add member" sheet carry three smaller slots,### Inventory+#### `purchase_order.form_main`++| Where | Purchase order detail page (`purchase-orders/$purchaseOrderId`), end of the main column |+|---|---|+| Use | Supplier correspondence, shipment tracking for inbound goods, quality-check results |+| Context | `{ purchaseOrder }` — the full `PurchaseOrder` record |+| Host form | No |+#### `purchase_order.form_sidebar`| Where | Purchase order detail page (`purchase-orders/$purchaseOrderId`), end of the sidebar column |@@ -200,6 +290,14 @@ The company's member list and its "Add member" sheet carry three smaller slots,| Context | `{ purchaseOrder }` — the full `PurchaseOrder` record || Host form | No |+#### `stock_transfer.form_main`++| Where | Stock transfer detail page (`transfers/$transferId`), end of the main column |+|---|---|+| Use | Carrier tracking events, packing lists from a warehouse system |+| Context | `{ transfer }` — the full `StockTransfer` record |+| Host form | No |+#### `stock_transfer.form_sidebar`| Where | Stock transfer detail page (`transfers/$transferId`), end of the sidebar column |@@ -254,6 +352,22 @@ These slots are on the store owner's seller management pages in the admin dashbo| Context | `{ store }` — the full `Store` record || Host form | **Yes** — form key `store` |+#### `delivery_profile.form_main`++| Where | Delivery profile page (`settings/delivery-profiles/$profileId`), below the zones and methods |+|---|---|+| Use | Rate tables from a carrier, a preview of what checkout offers for the profile |+| Context | `{ deliveryProfile }` — the full `DeliveryProfile` record |+| Host form | No — the page edits through sheets; widgets save via their own API calls |++#### `delivery_profile.form_sidebar`++| Where | Delivery profile page, end of the sidebar column |+|---|---|+| Use | Carrier account status, a sync state from a fulfillment system |+| Context | `{ deliveryProfile }` — the full `DeliveryProfile` record |+| Host form | No |+#### `webhook_endpoint.form_sidebar`| Where | Webhook endpoint detail page (`settings/webhooks/$webhookEndpointId`), end of the sidebar column |@@ -262,19 +376,48 @@ These slots are on the store owner's seller management pages in the admin dashbo| Context | `{ endpoint }` — the full `WebhookEndpoint` record || Host form | No |+## Sheet slots++The create and edit sheets of the resources below render a slot after their built-in fields. Each sheet is a host form: a widget binds inputs with `useHostForm()`, registers them under the form key (the slot's prefix), and they save with the sheet's own Create or Save button. The matching Admin API endpoint accepts what the model's `additional_permitted_attributes` declares (see [Adding an Attribute to a Core Resource](/developer/customization/api#adding-an-attribute-to-a-core-resource)).++Every sheet passes `mode` — `'new'` or `'edit'` — and its record, which is `undefined` while creating.++| Slot | Where | Context |+|---|---|---|+| `market.form_fields` | Settings → Markets | `{ market, mode }` |+| `stock_location.form_fields` | Settings → Stock locations | `{ stockLocation, mode }` |+| `tax_rate.form_fields` | Settings → Taxes → Rates | `{ taxRate, mode }` |+| `tax_category.form_fields` | Settings → Taxes → Categories | `{ taxCategory, mode }` |+| `channel.form_fields` | Settings → Sales channels | `{ channel, mode }` |+| `policy.form_fields` | Settings → Policies | `{ policy, mode }` |+| `package_type.form_fields` | Settings → Package types | `{ packageType, mode }` |+| `product_type.form_fields` | Settings → Product types | `{ productType, mode }` |+| `delivery_zone.form_fields` | A delivery profile's zone sheet | `{ deliveryZone, deliveryProfileId, mode }` |+| `delivery_method.form_fields` | A delivery profile's method sheet | `{ deliveryMethod, deliveryProfile, mode }` |+| `option_type.form_fields` | Products → Options | `{ optionType, mode }` |+| `customer_group.form_fields` | Customers → Groups | `{ customerGroup, mode }` |++Staff invitations have no slot: the invitations endpoint deliberately accepts no extension attributes, because what it takes decides who gets access.+## Seller panel slotsRendered by the marketplace seller panel (`@spree/seller-dashboard`) rather than the admin dashboard, and registered the same way, in the seller panel's own plugins. Their names start with `seller.` followed by the page — `seller.form_main` and `seller.form_sidebar` above belong to the admin dashboard instead.-The product page is a host form with the form key `seller.product`: fields a widget binds with `useHostForm()` save with the product. The Seller API accepts only the attributes your extension declares in `additional_seller_permitted_attributes` — see [Writable by sellers](/developer/customization/api#writable-by-sellers). The other seller panel pages have no page-wide form, so widgets there save via their own Seller API calls.+The product page is a host form with the form key `seller.product` (`seller.product.media` and `seller.product.variant` for the rows its sheets edit): fields a widget binds with `useHostForm()` save with the product. The Seller API accepts only the attributes your extension declares in `additional_seller_permitted_attributes` — see [Writable by sellers](/developer/customization/api#writable-by-sellers). The other seller panel pages have no page-wide form, so widgets there save via their own Seller API calls.| Slot | Where | Context ||---|---|---|+| `seller.product.form_main` | Product create and edit pages, end of the main column | `{ product, mode }` — `mode` is `'new'` or `'edit'`; `product` is `undefined` while creating || `seller.product.form_sidebar` | Product create and edit pages, end of the sidebar column | `{ product, mode }` — `mode` is `'new'` or `'edit'`; `product` is `undefined` while creating |+| `seller.product.media.form_fields` | The media editor sheet on the product pages | `{ productId, media, mediaIndex, fieldPrefix }` — host form key `seller.product.media` |+| `seller.product.media.actions` | The product pages' Media card, after the "Add video link" button | `{ productId, addMedia }` — see [`product.media.actions`](#product-media-actions) |+| `seller.product.variant.form_fields` | The variant editor sheet on the product pages | `{ variant, variantIndex, fieldPrefix }` — host form key `seller.product.variant` || `seller.order.form_sidebar` | Order detail page, end of the sidebar column | `{ order }` || `seller.payout.form_sidebar` | Payout detail page, end of the sidebar column | `{ payout }` || `seller.profile.form_main` | Profile page, end of the main column | `{ profile }` || `seller.profile.form_sidebar` | Profile page, end of the sidebar column | `{ profile }` |+| `seller.stock_location.form_fields` | Stock location create and edit sheets | `{ stockLocation, mode }` — host form key `seller.stock_location` |+| `seller.package_type.form_fields` | Package type create and edit sheets | `{ packageType, mode }` — host form key `seller.package_type` || `seller.team.actions` | Team page, in the header's action area — bulk invite, export, an external directory sync | `{ sellerId }` || `seller.team.after` | Team page, below the member list — audit log, role explainer, seat usage | `{ sellerId }` |diff --git a/packages/dashboard-core/src/components/file-upload-field.tsx b/packages/dashboard-core/src/components/file-upload-field.tsxindex 1f250beb08..ec96d41f5e 100644--- a/packages/dashboard-core/src/components/file-upload-field.tsx+++ b/packages/dashboard-core/src/components/file-upload-field.tsx@@ -270,6 +270,7 @@ export function FileUploadField({</AttachmentContent><AttachmentActions><AttachmentAction+ type="button"aria-label={t('admin.actions.remove')}onClick={handleRemove}disabled={disabled || !!pending}diff --git a/packages/dashboard-core/src/components/slot.tsx b/packages/dashboard-core/src/components/slot.tsxindex e28b32ca1a..2d5a8d9c12 100644--- a/packages/dashboard-core/src/components/slot.tsx+++ b/packages/dashboard-core/src/components/slot.tsx@@ -1,7 +1,8 @@import { Fragment } from 'react'+import { FormProvider, type UseFormReturn } from 'react-hook-form'import { type SlotAmbientContext, useSlotEntries } from '../lib/slot-registry'-interface SlotProps<TContext> {+export interface SlotProps<TContext> {/** Slot name, e.g. "product.form_sidebar" or "order.dropdown". */name: string/** Slot-specific context passed to every registered component. */@@ -48,3 +49,22 @@ export function Slot<TContext extends object = object>({</>)}++/**+ * A slot inside a form that isn't wrapped in `FormProvider` — a create or edit+ * sheet. Widgets rendered here reach the form with `useHostForm()`, so fields+ * they bind save with the sheet's own submit.+ */+export function HostFormSlot<TContext extends object = object>({+ form,+ ...slot+}: SlotProps<TContext> & {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ form: UseFormReturn<any, any, any>+}) {+ return (+ <FormProvider {...form}>+ <Slot {...slot} />+ </FormProvider>+ )+}diff --git a/packages/dashboard-core/src/lib/form-fields-registry.ts b/packages/dashboard-core/src/lib/form-fields-registry.tsindex de125a6947..56ccb9db11 100644--- a/packages/dashboard-core/src/lib/form-fields-registry.ts+++ b/packages/dashboard-core/src/lib/form-fields-registry.ts@@ -30,7 +30,8 @@ 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+ * slot prefix — `'product'` for the product detail form, `'product.media'` and+ * `'product.variant'` for the rows of its media and variant lists. Registered names* must be unique per form; duplicates throw so two plugins can't silently* fight over one attribute.*/@@ -96,6 +97,27 @@ export function extensionSubmitValues(return out}+/** Names of every extension field registered on `formKey`. */+export function extensionFieldNames(formKey: string): string[] {+ return (registrations.get(formKey) ?? []).map((registration) => registration.name)+}++/**+ * Extension field values carried by one row of a nested list — a media or+ * variant row of the product form, registered under `'product.media'` /+ * `'product.variant'`. Only keys the row actually holds are returned, so a+ * row added after hydration (a fresh upload) sends nothing it never had.+ */+export function extensionRowValues(formKey: string, row: unknown): Record<string, unknown> {+ if (!row || typeof row !== 'object') return {}++ const out: Record<string, unknown> = {}+ for (const name of extensionFieldNames(formKey)) {+ if (name in row) out[name] = (row as Record<string, unknown>)[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/pages/package-types.tsx b/packages/dashboard-core/src/pages/package-types.tsxindex e5e14e38cf..23c8cc7cfd 100644--- a/packages/dashboard-core/src/pages/package-types.tsx+++ b/packages/dashboard-core/src/pages/package-types.tsx@@ -33,6 +33,7 @@ import { z } from 'zod/v4'import type { PanelPackageType } from '../api-client'import { Can } from '../components/can'import { ResourceTable, resourceSearchSchema } from '../components/resource-table'+import { HostFormSlot } from '../components/slot'import {canDeletePackageTypes,canWritePackageTypes,@@ -43,6 +44,7 @@ import {useUpdatePackageType,} from '../hooks/use-package-types'import { mapSpreeErrorsToForm } from '../lib/form-errors'+import { extensionFormValues, extensionSubmitValues } from '../lib/form-fields-registry'import { Subject } from '../lib/permissions'import { usePermissions } from '../providers/permission-provider'import {@@ -88,7 +90,14 @@ export type PackageTypesSearch = z.infer<typeof packageTypesSearchSchema>*/function noop() {}-export function PackageTypesPage({ search }: { search: PackageTypesSearch }) {+export function PackageTypesPage({+ search,+ formKey = 'package_type',+}: {+ search: PackageTypesSearch+ /** Names the sheets' slot and extension fields — `seller.package_type` in the seller panel. */+ formKey?: string+}) {const { t } = useTranslation()const navigate = useNavigate()const confirm = useConfirm()@@ -193,16 +202,27 @@ export function PackageTypesPage({ search }: { search: PackageTypesSearch }) {}/>- {isCreating && <CreatePackageTypeSheet open onOpenChange={(o) => !o && closeSheet()} />}- {editId && <EditPackageTypeSheet id={editId} open onOpenChange={(o) => !o && closeSheet()} />}+ {isCreating && (+ <CreatePackageTypeSheet formKey={formKey} open onOpenChange={(o) => !o && closeSheet()} />+ )}+ {editId && (+ <EditPackageTypeSheet+ id={editId}+ formKey={formKey}+ open+ onOpenChange={(o) => !o && closeSheet()}+ />+ )}</>)}function CreatePackageTypeSheet({+ formKey,open,onOpenChange,}: {+ formKey: stringopen: booleanonOpenChange: (open: boolean) => void}) {@@ -210,12 +230,15 @@ function CreatePackageTypeSheet({const createMutation = useCreatePackageType()const form = useForm<PackageTypeFormValues>({resolver: zodResolver(packageTypeFormSchema),- defaultValues: PACKAGE_TYPE_DEFAULTS,+ defaultValues: { ...PACKAGE_TYPE_DEFAULTS, ...extensionFormValues(formKey, null) },})async function onSubmit(values: PackageTypeFormValues) {try {- await createMutation.mutateAsync(packageTypeFormValuesToParams(values))+ await createMutation.mutateAsync({+ ...packageTypeFormValuesToParams(values),+ ...extensionSubmitValues(formKey, form),+ })form.reset(PACKAGE_TYPE_DEFAULTS)onOpenChange(false)} catch (err) {@@ -239,6 +262,11 @@ function CreatePackageTypeSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><PackageTypeFormFields form={form} />+ <HostFormSlot+ form={form}+ name={`${formKey}.form_fields`}+ context={{ packageType: undefined, mode: 'new' }}+ /></div><SheetFooter><Button type="submit" disabled={createMutation.isPending}>@@ -253,10 +281,12 @@ function CreatePackageTypeSheet({function EditPackageTypeSheet({id,+ formKey,open,onOpenChange,}: {id: string+ formKey: stringopen: booleanonOpenChange: (open: boolean) => void}) {@@ -270,12 +300,17 @@ function EditPackageTypeSheet({const form = useForm<PackageTypeFormValues>({resolver: zodResolver(packageTypeFormSchema),defaultValues: PACKAGE_TYPE_DEFAULTS,- values: packageType ? packageTypeToFormValues(packageType) : undefined,+ values: packageType+ ? { ...packageTypeToFormValues(packageType), ...extensionFormValues(formKey, packageType) }+ : undefined,})async function onSubmit(values: PackageTypeFormValues) {try {- await updateMutation.mutateAsync(packageTypeFormValuesToParams(values))+ await updateMutation.mutateAsync({+ ...packageTypeFormValuesToParams(values),+ ...extensionSubmitValues(formKey, form),+ })onOpenChange(false)} catch (err) {if (!mapSpreeErrorsToForm(err, form.setError)) throw err@@ -298,6 +333,11 @@ function EditPackageTypeSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><PackageTypeFormFields form={form} />+ <HostFormSlot+ form={form}+ name={`${formKey}.form_fields`}+ context={{ packageType, mode: 'edit' }}+ /></div><SheetFooter><Button type="submit" disabled={updateMutation.isPending}>diff --git a/packages/dashboard-core/src/pages/stock-locations.tsx b/packages/dashboard-core/src/pages/stock-locations.tsxindex abc2522878..06ecec8cf7 100644--- a/packages/dashboard-core/src/pages/stock-locations.tsx+++ b/packages/dashboard-core/src/pages/stock-locations.tsx@@ -34,6 +34,7 @@ import { Can } from '../components/can'import { CountryCombobox } from '../components/country-combobox'import { StateCombobox, useCountryStates } from '../components/country-state-fields'import { ResourceTable, resourceSearchSchema } from '../components/resource-table'+import { HostFormSlot } from '../components/slot'import {canDeleteStockLocations,listStockLocations,@@ -43,6 +44,7 @@ import {useUpdateStockLocation,} from '../hooks/use-stock-locations'import { mapSpreeErrorsToForm } from '../lib/form-errors'+import { extensionFormValues, extensionSubmitValues } from '../lib/form-fields-registry'import { Subject } from '../lib/permissions'import { usePermissions } from '../providers/permission-provider'import {@@ -90,8 +92,11 @@ export function StockLocationsPage({search,stockLevelsPanel: StockLevelsPanel,activityPanel: ActivityPanel,+ formKey = 'stock_location',}: {search: StockLocationsSearch+ /** Names the sheets' slot and extension fields — `seller.stock_location` in the seller panel. */+ formKey?: string/** Rendered inside the edit sheet, below the form. Optional — see above. */stockLevelsPanel?: ComponentType<{ stockLocationId: string }>/** What changed in this warehouse, for reconciliation. Optional. */@@ -170,10 +175,13 @@ export function StockLocationsPage({}/>- {isCreating && <CreateStockLocationSheet open onOpenChange={(o) => !o && closeSheet()} />}+ {isCreating && (+ <CreateStockLocationSheet formKey={formKey} open onOpenChange={(o) => !o && closeSheet()} />+ )}{editId && (<EditStockLocationSheetid={editId}+ formKey={formKey}openonOpenChange={(o) => !o && closeSheet()}stockLevelsPanel={StockLevelsPanel}@@ -189,9 +197,11 @@ export function StockLocationsPage({// ============================================================================function CreateStockLocationSheet({+ formKey,open,onOpenChange,}: {+ formKey: stringopen: booleanonOpenChange: (open: boolean) => void}) {@@ -201,13 +211,13 @@ function CreateStockLocationSheet({const form = useForm<StockLocationFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(stockLocationFormSchema) as any,- defaultValues: STOCK_LOCATION_DEFAULTS,+ defaultValues: { ...STOCK_LOCATION_DEFAULTS, ...extensionFormValues(formKey, null) },})async function onSubmit(values: StockLocationFormValues) {try {const params = formValuesToParams(values)- await createMutation.mutateAsync(params)+ await createMutation.mutateAsync({ ...params, ...extensionSubmitValues(formKey, form) })form.reset(STOCK_LOCATION_DEFAULTS)onOpenChange(false)} catch (err) {@@ -231,6 +241,11 @@ function CreateStockLocationSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><StockLocationFormFields form={form} />+ <HostFormSlot+ form={form}+ name={`${formKey}.form_fields`}+ context={{ stockLocation: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -259,12 +274,14 @@ function CreateStockLocationSheet({function EditStockLocationSheet({id,+ formKey,open,onOpenChange,stockLevelsPanel: StockLevelsPanel,activityPanel: ActivityPanel,}: {id: string+ formKey: stringopen: booleanonOpenChange: (open: boolean) => voidstockLevelsPanel?: ComponentType<{ stockLocationId: string }>@@ -284,14 +301,17 @@ function EditStockLocationSheet({// with whatever the server last persisted (including external edits).useEffect(() => {if (stockLocation) {- form.reset(stockLocationToFormValues(stockLocation))+ form.reset({+ ...stockLocationToFormValues(stockLocation),+ ...extensionFormValues(formKey, stockLocation),+ })}- }, [stockLocation, form])+ }, [stockLocation, form, formKey])async function onSubmit(values: StockLocationFormValues) {try {const params = formValuesToParams(values)- await updateMutation.mutateAsync(params)+ await updateMutation.mutateAsync({ ...params, ...extensionSubmitValues(formKey, form) })form.reset(values)onOpenChange(false)} catch (err) {@@ -314,6 +334,11 @@ function EditStockLocationSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><StockLocationFormFields form={form} />+ <HostFormSlot+ form={form}+ name={`${formKey}.form_fields`}+ context={{ stockLocation, mode: 'edit' }}+ />{StockLevelsPanel && <StockLevelsPanel stockLocationId={id} />}{ActivityPanel && <ActivityPanel stockLocationId={id} />}</div>diff --git a/packages/dashboard-core/src/products/media-edit-sheet.tsx b/packages/dashboard-core/src/products/media-edit-sheet.tsxindex ebbc940602..2cdabe1c12 100644--- a/packages/dashboard-core/src/products/media-edit-sheet.tsx+++ b/packages/dashboard-core/src/products/media-edit-sheet.tsx@@ -1,5 +1,11 @@import type { ProductFormValues } from '@spree/dashboard-core'-import { ImageUploadField, parseVideoUrl, useTranslation } from '@spree/dashboard-core'+import {+ extensionFieldNames,+ ImageUploadField,+ parseVideoUrl,+ Slot,+ useTranslation,+} from '@spree/dashboard-core'import {Button,Field,@@ -39,13 +45,24 @@ interface Props {variants: Variant[]open: booleanonOpenChange: (open: boolean) => void+ /** The product form's key — names the slot and the row's extension fields. */+ formKey: string+ productId?: string}// Form-backed media editor. The sheet edits `form.media[index]` directly —// changes ride the parent product PATCH/POST, no per-asset API calls.// Cancel restores a snapshot taken on open; Done closes (parent form Save// commits). Same model as the per-variant Sheet.-export function MediaEditSheet({ form, mediaIndex, variants, open, onOpenChange }: Props) {+export function MediaEditSheet({+ form,+ mediaIndex,+ variants,+ open,+ onOpenChange,+ formKey,+ productId,+}: Props) {const { t } = useTranslation()// Snapshot on open so Cancel can restore. Re-snapshot if mediaIndex changes@@ -58,7 +75,11 @@ export function MediaEditSheet({ form, mediaIndex, variants, open, onOpenChange// freshly-uploaded row that has no id yet we fall back to the current// index — uploads don't surface a drag handle so the race is impossible.type MediaRow = NonNullable<ProductFormValues['media']>[number]- type Snapshot = Pick<MediaRow, (typeof EDITED_FIELDS)[number]> & { key: string | null }+ type Snapshot = Pick<MediaRow, (typeof EDITED_FIELDS)[number]> & {+ key: string | null+ // Fields a `<formKey>.media.form_fields` widget edits, restored the same way.+ extensions: Record<string, unknown>+ }const snapshotRef = useRef<Snapshot | null>(null)const rowKey = useCallback((m: MediaRow): string | null => m.id ?? m.signed_id ?? m.uploadId ?? null,@@ -84,8 +105,16 @@ export function MediaEditSheet({ form, mediaIndex, variants, open, onOpenChange// Copy the array — the snapshot must not alias the row's own value.variant_ids: [...(row.variant_ids ?? [])],key: rowKey(row),+ extensions: structuredClone(+ Object.fromEntries(+ extensionFieldNames(`${formKey}.media`).map((name) => [+ name,+ (row as Record<string, unknown>)[name],+ ]),+ ),+ ),}- }, [open, mediaIndex, form, rowKey])+ }, [open, mediaIndex, form, rowKey, formKey])const entry = form.watch(`media.${mediaIndex}`)if (!entry) return null@@ -203,6 +232,13 @@ export function MediaEditSheet({ form, mediaIndex, variants, open, onOpenChangeshouldTouch: false,})}+ for (const [name, value] of Object.entries(snap.extensions)) {+ // Extension names are outside the typed row.+ form.setValue(`media.${targetIndex}.${name}` as any, value, {+ shouldDirty: false,+ shouldTouch: false,+ })+ }}onOpenChange(false)}@@ -309,6 +345,16 @@ export function MediaEditSheet({ form, mediaIndex, variants, open, onOpenChange</div></Field>)}++ <Slot+ name={`${formKey}.media.form_fields`}+ context={{+ productId,+ media: entry,+ mediaIndex,+ fieldPrefix: `media.${mediaIndex}`,+ }}+ /></div><SheetFooter>diff --git a/packages/dashboard-core/src/products/product-form-cards.tsx b/packages/dashboard-core/src/products/product-form-cards.tsxindex a26df6a974..99acf80a82 100644--- a/packages/dashboard-core/src/products/product-form-cards.tsx+++ b/packages/dashboard-core/src/products/product-form-cards.tsx@@ -20,6 +20,7 @@ import {MediaPickerSheet,parseVideoUrl,ResourceMultiAutocomplete,+ Slot,TagCombobox,useFileUpload,useOptionalStore,@@ -86,7 +87,7 @@ import { InventorySection } from './inventory-section'import { MediaEditSheet } from './media-edit-sheet'import { ProductBulkPriceEditor } from './product-bulk-price-editor'import { variantHasTaxCategoryOverride } from './product-form-mapping'-import type { VariantFormValues } from './product-schema'+import type { MediaFormValues, VariantFormValues } from './product-schema'import type {PanelMedia as Media,PanelProduct as Product,@@ -175,8 +176,12 @@ export function GeneralCard({// Variants (just a passthrough so the page composition reads top-down)// ----------------------------------------------------------------------------export function VariantsCard({ form, seedFromType }: FormCardProps & { seedFromType?: boolean }) {- return <VariantsSection form={form} seedFromType={seedFromType} />+export function VariantsCard({+ form,+ seedFromType,+ formKey = 'product',+}: FormCardProps & { seedFromType?: boolean; formKey?: string }) {+ return <VariantsSection form={form} seedFromType={seedFromType} formKey={formKey} />}// ---------------------------------------------------------------------------@@ -260,6 +265,13 @@ export function PricesCard({// merchant sees where uploads will go but can't trigger them.// ---------------------------------------------------------------------------+/**+ * A media entry appended to the gallery without an upload: a `signed_id` from+ * a finished upload, a library `source_media_id`, or an external video link.+ * `previewUrl` is what the tile shows until the product is saved.+ */+export type NewMediaEntry = Omit<MediaFormValues, 'position' | 'uploadId'>+interface PendingUpload {id: stringfile: File@@ -289,8 +301,11 @@ export function MediaCard({productId,variants,form,+ formKey = 'product',}: {productId?: string+ /** The product form's key — names the media slots and the rows' extension fields. */+ formKey?: string// The MediaEditSheet's "assign to variant" pill row needs the list of// server-persisted variants — only those have an id that can ride the// PATCH's media[].variant_ids. Form-state variants without a server id@@ -413,20 +428,21 @@ export function MediaCard({// An external video has no file to upload — it goes straight into form state// with its link, and the provider's own still stands in as the preview.- const handleAddVideo = useCallback(- (url: string) => {+ // Appends entries that need no upload of their own — a video link, a+ // library pick, or whatever a `<formKey>.media.actions` widget hands over —+ // positioned after the existing ones. They save with the product.+ const appendMedia = useCallback(+ (entries: NewMediaEntry[]) => {const current = form.getValues('media') ?? []form.setValue('media',[...current,- {- media_type: 'external_video' as const,- external_video_url: url,- position: current.length + 1,- previewUrl: parseVideoUrl(url)?.thumbnailUrl ?? undefined,+ ...entries.map((entry, index) => ({+ ...entry,+ position: current.length + index + 1,uploadId: crypto.randomUUID(),- },+ })),],{ shouldDirty: true },)@@ -434,31 +450,34 @@ export function MediaCard({[form],)+ const handleAddVideo = useCallback(+ (url: string) =>+ appendMedia([+ {+ media_type: 'external_video',+ external_video_url: url,+ previewUrl: parseVideoUrl(url)?.thumbnailUrl ?? undefined,+ },+ ]),+ [appendMedia],+ )+// Files picked from the library become ordinary form entries carrying the// source's id. The product save places them, sharing the file rather than// uploading a second copy.const handleAddFromLibrary = useCallback(- (picked: Media[]) => {- const current = form.getValues('media') ?? []- form.setValue(- 'media',- [- ...current,- ...picked.map((media, index) => ({- source_media_id: media.id,- alt: media.alt ?? undefined,- media_type: (media.media_type ?? 'image') as MediaType,- position: current.length + index + 1,- previewUrl: media.small_url ?? media.original_url ?? undefined,- videoUrl: media.video_url ?? null,- posterUrl: media.poster_url ?? null,- uploadId: crypto.randomUUID(),- })),- ],- { shouldDirty: true },- )- },- [form],+ (picked: Media[]) =>+ appendMedia(+ picked.map((media) => ({+ source_media_id: media.id,+ alt: media.alt ?? undefined,+ media_type: (media.media_type ?? 'image') as MediaType,+ previewUrl: media.small_url ?? media.original_url ?? undefined,+ videoUrl: media.video_url ?? null,+ posterUrl: media.poster_url ?? null,+ })),+ ),+ [appendMedia],)const handleDelete = useCallback(@@ -620,6 +639,11 @@ export function MediaCard({<FilmIcon />{t('admin.products.media.add_video')}</Button>++ <Slot+ name={`${formKey}.media.actions`}+ context={{ productId, addMedia: appendMedia }}+ /></div></CardContent></Card>@@ -649,6 +673,8 @@ export function MediaCard({onOpenChange={(open) => {if (!open) setEditingIndex(null)}}+ formKey={formKey}+ productId={productId}/>)}</>diff --git a/packages/dashboard-core/src/products/product-form-mapping.ts b/packages/dashboard-core/src/products/product-form-mapping.tsindex 3dc4349718..baef421e3a 100644--- a/packages/dashboard-core/src/products/product-form-mapping.ts+++ b/packages/dashboard-core/src/products/product-form-mapping.ts@@ -1,3 +1,4 @@+import { extensionFormValues, extensionRowValues } from '../lib/form-fields-registry'import { i18n } from '../lib/i18n'import { normalizeQuantityRule } from './normalize-quantity'import type { MediaType, ProductFormValues, VariantFormValues } from './product-schema'@@ -11,8 +12,18 @@ import type { PanelMedia, PanelProduct, PanelVariant } from './product-types'* this mapping would be two ways to disagree.*/-export function variantToFormValues(variant: PanelVariant, position: number): VariantFormValues {+/**+ * `formKey` is the product form's key (`'product'`, or `'seller.product'` in+ * the seller panel); the rows' extension fields are registered under+ * `${formKey}.variant` and `${formKey}.media`.+ */+export function variantToFormValues(+ variant: PanelVariant,+ position: number,+ formKey = 'product',+): VariantFormValues {return {+ ...extensionFormValues(`${formKey}.variant`, variant),id: variant.id,sku: variant.sku ?? null,barcode: variant.barcode ?? null,@@ -76,8 +87,9 @@ export function variantToFormValues(variant: PanelVariant, position: number): Va// late paint) so a new media field can't reach one and miss the other.// Takes the generated SDK type rather than a hand-listed shape, so a field// added to the serializer can't quietly go missing here.-export function mediaToFormValues(media: PanelMedia, index: number) {+export function mediaToFormValues(media: PanelMedia, index: number, formKey = 'product') {return {+ ...extensionFormValues(`${formKey}.media`, media),id: media.id,alt: media.alt ?? null,position: media.position ?? index + 1,@@ -108,6 +120,7 @@ export function productToFormValues(// captures it atomically instead of via a follow-up setValue that races// with the merchant's unsaved edits.media?: PanelMedia[],+ formKey = 'product',): ProductFormValues {const hasVariants = (product.variant_count ?? 0) > 0const variantSource = hasVariants@@ -140,14 +153,14 @@ export function productToFormValues(meta_title: product.meta_title ?? '',meta_description: product.meta_description ?? '',slug: product.slug ?? '',- variants: variantSource.map((v, i) => variantToFormValues(v, i)),+ variants: variantSource.map((v, i) => variantToFormValues(v, i, formKey)),custom_fields:product.custom_fields?.map((cf) => ({id: cf.id,custom_field_definition_id: cf.custom_field_definition_id,value: cf.value,})) ?? [],- media: media?.map(mediaToFormValues) ?? [],+ media: media?.map((m, i) => mediaToFormValues(m, i, formKey)) ?? [],product_publications: (product.product_publications ?? []).map((l) => ({id: l.id,channel_id: l.channel_id,@@ -157,6 +170,31 @@ export function productToFormValues(}}+/**+ * The submitted values with each variant and media row's extension fields put+ * back from live form state. The Zod parse behind a submit strips keys the+ * schema doesn't know from every row; it keeps the rows' order, so row `i` of+ * the parse is row `i` of the form. Call it first in a submit handler, before+ * rows are filtered or reordered.+ */+export function withExtensionRowValues(+ formKey: string,+ values: ProductFormValues,+ raw: Partial<ProductFormValues>,+): ProductFormValues {+ return {+ ...values,+ variants: values.variants?.map((variant, index) => ({+ ...variant,+ ...extensionRowValues(`${formKey}.variant`, raw.variants?.[index]),+ })),+ media: values.media?.map((media, index) => ({+ ...media,+ ...extensionRowValues(`${formKey}.media`, raw.media?.[index]),+ })),+ }+}+// Strip UI-only fields (stock_location_name) and undefined entries so the// PATCH body matches the Admin API VariantUpdateParams shape exactly. The// Spree::Product#variants= setter reconciles by id, creates new entries,@@ -187,13 +225,14 @@ export function prepareVariantsTaxForProductSave(})}-export function variantToWirePayload(v: VariantFormValues, index: number) {+export function variantToWirePayload(v: VariantFormValues, index: number, formKey = 'product') {// DB columns `sku` and `weight` are NOT NULL with defaults ("", 0.0).// The other scalar fields (barcode, dimensions, weight_unit,// dimensions_unit, tax_category_id) ARE nullable — those we always send// even when null so the merchant can clear them. NOT-NULL fields fall// back to their schema defaults when blank.const payload: Record<string, unknown> = {+ ...extensionRowValues(`${formKey}.variant`, v),position: index + 1,options: v.options,sku: v.sku ?? '',diff --git a/packages/dashboard-core/src/products/variant-edit-sheet.tsx b/packages/dashboard-core/src/products/variant-edit-sheet.tsxindex 326a78ada9..2b4ac4eb54 100644--- a/packages/dashboard-core/src/products/variant-edit-sheet.tsx+++ b/packages/dashboard-core/src/products/variant-edit-sheet.tsx@@ -1,6 +1,6 @@import { DimensionUnit, WeightUnit } from '@spree/core'import type { ProductFormValues, VariantFormValues } from '@spree/dashboard-core'-import { CountryCombobox, StoreDatePicker } from '@spree/dashboard-core'+import { CountryCombobox, Slot, StoreDatePicker } from '@spree/dashboard-core'import {Alert,AlertDescription,@@ -48,6 +48,8 @@ interface Props {// eslint-disable-next-line @typescript-eslint/no-explicit-anyform: UseFormReturn<ProductFormValues, any, any>variantIndex: number+ /** The product form's key — names the `<formKey>.variant.form_fields` slot. */+ formKey: stringopen: booleanonOpenChange: (open: boolean) => void}@@ -56,7 +58,7 @@ interface Props {// form — no own form state. Save closes the sheet (changes are already in// form state; the product Save button commits them). Cancel restores the// snapshot captured when the sheet opened.-export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Props) {+export function VariantEditSheet({ form, variantIndex, formKey, open, onOpenChange }: Props) {const { t } = useTranslation()const { data: taxCategoriesResponse } = useTaxCategories()const taxCategories = taxCategoriesResponse?.data ?? []@@ -707,6 +709,11 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Pro</Field></FormSection>)}++ <Slot+ name={`${formKey}.variant.form_fields`}+ context={{ variant, variantIndex, fieldPrefix: `variants.${variantIndex}` }}+ /></div><SheetFooter>diff --git a/packages/dashboard-core/src/products/variants-section.tsx b/packages/dashboard-core/src/products/variants-section.tsxindex 31bae2f2c1..4609898182 100644--- a/packages/dashboard-core/src/products/variants-section.tsx+++ b/packages/dashboard-core/src/products/variants-section.tsx@@ -64,6 +64,8 @@ interface Props {* whatever it already has.*/seedFromType?: boolean+ /** The product form's key — names the variant sheet's slot. */+ formKey?: string}// Derive the initial selected option types from current variant rows so the@@ -125,7 +127,7 @@ function seedFromProductType(.filter((entry): entry is SelectedOptionType => entry !== null)}-export function VariantsSection({ form, seedFromType = false }: Props) {+export function VariantsSection({ form, seedFromType = false, formKey = 'product' }: Props) {const { t } = useTranslation()const { data: optionTypesData } = useOptionTypes()const allOptionTypes = useMemo(() => optionTypesData?.data ?? [], [optionTypesData])@@ -447,6 +449,7 @@ export function VariantsSection({ form, seedFromType = false }: Props) {<VariantEditSheetform={form}variantIndex={editingIndex}+ formKey={formKey}open={sheetOpen}onOpenChange={(o) => {setSheetOpen(o)diff --git a/packages/dashboard-core/tests/form-fields-registry.test.ts b/packages/dashboard-core/tests/form-fields-registry.test.tsindex 54b0304c54..8ec9a7edb3 100644--- a/packages/dashboard-core/tests/form-fields-registry.test.ts+++ b/packages/dashboard-core/tests/form-fields-registry.test.ts@@ -2,9 +2,16 @@ import { beforeEach, describe, expect, it } from 'vitest'import {__resetFormFieldsRegistry,extensionFormValues,+ extensionRowValues,extensionSubmitValues,formFields,} from '../src/lib/form-fields-registry'+import {+ mediaToFormValues,+ variantToWirePayload,+ withExtensionRowValues,+} from '../src/products/product-form-mapping'+import type { ProductFormValues, VariantFormValues } from '../src/products/product-schema'interface FakeProduct {tech_specs?: string@@ -69,6 +76,55 @@ describe('formFields registry', () => {expect(extensionSubmitValues('category', fakeForm)).toEqual({})})+ it('picks only the registered fields a row holds', () => {+ formFields.register('product.media', { name: 'credit', from: () => '' })+ formFields.register('product.media', { name: 'license', from: () => null })++ expect(extensionRowValues('product.media', { alt: 'Front', credit: 'Jane' })).toEqual({+ credit: 'Jane',+ })+ expect(extensionRowValues('product.media', undefined)).toEqual({})+ })++ it('carries row fields from the API record through the form and back out', () => {+ formFields.register('product.media', {+ name: 'credit',+ from: (media) => (media as { credit?: string } | null)?.credit ?? '',+ })+ formFields.register('product.variant', { name: 'brand_code', from: () => '' })++ expect(mediaToFormValues({ id: 'media_1', credit: 'Jane' } as never, 0)).toMatchObject({+ id: 'media_1',+ credit: 'Jane',+ })++ // The parse strips unknown keys from every row; live form state has them.+ const parsed = {+ name: 'Shirt',+ media: [{ id: 'media_1', alt: 'Front' }],+ variants: [{ position: 0, options: [] }],+ } as ProductFormValues+ const raw = {+ media: [{ id: 'media_1', alt: 'Front', credit: 'Jane' }],+ variants: [{ position: 0, options: [], brand_code: 'ACME' }],+ } as unknown as ProductFormValues+ const restored = withExtensionRowValues('product', parsed, raw)++ expect(restored.media?.[0]).toMatchObject({ credit: 'Jane' })+ expect(variantToWirePayload(restored.variants?.[0] as VariantFormValues, 0)).toMatchObject({+ brand_code: 'ACME',+ position: 1,+ })+ })++ it('keeps each panel to its own row fields', () => {+ formFields.register('seller.product.variant', { name: 'brand_code', from: () => '' })+ const variant = { position: 0, options: [], brand_code: 'ACME' } as VariantFormValues++ expect(variantToWirePayload(variant, 0)).not.toHaveProperty('brand_code')+ expect(variantToWirePayload(variant, 0, 'seller.product')).toMatchObject({ brand_code: 'ACME' })+ })+it('remove() unregisters and is a no-op when absent', () => {formFields.register('product', { name: 'tech_specs', from: () => '' })formFields.remove('product', 'tech_specs')diff --git a/packages/dashboard/e2e/categories.spec.ts b/packages/dashboard/e2e/categories.spec.tsindex 8bdbb918a1..331334965d 100644--- a/packages/dashboard/e2e/categories.spec.ts+++ b/packages/dashboard/e2e/categories.spec.ts@@ -45,6 +45,23 @@ test.describe('categories management', () => {await expect(treeRow(page, name)).toBeVisible()})+ // Filled by the probes in src/testing/slot-probes.tsx.+ test('renders the plugin slots on the create and edit pages', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, CATEGORIES_PATH(creds.store_id), CTA)++ await page.getByRole('button', { name: CTA }).click()+ await expect(page.getByText('Slot probe: category.form_main (new)')).toBeVisible()+ await expect(page.getByText('Slot probe: category.form_sidebar (new)')).toBeVisible()++ await page.locator('#category-name').fill(`E2E Slots ${Date.now()}`)+ await page.getByRole('button', { name: /^save$/i }).click()+ await expect(page.getByText('Slot probe: category.form_main (edit)')).toBeVisible({+ timeout: 15_000,+ })+ await expect(page.getByText('Slot probe: category.form_sidebar (edit)')).toBeVisible()+ })+test('edits a category name', async ({ page }) => {const creds = await login(page)await gotoIndex(page, CATEGORIES_PATH(creds.store_id), CTA)diff --git a/packages/dashboard/e2e/channels-settings.spec.ts b/packages/dashboard/e2e/channels-settings.spec.tsindex bc27c48f5f..3ec4a5128e 100644--- a/packages/dashboard/e2e/channels-settings.spec.ts+++ b/packages/dashboard/e2e/channels-settings.spec.ts@@ -13,6 +13,8 @@ async function createChannel(page: Page, attrs: { name: string; code?: string })await page.getByLabel(/^code$/i).fill(attrs.code)}+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: channel.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create sales channel/i }).click()}diff --git a/packages/dashboard/e2e/collections.spec.ts b/packages/dashboard/e2e/collections.spec.tsindex 9e025c8ff0..e145d18bce 100644--- a/packages/dashboard/e2e/collections.spec.ts+++ b/packages/dashboard/e2e/collections.spec.ts@@ -36,6 +36,23 @@ test.describe('collections management', () => {await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })})+ // Filled by the probes in src/testing/slot-probes.tsx.+ test('renders the plugin slots on the create and edit pages', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, COLLECTIONS_PATH(creds.store_id), CTA)++ await page.getByRole('button', { name: CTA }).click()+ await expect(page.getByText('Slot probe: collection.form_main (new)')).toBeVisible()+ await expect(page.getByText('Slot probe: collection.form_sidebar (new)')).toBeVisible()++ await page.locator('#collection-name').fill(`E2E Slots ${Date.now()}`)+ await page.getByRole('button', { name: /^save$/i }).click()+ await expect(page.getByText('Slot probe: collection.form_main (edit)')).toBeVisible({+ timeout: 15_000,+ })+ await expect(page.getByText('Slot probe: collection.form_sidebar (edit)')).toBeVisible()+ })+test('edits the name and default sorting', async ({ page }) => {const creds = await login(page)await gotoIndex(page, COLLECTIONS_PATH(creds.store_id), CTA)diff --git a/packages/dashboard/e2e/customer-groups.spec.ts b/packages/dashboard/e2e/customer-groups.spec.tsindex 580a808075..a00da6325c 100644--- a/packages/dashboard/e2e/customer-groups.spec.ts+++ b/packages/dashboard/e2e/customer-groups.spec.ts@@ -11,6 +11,8 @@ async function createCustomerGroup(page: Page, attrs: { name: string; descriptioawait page.locator('#name').fill(attrs.name)if (attrs.description) await page.locator('#description').fill(attrs.description)+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: customer_group.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create customer group/i }).click()}diff --git a/packages/dashboard/e2e/customers.spec.ts b/packages/dashboard/e2e/customers.spec.tsindex 003e704f83..9999b2e3d2 100644--- a/packages/dashboard/e2e/customers.spec.ts+++ b/packages/dashboard/e2e/customers.spec.ts@@ -64,6 +64,15 @@ test.describe('customers', () => {await expect(ordersCard.locator('[data-slot="card-title"]')).toHaveText('Orders')})+ // Filled by the probes in src/testing/slot-probes.tsx.+ test('renders the plugin slot at the end of the main column', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)+ await createCustomer(page, `e2e-slots-${Date.now()}@example.com`)++ await expect(page.getByText('Slot probe: customer.form_main')).toBeVisible()+ })+test('edits a customer profile', async ({ page }) => {const creds = await login(page)await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)diff --git a/packages/dashboard/e2e/delivery-settings.spec.ts b/packages/dashboard/e2e/delivery-settings.spec.tsindex b1a01dc83f..4561d9c546 100644--- a/packages/dashboard/e2e/delivery-settings.spec.ts+++ b/packages/dashboard/e2e/delivery-settings.spec.ts@@ -34,6 +34,16 @@ test.describe('delivery profiles', () => {await expect(page.getByText(/^default$/i).first()).toBeVisible({ timeout: 15_000 })})+ // Filled by the probes in src/testing/slot-probes.tsx.+ test('renders the plugin slots on a profile page', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, DELIVERY_PROFILES_PATH(creds.store_id), PROFILE_CTA)+ await createProfile(page, `E2E Slots ${Date.now()}`)++ await expect(page.getByText('Slot probe: delivery_profile.form_main')).toBeVisible()+ await expect(page.getByText('Slot probe: delivery_profile.form_sidebar')).toBeVisible()+ })+test('creates a profile, a zone inside it, and a method inside the zone', async ({ page }) => {const creds = await login(page)await gotoIndex(page, DELIVERY_PROFILES_PATH(creds.store_id), PROFILE_CTA)@@ -65,6 +75,8 @@ test.describe('delivery profiles', () => {await zoneSheet.getByPlaceholder(/search countries and regions/i).fill('United States')await zoneSheet.getByRole('checkbox', { name: /^united states$/i }).check()+ // The sheets' plugin slots, filled by src/testing/slot-probes.tsx.+ await expect(zoneSheet.getByText('Slot probe: delivery_zone.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create delivery zone/i }).click()await expect(page.getByText(zoneName)).toBeVisible({ timeout: 15_000 })@@ -89,6 +101,9 @@ test.describe('delivery profiles', () => {await expect(page.getByRole('dialog').getByText(/^zone$/i)).toHaveCount(0)await page.getByRole('dialog').locator('#name').fill(methodName)+ await expect(+ page.getByRole('dialog').getByText('Slot probe: delivery_method.form_fields (new)'),+ ).toBeVisible()await page.getByRole('button', { name: /create delivery method/i }).click()// Saving closes the sheet and the method appears under its zone.diff --git a/packages/dashboard/e2e/global-setup.ts b/packages/dashboard/e2e/global-setup.tsindex 5ff9a57b88..f8609bf430 100644--- a/packages/dashboard/e2e/global-setup.ts+++ b/packages/dashboard/e2e/global-setup.ts@@ -50,6 +50,7 @@ import {ASYNC_JOBS_INITIALIZER,CREDENTIALS_FILE,RAILS_PID_FILE,+ SLOT_PROBES_INITIALIZER,TEST_INTEGRATION_INITIALIZER,} from './paths'import { API_GEM_DIR, rmIfExists, runRailsBootstrap, startRails } from './rails'@@ -239,6 +240,23 @@ export default async function globalSetup() {].join('\n'),)+ writeFileSync(+ SLOT_PROBES_INITIALIZER,+ [+ '# Written by packages/dashboard/e2e/global-setup.ts — safe to delete.',+ "if ENV['DASHBOARD_E2E'] == '1'",+ ' Rails.application.config.after_initialize do',+ ' [Spree::Media, Spree::TaxRate, Spree::Variant].each do |model|',+ ' next if model.additional_permitted_attributes.include?({ metadata: {} })',+ '',+ ' model.additional_permitted_attributes += [{ metadata: {} }]',+ ' end',+ ' end',+ 'end',+ '',+ ].join('\n'),+ )+const credentials = runRailsBootstrap(BOOTSTRAP_RUBY, RAILS_ENV)writeFileSync(CREDENTIALS_FILE, credentials)diff --git a/packages/dashboard/e2e/global-teardown.ts b/packages/dashboard/e2e/global-teardown.tsindex 83302035c3..bb9a0ee8df 100644--- a/packages/dashboard/e2e/global-teardown.ts+++ b/packages/dashboard/e2e/global-teardown.ts@@ -1,8 +1,14 @@-import { ASYNC_JOBS_INITIALIZER, RAILS_PID_FILE, TEST_INTEGRATION_INITIALIZER } from './paths'+import {+ ASYNC_JOBS_INITIALIZER,+ RAILS_PID_FILE,+ SLOT_PROBES_INITIALIZER,+ TEST_INTEGRATION_INITIALIZER,+} from './paths'import { rmIfExists, stopRails } from './rails'export default async function globalTeardown() {rmIfExists(ASYNC_JOBS_INITIALIZER)rmIfExists(TEST_INTEGRATION_INITIALIZER)+ rmIfExists(SLOT_PROBES_INITIALIZER)await stopRails(RAILS_PID_FILE)}diff --git a/packages/dashboard/e2e/markets.spec.ts b/packages/dashboard/e2e/markets.spec.tsindex 9efff2b47f..6ba6f5b773 100644--- a/packages/dashboard/e2e/markets.spec.ts+++ b/packages/dashboard/e2e/markets.spec.ts@@ -35,6 +35,8 @@ async function createMarket(await addSupportedLocale(page, locale)}+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: market.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create market/i }).click()}diff --git a/packages/dashboard/e2e/media-library.spec.ts b/packages/dashboard/e2e/media-library.spec.tsindex 8a9f330f93..ccfaa2816c 100644--- a/packages/dashboard/e2e/media-library.spec.ts+++ b/packages/dashboard/e2e/media-library.spec.ts@@ -153,6 +153,36 @@ test.describe('media library', () => {await page.unrouteAll({ behavior: 'ignoreErrors' })})+ // The probes in src/testing/slot-probes.tsx stand in for a plugin.+ test('a plugin field saves with the file and a plugin item joins the grid menu', async ({+ page,+ }) => {+ const creds = await login(page)+ await page.goto(MEDIA_PATH(creds.store_id))+ await expect(page.getByRole('heading', { name: /^media$/i })).toBeVisible({ timeout: 15_000 })++ const name = `e2e-slots-${Date.now()}.png`+ await uploadImage(page, name)++ const tile = await findTile(page, name)+ await tile.click({ button: 'right' })+ await expect(page.getByRole('menuitem', { name: 'Probe menu action' })).toBeVisible()+ await page.keyboard.press('Escape')++ await tile.click()+ const sheet = page.getByRole('dialog')+ await sheet.getByLabel('Probe library credit').fill('Photo by Jane')+ await sheet.getByRole('button', { name: /^save$/i }).click()+ await expect(page.getByText(/^saved$/i).first()).toBeVisible({ timeout: 15_000 })+ await sheet.getByRole('button', { name: /^cancel$/i }).click()++ await page.reload()+ await (await findTile(page, name)).click()+ await expect(page.getByRole('dialog').getByLabel('Probe library credit')).toHaveValue(+ 'Photo by Jane',+ )+ })+test('deletes a file from the grid after confirming', async ({ page }) => {const creds = await login(page)await page.goto(MEDIA_PATH(creds.store_id))diff --git a/packages/dashboard/e2e/option-types.spec.ts b/packages/dashboard/e2e/option-types.spec.tsindex 13c3042e6a..8b5392ce23 100644--- a/packages/dashboard/e2e/option-types.spec.ts+++ b/packages/dashboard/e2e/option-types.spec.ts@@ -27,6 +27,8 @@ async function createOptionType(await row.getByLabel('Label').fill(value.label)}+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: option_type.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create option type/i }).click()}diff --git a/packages/dashboard/e2e/orders.spec.ts b/packages/dashboard/e2e/orders.spec.tsindex d62912251f..f6e60edd67 100644--- a/packages/dashboard/e2e/orders.spec.ts+++ b/packages/dashboard/e2e/orders.spec.ts@@ -98,6 +98,8 @@ test.describe('new order', () => {await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/orders/or_[^/]+$`), {timeout: 15_000,})+ // The main column's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: order.form_main')).toBeVisible()})// The motivating case for this form: a purchase order arrives by email anddiff --git a/packages/dashboard/e2e/package-types.spec.ts b/packages/dashboard/e2e/package-types.spec.tsindex bbef19c4d1..6418778bf4 100644--- a/packages/dashboard/e2e/package-types.spec.ts+++ b/packages/dashboard/e2e/package-types.spec.ts@@ -11,6 +11,8 @@ async function createPackageType(page: Page, name: string) {await page.locator('#package-type-width').fill('30')await page.locator('#package-type-height').fill('20')await page.locator('#package-type-weight').fill('0.5')+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: package_type.form_fields (new)')).toBeVisible()await page.getByRole('dialog').getByRole('button', { name: /^save$/i })diff --git a/packages/dashboard/e2e/paths.ts b/packages/dashboard/e2e/paths.tsindex 4808b9b07b..20039301ee 100644--- a/packages/dashboard/e2e/paths.ts+++ b/packages/dashboard/e2e/paths.ts@@ -17,6 +17,13 @@ export const TEST_INTEGRATION_INITIALIZER = resolve(E2E_DIR,'../../../spree/api/spec/dummy/config/initializers/zz_dashboard_e2e_integration.rb',)+// What the slot probes' fields write (src/testing/slot-probes.tsx), permitted+// the way an extension permits its own attributes. Written and removed+// alongside the files above.+export const SLOT_PROBES_INITIALIZER = resolve(+ E2E_DIR,+ '../../../spree/api/spec/dummy/config/initializers/zz_dashboard_e2e_slot_probes.rb',+)// The first-run setup suite runs its own Rails against its own database, so// its state files live apart from the main suite's.export const FIRST_RUN_CREDENTIALS_FILE = resolve(E2E_DIR, '.first-run.json')diff --git a/packages/dashboard/e2e/policies.spec.ts b/packages/dashboard/e2e/policies.spec.tsindex 2d9e984918..b42367dedf 100644--- a/packages/dashboard/e2e/policies.spec.ts+++ b/packages/dashboard/e2e/policies.spec.ts@@ -8,6 +8,8 @@ async function createPolicy(page: Page, name: string) {await page.getByRole('button', { name: CTA }).click()await expect(page.getByRole('heading', { name: /^add policy$/i })).toBeVisible()await page.locator('#policy-name').fill(name)+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: policy.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create policy/i }).click()await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })}diff --git a/packages/dashboard/e2e/product-types.spec.ts b/packages/dashboard/e2e/product-types.spec.tsindex 15fb766fe5..c1b6783d11 100644--- a/packages/dashboard/e2e/product-types.spec.ts+++ b/packages/dashboard/e2e/product-types.spec.ts@@ -20,6 +20,8 @@ test.describe('product types', () => {await expect(page.getByRole('heading', { name: /new product type/i })).toBeVisible()await page.locator('#name').fill(name)+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: product_type.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create product type/i }).click()await expect(page.getByText(name)).toBeVisible({ timeout: 15_000 })diff --git a/packages/dashboard/e2e/products-edit-media-variants.spec.ts b/packages/dashboard/e2e/products-edit-media-variants.spec.tsindex 9dc887c923..9e77923283 100644--- a/packages/dashboard/e2e/products-edit-media-variants.spec.ts+++ b/packages/dashboard/e2e/products-edit-media-variants.spec.ts@@ -105,7 +105,7 @@ test.describe('edit product — media variant linking', () => {// Open the sheet, type new alt text, click Done.await clickMediaThumbnailAction(media, 'edit')const sheet = page.getByRole('dialog')- const altInput = sheet.getByRole('textbox')+ const altInput = sheet.getByLabel('Alt text')const newAlt = `Alt text ${Date.now()}`await altInput.fill(newAlt)await sheet.getByRole('button', { name: /^done$/i }).click()@@ -121,13 +121,13 @@ test.describe('edit product — media variant linking', () => {await page.reload()await expect(media.locator('img[src]').first()).toBeVisible({ timeout: 30_000 })await clickMediaThumbnailAction(media, 'edit')- await expect(sheet.getByRole('textbox')).toHaveValue(newAlt)+ await expect(sheet.getByLabel('Alt text')).toHaveValue(newAlt)// ---- Regression: Cancel after editing must actually discard. ----// The earlier implementation used form.reset(..., { keepDirtyValues:true })// which PRESERVES dirty values rather than restoring the snapshot — so// Cancel was a silent no-op for any edit the user actually made.- await sheet.getByRole('textbox').fill('TYPED THEN CANCELLED')+ await sheet.getByLabel('Alt text').fill('TYPED THEN CANCELLED')await sheet.getByRole('button', { name: /^cancel$/i }).click()await expect(page.getByRole('heading', { name: /^edit media$/i })).toBeHidden()@@ -137,6 +137,6 @@ test.describe('edit product — media variant linking', () => {// acceptable trade-off for a per-field-scoped restore that doesn't// accidentally wipe sibling edits.)await clickMediaThumbnailAction(media, 'edit')- await expect(sheet.getByRole('textbox')).toHaveValue(newAlt)+ await expect(sheet.getByLabel('Alt text')).toHaveValue(newAlt)})})diff --git a/packages/dashboard/e2e/products-slots.spec.ts b/packages/dashboard/e2e/products-slots.spec.tsnew file mode 100644index 0000000000..64b3cdb301--- /dev/null+++ b/packages/dashboard/e2e/products-slots.spec.ts@@ -0,0 +1,134 @@+import * as path from 'node:path'+import { fileURLToPath } from 'node:url'+import { expect, type Page, test } from '@playwright/test'+import { gotoIndex, login } from './helpers'+import {+ addOptionToVariants,+ clickMediaThumbnailAction,+ createProduct,+ mediaCard,+ PRODUCTS_PATH,+ seedOptionType,+ variantsCard,+} from './products-helpers'++// The slots plugins extend the product page with, filled by the probes in+// src/testing/slot-probes.tsx. A host-form field proves the slot renders+// inside the product form and saves with its Save button.++const FIXTURE_IMAGE = path.join(+ path.dirname(fileURLToPath(import.meta.url)),+ 'fixtures/test-image.png',+)++async function saveProduct(page: Page) {+ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByRole('button', { name: /save product/i })).toBeDisabled({+ timeout: 30_000,+ })+}++test.describe('product page slots', () => {+ test('renders the column slots on the create and edit pages', async ({ page }) => {+ const creds = await login(page)++ await gotoIndex(page, PRODUCTS_PATH(creds.store_id), /add product/i)+ await page.getByRole('button', { name: /add product/i }).click()+ await expect(page.getByText('Slot probe: product.form_main (new)')).toBeVisible()+ await expect(page.getByText('Slot probe: product.form_sidebar (new)')).toBeVisible()++ await createProduct(page, creds.store_id, `E2E Slots ${Date.now()}`)+ await expect(page.getByText('Slot probe: product.form_main (edit)')).toBeVisible()+ await expect(page.getByText('Slot probe: product.form_sidebar (edit)')).toBeVisible()+ })++ test('a media sheet field saves with the product and Cancel discards it', async ({ page }) => {+ const creds = await login(page)+ await createProduct(page, creds.store_id, `E2E Media Slot ${Date.now()}`)++ const media = mediaCard(page)+ await media.locator('input[type="file"]').setInputFiles(FIXTURE_IMAGE)+ await expect(media.locator('.animate-spin')).toHaveCount(0, { timeout: 15_000 })+ await saveProduct(page)+ await page.reload()++ await clickMediaThumbnailAction(media, 'edit')+ const sheet = page.getByRole('dialog')+ await sheet.getByLabel('Probe media credit').fill('Photo by Jane')+ await sheet.getByRole('button', { name: /^done$/i }).click()+ await saveProduct(page)++ await page.reload()+ await clickMediaThumbnailAction(media, 'edit')+ await expect(sheet.getByLabel('Probe media credit')).toHaveValue('Photo by Jane')++ await sheet.getByLabel('Probe media credit').fill('Typed then cancelled')+ await sheet.getByRole('button', { name: /^cancel$/i }).click()+ await clickMediaThumbnailAction(media, 'edit')+ await expect(sheet.getByLabel('Probe media credit')).toHaveValue('Photo by Jane')+ })++ test('media added by a media actions widget saves with the product', async ({ page }) => {+ const creds = await login(page)+ await createProduct(page, creds.store_id, `E2E Media Action ${Date.now()}`)++ const media = mediaCard(page)+ await media.getByRole('button', { name: 'Probe attach video' }).click()+ await expect(media.locator('[data-slot="media-thumbnail"]')).toHaveCount(1)+ await saveProduct(page)++ await page.reload()+ await expect(media.locator('[data-slot="media-thumbnail"]')).toHaveCount(1, {+ timeout: 30_000,+ })+ })++ // A simple product's only variant is dropped as a placeholder unless the+ // merchant set something on it — a plugin's field counts.+ test('a variant sheet field set on the new product page is created with it', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRODUCTS_PATH(creds.store_id), /add product/i)+ await page.getByRole('button', { name: /add product/i }).click()+ await page.getByLabel(/^name$/i).fill(`E2E New Variant Slot ${Date.now()}`)++ const variants = variantsCard(page)+ await variants+ .getByRole('button', { name: /^edit /i })+ .first()+ .click()+ const sheet = page.getByRole('dialog')+ await sheet.getByLabel('Probe variant code').fill('ACME-SIMPLE')+ await sheet.getByRole('button', { name: /^done$/i }).click()+ await page.getByRole('button', { name: /^create product$/i }).click()+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/products/prod_[^/]+$`), {+ timeout: 15_000,+ })++ await variants+ .getByRole('button', { name: /^edit /i })+ .first()+ .click()+ await expect(page.getByRole('dialog').getByLabel('Probe variant code')).toHaveValue(+ 'ACME-SIMPLE',+ { timeout: 15_000 },+ )+ })++ test('a variant sheet field saves with the product', async ({ page }) => {+ const creds = await login(page)+ const colorLabel = await seedOptionType(page, creds.store_id, 'color', ['red'])+ await createProduct(page, creds.store_id, `E2E Variant Slot ${Date.now()}`)+ await addOptionToVariants(page, colorLabel, ['Red'])++ const variants = variantsCard(page)+ await variants.getByRole('button', { name: /^edit .*\bred$/i }).click()+ const sheet = page.getByRole('dialog')+ await sheet.getByLabel('Probe variant code').fill('ACME-RED')+ await sheet.getByRole('button', { name: /^done$/i }).click()+ await saveProduct(page)++ await page.reload()+ await variants.getByRole('button', { name: /^edit .*\bred$/i }).click()+ await expect(page.getByRole('dialog').getByLabel('Probe variant code')).toHaveValue('ACME-RED')+ })+})diff --git a/packages/dashboard/e2e/purchase-orders.spec.ts b/packages/dashboard/e2e/purchase-orders.spec.tsindex 895df5140e..15c4c24058 100644--- a/packages/dashboard/e2e/purchase-orders.spec.ts+++ b/packages/dashboard/e2e/purchase-orders.spec.ts@@ -245,6 +245,15 @@ test.describe('purchase orders', () => {await expect(page.getByText(/^cancelled$/i).first()).toBeVisible({ timeout: 15_000 })})+ // Filled by the probes in src/testing/slot-probes.tsx.+ test('renders the plugin slot at the end of the main column', async ({ page }) => {+ const creds = await login(page)+ const purchaseOrder = await createPurchaseOrder(page, creds.accessToken, { quantity: 1 })+ await openPurchaseOrder(page, creds.store_id, purchaseOrder)++ await expect(page.getByText('Slot probe: purchase_order.form_main')).toBeVisible()+ })+test('deletes a draft from the list', async ({ page }) => {const creds = await login(page)const purchaseOrder = await createPurchaseOrder(page, creds.accessToken, { quantity: 1 })diff --git a/packages/dashboard/e2e/stock-locations.spec.ts b/packages/dashboard/e2e/stock-locations.spec.tsindex 9577864b23..f81e1839b6 100644--- a/packages/dashboard/e2e/stock-locations.spec.ts+++ b/packages/dashboard/e2e/stock-locations.spec.ts@@ -8,6 +8,8 @@ async function createStockLocation(page: Page, name: string) {await page.getByRole('button', { name: /add stock location/i }).click()await expect(page.getByRole('heading', { name: /add stock location/i })).toBeVisible()await page.locator('#name').fill(name)+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: stock_location.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create stock location/i }).click()}diff --git a/packages/dashboard/e2e/stock-transfers.spec.ts b/packages/dashboard/e2e/stock-transfers.spec.tsindex 0c390cc88a..a777d0ca09 100644--- a/packages/dashboard/e2e/stock-transfers.spec.ts+++ b/packages/dashboard/e2e/stock-transfers.spec.ts@@ -157,6 +157,17 @@ test.describe('stock transfers', () => {await expect(page.getByText(/receive a delivery/i)).toHaveCount(0)})+ // Filled by the probes in src/testing/slot-probes.tsx.+ test('renders the plugin slot at the end of the main column', async ({ page }) => {+ const creds = await login(page)+ const draft = await createDraftTransfer(page, creds.accessToken, 1)++ await page.goto(`${TRANSFERS_PATH(creds.store_id)}/${draft.id}`)+ await expect(page.getByText('Slot probe: stock_transfer.form_main')).toBeVisible({+ timeout: 15_000,+ })+ })+test('a draft can be corrected, a shipped one cannot', async ({ page }) => {const creds = await login(page)const draft = await createDraftTransfer(page, creds.accessToken, 3)diff --git a/packages/dashboard/e2e/tax-categories.spec.ts b/packages/dashboard/e2e/tax-categories.spec.tsindex 9762c0c8e5..0820e1c25d 100644--- a/packages/dashboard/e2e/tax-categories.spec.ts+++ b/packages/dashboard/e2e/tax-categories.spec.ts@@ -15,6 +15,8 @@ async function createTaxCategory(if (attrs.taxCode) await page.locator('#tax_code').fill(attrs.taxCode)if (attrs.description) await page.locator('#description').fill(attrs.description)+ // The sheet's plugin slot, filled by src/testing/slot-probes.tsx.+ await expect(page.getByText('Slot probe: tax_category.form_fields (new)')).toBeVisible()await page.getByRole('button', { name: /create tax category/i }).click()}diff --git a/packages/dashboard/e2e/tax-rates.spec.ts b/packages/dashboard/e2e/tax-rates.spec.tsindex 69bf185884..88759d6478 100644--- a/packages/dashboard/e2e/tax-rates.spec.ts+++ b/packages/dashboard/e2e/tax-rates.spec.ts@@ -68,6 +68,26 @@ test.describe('tax rates', () => {await expect(row.getByText('12.5%')).toBeVisible({ timeout: 15_000 })})+ // The probes in src/testing/slot-probes.tsx stand in for a plugin.+ test('a plugin field in the rate sheet saves with the rate', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, TAX_RATES_PATH(creds.store_id), CTA)++ const name = `E2E Slot Rate ${Date.now()}`+ await createTaxRate(page, { name, ratePercent: '10' })+ await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })+ await rowButton(page, name).click()+ await expect(page.locator('#rate_percent')).toHaveValue('10', { timeout: 15_000 })+ await page.getByLabel('Probe tax rate note').fill('Filed with the regulator')+ await page.getByRole('button', { name: /^save$/i }).click()+ await expect(page.getByRole('dialog')).toBeHidden({ timeout: 15_000 })++ await rowButton(page, name).click()+ await expect(page.getByLabel('Probe tax rate note')).toHaveValue('Filed with the regulator', {+ timeout: 15_000,+ })+ })+// The API stores the fraction (0.07125); the form must read back exactly// what the merchant typed, not a rounded 7.13.test('keeps a rate with three decimals exactly', async ({ page }) => {diff --git a/packages/dashboard/playwright.config.ts b/packages/dashboard/playwright.config.tsindex 94927199ec..b8197e7697 100644--- a/packages/dashboard/playwright.config.ts+++ b/packages/dashboard/playwright.config.ts@@ -72,6 +72,9 @@ export default defineConfig({// `VITE_SPREE_API_URL` here would flip the SDK to absolute URLs and// break the cookie path the refresh flow depends on.VITE_API_PROXY_TARGET: `http://localhost:${RAILS_PORT}`,+ // Slot probes (src/testing/slot-probes.tsx). Preview mode serves a+ // build that already has them, so the build step sets it too.+ VITE_E2E_SLOT_PROBES: '1',},},{diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsxindex c57ad4ee15..546d3317b7 100644--- a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx@@ -1,7 +1,12 @@import { zodResolver } from '@hookform/resolvers/zod'import type { DeliveryProfile, DeliveryZone } from '@spree/admin-sdk'import { isDecimalString, isZeroMoney } from '@spree/core'-import { mapSpreeErrorsToForm } from '@spree/dashboard-core'+import {+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,+ mapSpreeErrorsToForm,+} from '@spree/dashboard-core'import {Button,Sheet,@@ -97,7 +102,11 @@ export function DeliveryMethodSheet({const form = useForm<DeliveryMethodFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(deliveryMethodFormSchema) as any,- defaultValues: { ...DELIVERY_METHOD_DEFAULTS, delivery_zone_id: zoneId ?? '' },+ defaultValues: {+ ...DELIVERY_METHOD_DEFAULTS,+ delivery_zone_id: zoneId ?? '',+ ...extensionFormValues('delivery_method', null),+ },})// A new method is seeded once, from values that owe nothing to any query.@@ -107,7 +116,11 @@ export function DeliveryMethodSheet({// in the other order.useEffect(() => {if (!editing) {- form.reset({ ...DELIVERY_METHOD_DEFAULTS, delivery_zone_id: zoneId ?? '' })+ form.reset({+ ...DELIVERY_METHOD_DEFAULTS,+ delivery_zone_id: zoneId ?? '',+ ...extensionFormValues('delivery_method', null),+ })}}, [editing, zoneId, form])@@ -155,6 +168,7 @@ export function DeliveryMethodSheet({product_ids: rule.product_ids,takes_products: takesProducts(ruleTypes?.data, rule.type),})),+ ...extensionFormValues('delivery_method', method),})}, [editing, method, ruleTypes, form])@@ -174,10 +188,14 @@ export function DeliveryMethodSheet({async function onSubmit(values: DeliveryMethodFormValues) {try {if (editing) {- await updateMutation.mutateAsync(deliveryMethodValuesToParams(values))+ await updateMutation.mutateAsync({+ ...deliveryMethodValuesToParams(values),+ ...extensionSubmitValues('delivery_method', form),+ })} else {await createMutation.mutateAsync({...deliveryMethodValuesToParams(values),+ ...extensionSubmitValues('delivery_method', form),delivery_profile_id: profile.id,// Only sent when the merchant added the method from a specific// group; otherwise the server files it under the zone's group, else@@ -224,6 +242,15 @@ export function DeliveryMethodSheet({// editing still needs the picker to move a method or clear it.zonePreselected={!methodId && !!zoneId}/>+ <HostFormSlot+ form={form}+ name="delivery_method.form_fields"+ context={{+ deliveryMethod: method,+ deliveryProfile: profile,+ mode: editing ? 'edit' : 'new',+ }}+ /></div><SheetFooter><Buttondiff --git a/packages/dashboard/src/components/spree/shipping/delivery-zone-sheet.tsx b/packages/dashboard/src/components/spree/shipping/delivery-zone-sheet.tsxindex 40ee8cdd8f..e53a174c89 100644--- a/packages/dashboard/src/components/spree/shipping/delivery-zone-sheet.tsx+++ b/packages/dashboard/src/components/spree/shipping/delivery-zone-sheet.tsx@@ -1,6 +1,11 @@import { zodResolver } from '@hookform/resolvers/zod'import type { DeliveryZone } from '@spree/admin-sdk'-import { mapSpreeErrorsToForm } from '@spree/dashboard-core'+import {+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,+ mapSpreeErrorsToForm,+} from '@spree/dashboard-core'import {Button,Field,@@ -36,6 +41,11 @@ import { DeliveryZoneRegionPicker } from './delivery-zone-region-picker'* that owns them and never move between profiles, so the profile always* comes from the page that opened this sheet.*/+// A new zone's starting values, extension fields' blanks included.+function blankZoneValues(): DeliveryZoneFormValues {+ return { ...DELIVERY_ZONE_DEFAULTS, ...extensionFormValues('delivery_zone', null) }+}+export function DeliveryZoneSheet({deliveryProfileId,deliveryOriginGroupId,@@ -69,12 +79,12 @@ export function DeliveryZoneSheet({const form = useForm<DeliveryZoneFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(deliveryZoneFormSchema) as any,- defaultValues: DELIVERY_ZONE_DEFAULTS,+ defaultValues: blankZoneValues(),})useEffect(() => {if (!zoneId) {- form.reset(DELIVERY_ZONE_DEFAULTS)+ form.reset(blankZoneValues())return}if (!zone) return@@ -94,19 +104,24 @@ export function DeliveryZoneSheet({postal_code_from: member.postal_code_from ?? '',postal_code_to: member.postal_code_to ?? '',})),+ ...extensionFormValues('delivery_zone', zone),})}, [zone, zoneId, form])async function onSubmit(values: DeliveryZoneFormValues) {try {if (zoneId) {- await updateMutation.mutateAsync(deliveryZoneValuesToParams(values))+ await updateMutation.mutateAsync({+ ...deliveryZoneValuesToParams(values),+ ...extensionSubmitValues('delivery_zone', form),+ })} else {- await createMutation.mutateAsync(- deliveryZoneValuesToParams(values, deliveryProfileId, deliveryOriginGroupId),- )+ await createMutation.mutateAsync({+ ...deliveryZoneValuesToParams(values, deliveryProfileId, deliveryOriginGroupId),+ ...extensionSubmitValues('delivery_zone', form),+ })}- form.reset(zoneId ? values : DELIVERY_ZONE_DEFAULTS)+ form.reset(zoneId ? values : blankZoneValues())onOpenChange(false)} catch (err) {if (!mapSpreeErrorsToForm(err, form.setError)) throw err@@ -120,7 +135,7 @@ export function DeliveryZoneSheet({<Sheetopen={open}onOpenChange={(next) => {- if (!next && !editing) form.reset(DELIVERY_ZONE_DEFAULTS)+ if (!next && !editing) form.reset(blankZoneValues())onOpenChange(next)}}>@@ -155,6 +170,15 @@ export function DeliveryZoneSheet({form={form}siblingZones={siblingZones.filter((sibling) => sibling.id !== zoneId)}/>+ <HostFormSlot+ form={form}+ name="delivery_zone.form_fields"+ context={{+ deliveryZone: zone,+ deliveryProfileId,+ mode: editing ? 'edit' : 'new',+ }}+ /></div><SheetFooter><Buttondiff --git a/packages/dashboard/src/main.tsx b/packages/dashboard/src/main.tsxindex ddd4598f2d..d176970f7a 100644--- a/packages/dashboard/src/main.tsx+++ b/packages/dashboard/src/main.tsx@@ -12,6 +12,10 @@ import 'virtual:spree-dashboard-plugins'import './styles.css'import { routeTree } from './routeTree.gen'+// The end-to-end suite fills the extension slots with probes. The flag is+// unset in every other build, so the branch and its chunk are dropped.+if (import.meta.env.VITE_E2E_SLOT_PROBES === '1') await import('./testing/slot-probes')+// basepath mirrors Vite's `base` so sub-path mounts (/dashboard on the// single-node topology) route correctly; '/' in dev and root deploys.const router = createDashboardRouter(routeTree, { basepath: import.meta.env.BASE_URL })diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsxindex 97bc3b966b..8e76a0392c 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx@@ -123,6 +123,7 @@ function CustomerBody({ customer }: { customer: Customer }) {emptyTitle={t('admin.components.metadata_card.empty_title')}emptyDescription={t('admin.components.metadata_card.empty_description')}/>+ <Slot name="customer.form_main" context={{ customer }} /></>}sidebar={diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/customers/groups.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/customers/groups.tsxindex e1840d5f04..dfe3203470 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/customers/groups.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/customers/groups.tsx@@ -3,6 +3,9 @@ import type { CustomerGroup, CustomerGroupCreateParams } from '@spree/admin-sdk'import {adminClient,Can,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,mapSpreeErrorsToForm,ResourceTable,resourceSearchSchema,@@ -155,14 +158,15 @@ function CreateCustomerGroupSheet({const form = useForm<CustomerGroupFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(customerGroupFormSchema) as any,- defaultValues: CUSTOMER_GROUP_DEFAULTS,+ defaultValues: { ...CUSTOMER_GROUP_DEFAULTS, ...extensionFormValues('customer_group', null) },})async function onSubmit(values: CustomerGroupFormValues) {try {- await createMutation.mutateAsync(- customerGroupValuesToParams(values) as CustomerGroupCreateParams,- )+ await createMutation.mutateAsync({+ ...(customerGroupValuesToParams(values) as CustomerGroupCreateParams),+ ...extensionSubmitValues('customer_group', form),+ })form.reset(CUSTOMER_GROUP_DEFAULTS)onOpenChange(false)} catch (err) {@@ -186,6 +190,11 @@ function CreateCustomerGroupSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><NameDescriptionFields form={form} />+ <HostFormSlot+ form={form}+ name="customer_group.form_fields"+ context={{ customerGroup: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -233,13 +242,17 @@ function EditCustomerGroupSheet({form.reset({name: group.name,description: group.description ?? '',+ ...extensionFormValues('customer_group', group),})}}, [group, form])async function onSubmit(values: CustomerGroupFormValues) {try {- await updateMutation.mutateAsync(customerGroupValuesToParams(values))+ await updateMutation.mutateAsync({+ ...customerGroupValuesToParams(values),+ ...extensionSubmitValues('customer_group', form),+ })form.reset(values)onOpenChange(false)} catch (err) {@@ -268,6 +281,11 @@ function EditCustomerGroupSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><NameDescriptionFields form={form} />+ <HostFormSlot+ form={form}+ name="customer_group.form_fields"+ context={{ customerGroup: group, mode: 'edit' }}+ /><MembersSummarycount={group?.customers_count ?? 0}href={`/${storeId}/customers?filters=${encodeURIComponent(membersFilter)}`}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/index.tsxindex 31949c1d3e..1e91f79fbd 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/index.tsx@@ -96,6 +96,7 @@ function OrderDetailPage() {emptyTitle={t('admin.components.metadata_card.empty_title')}emptyDescription={t('admin.components.metadata_card.empty_description')}/>+ <Slot name="order.form_main" context={{ order }} /></>}sidebar={diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex f4e9c1ddde..3b47c9f4d9 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -22,6 +22,7 @@ import {TaxCard,VariantsCard,variantToWirePayload,+ withExtensionRowValues,} from '@spree/dashboard-core'import {ErrorState,@@ -171,10 +172,17 @@ function ProductForm({ product }: { product: Product }) {const current = form.getValues('media') ?? []if (current.length > 0) returnif (form.formState.dirtyFields?.media) return- form.setValue('media', mediaItems.map(mediaToFormValues), { shouldDirty: false })+ form.setValue(+ 'media',+ mediaItems.map((media, index) => mediaToFormValues(media, index)),+ { shouldDirty: false },+ )}, [mediaItems, form])- const onSubmit = async (data: ProductFormValues) => {+ const onSubmit = async (submitted: ProductFormValues) => {+ // Media and variant rows get their extension fields back from live form+ // state, which the parse behind `submitted` stripped.+ const data = withExtensionRowValues('product', submitted, form.getValues())const { variants, media, ...rest } = data// Extension fields come from live form state: the Zod parse behind// `data` strips keys the first-party schema doesn't know.@@ -238,7 +246,11 @@ function ProductForm({ product }: { product: Product }) {// read: a failed refetch keeps the stale list in `data`.const mediaRefetch = await refetchMedia()if (mediaRefetch.status === 'success' && !form.formState.dirtyFields.media) {- form.resetField('media', { defaultValue: mediaRefetch.data.data.map(mediaToFormValues) })+ form.resetField('media', {+ defaultValue: mediaRefetch.data.data.map((media, index) =>+ mediaToFormValues(media, index),+ ),+ })}toastManager.add({ type: 'success', title: t('admin.messages.product_saved') })} catch (err) {@@ -265,9 +277,10 @@ function ProductForm({ product }: { product: Product }) {}return (- // 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 exposes the form to slot widgets: a `product.*` extension+ // (the page columns, the media and variant sheets) 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 && (@@ -325,6 +338,7 @@ function ProductForm({ product }: { product: Product }) {emptyTitle={t('admin.components.metadata_card.empty_title')}emptyDescription={t('admin.components.metadata_card.empty_description')}/>+ <Slot name="product.form_main" context={{ product, mode: 'edit' }} /></>}sidebar={@@ -344,7 +358,7 @@ function ProductForm({ product }: { product: Product }) {<CategorizationCard form={form} /><TaxCard form={form} /><SEOCard form={form} product={product} />- <Slot name="product.form_sidebar" context={{ product }} />+ <Slot name="product.form_sidebar" context={{ product, mode: 'edit' }} /></>}/>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsxindex 31c53c469c..a9629b98ee 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx@@ -165,11 +165,16 @@ function CategoryDetail({ categoryId, storeId }: { categoryId: string; storeId:}}/>}- main={<CategoryMain form={form} category={category} />}+ main={+ <>+ <CategoryMain form={form} category={category} />+ <Slot name="category.form_main" context={{ category, mode: 'edit' }} />+ </>+ }sidebar={<><CategorySidebar form={form} category={category} />- <Slot name="category.form_sidebar" context={{ category }} />+ <Slot name="category.form_sidebar" context={{ category, mode: 'edit' }} /></>}/>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsxindex 50eb5d2e5a..60a6aa92ba 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/new.tsx@@ -5,6 +5,7 @@ import {extensionSubmitValues,mapSpreeErrorsToForm,PageHeader,+ Slot,} from '@spree/dashboard-core'import {FormActions,@@ -85,8 +86,18 @@ function NewCategoryPage() {actions={<FormActions form={form} saveLabel={t('admin.actions.save')} />}/>}- main={<CategoryMain form={form} />}- sidebar={<CategorySidebar form={form} />}+ main={+ <>+ <CategoryMain form={form} />+ <Slot name="category.form_main" context={{ category: undefined, mode: 'new' }} />+ </>+ }+ sidebar={+ <>+ <CategorySidebar form={form} />+ <Slot name="category.form_sidebar" context={{ category: undefined, mode: 'new' }} />+ </>+ }/></form></FormProvider>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/$collectionId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/$collectionId.tsxindex 959c373372..c077871412 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/$collectionId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/$collectionId.tsx@@ -179,11 +179,16 @@ function CollectionDetail({ collectionId, storeId }: { collectionId: string; sto}}/>}- main={<CollectionMain form={form} collection={collection} />}+ main={+ <>+ <CollectionMain form={form} collection={collection} />+ <Slot name="collection.form_main" context={{ collection, mode: 'edit' }} />+ </>+ }sidebar={<><CollectionSidebar form={form} collection={collection} />- <Slot name="collection.form_sidebar" context={{ collection }} />+ <Slot name="collection.form_sidebar" context={{ collection, mode: 'edit' }} /></>}/>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/new.tsxindex 25ec489f1a..8b3c865115 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/collections/new.tsx@@ -5,6 +5,7 @@ import {extensionSubmitValues,mapSpreeErrorsToForm,PageHeader,+ Slot,} from '@spree/dashboard-core'import {FormActions,@@ -85,8 +86,21 @@ function NewCollectionPage() {actions={<FormActions form={form} saveLabel={t('admin.actions.save')} />}/>}- main={<CollectionMain form={form} />}- sidebar={<CollectionSidebar form={form} />}+ main={+ <>+ <CollectionMain form={form} />+ <Slot name="collection.form_main" context={{ collection: undefined, mode: 'new' }} />+ </>+ }+ sidebar={+ <>+ <CollectionSidebar form={form} />+ <Slot+ name="collection.form_sidebar"+ context={{ collection: undefined, mode: 'new' }}+ />+ </>+ }/></form></FormProvider>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/media.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/media.tsxindex e1e565689a..8b904424e4 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/media.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/media.tsx@@ -2,8 +2,12 @@ import type { Media, MediaUsageReference } from '@spree/admin-sdk'import {adminClient,Can,+ extensionFormValues,+ extensionSubmitValues,ImageUploadField,+ mapSpreeErrorsToForm,PageHeader,+ Slot,Subject,useFileUpload,usePermissions,@@ -47,7 +51,8 @@ import {UploadIcon,} from '@spree/dashboard-ui/icons'import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'-import { useDeferredValue, useRef, useState } from 'react'+import { useDeferredValue, useEffect, useRef, useState } from 'react'+import { FormProvider, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod'import {@@ -353,6 +358,7 @@ function MediaLibraryPage() {{t('admin.media_library.download')}</ContextMenuItem>)}+ <Slot name="media.context_menu" context={{ media, canWrite }} />{canWrite && (<><ContextMenuSeparator />@@ -426,6 +432,14 @@ function MediaPlaceholderIcon({ media }: { media: Media }) {return <Icon className="size-6 text-muted-foreground" />}+interface MediaDetailFormValues {+ alt: string+}++function mediaDetailFormValues(media: Media): MediaDetailFormValues {+ return { alt: media.alt ?? '', ...extensionFormValues('media', media) }+}+function MediaDetailSheet({media,onOpenChange,@@ -440,11 +454,9 @@ function MediaDetailSheet({const confirm = useConfirm()const updateFile = useUpdateMediaLibraryFile()const usage = useMediaUsage(media?.id ?? null)- const [alt, setAlt] = useState('')- // Compared against what was last saved, not against the record the sheet- // opened with: that snapshot never refreshes, so after a successful save it- // would still hold the old alt and every close would ask to discard.- const [savedAlt, setSavedAlt] = useState('')+ // A host form for `media.form_fields` widgets: what they bind saves with the+ // sheet's Save, alongside the alt text.+ const form = useForm<MediaDetailFormValues>({ defaultValues: { alt: '' } })const [poster, setPoster] = useState<{signedId: string | nullpreviewUrl: string | null@@ -453,34 +465,43 @@ function MediaDetailSheet({// Seeded from the record each time a different file is opened, so typing is// not overwritten by a background refetch of the same row.+ // Cleared on close, so reopening the same file drops what was discarded.const [seededFor, setSeededFor] = useState<string | null>(null)+ if (!media && seededFor !== null) setSeededFor(null)if (media && seededFor !== media.id) {setSeededFor(media.id)- setAlt(media.alt ?? '')- setSavedAlt(media.alt ?? '')setPoster({ signedId: null, previewUrl: null, cleared: false })}+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the file, not on each refetch of it+ useEffect(() => {+ if (media) form.reset(mediaDetailFormValues(media))+ }, [seededFor, form])const references = usage.data?.data ?? []- const isDirty = !!media && alt !== savedAlt+ const isDirty = !!media && form.formState.isDirty// An explicit save, not save-on-blur: blur is invisible, so a merchant had// no way to tell whether their edit stuck.- function saveAlt() {+ async function save(values: MediaDetailFormValues) {if (!media || !isDirty) return- const submitted = alt- updateFile.mutate(- { id: media.id, alt: submitted },- {- onSuccess: () => {- setSavedAlt(submitted)- toastManager.add({ type: 'success', title: t('admin.messages.saved') })- },- onError: () => toastManager.add({ type: 'error', title: t('admin.errors.failed_to_save') }),- },- )+ try {+ await updateFile.mutateAsync({+ id: media.id,+ alt: values.alt,+ ...extensionSubmitValues('media', form),+ })+ // Re-baselined against what was just saved, not the record the sheet+ // opened with: that snapshot never refreshes, so after a save every+ // close would otherwise ask to discard.+ form.reset(form.getValues())+ toastManager.add({ type: 'success', title: t('admin.messages.saved') })+ } catch (error) {+ if (!mapSpreeErrorsToForm(error, form.setError)) {+ toastManager.add({ type: 'error', title: t('admin.errors.failed_to_save') })+ }+ }}// Closing with an unsaved edit would drop it silently, so ask first.@@ -496,8 +517,7 @@ function MediaDetailSheet({if (discard) onOpenChange(false)}- // The poster saves on the spot — picking a file is already an explicit act,- // and there is no surrounding form to carry it.+ // The poster saves on the spot — picking a file is already an explicit act.function savePoster(value: {signedId: string | nullpreviewUrl: string | null@@ -517,117 +537,125 @@ function MediaDetailSheet({<Sheet open={!!media} onOpenChange={handleOpenChange}><SheetContent className="w-full sm:max-w-md">{media && (- <>- <SheetHeader>- <SheetTitle>{media.filename || t('admin.media_library.file')}</SheetTitle>- <SheetDescription>- {media.attached- ? t('admin.media_library.placement.attached')- : t('admin.media_library.placement.unattached')}- </SheetDescription>- </SheetHeader>-- <div className="flex-1 space-y-5 overflow-y-auto p-4">- <MediaPreview- mediaType={media.media_type}- previewUrl={mediaPreviewUrl(media)}- videoUrl={media.video_url}- embedUrl={media.video_embed_url}- alt={media.alt ?? ''}- />-- {/* A video needs a still for gallery tiles, emails and every- listing that renders an <img>. YouTube supplies one; an- upload or a Vimeo link does not. */}- {media.media_type !== 'image' && canWrite && (- <ImageUploadField- label={t('admin.fields.media.poster.label')}- help={t('admin.fields.media.poster.help')}- serverUrl={media.poster_url}- value={poster}- onChange={savePoster}+ <FormProvider {...form}>+ {/* A form, so Enter in any field saves, like any single-field form. */}+ <form onSubmit={form.handleSubmit(save)} className="flex min-h-0 flex-1 flex-col">+ <SheetHeader>+ <SheetTitle>{media.filename || t('admin.media_library.file')}</SheetTitle>+ <SheetDescription>+ {media.attached+ ? t('admin.media_library.placement.attached')+ : t('admin.media_library.placement.unattached')}+ </SheetDescription>+ </SheetHeader>++ <div className="flex-1 space-y-5 overflow-y-auto p-4">+ <MediaPreview+ mediaType={media.media_type}+ previewUrl={mediaPreviewUrl(media)}+ videoUrl={media.video_url}+ embedUrl={media.video_embed_url}+ alt={form.watch('alt')}/>- )}- <Field>- <FieldLabel htmlFor="media-alt">{t('admin.fields.media.alt.label')}</FieldLabel>- <Input- id="media-alt"- value={alt}- disabled={!canWrite}- onChange={(e) => setAlt(e.target.value)}- // Enter saves, like any single-field form.- onKeyDown={(e) => {- if (e.key === 'Enter' && isDirty) {- e.preventDefault()- saveAlt()- }- }}- placeholder={t('admin.fields.media.alt.placeholder')}- />- </Field>+ {/* A video needs a still for gallery tiles, emails and every+ listing that renders an <img>. YouTube supplies one; an+ upload or a Vimeo link does not. */}+ {media.media_type !== 'image' && canWrite && (+ <ImageUploadField+ label={t('admin.fields.media.poster.label')}+ help={t('admin.fields.media.poster.help')}+ serverUrl={media.poster_url}+ value={poster}+ onChange={savePoster}+ />+ )}- <dl className="space-y-2 text-sm">- <FileFact label={t('admin.media_library.facts.type')} value={media.content_type} />- <FileFact- label={t('admin.media_library.facts.size')}- value={formatBytes(media.byte_size)}- />- </dl>-- <div>- <h3 className="mb-2 font-medium text-sm">{t('admin.media_library.usage.title')}</h3>- {usage.isLoading ? (- <Loader2Icon className="size-4 animate-spin text-muted-foreground" />- ) : references.length === 0 ? (- <p className="text-muted-foreground text-sm">- {t('admin.media_library.usage.empty')}+ {form.formState.errors.root?.message && (+ <p className="text-destructive text-sm" role="alert">+ {form.formState.errors.root.message}</p>- ) : (- <ul className="space-y-1.5">- {references.map((reference) => {- const target = usageLink(reference)-- return (- <li- key={`${reference.kind}-${reference.owner_type}-${reference.owner_id}-${reference.field}`}- className="flex items-center justify-between gap-2 text-sm"- >- {target ? (- <Link- to={target.to}- params={{ storeId, ...target.params }}- className="truncate underline-offset-4 hover:underline"- >- {reference.name}- </Link>- ) : (- <span className="truncate">{reference.name}</span>- )}- <Badge variant="secondary">{usageBadgeLabel(reference, t)}</Badge>- </li>- )- })}- </ul>)}++ <Field>+ <FieldLabel htmlFor="media-alt">{t('admin.fields.media.alt.label')}</FieldLabel>+ <Input+ id="media-alt"+ disabled={!canWrite}+ placeholder={t('admin.fields.media.alt.placeholder')}+ {...form.register('alt')}+ />+ </Field>++ <Slot name="media.form_fields" context={{ media, canWrite }} />++ <dl className="space-y-2 text-sm">+ <FileFact+ label={t('admin.media_library.facts.type')}+ value={media.content_type}+ />+ <FileFact+ label={t('admin.media_library.facts.size')}+ value={formatBytes(media.byte_size)}+ />+ </dl>++ <div>+ <h3 className="mb-2 font-medium text-sm">+ {t('admin.media_library.usage.title')}+ </h3>+ {usage.isLoading ? (+ <Loader2Icon className="size-4 animate-spin text-muted-foreground" />+ ) : references.length === 0 ? (+ <p className="text-muted-foreground text-sm">+ {t('admin.media_library.usage.empty')}+ </p>+ ) : (+ <ul className="space-y-1.5">+ {references.map((reference) => {+ const target = usageLink(reference)++ return (+ <li+ key={`${reference.kind}-${reference.owner_type}-${reference.owner_id}-${reference.field}`}+ className="flex items-center justify-between gap-2 text-sm"+ >+ {target ? (+ <Link+ to={target.to}+ params={{ storeId, ...target.params }}+ className="truncate underline-offset-4 hover:underline"+ >+ {reference.name}+ </Link>+ ) : (+ <span className="truncate">{reference.name}</span>+ )}+ <Badge variant="secondary">{usageBadgeLabel(reference, t)}</Badge>+ </li>+ )+ })}+ </ul>+ )}+ </div></div>- </div>- {canWrite && (- // Cancel / Save, matching the product gallery's edit sheet.- // Deleting a file is not editing it — that lives in the grid's- // context menu, away from the field a merchant is typing in.- <SheetFooter className="flex-row justify-end">- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- {t('admin.actions.cancel')}- </Button>- <Button type="button" disabled={!isDirty || updateFile.isPending} onClick={saveAlt}>- {updateFile.isPending && <Loader2Icon className="size-4 animate-spin" />}- {t('admin.actions.save')}- </Button>- </SheetFooter>- )}- </>+ {canWrite && (+ // Cancel / Save, matching the product gallery's edit sheet.+ // Deleting a file is not editing it — that lives in the grid's+ // context menu, away from the field a merchant is typing in.+ <SheetFooter className="flex-row justify-end">+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={!isDirty || updateFile.isPending}>+ {updateFile.isPending && <Loader2Icon className="size-4 animate-spin" />}+ {t('admin.actions.save')}+ </Button>+ </SheetFooter>+ )}+ </form>+ </FormProvider>)}</SheetContent></Sheet>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex 21109771c4..c5687ad2e7 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -3,6 +3,7 @@ import { type ProductCreateParams, SpreeError } from '@spree/admin-sdk'import {CategorizationCard,extensionFormValues,+ extensionRowValues,extensionSubmitValues,GeneralCard,InventoryCard,@@ -16,10 +17,13 @@ import {prepareVariantsTaxForProductSave,productFormSchema,SEOCard,+ Slot,StatusCard,TaxCard,+ type VariantFormValues,VariantsCard,variantToWirePayload,+ withExtensionRowValues,} from '@spree/dashboard-core'import {FormActions,@@ -54,14 +58,21 @@ function NewProductPage() {defaultValues: { ...newProductFormDefaults(), ...extensionFormValues('product', null) },})- const onSubmit = async (data: ProductFormValues) => {+ const onSubmit = async (submitted: ProductFormValues) => {+ // Before the placeholder variant is filtered out below, so row `i` of the+ // parse still lines up with row `i` of the form.+ const data = withExtensionRowValues('product', submitted, form.getValues())const { variants, custom_fields, media, digital_assets, ...rest } = data// Strip the placeholder default variant if the merchant didn't touch it.// Spree::Product#variants= auto-creates the canonical default variant// server-side when none is provided. Any variant with options, SKU,- // prices, or stock_levels survives as merchant intent.- const meaningful = (variants ?? []).filter((v) => !isPlaceholderDefaultVariant(v))+ // prices, stock_levels or a plugin's field survives as merchant intent.+ const hasExtensionValues = (variant: VariantFormValues) =>+ Object.keys(extensionRowValues('product.variant', variant)).length > 0+ const meaningful = (variants ?? []).filter(+ (v) => !isPlaceholderDefaultVariant(v) || hasExtensionValues(v),+ )const payload: ProductCreateParams = {...(rest as ProductCreateParams),@@ -121,6 +132,7 @@ function NewProductPage() {// upserts onto the default variant rather than leaving the field at its// default.const hasVariantOnlyData =+ hasExtensionValues(v) ||v.sku != null ||v.barcode != null ||v.weight != null ||@@ -216,6 +228,7 @@ function NewProductPage() {><CustomFieldsInlineCard /></ProductCustomFieldsProvider>+ <Slot name="product.form_main" context={{ product: undefined, mode: 'new' }} /></>}sidebar={@@ -225,6 +238,7 @@ function NewProductPage() {<CategorizationCard form={form} /><TaxCard form={form} /><SEOCard form={form} />+ <Slot name="product.form_sidebar" context={{ product: undefined, mode: 'new' }} /></>}/>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsxindex f74912b01e..9e25cbb800 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx@@ -19,6 +19,9 @@ import type { OptionType, OptionTypeCreateParams } from '@spree/admin-sdk'import {adminClient,Can,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,mapSpreeErrorsToForm,ResourceTable,resourceSearchSchema,@@ -213,13 +216,14 @@ function CreateOptionTypeSheet({const form = useForm<OptionTypeFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(optionTypeFormSchema) as any,- defaultValues: OPTION_TYPE_DEFAULTS,+ defaultValues: { ...OPTION_TYPE_DEFAULTS, ...extensionFormValues('option_type', null) },})async function onSubmit(values: OptionTypeFormValues) {try {await createMutation.mutateAsync({...values,+ ...extensionSubmitValues('option_type', form),option_values: values.option_values.map(valueToParam),} as OptionTypeCreateParams)form.reset(OPTION_TYPE_DEFAULTS)@@ -250,6 +254,11 @@ function CreateOptionTypeSheet({</p>)}<OptionTypeFormFields form={form} />+ <HostFormSlot+ form={form}+ name="option_type.form_fields"+ context={{ optionType: undefined, mode: 'new' }}+ /><OptionValuesFieldArray form={form} /></div><SheetFooter>@@ -302,6 +311,7 @@ function EditOptionTypeSheet({...optionType,kind: optionType.kind as OptionTypeFormValues['kind'],option_values: (optionType.option_values ?? []).map(optionValueToFormRow),+ ...extensionFormValues('option_type', optionType),})}}, [optionType, form])@@ -310,6 +320,7 @@ function EditOptionTypeSheet({try {await updateMutation.mutateAsync({...values,+ ...extensionSubmitValues('option_type', form),option_values: values.option_values.map(valueToParam),})// The sheet closes here; the `useOptionType` cache invalidation done by@@ -368,6 +379,11 @@ function EditOptionTypeSheet({</p>)}<OptionTypeFormFields form={form} />+ <HostFormSlot+ form={form}+ name="option_type.form_fields"+ context={{ optionType, mode: 'edit' }}+ /><OptionValuesFieldArray form={form} /></div><SheetFooter>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/index.tsxindex 43af0e896d..f1af825e56 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/index.tsx@@ -96,6 +96,7 @@ function PurchaseOrderDetailPage() {purchaseOrderId={purchaseOrder.id}title={t('admin.purchase_orders.history_title')}/>+ <Slot name="purchase_order.form_main" context={{ purchaseOrder }} /></>}sidebar={diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsxindex 65f0a01741..c49d34df2d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx@@ -3,6 +3,9 @@ import type { Catalog, Channel, ChannelCreateParams } from '@spree/admin-sdk'import {adminClient,Can,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,mapSpreeErrorsToForm,ResourceCombobox,ResourceTable,@@ -159,7 +162,7 @@ function CreateChannelSheet({const form = useForm<ChannelFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(channelFormSchema) as any,- defaultValues: CHANNEL_DEFAULTS,+ defaultValues: { ...CHANNEL_DEFAULTS, ...extensionFormValues('channel', null) },})// Auto-derive +code+ from +name+ while the user hasn't touched +code+ yet.@@ -173,7 +176,10 @@ function CreateChannelSheet({async function onSubmit(values: ChannelFormValues) {try {- await createMutation.mutateAsync(channelValuesToParams(values) as ChannelCreateParams)+ await createMutation.mutateAsync({+ ...(channelValuesToParams(values) as ChannelCreateParams),+ ...extensionSubmitValues('channel', form),+ })form.reset(CHANNEL_DEFAULTS)onOpenChange(false)} catch (err) {@@ -197,6 +203,11 @@ function CreateChannelSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><ChannelFormFields form={form} />+ <HostFormSlot+ form={form}+ name="channel.form_fields"+ context={{ channel: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -258,13 +269,17 @@ function EditChannelSheet({guest_checkout: channel.guest_checkout == null ? '' : String(channel.guest_checkout),default_catalog_id: channel.default_catalog_id ?? '',stock_location_ids: channel.stock_location_ids ?? [],+ ...extensionFormValues('channel', channel),})}}, [channel, form])async function onSubmit(values: ChannelFormValues) {try {- await updateMutation.mutateAsync(channelValuesToParams(values))+ await updateMutation.mutateAsync({+ ...channelValuesToParams(values),+ ...extensionSubmitValues('channel', form),+ })form.reset(values)onOpenChange(false)} catch (err) {@@ -285,6 +300,11 @@ function EditChannelSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><ChannelFormFields form={form} />+ <HostFormSlot+ form={form}+ name="channel.form_fields"+ context={{ channel, mode: 'edit' }}+ />{effectiveStrategy === RULES_ORDER_ROUTING_STRATEGY && (<OrderRoutingRulesSection channelId={id} />)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsxindex bd24209ab5..e230c949fb 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsx@@ -1,5 +1,5 @@import type { DeliveryProfile } from '@spree/admin-sdk'-import { adminClient, PageHeader } from '@spree/dashboard-core'+import { adminClient, PageHeader, Slot } from '@spree/dashboard-core'import { ErrorState, ResourceLayout } from '@spree/dashboard-ui'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { useTranslation } from 'react-i18next'@@ -86,11 +86,17 @@ function DeliveryProfileDetailBody({ profile }: { profile: DeliveryProfile }) {})}/>}- main={<DeliveryZonesAndMethodsSection profile={profile} search={search} />}+ main={+ <>+ <DeliveryZonesAndMethodsSection profile={profile} search={search} />+ <Slot name="delivery_profile.form_main" context={{ deliveryProfile: profile }} />+ </>+ }sidebar={<><DeliveryProfileGeneralCard profile={profile} /><DeliveryProfileOriginsCard profile={profile} />+ <Slot name="delivery_profile.form_sidebar" context={{ deliveryProfile: profile }} /></>}/>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsxindex f1070cd145..dcc069fb13 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx@@ -6,6 +6,9 @@ import {Can,CountryMultiCombobox,CurrencySelect,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,LocaleSelect,mapSpreeErrorsToForm,ResourceTable,@@ -164,6 +167,7 @@ function CreateMarketSheet({...MARKET_DEFAULTS,currency: defaultCurrency,default_locale: defaultLocale,+ ...extensionFormValues('market', null),}),[defaultCurrency, defaultLocale],)@@ -176,7 +180,10 @@ function CreateMarketSheet({async function onSubmit(values: MarketFormValues) {try {- await createMutation.mutateAsync(marketValuesToParams(values))+ await createMutation.mutateAsync({+ ...marketValuesToParams(values),+ ...extensionSubmitValues('market', form),+ })form.reset(initialDefaults)onOpenChange(false)} catch (err) {@@ -200,6 +207,11 @@ function CreateMarketSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><MarketFormFields form={form} />+ <HostFormSlot+ form={form}+ name="market.form_fields"+ context={{ market: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -252,13 +264,17 @@ function EditMarketSheet({default: market.default,country_codes: market.country_codes,tax_provider: market.tax_provider ?? '',+ ...extensionFormValues('market', market),})}}, [market, form])async function onSubmit(values: MarketFormValues) {try {- await updateMutation.mutateAsync(marketValuesToParams(values))+ await updateMutation.mutateAsync({+ ...marketValuesToParams(values),+ ...extensionSubmitValues('market', form),+ })form.reset(values)onOpenChange(false)} catch (err) {@@ -281,6 +297,11 @@ function EditMarketSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><MarketFormFields form={form} />+ <HostFormSlot+ form={form}+ name="market.form_fields"+ context={{ market, mode: 'edit' }}+ /></div><SheetFooter><Buttondiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/policies.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/policies.tsxindex 204e0bb91a..1dda8f538c 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/policies.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/policies.tsx@@ -3,6 +3,9 @@ import type { Policy, PolicyCreateParams } from '@spree/admin-sdk'import {adminClient,Can,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,mapSpreeErrorsToForm,ResourceTable,resourceSearchSchema,@@ -148,12 +151,15 @@ function CreatePolicySheet({const form = useForm<PolicyFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(policyFormSchema) as any,- defaultValues: POLICY_DEFAULTS,+ defaultValues: { ...POLICY_DEFAULTS, ...extensionFormValues('policy', null) },})async function onSubmit(values: PolicyFormValues) {try {- await createMutation.mutateAsync(policyValuesToParams(values) as PolicyCreateParams)+ await createMutation.mutateAsync({+ ...(policyValuesToParams(values) as PolicyCreateParams),+ ...extensionSubmitValues('policy', form),+ })form.reset(POLICY_DEFAULTS)onOpenChange(false)} catch (err) {@@ -177,6 +183,11 @@ function CreatePolicySheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><PolicyFormFields form={form} />+ <HostFormSlot+ form={form}+ name="policy.form_fields"+ context={{ policy: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -219,12 +230,17 @@ function EditPolicySheet({})useEffect(() => {- if (policy) form.reset(policyToFormValues(policy))+ if (policy) {+ form.reset({ ...policyToFormValues(policy), ...extensionFormValues('policy', policy) })+ }}, [policy, form])async function onSubmit(values: PolicyFormValues) {try {- await updateMutation.mutateAsync(policyValuesToParams(values))+ await updateMutation.mutateAsync({+ ...policyValuesToParams(values),+ ...extensionSubmitValues('policy', form),+ })form.reset(values)onOpenChange(false)} catch (err) {@@ -247,6 +263,11 @@ function EditPolicySheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><PolicyFormFields form={form} />+ <HostFormSlot+ form={form}+ name="policy.form_fields"+ context={{ policy, mode: 'edit' }}+ /></div><SheetFooter><Buttondiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsxindex 68335af499..ffac9077e9 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx@@ -19,6 +19,9 @@ import type { ProductType } from '@spree/admin-sdk'import {adminClient,Can,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,mapSpreeErrorsToForm,ResourceMultiAutocomplete,ResourceTable,@@ -205,12 +208,15 @@ function CreateProductTypeSheet({const form = useForm<ProductTypeFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(productTypeFormSchema) as any,- defaultValues: PRODUCT_TYPE_DEFAULTS,+ defaultValues: { ...PRODUCT_TYPE_DEFAULTS, ...extensionFormValues('product_type', null) },})async function onSubmit(values: ProductTypeFormValues) {try {- await createMutation.mutateAsync(withSortOrder(values))+ await createMutation.mutateAsync({+ ...withSortOrder(values),+ ...extensionSubmitValues('product_type', form),+ })form.reset(PRODUCT_TYPE_DEFAULTS)onOpenChange(false)} catch (err) {@@ -234,6 +240,11 @@ function CreateProductTypeSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><ProductTypeFormFields form={form} />+ <HostFormSlot+ form={form}+ name="product_type.form_fields"+ context={{ productType: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -288,13 +299,17 @@ function EditProductTypeSheet({required: definition.required,}),),+ ...extensionFormValues('product_type', productType),})}}, [productType, form])async function onSubmit(values: ProductTypeFormValues) {try {- await updateMutation.mutateAsync(withSortOrder(values))+ await updateMutation.mutateAsync({+ ...withSortOrder(values),+ ...extensionSubmitValues('product_type', form),+ })form.reset(values)onOpenChange(false)} catch (err) {@@ -315,6 +330,11 @@ function EditProductTypeSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><ProductTypeFormFields form={form} />+ <HostFormSlot+ form={form}+ name="product_type.form_fields"+ context={{ productType, mode: 'edit' }}+ /><ApplyToProductsSection id={id} productType={productType} /></div><SheetFooter>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories.tsxindex 1010203e95..c315bc7d2c 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/categories.tsx@@ -1,6 +1,14 @@import { zodResolver } from '@hookform/resolvers/zod'import type { TaxCategory, TaxCategoryCreateParams } from '@spree/admin-sdk'-import { Can, mapSpreeErrorsToForm, Subject, usePermissions } from '@spree/dashboard-core'+import {+ Can,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,+ mapSpreeErrorsToForm,+ Subject,+ usePermissions,+} from '@spree/dashboard-core'import {ActiveBadge,Button,@@ -190,12 +198,15 @@ function CreateTaxCategorySheet({const form = useForm<TaxCategoryFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(taxCategoryFormSchema) as any,- defaultValues: TAX_CATEGORY_DEFAULTS,+ defaultValues: { ...TAX_CATEGORY_DEFAULTS, ...extensionFormValues('tax_category', null) },})async function onSubmit(values: TaxCategoryFormValues) {try {- await createMutation.mutateAsync(taxCategoryValuesToParams(values) as TaxCategoryCreateParams)+ await createMutation.mutateAsync({+ ...(taxCategoryValuesToParams(values) as TaxCategoryCreateParams),+ ...extensionSubmitValues('tax_category', form),+ })form.reset(TAX_CATEGORY_DEFAULTS)onOpenChange(false)} catch (err) {@@ -219,6 +230,11 @@ function CreateTaxCategorySheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><TaxCategoryFormFields form={form} />+ <HostFormSlot+ form={form}+ name="tax_category.form_fields"+ context={{ taxCategory: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -267,13 +283,17 @@ function EditTaxCategorySheet({tax_code: taxCategory.tax_code ?? '',description: taxCategory.description ?? '',is_default: taxCategory.is_default,+ ...extensionFormValues('tax_category', taxCategory),})}}, [taxCategory, form])async function onSubmit(values: TaxCategoryFormValues) {try {- await updateMutation.mutateAsync(taxCategoryValuesToParams(values))+ await updateMutation.mutateAsync({+ ...taxCategoryValuesToParams(values),+ ...extensionSubmitValues('tax_category', form),+ })form.reset(values)onOpenChange(false)} catch (err) {@@ -296,6 +316,11 @@ function EditTaxCategorySheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><TaxCategoryFormFields form={form} />+ <HostFormSlot+ form={form}+ name="tax_category.form_fields"+ context={{ taxCategory, mode: 'edit' }}+ /></div><SheetFooter><Buttondiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates.tsxindex 7f447aa8d1..b8f5c75540 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/taxes/rates.tsx@@ -3,6 +3,9 @@ import type { TaxRate } from '@spree/admin-sdk'import {Can,CountryCombobox,+ extensionFormValues,+ extensionSubmitValues,+ HostFormSlot,mapSpreeErrorsToForm,StateCombobox,Subject,@@ -205,12 +208,15 @@ function CreateTaxRateSheet({const form = useForm<TaxRateFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(taxRateFormSchema) as any,- defaultValues: TAX_RATE_DEFAULTS,+ defaultValues: { ...TAX_RATE_DEFAULTS, ...extensionFormValues('tax_rate', null) },})async function onSubmit(values: TaxRateFormValues) {try {- await createMutation.mutateAsync(taxRateValuesToParams(values))+ await createMutation.mutateAsync({+ ...taxRateValuesToParams(values),+ ...extensionSubmitValues('tax_rate', form),+ })form.reset(TAX_RATE_DEFAULTS)onOpenChange(false)} catch (err) {@@ -234,6 +240,11 @@ function CreateTaxRateSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><TaxRateFormFields form={form} />+ <HostFormSlot+ form={form}+ name="tax_rate.form_fields"+ context={{ taxRate: undefined, mode: 'new' }}+ /></div><SheetFooter><Button@@ -284,13 +295,17 @@ function EditTaxRateSheet({country_code: taxRate.country_code ?? '',state_code: taxRate.state_code ?? '',show_rate_in_label: taxRate.show_rate_in_label,+ ...extensionFormValues('tax_rate', taxRate),})}}, [taxRate, form])async function onSubmit(values: TaxRateFormValues) {try {- await updateMutation.mutateAsync(taxRateValuesToParams(values))+ await updateMutation.mutateAsync({+ ...taxRateValuesToParams(values),+ ...extensionSubmitValues('tax_rate', form),+ })form.reset(values)onOpenChange(false)} catch (err) {@@ -313,6 +328,11 @@ function EditTaxRateSheet({<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><TaxRateFormFields form={form} />+ <HostFormSlot+ form={form}+ name="tax_rate.form_fields"+ context={{ taxRate, mode: 'edit' }}+ /></div><SheetFooter><Buttondiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/transfers/$transferId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/transfers/$transferId/index.tsxindex 12cf3f7d02..3d6c1ca322 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/transfers/$transferId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/transfers/$transferId/index.tsx@@ -104,6 +104,7 @@ function StockTransferDetailPage() {stockTransferId={transfer.id}title={t('admin.stock_transfers.history_title')}/>+ <Slot name="stock_transfer.form_main" context={{ transfer }} /></>}sidebar={diff --git a/packages/dashboard/src/testing/slot-probes.tsx b/packages/dashboard/src/testing/slot-probes.tsxnew file mode 100644index 0000000000..bb86c27305--- /dev/null+++ b/packages/dashboard/src/testing/slot-probes.tsx@@ -0,0 +1,121 @@+// Slot probes for the end-to-end suite — loaded only when the build sets+// VITE_E2E_SLOT_PROBES=1 (see main.tsx), never in a shipped dashboard. Each+// probe marks where a slot renders, and the host-form ones bind a field that+// saves through the page, so a spec proves a slot both renders and persists.+// The strings are test fixtures, so they are not translated.+//+// The fields write into `metadata`, which the e2e server permits on the+// records involved (e2e/global-setup.ts) the way an extension permits its+// own columns.+import {+ defineDashboardPlugin,+ type NewMediaEntry,+ type SlotEntry,+ useHostForm,+} from '@spree/dashboard-core'+import {+ Button,+ Card,+ CardContent,+ ContextMenuItem,+ Field,+ FieldLabel,+ Input,+} from '@spree/dashboard-ui'+import type { ComponentType } from 'react'++function probe<TContext>(component: ComponentType<TContext>): SlotEntry[] {+ return [{ id: 'e2e-probe', component: component as never }]+}++function marker(slot: string) {+ return probe(({ mode }: { mode?: string }) => (+ <Card>+ <CardContent className="text-muted-foreground text-sm">+ Slot probe: {slot}+ {mode ? ` (${mode})` : ''}+ </CardContent>+ </Card>+ ))+}++function HostField({ label, name }: { label: string; name: string }) {+ const form = useHostForm()+ const id = `probe-${name.replaceAll('.', '-')}`++ return (+ <Field>+ <FieldLabel htmlFor={id}>{label}</FieldLabel>+ <Input id={id} {...form.register(name)} />+ </Field>+ )+}++function hostField(label: string, key: string) {+ return probe(({ fieldPrefix }: { fieldPrefix?: string }) => (+ <HostField+ label={label}+ name={fieldPrefix ? `${fieldPrefix}.metadata.${key}` : `metadata.${key}`}+ />+ ))+}++const metadataField = {+ name: 'metadata',+ from: (record: unknown) =>+ (record as { metadata?: Record<string, unknown> } | null)?.metadata ?? {},+}++const PROBE_VIDEO_URL = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'++defineDashboardPlugin({+ formFields: {+ media: [metadataField],+ 'product.media': [metadataField],+ 'product.variant': [metadataField],+ tax_rate: [metadataField],+ },+ slots: {+ 'channel.form_fields': marker('channel.form_fields'),+ 'customer_group.form_fields': marker('customer_group.form_fields'),+ 'delivery_method.form_fields': marker('delivery_method.form_fields'),+ 'delivery_zone.form_fields': marker('delivery_zone.form_fields'),+ 'market.form_fields': marker('market.form_fields'),+ 'option_type.form_fields': marker('option_type.form_fields'),+ 'package_type.form_fields': marker('package_type.form_fields'),+ 'policy.form_fields': marker('policy.form_fields'),+ 'product_type.form_fields': marker('product_type.form_fields'),+ 'stock_location.form_fields': marker('stock_location.form_fields'),+ 'tax_category.form_fields': marker('tax_category.form_fields'),+ 'tax_rate.form_fields': hostField('Probe tax rate note', 'e2e_note'),+ 'category.form_main': marker('category.form_main'),+ 'category.form_sidebar': marker('category.form_sidebar'),+ 'collection.form_main': marker('collection.form_main'),+ 'collection.form_sidebar': marker('collection.form_sidebar'),+ 'customer.form_main': marker('customer.form_main'),+ 'delivery_profile.form_main': marker('delivery_profile.form_main'),+ 'delivery_profile.form_sidebar': marker('delivery_profile.form_sidebar'),+ 'media.form_fields': hostField('Probe library credit', 'e2e_credit'),+ 'media.context_menu': probe(() => <ContextMenuItem>Probe menu action</ContextMenuItem>),+ 'order.form_main': marker('order.form_main'),+ 'product.form_main': marker('product.form_main'),+ 'product.form_sidebar': marker('product.form_sidebar'),+ 'product.media.form_fields': hostField('Probe media credit', 'e2e_credit'),+ 'product.media.actions': probe(+ ({ addMedia }: { addMedia: (entries: NewMediaEntry[]) => void }) => (+ <Button+ type="button"+ variant="outline"+ onClick={() =>+ addMedia([{ media_type: 'external_video', external_video_url: PROBE_VIDEO_URL }])+ }+ >+ Probe attach video+ </Button>+ ),+ ),+ 'product.variant.form_fields': hostField('Probe variant code', 'e2e_code'),+ 'purchase_order.form_main': marker('purchase_order.form_main'),+ 'stock_transfer.form_main': marker('stock_transfer.form_main'),+ },+})diff --git a/packages/seller-dashboard-starter/src/plugins.ts b/packages/seller-dashboard-starter/src/plugins.tsindex b643033dcb..f3bbddd177 100644--- a/packages/seller-dashboard-starter/src/plugins.ts+++ b/packages/seller-dashboard-starter/src/plugins.ts@@ -25,7 +25,10 @@// })//// Slots the built-in screens expose: `seller.team.actions`, `seller.team.after`,-// `seller.product.form_sidebar`, `seller.order.form_sidebar`,+// `seller.product.form_main`, `seller.product.form_sidebar`,+// `seller.product.media.form_fields`, `seller.product.media.actions`,+// `seller.product.variant.form_fields`, `seller.stock_location.form_fields`,+// `seller.package_type.form_fields`, `seller.order.form_sidebar`,// `seller.payout.form_sidebar`, `seller.profile.form_main`,// `seller.profile.form_sidebar`.//diff --git a/packages/seller-dashboard/src/pages/product.tsx b/packages/seller-dashboard/src/pages/product.tsxindex 65752087da..444cead184 100644--- a/packages/seller-dashboard/src/pages/product.tsx+++ b/packages/seller-dashboard/src/pages/product.tsx@@ -2,6 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'import {CategorizationCard,extensionFormValues,+ extensionRowValues,extensionSubmitValues,GeneralCard,InventoryCard,@@ -17,6 +18,7 @@ import {Slot,VariantsCard,variantToWirePayload,+ withExtensionRowValues,} from '@spree/dashboard-core'import { FormActions, ResourceLayout, StatusBadge, toastManager } from '@spree/dashboard-ui'import type { ProductCreateParams } from '@spree/seller-sdk'@@ -106,7 +108,7 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {if (form.formState.isDirty) returnform.reset({- ...productToFormValues(product as PanelProduct, product.media),+ ...productToFormValues(product as PanelProduct, product.media, 'seller.product'),...extensionFormValues('seller.product', product),})}, [product, form])@@ -137,6 +139,7 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {// cards offer both — an allow-list that omitted them let a seller// set a crop or paste a video URL and watch it vanish on save.media: (values.media ?? []).map((item) => ({+ ...extensionRowValues('seller.product.media', item),id: item.id,signed_id: item.signed_id ?? undefined,poster_signed_id: item.poster_signed_id ?? undefined,@@ -149,7 +152,7 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {variant_ids: item.variant_ids,})),variants: (values.variants ?? []).map((variant, index) =>- variantToWirePayload(variant, index),+ variantToWirePayload(variant, index, 'seller.product'),) as ProductCreateParams['variants'],}@@ -181,7 +184,7 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {// Raw form state, not `values`: the Zod parse strips keys the schema// doesn't know, which is every field a slot widget registered.await save.mutateAsync({- values,+ values: withExtensionRowValues('seller.product', values, form.getValues()),extensionValues: extensionSubmitValues('seller.product', form),})} catch (err) {@@ -236,8 +239,13 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {main={<><GeneralCard form={form} />- <VariantsCard form={form} />- <MediaCard productId={productId} variants={product?.variants ?? []} form={form} />+ <VariantsCard form={form} formKey="seller.product" />+ <MediaCard+ productId={productId}+ variants={product?.variants ?? []}+ form={form}+ formKey="seller.product"+ /><PricesCardform={form}productName={product?.name ?? ''}@@ -245,6 +253,7 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {defaultCurrency={profile?.default_currency}/><InventoryCard form={form} />+ <Slot name="seller.product.form_main" context={{ product, mode }} /></>}sidebar={diff --git a/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/package-types.tsx b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/package-types.tsxindex 7549345889..5b3ee23a03 100644--- a/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/package-types.tsx+++ b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/package-types.tsx@@ -17,5 +17,5 @@ export const Route = createFileRoute('/_authenticated/$sellerId/settings/packagefunction PackageTypesRoute() {const search = Route.useSearch() as z.infer<typeof packageTypesSearchSchema>- return <PackageTypesPage search={search} />+ return <PackageTypesPage search={search} formKey="seller.package_type" />}diff --git a/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/stock-locations.tsx b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/stock-locations.tsxindex 1460c70378..2538b45461 100644--- a/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/stock-locations.tsx+++ b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/settings/stock-locations.tsx@@ -18,5 +18,5 @@ export const Route = createFileRoute('/_authenticated/$sellerId/settings/stock-lfunction StockLocationsRoute() {const search = Route.useSearch() as z.infer<typeof stockLocationsSearchSchema>- return <StockLocationsPage search={search} />+ return <StockLocationsPage search={search} formKey="seller.stock_location" />}diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rbindex 7577786951..eda440bc82 100644--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb@@ -289,6 +289,10 @@ module SpreeSpree.product_update_workflowend+ def nested_permitted_models+ { media: Spree::Media, variants: Spree::Variant }+ end+# Use SearchProvider::Database for collection to handle price/best_selling# sorting correctly (counts before sorting, avoiding PG/Mobility issues).def collectiondiff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rbindex db28e85304..4fe7105eab 100644--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb@@ -559,7 +559,17 @@ module Spree# declared on the model. Override +resource_permitted_attributes+ rather# than this, so the extension union is not lost.def permitted_attributes- resource_permitted_attributes + model_additional_permitted_attributes+ with_nested_additional_permitted_attributes(resource_permitted_attributes) + model_additional_permitted_attributes+ end++ # Nested lists this resource writes, keyed by param name, mapped to the+ # model each entry becomes — +{ media: Spree::Media }+ lets an+ # extension's +Spree::Media.additional_permitted_attributes+ ride the+ # product's +media+ entries, not only the media endpoint.+ #+ # @return [Hash{Symbol => Class}]+ def nested_permitted_models+ {}end# The resource's writable attributes: its `request_params`@@ -580,13 +590,33 @@ module Spreedef model_additional_permitted_attributesreturn [] unless respond_to?(:model_class, true)- model = model_class- return [] unless model.respond_to?(:additional_permitted_attributes)-- Array(model.additional_permitted_attributes)+ additional_permitted_attributes_for(model_class)rescue NotImplementedError[]end++ # What extensions declared writable on +model+. `Spree.base_class` is+ # host-overridable, so the class_attribute may not be there at all.+ #+ # @param model [Class]+ # @return [Array]+ def additional_permitted_attributes_for(model)+ Array(model.try(:additional_permitted_attributes))+ end++ def with_nested_additional_permitted_attributes(attributes)+ return attributes if nested_permitted_models.empty?++ attributes.map do |attribute|+ next attribute unless attribute.is_a?(Hash)++ attribute.to_h do |name, nested|+ model = nested_permitted_models[name.to_sym]+ additional = model ? additional_permitted_attributes_for(model) : []+ [name, additional.any? && nested.is_a?(Array) ? nested + additional : nested]+ end+ end+ endendendenddiff --git a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rbindex 5e58919206..56a26692d1 100644--- a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb@@ -212,6 +212,10 @@ module SpreeSpree.product_update_workflowend+ def nested_permitted_models+ { media: Spree::Media, variants: Spree::Variant }+ end+# The workflow builds its own product, which would leave a seller's# listing unowned. Handing it one built through `current_seller.products`# keeps the seller on the record, whatever the payload claims.diff --git a/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rbindex d8799f12f5..b842aaa7fb 100644--- a/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/resource_controller.rb@@ -69,12 +69,8 @@ module Spree# What extensions opened to sellers, never the operator-level list:# an attribute opened to operators must not become seller-writable# by accident.- def model_additional_permitted_attributes- return [] unless respond_to?(:model_class, true)-- Array(model_class.try(:additional_seller_permitted_attributes))- rescue NotImplementedError- []+ def additional_permitted_attributes_for(model)+ Array(model.try(:additional_seller_permitted_attributes))enddef authorize_resource!(resource = @resource, action = action_name.to_sym)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rbindex 7c48249b2a..8db990f416 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb@@ -2421,9 +2421,9 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller dobefore { request.headers.merge!(headers) }around do |example|- original = Spree::Product.additional_permitted_attributes+ originals = [Spree::Product, Spree::Media, Spree::Variant].index_with(&:additional_permitted_attributes)example.run- Spree::Product.additional_permitted_attributes = original+ originals.each { |model, attributes| model.additional_permitted_attributes = attributes }endit 'permits an attribute the model declares' do@@ -2439,6 +2439,24 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller dopatch :update, params: { id: product.prefixed_id, brand_id: 'acme' }, as: :jsonend+ it 'permits attributes extensions declare on media and variants inside the nested lists' do+ Spree::Media.additional_permitted_attributes += [:credit]+ Spree::Variant.additional_permitted_attributes += [:brand_code]++ expect_any_instance_of(described_class).to receive(:permitted_params).at_least(:once).and_wrap_original do |original|+ result = original.call+ expect(result[:media].first.keys).to include('credit')+ expect(result[:variants].first.keys).to include('brand_code')+ result.except('media', 'variants')+ end++ patch :update, params: {+ id: product.prefixed_id,+ media: [{ alt: 'Front', credit: 'Jane' }],+ variants: [{ sku: 'EXT-1', brand_code: 'ACME' }]+ }, as: :json+ end+it 'drops an attribute nobody declared' doexpect_any_instance_of(described_class).to receive(:permitted_params).at_least(:once).and_wrap_original do |original|result = original.calldiff --git a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rbindex 37c0fdd157..ad400e4019 100644--- a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb@@ -470,11 +470,12 @@ RSpec.describe Spree::Api::V3::Seller::ProductsController, type: :controller docontext 'with extension-contributed attributes' doaround do |example|- admin_attributes = Spree::Product.additional_permitted_attributes- seller_attributes = Spree::Product.additional_seller_permitted_attributes+ models = [Spree::Product, Spree::Media]+ admin_attributes = models.index_with(&:additional_permitted_attributes)+ seller_attributes = models.index_with(&:additional_seller_permitted_attributes)example.run- Spree::Product.additional_permitted_attributes = admin_attributes- Spree::Product.additional_seller_permitted_attributes = seller_attributes+ admin_attributes.each { |model, attributes| model.additional_permitted_attributes = attributes }+ seller_attributes.each { |model, attributes| model.additional_seller_permitted_attributes = attributes }enddef permitted_keys_for(params)@@ -501,6 +502,22 @@ RSpec.describe Spree::Api::V3::Seller::ProductsController, type: :controller doexpect(permitted_keys_for(brand_id: 'acme')).not_to include('brand_id')end++ it 'permits a media attribute declared for sellers inside the nested media list, never an operator-only one' do+ Spree::Media.additional_seller_permitted_attributes += [:credit]+ Spree::Media.additional_permitted_attributes += [:license]++ media_keys = nil+ expect_any_instance_of(described_class).to receive(:permitted_params).at_least(:once).and_wrap_original do |original|+ result = original.call+ media_keys = result[:media].first.keys+ result.except('media')+ end+ patch :update, params: { id: mine.prefixed_id, media: [{ alt: 'Front', credit: 'Jane', license: 'CC' }] }, as: :json++ expect(media_keys).to include('credit')+ expect(media_keys).not_to include('license')+ endendend