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
Admin SPA layout improvements (#13975)
Damian Legawiecf4fecc9b3265
diff --git a/docs/plans/6.0-admin-spa.md b/docs/plans/6.0-admin-spa.mdindex a78358986c..8d78ea566c 100644--- a/docs/plans/6.0-admin-spa.md+++ b/docs/plans/6.0-admin-spa.md@@ -4,7 +4,7 @@**Target:** Spree 6.0**Depends on:** `6.0-admin-api.md`, `6.0-platform-auth.md`**Author:** damian-**Last updated:** 2026-04-11+**Last updated:** 2026-04-30## Summary@@ -20,8 +20,9 @@ A new single-page React admin dashboard that replaces the Rails `spree/admin` en- **Auth via JWT + refresh token.** Access token in React context, refresh token in `localStorage` (or httpOnly cookie when we have a hosted deployment). 401 → auto-refresh via SDK `onUnauthorized` hook → retry.- **Permissions are server-driven.** `GET /api/v3/admin/me` returns the CanCanCan rules serialized; SPA mirrors them via `<Can I="..." a="..." />` and the `usePermissions()` hook. Server still enforces `authorize!` — SPA is UX only.- **Shadcn/ui copy-paste ownership model** — plugin authors can extend or override components without fighting a component library's abstraction.-- **Table registry + navigation registry + component injection** are the three extension points. Nothing else is pluggable yet.+- **Table registry + navigation registry + slot registry** are the three extension points. Nothing else is pluggable yet. Slot names mirror Rails admin's `render_admin_partials` slots so plugin authors carry their mental model across.- **No global state library.** TanStack Query handles server state, React Hook Form handles form state, `AuthProvider` + `PermissionProvider` handle session. Add Zustand only if we hit a legitimate client-state problem.+- **No breadcrumbs.** Legacy admin used breadcrumbs because deep flows (Product → Variants → Variant edit) were full-page navigations. The SPA collapses those into drawers and inline UIs, so the chains shrink to one or two segments — covered by `<BackButton>` (in `<PageHeader>`), the page title itself, and the highlighted sidebar section. Do not reintroduce a breadcrumb component.- **shipping_category_id is not part of product forms** — dropped in 6.0 per `6.0-fulfillment-and-delivery.md`.## Design Details@@ -235,7 +236,7 @@ function OrdersPage() {Three extension points only (do not add more without discussion):-1. **Navigation registry** — plugins add sidebar items by registering nav entries with required permissions.+1. **Navigation registry** — plugins add sidebar items by registering nav entries with required permissions. Mirrors Rails admin's `Spree.admin.navigation.sidebar` DSL (`spree/admin/config/initializers/spree_admin_navigation.rb`).2. **Table registry** — plugins add/remove/update columns, filters, and sorts on existing tables:```tsx@@ -256,7 +257,94 @@ tables.products.updateColumn('sku', {})```-3. **Component injection** — plugins inject components into defined slots on existing pages (e.g., extra fields on the product form, extra cards on the order detail page). Slot API is still being designed.+3. **Slot registry** — plugins inject components into named slots on existing pages. Mirrors the Rails admin's `render_admin_partials(:slot_name, ...)` mechanism (defined as the `Environment` Struct in `spree/admin/lib/spree/admin/engine.rb`). See **Slot API** below.++### Slot API++The legacy Rails admin exposes ~80 named partial slots via `Spree.admin.partials.<slot_name> << 'path/to/partial'`, rendered with `render_admin_partials(:slot_name, locals: { ... })`. The React equivalent uses the same slot names and roughly the same locals so plugin authors can carry their mental model across.++#### Concept++```tsx+// Plugin code (registered at app start)+import { registerSlot } from '@spree/admin/slots'++registerSlot('product_form_sidebar', {+ id: 'vendor-info',+ component: VendorInfoCard,+ position: 100,+ if: ({ permissions }) => permissions.can('read', 'Spree::Vendor'),+})++// Spree admin page (built-in)+<Slot name="product_form_sidebar" context={{ form, product }} />+```++`<Slot>` looks up all registered entries for that name, filters by `if`, sorts by `position`, and renders each component with the supplied `context` as props. Slots compose multiple registrations — same as Rails appending to a partials array.++#### `registerSlot(name, entry)` reference++| Field | Type | Description |+|---|---|---|+| `id` | `string` (required) | Unique within the slot — required so plugins can `removeSlot(name, id)` or `updateSlot(name, id, …)`. |+| `component` | `ComponentType<SlotContext>` | Receives the slot's context as props. |+| `position` | `number` (default `100`) | Sort order. Built-in entries use 100/200/300 to leave room. |+| `if` | `(ctx) => boolean` | Optional gate; receives the slot context plus `{ permissions, store, user }`. |++`removeSlot(name, id)` and `updateSlot(name, id, patch)` mirror the table registry methods.++#### Built-in slot names (mirror of Rails admin)++Slot naming convention: drop the `_partials` suffix from the Rails struct member, keep the rest. Built-in slots, organized by location:++**Layout-wide:**+- `head` — `<head>` injection (rare; analytics, custom fonts)+- `body_start`, `body_end` — adjacent to `<App>` root (banners, modals, devtools)++**Page chrome (replaces `content_for` seams):**+- `page.title`, `page.subtitle`, `page.actions`, `page.actions_dropdown`, `page.alerts`, `page.tabs` — consumed by `<PageHeader>` / `<PageTabs>`. Context: `{ resource, route }`.++**Dashboard:**+- `dashboard.sidebar`, `dashboard.analytics`++**Product page (`/$storeId/products/$productId`):**+- `product.form` — main form body, after Variants card. Context: `{ form, product }`.+- `product.form_sidebar` — right column. Context: `{ form, product }`.+- `product.dropdown` — extra items in the more-actions dropdown.+- `product.page_title` — adjacent to the title (badges, indicators).++**Order page (`/$storeId/orders/$orderId`):**+- `order.page_header` — above the header row.+- `order.page_body` — main content area (extra cards).+- `order.page_sidebar` — right column.+- `order.summary` — inside the totals card.+- `order.dropdown` — more-actions dropdown items.+- Context for all order slots: `{ order }`.++**Customer page (`/$storeId/customers/$customerId`):**+- `customer.page_body`, `customer.page_sidebar`, `customer.dropdown`. Context: `{ customer }`.++**Index pages — every resource gets a triplet:**+- `<resource>.actions` — top-right action buttons next to "Add"/"New".+- `<resource>.header` — banner/alert area above the table.+- `<resource>.filters` — extra filter controls.++Resources covered (matches the Rails struct): `admin_users`, `coupon_codes`, `customer_returns`, `customers`, `digital_assets`, `exports`, `gift_cards`, `integrations`, `invitations`, `oauth_applications`, `option_types`, `orders`, `pages`, `payment_methods`, `posts`, `price_lists`, `products`, `promotions`, `properties`, `refund_reasons`, `reimbursement_types`, `reports`, `return_authorization_reasons`, `roles`, `shipping_categories`, `shipping_methods`, `stock_items`, `stock_locations`, `stock_movements`, `stock_transfers`, `store_credit_categories`, `store_credits`, `tax_categories`, `tax_rates`, `users`, `zones`.++**Form pages (settings):**+- `store.form` — store edit form sections.+- `payment_method.form`, `shipping_method.form` — form bodies for those resources.++**Sub-nav (was `content_for(:page_tabs)` plus `_*_nav.html.erb`):**+- `nav.tax`, `nav.shipping`, `nav.stock`, `nav.returns_and_refunds`, `nav.team` — consumed by `<PageTabs>` on settings pages where these existed in Rails.++#### Adding a new slot++Slots are not free — every new slot is an API surface the SPA owes back-compat to. Rule: add a slot only when at least one real plugin needs it. To add: declare the name in `src/lib/slot-registry.ts`, drop a `<Slot>` in the page, document it here.++#### Why named slots over render-prop component overrides++Render props give plugins more power but worse UX: they must understand the host component, the surrounding layout breaks when two plugins both want to wrap the same node, and merge conflicts on upgrades become routine. Named slots are append-only and composable, which matches how the Rails admin worked and keeps the upgrade path predictable.### Comparison with Rails admin DSL@@ -271,6 +359,80 @@ tables.products.updateColumn('sku', {| `ransack_attribute: 'master_sku'` | `ransackAttribute: 'master_sku'` || `filter_type: :status, value_options: [...]` | `filterType: 'status', filterOptions: [...]` || `displayable: false` | `displayable: false` |+| `Spree.admin.partials.product_form << 'path'` | `registerSlot('product.form', { id, component })` |+| `render_admin_partials(:product_form, locals: { f:, product: })` | `<Slot name="product.form" context={{ form, product }} />` |+| `content_for :page_actions { ... }` | `<Slot name="page.actions" context={{ resource }} />` |+| `Spree.admin.navigation.sidebar.add :menu, ...` | `nav.add({ key, label, url, icon, position, if })` |++### Component library (`src/components/spree/`)++The shadcn copy-paste model is preserved for primitives (`src/components/ui/`). On top of those primitives we maintain a Spree compound layer at `src/components/spree/` that supplies the page chrome, drawers, and form widgets used across resources. Plugin authors can fork any `spree/*` component into their own override file the same way they fork shadcn primitives — no framework lock-in.++#### Tier 1 — page chrome (built first; every detail page sits on this)++| Component | Purpose | Replaces in Rails admin |+|---|---|---|+| `<PageHeader>` | Title, subtitle, back button, status badges, primary actions, more-actions dropdown. Accepts a `resource` prop and auto-wires the dropdown items (Metafields, Translations, JSON, Audit, Copy ID/Number, Delete) by capability detection. Hosts `<Slot name="page.actions">` and `<Slot name="page.actions_dropdown">`. | `shared/_content_header.html.erb` + `content_for(:page_*)` |+| `<PageTabs>` | Tab strip below the header; integrates with TanStack Router (each tab = sub-route). Hosts `<Slot name="page.tabs">`. | `shared/_page_tabs.html.erb` |+| `<StickyFormFooter>` | Save/cancel bar that sticks to viewport bottom; reads `formState.isDirty` / `isSubmitting`. | `data-controller="sticky"` + `turbo_save_button_tag` |+| `<ResourceLayout>` | Two-column grid (8/4) with consistent gap; slots for `header`, `main`, `sidebar`. | `_edit_resource.html.erb` skeleton |+| `<EmptyState>` | Icon + title + description + optional CTA. Used by `ResourceTable` and any "show" empty case. | `_no_resource_found.html.erb` |+| `<ErrorState>` / `<RouteErrorBoundary>` | Friendly retry UI; wraps each route. | `_error_messages.html.erb` |++#### Tier 2 — resource meta tooling (the Rails "more actions" dropdown)++All drawer-based, opened from `<PageHeader>`'s actions dropdown.++| Component | Backed by |+|---|---|+| `<JsonPreviewDrawer>` | Pretty-prints the resource via Admin SDK serializer + copy-to-clipboard. Replaces `json_previews/show.html.erb`. |+| `<MetafieldsDrawer>` | Per-resource custom fields editor. Supports text/longtext/rich_text/number/date/select/json kinds (see `5.4-6.0-custom-fields-rename.md`). |+| `<TranslationsDrawer>` | Locale tabs + side-by-side editor (see `5.4-centralized-translations-admin.md`). |+| `<AuditLogDrawer>` | Compact timeline of resource changes via the Audit Log API endpoint. |+| `<InternalNoteCard>` | Card with rich text body + edit drawer. Reused for orders, customers, returns. Replaces `shared/_internal_note.html.erb`. |+| `<CopyButton>` | Single-line clipboard wrapper; replaces the inline `clipboard_controller` divs. |++#### Tier 3 — form/data primitives++| Component | Replaces |+|---|---|+| `<MoneyInput>` | `money_field_controller.js`; currency-aware decimal input. |+| `<SlugInput>` | `slug_form_controller.js`; auto-generates from a watched field until edited manually. |+| `<SeoFields>` | `_seo.html.erb` + `seo_form_controller.js`; meta_title + meta_description + slug + SERP preview + character counts. |+| `<UnitSystemToggle>` / `<DimensionsInput>` | `unit_system_controller.js`; imperial/metric toggle for weight/dimensions. |+| `<CodeEditor>` | `codemirror_controller.js`; CodeMirror 6 wrapper for JSON / HTML / Liquid / markdown. |+| `<ColorInput>` | `color_picker_controller.js`; for option swatches (per `5.4-option-type-enhancements.md`). |+| `<ImageGallery>` | Drag-reorder + alt text + delete; wraps existing `useDirectUpload`. Replaces `_media_form.html.erb` + `_media_asset.html.erb`. |+| `<MultiProductPicker>` | `_multi_product_picker.html.erb`; bundles, related products, gift card constraints. |+| `<SortableTree>` | `sortable_tree_controller.js`; categories, taxons, navigation builder (uses `dnd-kit`). |+| `<ResourcePicker>` | Combobox over an Admin API list endpoint; underlies `<MultiProductPicker>`. |++#### Tier 4 — table/list enhancements++Layered onto the existing `<ResourceTable>`.++| Component | Replaces |+|---|---|+| `<BulkActionsBar>` | `_bulk_modal.html.erb` + `bulk_operation_controller.js`; floating bar above selected rows; pluggable actions. |+| `<FilterChips>` | `_filter_badge_template.erb`; active filters as removable pills. |+| `<SavedViews>` | New (no Rails equivalent); persists URL search state to localStorage as named views. |+| `<ExportDropdown>` | `_export_modal.html.erb`; "Export CSV" + format options. |+| `<ImportDialog>` | `imports/` + `import_form_controller.js`; file upload + column mapping wizard. |++#### Tier 5 — power-user / shell++| Component | Replaces |+|---|---|+| `<CommandPalette>` | `search_picker_controller.js`; ⌘-K global search across products, orders, customers via Admin API. |+| `<KeyboardShortcuts>` | `admin_controller.js` ⌘-S save shortcut + a `?` help modal listing all shortcuts. |+| `<NotificationCenter>` | Persistent dropdown for past Sonner notifications (optional, no Rails equivalent). |++#### Naming and ownership rules++- `src/components/ui/` — shadcn primitives, copy-paste owned.+- `src/components/spree/` — Spree compound components built on `ui/` primitives. Plugin authors override by forking a single file into their app, no framework hooks needed.+- `src/components/*.tsx` (top-level) — current home for `app-sidebar.tsx`, `resource-table.tsx`, `nav-main.tsx`, `can.tsx`, `back-button.tsx`, `confirm-dialog.tsx`, `tag-combobox.tsx`. Migrate gradually into `spree/` as Tier 1 lands; do not bulk-rename.+- New compound components default to `src/components/spree/`. The exception is anything that's clearly a primitive (a generic `MoneyInput` could go in `ui/`); use `spree/` whenever the component encodes Spree-specific knowledge (knows about resources, slots, permissions, the Admin SDK, etc.).### File structure@@ -312,7 +474,23 @@ packages/admin/│ │ ├── back-button.tsx # history.back() with fallback│ │ ├── resource-table.tsx│ │ ├── table-toolbar.tsx-│ │ └── ui/ # shadcn components+│ │ ├── ui/ # shadcn primitives (copy-paste owned)+│ │ └── spree/ # Spree compound components+│ │ ├── page-header.tsx # Tier 1+│ │ ├── page-tabs.tsx+│ │ ├── sticky-form-footer.tsx+│ │ ├── resource-layout.tsx+│ │ ├── empty-state.tsx+│ │ ├── route-error-boundary.tsx+│ │ ├── slot.tsx # <Slot name="..." context={...} />+│ │ ├── json-preview-drawer.tsx # Tier 2+│ │ ├── metafields-drawer.tsx+│ │ ├── translations-drawer.tsx+│ │ ├── audit-log-drawer.tsx+│ │ ├── internal-note-card.tsx+│ │ ├── copy-button.tsx+│ │ ├── money-input.tsx # Tier 3 (added as needed)+│ │ └── ...│ ├── tables/│ │ ├── orders.tsx # defineTable('orders', ...)│ │ ├── products.tsx@@ -323,6 +501,8 @@ packages/admin/│ └── lib/│ ├── query-client.ts│ ├── table-registry.ts # defineTable, getTable, tables proxy+│ ├── slot-registry.ts # registerSlot, removeSlot, useSlots+│ ├── nav-registry.ts # nav.add, nav.remove, nav.update│ ├── permissions.ts # Subject + Action constants│ ├── formatters.ts # formatPrice, formatRelativeTime│ └── utils.ts@@ -330,27 +510,50 @@ packages/admin/## Migration Path-### Phase 1 — parity with Rails admin (in progress)+### Phase 1 — foundation (✅ done)- ✅ Package skeleton, Vite, TanStack Router, TanStack Query- ✅ Auth (login, logout, JWT refresh, 401 auto-retry)- ✅ Permission provider + `<Can>` + sidebar filtering- ✅ Table registry + resource table- ✅ Multi-store routing (`$storeId` prefix)-- ⏳ Products list + detail/edit++### Phase 2 — page chrome + slot API (in progress)++Highest-leverage work. Every detail page reuses the same chrome and gains the legacy "more actions" drawer toolkit.++- ⏳ Tier 1 components (`<PageHeader>`, `<PageTabs>`, `<StickyFormFooter>`, `<ResourceLayout>`, `<EmptyState>`, `<RouteErrorBoundary>`)+- ⏳ Slot registry (`registerSlot`, `<Slot>`, `removeSlot`, `updateSlot`) with the built-in slot names from the Slot API section+- ⏳ Navigation registry (`nav.add` / `remove` / `update` / `insert_before` / `insert_after`)+- ⏳ Refactor `orders/$orderId.tsx` and `products/$productId.tsx` onto the new chrome — proves the design+- ⏳ Normalize per-resource hooks into `src/hooks/` (currently inline in route files); add `useResourceMutation` helper for the toast + invalidate pattern++### Phase 3 — resource meta tooling (Tier 2)++- ⏳ `<JsonPreviewDrawer>` (cheapest, biggest debug payoff)+- ⏳ `<MetafieldsDrawer>` — unblocks the SPA half of `5.4-6.0-custom-fields-rename.md`+- ⏳ `<TranslationsDrawer>` — per `5.4-centralized-translations-admin.md`+- ⏳ `<AuditLogDrawer>`+- ⏳ `<InternalNoteCard>` extracted from inline order code++### Phase 4 — resource parity with Rails admin++Build remaining resource pages on top of the chrome and Tier 3 form primitives (added as needed, not speculatively).++- ⏳ Products list + detail/edit (extract sub-cards into `spree/` layer)- ⏳ Orders list + detail/edit- ⏳ Customers- ⏳ Promotions- ⏳ Stock, categories, store settings, admin users, roles- ⏳ Reports, exports, imports, dashboard-### Phase 2 — extension API+### Phase 5 — bulk + power-user (Tiers 4 + 5)-- Navigation registry-- Component injection slot API-- Plugin loader / discovery mechanism+- ⏳ `<BulkActionsBar>`, `<FilterChips>`, `<SavedViews>`, `<ExportDropdown>`, `<ImportDialog>` (Admin API batch operation support is a prereq)+- ⏳ `<CommandPalette>`, `<KeyboardShortcuts>`, `<NotificationCenter>`+- ⏳ Plugin loader / discovery mechanism (build-time first; runtime later)-### Phase 3 — drop Rails admin+### Phase 6 — drop Rails admin- Remove `spree/admin` engine entirely- Update `create-spree-app` scaffolding to install `@spree/admin` by default@@ -367,14 +570,18 @@ packages/admin/- **Permission-gate UI optimistically.** Show the button, handle 403 with a toast. Only hide when there's a clear `read` denial.- **All nav items, routes, and action buttons that correspond to Admin API resources must pass a `subject` to `<Can>` or the equivalent check.** Sidebar filtering already does this — keep it consistent.- **Field names must match the API.** No `zipcode`, `firstname`, `shipment_state`, `line_items` in SPA code — use `postal_code`, `first_name`, `fulfillment_status`, `items`. See `5.4-store-api-naming-standardization.md`.+- **New compound components go in `src/components/spree/`,** not the top-level `src/components/`. The top-level dir is legacy; gradually migrate as Tier 1 lands. Primitives stay in `src/components/ui/`.+- **Detail pages must use `<PageHeader>` + `<ResourceLayout>`** once those exist — do not reinvent the title row, more-actions dropdown, or two-column grid per page.+- **Don't add new slot names speculatively.** A slot is an API surface; only add one when a real plugin needs it. Document any new slot in this plan's Slot API section in the same PR.## Open Questions- **Plugin distribution** — npm packages? Dynamic imports? Build-time registration? Current default is build-time (`import '@plugin/foo'` in a project's entry file), but we want to support runtime plugin loading for hosted deployments.-- **Component injection slot API** — named slots like `<Slot name="product.sidebar" />`? Portal-based? React-aria–style provider/consumer?- **Theme customization** — how deep? Tailwind config overrides? CSS variables? shadcn theme tokens?- **Bundled vs. standalone deployment** — do we ship SPA compiled into the gem, or require a separate static host? Hybrid (gem ships fallback, ops can override URL)?-- **Offline / optimistic mutations** — TanStack Query supports it but we haven't wired it in. Priority for Phase 2?+- **Offline / optimistic mutations** — TanStack Query supports it but we haven't wired it in. Priority for Phase 5?+- **Storybook** — light visual docs would help plugin authors discover components and slots. Likely Phase 3 deliverable, not a blocker.+- **Print views (packing slip, invoice)** — Rails admin doesn't ship these in core (likely enterprise). Decide whether the SPA owns a basic print view or stays out.## Referencesdiff --git a/packages/admin/src/components/resource-table.tsx b/packages/admin/src/components/resource-table.tsxindex f9f8c38ccb..6f52b470a8 100644--- a/packages/admin/src/components/resource-table.tsx+++ b/packages/admin/src/components/resource-table.tsx@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'import { useNavigate } from '@tanstack/react-router'import { type ReactNode, useDeferredValue, useState } from 'react'import { z } from 'zod/v4'+import { EmptyState } from '@/components/spree/empty-state'import { TableToolbar } from '@/components/table-toolbar'import { Card, CardContent } from '@/components/ui/card'import {@@ -229,13 +230,16 @@ export function ResourceTable<T extends Record<string, any>>({<TableEmpty colSpan={visibleColumns.length}>Loading...</TableEmpty>) : rows.length === 0 ? (<TableEmpty colSpan={visibleColumns.length}>- <div className="flex flex-col items-center gap-2">- {table.emptyIcon}- <p>{table.emptyMessage ?? 'No results found'}</p>- {(deferredSearch || (filters as FilterRule[]).length > 0) && (- <p className="text-xs">Try adjusting your search or filters</p>- )}- </div>+ <EmptyState+ compact+ icon={table.emptyIcon}+ title={table.emptyMessage ?? 'No results found'}+ description={+ deferredSearch || (filters as FilterRule[]).length > 0+ ? 'Try adjusting your search or filters'+ : undefined+ }+ /></TableEmpty>) : (rows.map((row, i) => (diff --git a/packages/admin/src/components/spree/empty-state.tsx b/packages/admin/src/components/spree/empty-state.tsxnew file mode 100644index 0000000000..b8a58e60e4--- /dev/null+++ b/packages/admin/src/components/spree/empty-state.tsx@@ -0,0 +1,38 @@+import type { ReactNode } from 'react'++interface EmptyStateProps {+ /** Optional icon (lucide-react icon, sized). Rendered above the title in muted color. */+ icon?: ReactNode+ /** Headline. */+ title: ReactNode+ /** Smaller helper text below the title. */+ description?: ReactNode+ /** Action button(s) — typically a "Create…" CTA. */+ action?: ReactNode+ /** Compact variant for inline use (table rows, cards). Default false. */+ compact?: boolean+}++/**+ * Empty state placeholder. Replaces `_no_resource_found.html.erb` and the+ * inline empty markup currently embedded in `<ResourceTable>`.+ *+ * Use full variant for page-level emptiness ("This store has no products yet"),+ * compact variant for inside cards/tables.+ */+export function EmptyState({ icon, title, description, action, compact = false }: EmptyStateProps) {+ return (+ <div+ className={+ compact+ ? 'flex flex-col items-center justify-center gap-2 py-6 text-center'+ : 'flex flex-col items-center justify-center gap-3 py-16 text-center'+ }+ >+ {icon && <div className="text-muted-foreground [&>svg]:size-8">{icon}</div>}+ <p className={compact ? 'text-sm font-medium' : 'text-base font-medium'}>{title}</p>+ {description && <p className="max-w-md text-sm text-muted-foreground">{description}</p>}+ {action && <div className="mt-2">{action}</div>}+ </div>+ )+}diff --git a/packages/admin/src/components/spree/page-header.tsx b/packages/admin/src/components/spree/page-header.tsxnew file mode 100644index 0000000000..019a194fd1--- /dev/null+++ b/packages/admin/src/components/spree/page-header.tsx@@ -0,0 +1,200 @@+import { CheckIcon, CopyIcon, EllipsisVerticalIcon, TrashIcon } from 'lucide-react'+import { type ReactNode, useState } from 'react'+import { BackButton } from '@/components/back-button'+import { useConfirm } from '@/components/confirm-dialog'+import { Slot } from '@/components/spree/slot'+import { Button } from '@/components/ui/button'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'++/**+ * Resource-shaped value PageHeader inspects to wire the more-actions dropdown.+ * Anything not present is simply omitted — no errors, no required fields beyond `id`.+ */+export interface PageHeaderResource {+ id: string+ /** Display number for "Copy number". Used on orders. */+ number?: string | null+}++interface PageHeaderProps {+ /** Main title (left of any badges). */+ title: ReactNode+ /** Small text below or beside the title (updated_at badge, customer email, etc.). */+ subtitle?: ReactNode+ /** Back button target — passed to <BackButton fallback="..."/>. Omit for top-level pages. */+ backTo?: string+ /** Status badges rendered next to the title. Use <StatusBadge /> for consistency. */+ badges?: ReactNode+ /** Primary action buttons (rightmost, before the dropdown). Most pages use this for "Save". */+ actions?: ReactNode+ /**+ * Domain-specific items to render at the top of the more-actions dropdown+ * (e.g., Complete/Approve/Cancel on orders). Rendered above the+ * `page.actions_dropdown` slot and the auto-wired Copy ID / Delete items.+ */+ dropdownItems?: ReactNode+ /**+ * The resource being edited. When supplied, PageHeader renders the legacy+ * "more actions" dropdown (Copy ID, Copy number, Delete). When omitted, the+ * dropdown is only rendered if a plugin has registered into `page.actions_dropdown`.+ */+ resource?: PageHeaderResource+ /** Slot context name. Defaults to inferring from `resource` keys. Optional. */+ slotContext?: Record<string, unknown>+ /**+ * Called after the user confirms the auto-rendered Delete action.+ * When provided, the Delete item is enabled. The confirmation prompt is+ * fixed ("Are you sure? This action cannot be undone.") — pass `dropdownItems`+ * directly if you need a custom delete flow.+ */+ onDelete?: () => void | Promise<void>+ /** Override the destructive label ("Delete order", "Delete product", etc.). */+ deleteLabel?: string+}++/**+ * Top-of-page chrome: back button + title + badges + subtitle, with primary+ * actions and a more-actions dropdown on the right.+ *+ * Mirrors `spree/admin/app/views/spree/admin/shared/_content_header.html.erb`:+ * the legacy header yields `:page_title`, `:page_actions`, `:page_actions_dropdown`+ * via `content_for`. Here those become props + the `page.actions` and+ * `page.actions_dropdown` slots, so plugins extend without overriding.+ */+export function PageHeader({+ title,+ subtitle,+ backTo,+ badges,+ actions,+ dropdownItems,+ resource,+ slotContext,+ onDelete,+ deleteLabel = 'Delete',+}: PageHeaderProps) {+ const slotCtx = { ...slotContext, resource }+ const showDropdown = Boolean(resource || onDelete || dropdownItems)++ return (+ <header className="flex items-start gap-3">+ {backTo && <BackButton fallback={backTo} />}++ <div className="flex flex-1 flex-wrap items-center gap-x-3 gap-y-1">+ <h1 className="text-2xl font-medium leading-tight">{title}</h1>+ {badges}+ {subtitle && <span className="text-sm text-muted-foreground">{subtitle}</span>}+ </div>++ <div className="ml-auto flex items-center gap-2">+ <Slot name="page.actions" context={slotCtx} />+ {actions}+ {showDropdown && (+ <PageActionsDropdown+ resource={resource}+ slotContext={slotCtx}+ dropdownItems={dropdownItems}+ onDelete={onDelete}+ deleteLabel={deleteLabel}+ />+ )}+ </div>+ </header>+ )+}++// ---------------------------------------------------------------------------+// More-actions dropdown+// ---------------------------------------------------------------------------++interface PageActionsDropdownProps {+ resource?: PageHeaderResource+ slotContext: Record<string, unknown>+ dropdownItems?: ReactNode+ onDelete?: () => void | Promise<void>+ deleteLabel: string+}++function PageActionsDropdown({+ resource,+ slotContext,+ dropdownItems,+ onDelete,+ deleteLabel,+}: PageActionsDropdownProps) {+ const confirm = useConfirm()++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button size="icon-sm" variant="outline" aria-label="More actions">+ <EllipsisVerticalIcon className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {dropdownItems}+ <Slot name="page.actions_dropdown" context={slotContext} />++ {resource?.number && <CopyToClipboardItem label="Copy number" value={resource.number} />}+ {resource && <CopyToClipboardItem label="Copy ID" value={resource.id} />}++ {onDelete && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={async () => {+ if (+ await confirm({+ message: 'Are you sure? This action cannot be undone.',+ variant: 'destructive',+ confirmLabel: deleteLabel,+ })+ ) {+ await onDelete()+ }+ }}+ >+ <TrashIcon className="size-4" />+ {deleteLabel}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}++// ---------------------------------------------------------------------------+// Copy-to-clipboard menu item+// ---------------------------------------------------------------------------++function CopyToClipboardItem({ label, value }: { label: string; value: string }) {+ const [copied, setCopied] = useState(false)++ return (+ <DropdownMenuItem+ // Keep the menu open after click so the user sees the confirmation flash.+ closeOnClick={false}+ onClick={async (e) => {+ e.preventDefault()+ try {+ await navigator.clipboard.writeText(value)+ setCopied(true)+ setTimeout(() => setCopied(false), 1200)+ } catch {+ // Clipboard API can fail in insecure contexts; ignore silently.+ }+ }}+ >+ {copied ? <CheckIcon className="size-4" /> : <CopyIcon className="size-4" />}+ {copied ? 'Copied' : label}+ </DropdownMenuItem>+ )+}diff --git a/packages/admin/src/components/spree/page-tabs.tsx b/packages/admin/src/components/spree/page-tabs.tsxnew file mode 100644index 0000000000..f28f658cfb--- /dev/null+++ b/packages/admin/src/components/spree/page-tabs.tsx@@ -0,0 +1,78 @@+import { Link, type LinkProps, useLocation, useRouter } from '@tanstack/react-router'+import type { ReactNode } from 'react'+import { Slot } from '@/components/spree/slot'+import { cn } from '@/lib/utils'++export interface PageTab {+ /** Stable key used for React lists. */+ key: string+ /** Visible label. */+ label: ReactNode+ /** Link target — same shape as TanStack Router <Link>. */+ to: LinkProps['to']+ /** Path/search params for the target route. */+ params?: LinkProps['params']+ search?: LinkProps['search']+ /**+ * Match strategy. `"exact"` (default) matches only when the pathname is+ * identical; `"prefix"` matches when the current pathname starts with `to`.+ */+ match?: 'exact' | 'prefix'+}++interface PageTabsProps {+ tabs: PageTab[]+ /** Slot name for plugin-injected tabs. Default `'page.tabs'`. */+ slotName?: string+ /** Slot context. Receives `{ tabs }` so plugins can inspect built-ins. */+ slotContext?: Record<string, unknown>+ className?: string+}++/**+ * Sub-route–aware tab strip. Each tab is a TanStack Router `<Link>`; the+ * active tab is the one whose `to` matches the current pathname.+ *+ * Replaces `shared/_page_tabs.html.erb` and the various `_*_nav.html.erb`+ * partials. Plugins extend by registering into the `page.tabs` slot.+ */+export function PageTabs({ tabs, slotName = 'page.tabs', slotContext, className }: PageTabsProps) {+ const location = useLocation()+ const router = useRouter()++ return (+ <nav className={cn('flex items-center gap-1 border-b border-border', className)}>+ {tabs.map((tab) => {+ // Resolve to an absolute pathname so prefix-mode doesn't match every tab+ // when `to` is an object/relative form. Mirrors what <Link> itself does.+ const target =+ typeof tab.to === 'string'+ ? tab.to+ : router.buildLocation({ to: tab.to, params: tab.params, search: tab.search }).pathname+ const active =+ tab.match === 'prefix'+ ? location.pathname.startsWith(target)+ : location.pathname === target+ return (+ <Link+ key={tab.key}+ // <Link> generics need a literal route path; PageTab is a generic+ // declarative API where `to` is unknown at this site.+ to={tab.to as never}+ params={tab.params}+ search={tab.search}+ className={cn(+ 'inline-flex items-center px-3 py-2 -mb-px text-sm font-medium border-b-2 transition-colors',+ active+ ? 'border-foreground text-foreground'+ : 'border-transparent text-muted-foreground hover:text-foreground hover:border-border',+ )}+ >+ {tab.label}+ </Link>+ )+ })}+ <Slot name={slotName} context={{ tabs, ...slotContext }} />+ </nav>+ )+}diff --git a/packages/admin/src/components/spree/resource-layout.tsx b/packages/admin/src/components/spree/resource-layout.tsxnew file mode 100644index 0000000000..1a1f27729b--- /dev/null+++ b/packages/admin/src/components/spree/resource-layout.tsx@@ -0,0 +1,31 @@+import type { ReactNode } from 'react'++interface ResourceLayoutProps {+ /** Rendered above the two columns. Typically <PageHeader />. */+ header?: ReactNode+ /** Left column content (8/12 on lg+). */+ main: ReactNode+ /** Right column content (4/12 on lg+). Optional — when omitted, main spans full width. */+ sidebar?: ReactNode+}++/**+ * Standard detail-page scaffold: header above, two columns below (8/4 on lg+,+ * stacked under). Replaces the ad-hoc grid duplicated in product/order detail+ * pages and the legacy `_edit_resource.html.erb` skeleton.+ */+export function ResourceLayout({ header, main, sidebar }: ResourceLayoutProps) {+ return (+ <div className="flex flex-col gap-6">+ {header}+ {sidebar ? (+ <div className="grid grid-cols-12 gap-6">+ <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">{main}</div>+ <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">{sidebar}</div>+ </div>+ ) : (+ <div className="flex flex-col gap-6">{main}</div>+ )}+ </div>+ )+}diff --git a/packages/admin/src/components/spree/route-error-boundary.tsx b/packages/admin/src/components/spree/route-error-boundary.tsxnew file mode 100644index 0000000000..b1f3b39ef7--- /dev/null+++ b/packages/admin/src/components/spree/route-error-boundary.tsx@@ -0,0 +1,93 @@+import { AlertTriangleIcon, RotateCcwIcon } from 'lucide-react'+import { Component, type ReactNode } from 'react'+import { EmptyState } from '@/components/spree/empty-state'+import { Button } from '@/components/ui/button'++interface ErrorStateProps {+ /** Headline. Defaults to "Something went wrong". */+ title?: ReactNode+ /** Smaller text below the title. Pass an Error and we'll show its message. */+ description?: ReactNode+ /** Error object — when supplied, its message is shown if `description` is omitted. */+ error?: Error | null+ /** Called by the retry button. When omitted, the button is hidden. */+ onRetry?: () => void+ /** Override the retry label. Default "Try again". */+ retryLabel?: string+}++/**+ * Friendly error display. Use directly when an async operation has failed+ * (replacing the inline `<p className="text-destructive">Failed to load…</p>`+ * scattered through detail pages), or as a route's `errorComponent`.+ */+export function ErrorState({+ title = 'Something went wrong',+ description,+ error,+ onRetry,+ retryLabel = 'Try again',+}: ErrorStateProps) {+ const message = description ?? error?.message ?? 'An unexpected error occurred. Please try again.'++ return (+ <EmptyState+ icon={<AlertTriangleIcon />}+ title={title}+ description={message}+ action={+ onRetry && (+ <Button variant="outline" size="sm" onClick={onRetry}>+ <RotateCcwIcon className="size-4" />+ {retryLabel}+ </Button>+ )+ }+ />+ )+}++interface RouteErrorBoundaryProps {+ children: ReactNode+ /** Optional fallback renderer; receives the caught error and a reset function. */+ fallback?: (error: Error, reset: () => void) => ReactNode+}++interface RouteErrorBoundaryState {+ error: Error | null+}++/**+ * Route-level error boundary. Wrap a route component (or any subtree) so a+ * thrown render error shows an `<ErrorState>` instead of crashing the SPA.+ *+ * For TanStack Router data errors (loader/component throws), prefer the+ * route's `errorComponent: ErrorState` — that surface receives `{ error, reset }`+ * directly. This boundary is for cases where a child component throws during+ * render outside the loader path.+ */+export class RouteErrorBoundary extends Component<+ RouteErrorBoundaryProps,+ RouteErrorBoundaryState+> {+ state: RouteErrorBoundaryState = { error: null }++ static getDerivedStateFromError(error: Error): RouteErrorBoundaryState {+ return { error }+ }++ reset = () => {+ this.setState({ error: null })+ }++ render() {+ const { error } = this.state+ if (!error) return this.props.children++ if (this.props.fallback) {+ return this.props.fallback(error, this.reset)+ }++ return <ErrorState error={error} onRetry={this.reset} />+ }+}diff --git a/packages/admin/src/components/spree/slot.tsx b/packages/admin/src/components/spree/slot.tsxnew file mode 100644index 0000000000..0cd86aae24--- /dev/null+++ b/packages/admin/src/components/spree/slot.tsx@@ -0,0 +1,50 @@+import { Fragment } from 'react'+import { type SlotAmbientContext, useSlotEntries } from '@/lib/slot-registry'++interface SlotProps<TContext> {+ /** Slot name, e.g. "product.form_sidebar" or "order.dropdown". */+ name: string+ /** Slot-specific context passed to every registered component. */+ context?: TContext+ /**+ * Rendered when no entries are registered or all are gated out by `if`.+ * Useful when a slot is the only thing in a section (avoid empty headings).+ */+ fallback?: React.ReactNode+}++/**+ * Renders all components registered to a slot, sorted by `position`,+ * filtered by each entry's `if` predicate. Each component receives `context`+ * as props plus ambient `{ permissions, store, user }` (populated as the+ * providers come online).+ */+export function Slot<TContext extends object = object>({+ name,+ context,+ fallback,+}: SlotProps<TContext>) {+ const entries = useSlotEntries(name)++ // Ambient context — wired up properly once SlotProvider lands. For now+ // an empty object so plugin `if` predicates can destructure safely.+ const ambient: SlotAmbientContext = {}+ const merged = { ...ambient, ...(context ?? {}) } as TContext & SlotAmbientContext++ const visible = entries.filter((entry) => (entry.if ? entry.if(merged) : true))++ if (visible.length === 0) return fallback ?? null++ return (+ <>+ {visible.map((entry) => {+ const Component = entry.component+ return (+ <Fragment key={entry.id}>+ <Component {...merged} />+ </Fragment>+ )+ })}+ </>+ )+}diff --git a/packages/admin/src/components/spree/sticky-form-footer.tsx b/packages/admin/src/components/spree/sticky-form-footer.tsxnew file mode 100644index 0000000000..a48ab222b7--- /dev/null+++ b/packages/admin/src/components/spree/sticky-form-footer.tsx@@ -0,0 +1,61 @@+import type { FieldValues, UseFormReturn } from 'react-hook-form'+import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'++interface StickyFormFooterProps<TFieldValues extends FieldValues = FieldValues> {+ /** RHF form instance. Reads `formState.isDirty` / `isSubmitting`. */+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ form: UseFormReturn<TFieldValues, any, any>+ /** Save button label. Default "Save". */+ saveLabel?: string+ /** Cancel button label. Default "Discard". */+ cancelLabel?: string+ /** Called when Discard is clicked. Default: `form.reset()`. */+ onCancel?: () => void+ /** Always render the footer (don't gate on isDirty). Useful for "create" forms. */+ alwaysVisible?: boolean+ className?: string+}++/**+ * Sticky save bar that appears at the bottom of the viewport while the form+ * has unsaved changes. Sits inside the form so its submit button triggers RHF.+ *+ * Replaces the legacy `data-controller="sticky"` save bar. Use in addition to+ * `<PageHeader actions={...}>` when forms are long enough that the top Save+ * button scrolls out of view.+ */+export function StickyFormFooter<TFieldValues extends FieldValues>({+ form,+ saveLabel = 'Save',+ cancelLabel = 'Discard',+ onCancel,+ alwaysVisible = false,+ className,+}: StickyFormFooterProps<TFieldValues>) {+ const { isDirty, isSubmitting } = form.formState++ if (!alwaysVisible && !isDirty) return null++ return (+ <div+ className={cn(+ 'sticky bottom-0 -mx-4 mt-4 flex items-center justify-end gap-2 border-t border-border bg-white/90 px-4 py-3 backdrop-blur supports-[backdrop-filter]:bg-white/75',+ className,+ )}+ >+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={onCancel ?? (() => form.reset())}+ disabled={isSubmitting}+ >+ {cancelLabel}+ </Button>+ <Button type="submit" size="sm" disabled={isSubmitting}>+ {isSubmitting ? 'Saving…' : saveLabel}+ </Button>+ </div>+ )+}diff --git a/packages/admin/src/components/ui/card.tsx b/packages/admin/src/components/ui/card.tsxindex 49b719a157..03dcd6570e 100644--- a/packages/admin/src/components/ui/card.tsx+++ b/packages/admin/src/components/ui/card.tsx@@ -20,7 +20,7 @@ function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {<divdata-slot="card-header"className={cn(- 'group/card-header @container/card-header grid auto-rows-min items-start gap-1 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] px-3 py-2 border-b border-gray-100 rounded-t-[calc(var(--radius-2xl)-1px)]',+ 'group/card-header @container/card-header grid auto-rows-min items-start gap-1 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] px-3 py-2.5 border-b border-gray-100 rounded-t-[calc(var(--radius-2xl)-1px)]',className,)}{...props}diff --git a/packages/admin/src/hooks/use-order.ts b/packages/admin/src/hooks/use-order.tsnew file mode 100644index 0000000000..c81ec8c609--- /dev/null+++ b/packages/admin/src/hooks/use-order.ts@@ -0,0 +1,46 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { adminClient } from '@/client'++export const orderQueryKey = (id: string) => ['order', id] as const+export const ordersQueryKey = ['orders'] as const++export function useOrder(orderId: string) {+ return useQuery({+ queryKey: orderQueryKey(orderId),+ queryFn: () =>+ adminClient.orders.get(orderId, {+ expand: [+ 'items',+ 'fulfillments',+ 'fulfillments.delivery_method',+ 'fulfillments.stock_location',+ 'payments',+ 'payments.payment_method',+ 'billing_address',+ 'shipping_address',+ 'customer',+ 'created_by',+ 'canceler',+ 'approver',+ 'market',+ ],+ }),+ enabled: !!orderId,+ })+}++/**+ * Generic factory for an order mutation that invalidates the order detail+ * query on success. Use this for operations that don't fit the toast-bundled+ * `useResourceMutation` (e.g., chained updates, custom error handling).+ */+export function useOrderMutation<TParams>(+ orderId: string,+ mutationFn: (params: TParams) => Promise<unknown>,+) {+ const queryClient = useQueryClient()+ return useMutation({+ mutationFn,+ onSuccess: () => queryClient.invalidateQueries({ queryKey: orderQueryKey(orderId) }),+ })+}diff --git a/packages/admin/src/hooks/use-resource-mutation.ts b/packages/admin/src/hooks/use-resource-mutation.tsnew file mode 100644index 0000000000..0b6c579d85--- /dev/null+++ b/packages/admin/src/hooks/use-resource-mutation.ts@@ -0,0 +1,71 @@+import {+ type QueryKey,+ type UseMutationOptions,+ useMutation,+ useQueryClient,+} from '@tanstack/react-query'+import { toast } from 'sonner'++interface UseResourceMutationOptions<TData, TError, TVariables>+ extends Omit<UseMutationOptions<TData, TError, TVariables>, 'onSuccess' | 'onError'> {+ /** Query keys to invalidate after success. Wrap singletons: `[orderQueryKey(id)]`. */+ invalidate?: QueryKey[]+ /** Toast on success. Pass `false` to disable. Default `'Saved'`. */+ successMessage?: string | false+ /** Toast on error. Pass `false` to disable. Default `'Something went wrong'`. */+ errorMessage?: string | false+ /** Forwarded onSuccess callback. Runs after invalidation + toast. */+ onSuccess?: UseMutationOptions<TData, TError, TVariables>['onSuccess']+ /** Forwarded onError callback. Runs after error toast. */+ onError?: UseMutationOptions<TData, TError, TVariables>['onError']+}++/**+ * Wrapper around `useMutation` that bundles the two patterns every resource+ * mutation needs: query invalidation and success/error toasts.+ *+ * Replaces the per-page `try/catch + toast.success/toast.error` boilerplate.+ *+ * ```ts+ * const updateProduct = useResourceMutation({+ * mutationFn: (params) => adminClient.products.update(id, params),+ * invalidate: [productQueryKey(id), productsQueryKey],+ * successMessage: 'Product saved',+ * errorMessage: 'Failed to save product',+ * })+ * ```+ */+export function useResourceMutation<TData = unknown, TError = Error, TVariables = void>(+ options: UseResourceMutationOptions<TData, TError, TVariables>,+) {+ const queryClient = useQueryClient()+ const {+ invalidate,+ successMessage = 'Saved',+ errorMessage = 'Something went wrong',+ onSuccess,+ onError,+ ...rest+ } = options++ return useMutation<TData, TError, TVariables>({+ ...rest,+ onSuccess: (data, variables, onMutateResult, ctx) => {+ if (invalidate) {+ for (const key of invalidate) {+ queryClient.invalidateQueries({ queryKey: key })+ }+ }+ if (successMessage !== false) {+ toast.success(successMessage)+ }+ return onSuccess?.(data, variables, onMutateResult, ctx)+ },+ onError: (error, variables, onMutateResult, ctx) => {+ if (errorMessage !== false) {+ toast.error(errorMessage)+ }+ return onError?.(error, variables, onMutateResult, ctx)+ },+ })+}diff --git a/packages/admin/src/lib/slot-registry.ts b/packages/admin/src/lib/slot-registry.tsnew file mode 100644index 0000000000..6ea8577a34--- /dev/null+++ b/packages/admin/src/lib/slot-registry.ts@@ -0,0 +1,116 @@+import type { ComponentType } from 'react'+import { useSyncExternalStore } from 'react'++// ============================================================================+// Types+// ============================================================================++/**+ * Ambient context every slot receives, on top of slot-specific context.+ * Populated by SlotProvider (see slot.tsx). Plugins reading these don't need+ * to import auth/permission hooks — the slot machinery passes them through.+ */+export interface SlotAmbientContext {+ permissions?: unknown+ store?: unknown+ user?: unknown+}++export interface SlotEntry<TContext = unknown> {+ /** Unique within a slot. Required for removeSlot/updateSlot. */+ id: string+ component: ComponentType<TContext & SlotAmbientContext>+ /** Lower numbers render first. Built-ins use 100/200/300 to leave gaps. */+ position?: number+ /** Visibility predicate. Receives the merged context. */+ if?: (ctx: TContext & SlotAmbientContext) => boolean+}++// ============================================================================+// Registry — module-singleton keyed by slot name+// ============================================================================++const registry = new Map<string, SlotEntry[]>()+const listeners = new Set<() => void>()++function notify() {+ for (const listener of listeners) listener()+}++function subscribe(listener: () => void) {+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ }+}++function getSnapshot(name: string): readonly SlotEntry[] {+ return registry.get(name) ?? EMPTY+}++const EMPTY: readonly SlotEntry[] = Object.freeze([])++// ============================================================================+// Public API+// ============================================================================++export function registerSlot<TContext = unknown>(name: string, entry: SlotEntry<TContext>): void {+ const list = registry.get(name) ?? []+ if (list.some((e) => e.id === entry.id)) {+ throw new Error(+ `Slot "${name}" already has an entry with id "${entry.id}". Use updateSlot() instead.`,+ )+ }+ registry.set(name, [...list, entry as SlotEntry])+ notify()+}++export function removeSlot(name: string, id: string): void {+ const list = registry.get(name)+ if (!list) return+ const next = list.filter((e) => e.id !== id)+ if (next.length === list.length) return+ registry.set(name, next)+ notify()+}++export function updateSlot<TContext = unknown>(+ name: string,+ id: string,+ patch: Partial<Omit<SlotEntry<TContext>, 'id'>>,+): void {+ const list = registry.get(name)+ const entry = list?.find((e) => e.id === id)+ if (!list || !entry) {+ throw new Error(`Slot entry "${name}#${id}" not found.`)+ }+ registry.set(+ name,+ list.map((e) => (e.id === id ? ({ ...e, ...patch } as SlotEntry) : e)),+ )+ notify()+}++/**+ * Subscribe to a slot's entries. Re-renders when entries are added/removed/updated+ * so plugins registered after first render still appear.+ *+ * Returned entries are sorted by position (default 100) and stable within ties.+ * Filtering by `if` happens at render time inside <Slot> — the hook returns the+ * full registered list so the caller can decide how to combine context.+ */+export function useSlotEntries(name: string): readonly SlotEntry[] {+ const entries = useSyncExternalStore(+ subscribe,+ () => getSnapshot(name),+ () => getSnapshot(name),+ )+ // Sort by position (stable). Returned array is fresh; safe to reference in render.+ return [...entries].sort((a, b) => (a.position ?? 100) - (b.position ?? 100))+}++/** Test-only: clear all registered slots. Not exported from the package index. */+export function __resetSlotRegistry(): void {+ registry.clear()+ notify()+}diff --git a/packages/admin/src/routes/_authenticated/$storeId.tsx b/packages/admin/src/routes/_authenticated/$storeId.tsxindex 2b23b96b78..b3fc2e1ed5 100644--- a/packages/admin/src/routes/_authenticated/$storeId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId.tsx@@ -2,13 +2,6 @@ import { createFileRoute, Outlet } from '@tanstack/react-router'import { useEffect } from 'react'import { adminClient } from '@/client'import { AppSidebar } from '@/components/app-sidebar'-import {- Breadcrumb,- BreadcrumbItem,- BreadcrumbList,- BreadcrumbPage,-} from '@/components/ui/breadcrumb'-import { Separator } from '@/components/ui/separator'import { SidebarInset, SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar'import { StoreProvider } from '@/providers/store-provider'@@ -31,14 +24,6 @@ function StoreLayout() {<header className="flex h-header-height shrink-0 items-center bg-white shadow-[inset_0_-1px_0_var(--color-border)]"><div className="flex items-center gap-2 px-4 h-header-height"><SidebarTrigger className="-ml-1 h-8 w-8" />- <Separator orientation="vertical" className="mr-2 h-8 bg-gray-200/75" />- <Breadcrumb>- <BreadcrumbList>- <BreadcrumbItem>- <BreadcrumbPage>Dashboard</BreadcrumbPage>- </BreadcrumbItem>- </BreadcrumbList>- </Breadcrumb></div></header><div className="container mx-auto flex flex-1 flex-col gap-4 p-4">diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsxindex 4e76659654..b1130ebf69 100644--- a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx@@ -15,6 +15,7 @@ import { adminClient } from '@/client'import { AddressFormDialog, type AddressParams } from '@/components/address-form-dialog'import { BackButton } from '@/components/back-button'import { useConfirm } from '@/components/confirm-dialog'+import { ErrorState } from '@/components/spree/route-error-boundary'import { TagCombobox } from '@/components/tag-combobox'import { Badge, StatusBadge } from '@/components/ui/badge'import { Button } from '@/components/ui/button'@@ -68,11 +69,18 @@ function useCustomerMutation<TParams>(function CustomerDetailPage() {const { customerId } = Route.useParams()- const { data: customer, isLoading, error } = useCustomer(customerId)+ const { data: customer, isLoading, error, refetch } = useCustomer(customerId)if (isLoading) return <p className="text-muted-foreground">Loading customer…</p>- if (error || !customer)- return <p className="text-destructive">Failed to load customer {customerId}.</p>+ if (error || !customer) {+ return (+ <ErrorState+ title="Failed to load customer"+ error={error as Error | undefined}+ onRetry={() => refetch()}+ />+ )+ }const defaultShipping = customer.addresses?.find((a) => a.is_default_shipping)const location = [defaultShipping?.city, defaultShipping?.country_iso].filter(Boolean).join(', ')diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex 67326f0ed8..98524d9500 100644--- a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -22,8 +22,10 @@ import { type FormEvent, useEffect, useState } from 'react'import { adminClient } from '@/client'import { AddressBlock } from '@/components/address-block'import { AddressFormDialog, type AddressParams } from '@/components/address-form-dialog'-import { BackButton } from '@/components/back-button'import { useConfirm } from '@/components/confirm-dialog'+import { PageHeader } from '@/components/spree/page-header'+import { ResourceLayout } from '@/components/spree/resource-layout'+import { ErrorState } from '@/components/spree/route-error-boundary'import { TagCombobox } from '@/components/tag-combobox'import { Badge, StatusBadge } from '@/components/ui/badge'import { Button } from '@/components/ui/button'@@ -65,7 +67,8 @@ import {import { Skeleton } from '@/components/ui/skeleton'import { Switch } from '@/components/ui/switch'import { Textarea } from '@/components/ui/textarea'-import { useAuth } from '@/hooks/use-auth'+import { orderQueryKey, useOrder, useOrderMutation } from '@/hooks/use-order'+import { useResourceMutation } from '@/hooks/use-resource-mutation'import { formatRelativeTime } from '@/lib/formatters'import { cn } from '@/lib/utils'@@ -73,48 +76,6 @@ export const Route = createFileRoute('/_authenticated/$storeId/orders/$orderId')component: OrderDetailPage,})-// ----------------------------------------------------------------------------// Data hooks-// -----------------------------------------------------------------------------function useOrder(orderId: string) {- const { isAuthenticated } = useAuth()- return useQuery({- queryKey: ['order', orderId],- queryFn: () =>- adminClient.orders.get(orderId, {- expand: [- 'items',- 'fulfillments',- 'fulfillments.delivery_method',- 'fulfillments.stock_location',- 'payments',- 'payments.payment_method',- 'billing_address',- 'shipping_address',- 'customer',- 'created_by',- 'canceler',- 'approver',- 'market',- ],- }),- enabled: isAuthenticated,- })-}--/** Wrapper for mutations that invalidate the order query on success */-function useOrderMutation<TParams>(- orderId: string,- mutationFn: (params: TParams) => Promise<unknown>,-) {- const queryClient = useQueryClient()- return useMutation({- mutationFn,- onSuccess: () => queryClient.invalidateQueries({ queryKey: ['order', orderId] }),- })-}-// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------@@ -136,34 +97,41 @@ function formatDate(iso: string | null) {function OrderDetailPage() {const { orderId } = Route.useParams()- const { data: order, isLoading, error } = useOrder(orderId)+ const { data: order, isLoading, error, refetch } = useOrder(orderId)if (isLoading) return <OrderSkeleton />- if (error || !order) return <p className="text-destructive">Failed to load order {orderId}.</p>+ if (error || !order) {+ return (+ <ErrorState+ title="Failed to load order"+ description={`We couldn't load order ${orderId}.`}+ error={error as Error | undefined}+ onRetry={() => refetch()}+ />+ )+ }return (- <div className="flex flex-col gap-6">- <OrderHeader order={order} />-- <div className="grid grid-cols-12 gap-6">- {/* Main content */}- <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">+ <ResourceLayout+ header={<OrderHeader order={order} />}+ main={+ <><LineItemsCard order={order} /><ShipmentsCard order={order} /><PaymentsCard order={order} /><OrderSummaryCard order={order} />- </div>-- {/* Sidebar */}- <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">+ </>+ }+ sidebar={+ <><CustomerCard order={order} /><TagsCard order={order} /><DiscountsCard order={order} /><SpecialInstructionsCard order={order} /><InternalNoteCard order={order} />- </div>- </div>- </div>+ </>+ }+ />)}@@ -177,126 +145,146 @@ function OrderHeader({ order }: { order: Order }) {const backFallback = order.completed_at ? 'orders' : 'orders/drafts'- const cancelMutation = useOrderMutation(orderId, () => adminClient.orders.cancel(orderId))- const completeMutation = useOrderMutation(orderId, () => adminClient.orders.complete(orderId))- const approveMutation = useOrderMutation(orderId, () => adminClient.orders.approve(orderId))- const resumeMutation = useOrderMutation(orderId, () => adminClient.orders.resume(orderId))- const resendMutation = useOrderMutation(orderId, () =>- adminClient.orders.resendConfirmation(orderId, {}),- )-- return (- <div className="flex items-center gap-3">- <BackButton fallback={backFallback} />-- <h1 className="text-2xl font-medium">{order.number}</h1>+ const cancelMutation = useResourceMutation({+ mutationFn: () => adminClient.orders.cancel(orderId),+ invalidate: [orderQueryKey(orderId)],+ successMessage: 'Order canceled',+ errorMessage: 'Failed to cancel order',+ })+ const completeMutation = useResourceMutation({+ mutationFn: () => adminClient.orders.complete(orderId),+ invalidate: [orderQueryKey(orderId)],+ successMessage: 'Order completed',+ errorMessage: 'Failed to complete order',+ })+ const approveMutation = useResourceMutation({+ mutationFn: () => adminClient.orders.approve(orderId),+ invalidate: [orderQueryKey(orderId)],+ successMessage: 'Order approved',+ errorMessage: 'Failed to approve order',+ })+ const resumeMutation = useResourceMutation({+ mutationFn: () => adminClient.orders.resume(orderId),+ invalidate: [orderQueryKey(orderId)],+ successMessage: 'Order resumed',+ errorMessage: 'Failed to resume order',+ })+ const resendMutation = useResourceMutation({+ mutationFn: () => adminClient.orders.resendConfirmation(orderId, {}),+ successMessage: 'Confirmation sent',+ errorMessage: 'Failed to send confirmation',+ })+ const badges = (+ <>{order.payment_status && <StatusBadge status={order.payment_status} />}{order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}+ </>+ )+ const subtitle = order.completed_at+ ? `Completed ${formatRelativeTime(order.completed_at)}`+ : undefined++ const dropdownItems = (+ <>+ {order.status === 'draft' && (+ <DropdownMenuItem+ onClick={async () => {+ if (+ await confirm({+ message: 'Complete this draft order now?',+ confirmLabel: 'Complete',+ })+ ) {+ completeMutation.mutate(undefined)+ }+ }}+ disabled={completeMutation.isPending}+ >+ <CheckCircleIcon className="size-4" />+ Complete Order+ </DropdownMenuItem>+ )}+ {order.considered_risky && !order.approved_at && (+ <DropdownMenuItem+ onClick={async () => {+ if (await confirm({ message: 'Approve this order?', confirmLabel: 'Approve' })) {+ approveMutation.mutate(undefined)+ }+ }}+ disabled={approveMutation.isPending}+ >+ <ShieldCheckIcon className="size-4" />+ Approve Order+ </DropdownMenuItem>+ )}+ {order.status === 'canceled' && (+ <DropdownMenuItem+ onClick={async () => {+ if (+ await confirm({+ message: 'Resume this canceled order?',+ confirmLabel: 'Resume',+ })+ ) {+ resumeMutation.mutate(undefined)+ }+ }}+ disabled={resumeMutation.isPending}+ >+ <RotateCcwIcon className="size-4" />+ Resume Order+ </DropdownMenuItem>+ )}{order.completed_at && (- <span className="text-sm text-muted-foreground">- Completed {order.completed_at ? formatRelativeTime(order.completed_at) : ''}- </span>+ <>+ <DropdownMenuItem>+ <ExternalLinkIcon className="size-4" />+ Preview Order+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => resendMutation.mutate(undefined)}+ disabled={resendMutation.isPending}+ >+ <MailIcon className="size-4" />+ Resend Confirmation+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ {order.status !== 'canceled' && (+ <DropdownMenuItem+ variant="destructive"+ onClick={async () => {+ if (+ await confirm({+ message: 'Are you sure you want to cancel this order?',+ variant: 'destructive',+ confirmLabel: 'Cancel Order',+ })+ ) {+ cancelMutation.mutate(undefined)+ }+ }}+ disabled={cancelMutation.isPending}+ >+ <XCircleIcon className="size-4" />+ Cancel Order+ </DropdownMenuItem>)}+ </>+ )- <div className="ml-auto">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button size="icon-sm" variant="outline">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- {order.status === 'draft' && (- <DropdownMenuItem- onClick={async () => {- if (- await confirm({- message: 'Complete this draft order now?',- confirmLabel: 'Complete',- })- ) {- completeMutation.mutate(undefined)- }- }}- disabled={completeMutation.isPending}- >- <CheckCircleIcon className="size-4" />- Complete Order- </DropdownMenuItem>- )}- {order.considered_risky && !order.approved_at && (- <DropdownMenuItem- onClick={async () => {- if (await confirm({ message: 'Approve this order?', confirmLabel: 'Approve' })) {- approveMutation.mutate(undefined)- }- }}- disabled={approveMutation.isPending}- >- <ShieldCheckIcon className="size-4" />- Approve Order- </DropdownMenuItem>- )}- {order.status === 'canceled' && (- <DropdownMenuItem- onClick={async () => {- if (- await confirm({- message: 'Resume this canceled order?',- confirmLabel: 'Resume',- })- ) {- resumeMutation.mutate(undefined)- }- }}- disabled={resumeMutation.isPending}- >- <RotateCcwIcon className="size-4" />- Resume Order- </DropdownMenuItem>- )}- {order.completed_at && (- <>- <DropdownMenuItem>- <ExternalLinkIcon className="size-4" />- Preview Order- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => resendMutation.mutate(undefined)}- disabled={resendMutation.isPending}- >- <MailIcon className="size-4" />- Resend Confirmation- </DropdownMenuItem>- <DropdownMenuSeparator />- </>- )}- {order.status !== 'canceled' && (- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={async () => {- if (- await confirm({- message: 'Are you sure you want to cancel this order?',- variant: 'destructive',- confirmLabel: 'Cancel Order',- })- ) {- cancelMutation.mutate(undefined)- }- }}- disabled={cancelMutation.isPending}- >- <XCircleIcon className="size-4" />- Cancel Order- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>- </div>- </div>+ return (+ <PageHeader+ title={order.number}+ subtitle={subtitle}+ backTo={backFallback}+ badges={badges}+ dropdownItems={dropdownItems}+ resource={{ id: order.id, number: order.number }}+ />)}diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsxindex 0c0088fc08..4192dc7331 100644--- a/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx@@ -4,7 +4,8 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'import { TrashIcon, XIcon } from 'lucide-react'import { type FormEvent, useState } from 'react'import { adminClient } from '@/client'-import { BackButton } from '@/components/back-button'+import { PageHeader } from '@/components/spree/page-header'+import { ResourceLayout } from '@/components/spree/resource-layout'import { Button } from '@/components/ui/button'import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'@@ -104,246 +105,243 @@ function NewOrderPage() {}return (- <div className="flex flex-col gap-6">- <div className="flex items-center gap-3">- <BackButton fallback="orders/drafts" />- <h1 className="text-2xl font-medium">New Order</h1>- </div>+ <form onSubmit={handleSubmit}>+ <ResourceLayout+ header={<PageHeader title="New Order" backTo="orders/drafts" />}+ main={+ <>+ <Card>+ <CardHeader>+ <CardTitle>Customer</CardTitle>+ </CardHeader>+ <CardContent>+ {customer ? (+ <div className="flex items-center justify-between rounded-md border p-3">+ <div>+ <div className="font-medium">{customer.email}</div>+ {(customer.first_name || customer.last_name) && (+ <div className="text-sm text-muted-foreground">+ {[customer.first_name, customer.last_name].filter(Boolean).join(' ')}+ </div>+ )}+ </div>+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => {+ setCustomer(null)+ setCustomerSearch('')+ }}+ >+ <XIcon className="size-4" />+ Change+ </Button>+ </div>+ ) : (+ <FieldGroup>+ <Field>+ <FieldLabel>Search by email or name</FieldLabel>+ <Input+ placeholder="Type 2+ chars to search…"+ value={customerSearch}+ onChange={(e) => setCustomerSearch(e.target.value)}+ />+ {customerSearch.length >= 2 && customerResults.length > 0 && (+ <div className="mt-1 rounded-lg border bg-white shadow-xs max-h-[280px] overflow-y-auto">+ {customerResults.map((c) => (+ <button+ key={c.id}+ type="button"+ onClick={() => {+ setCustomer(c)+ setCustomerSearch('')+ }}+ className="block w-full px-3 py-2.5 text-left text-sm hover:bg-muted transition-colors border-b last:border-0"+ >+ <div className="font-medium">{c.email}</div>+ {(c.first_name || c.last_name) && (+ <div className="text-xs text-muted-foreground">+ {[c.first_name, c.last_name].filter(Boolean).join(' ')}+ </div>+ )}+ </button>+ ))}+ </div>+ )}+ </Field>+ <Field>+ <FieldLabel>Or use a guest email</FieldLabel>+ <Input+ type="email"+ placeholder="[email protected]"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ />+ </Field>+ </FieldGroup>+ )}- <form onSubmit={handleSubmit} className="grid grid-cols-12 gap-6">- {/* Main */}- <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">- <Card>- <CardHeader>- <CardTitle>Customer</CardTitle>- </CardHeader>- <CardContent>- {customer ? (- <div className="flex items-center justify-between rounded-md border p-3">- <div>- <div className="font-medium">{customer.email}</div>- {(customer.first_name || customer.last_name) && (- <div className="text-sm text-muted-foreground">- {[customer.first_name, customer.last_name].filter(Boolean).join(' ')}- </div>- )}+ {customer && (+ <div className="mt-4 flex items-center gap-3">+ <Switch checked={useDefaultAddress} onCheckedChange={setUseDefaultAddress} />+ <span className="text-sm">+ Use customer's default billing & shipping addresses+ </span></div>- <Button- type="button"- size="sm"- variant="outline"- onClick={() => {- setCustomer(null)- setCustomerSearch('')- }}- >- <XIcon className="size-4" />- Change- </Button>- </div>- ) : (+ )}+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>Items</CardTitle>+ </CardHeader>+ <CardContent><FieldGroup><Field>- <FieldLabel>Search by email or name</FieldLabel>+ <FieldLabel>Add a variant</FieldLabel><Input- placeholder="Type 2+ chars to search…"- value={customerSearch}- onChange={(e) => setCustomerSearch(e.target.value)}+ placeholder="Search by name or SKU (3+ chars)…"+ value={variantSearch}+ onChange={(e) => setVariantSearch(e.target.value)}/>- {customerSearch.length >= 2 && customerResults.length > 0 && (+ {variantSearch.length >= 3 && variantResults.length > 0 && (<div className="mt-1 rounded-lg border bg-white shadow-xs max-h-[280px] overflow-y-auto">- {customerResults.map((c) => (+ {variantResults.map((v) => (<button- key={c.id}+ key={v.id}type="button"- onClick={() => {- setCustomer(c)- setCustomerSearch('')- }}+ onClick={() => addItem(v)}className="block w-full px-3 py-2.5 text-left text-sm hover:bg-muted transition-colors border-b last:border-0">- <div className="font-medium">{c.email}</div>- {(c.first_name || c.last_name) && (- <div className="text-xs text-muted-foreground">- {[c.first_name, c.last_name].filter(Boolean).join(' ')}- </div>- )}+ <div className="font-medium">{v.product_name ?? v.sku ?? v.id}</div>+ <div className="text-xs text-muted-foreground">+ SKU {v.sku} · {v.display_price ?? '—'}+ </div></button>))}</div>)}</Field>+ </FieldGroup>++ {items.length > 0 && (+ <div className="mt-4 overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b bg-muted/50 text-muted-foreground">+ <th className="p-3 pl-5 text-left font-normal">Variant</th>+ <th className="p-3 text-left font-normal">SKU</th>+ <th className="p-3 text-right font-normal">Qty</th>+ <th className="p-3 pr-5 w-10" />+ </tr>+ </thead>+ <tbody>+ {items.map(({ variant, quantity }) => (+ <tr key={variant.id} className="border-b last:border-b-0">+ <td className="p-3 pl-5 font-medium">+ {variant.product_name ?? variant.sku ?? variant.id}+ </td>+ <td className="p-3 text-muted-foreground">{variant.sku}</td>+ <td className="p-3 text-right">+ <Input+ type="number"+ min={1}+ value={quantity}+ onChange={(e) => updateQuantity(variant.id, Number(e.target.value))}+ className="w-20 text-right ml-auto"+ />+ </td>+ <td className="p-3 pr-5 text-right">+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ onClick={() => removeItem(variant.id)}+ >+ <TrashIcon className="size-4" />+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </CardContent>+ </Card>+ </>+ }+ sidebar={+ <>+ <Card>+ <CardHeader>+ <CardTitle>Notes</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup><Field>- <FieldLabel>Or use a guest email</FieldLabel>- <Input- type="email"- placeholder="[email protected]"- value={email}- onChange={(e) => setEmail(e.target.value)}+ <FieldLabel htmlFor="customer-note">+ Customer note (visible to customer)+ </FieldLabel>+ <Textarea+ id="customer-note"+ rows={3}+ value={customerNote}+ onChange={(e) => setCustomerNote(e.target.value)}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor="internal-note">Internal note (staff only)</FieldLabel>+ <Textarea+ id="internal-note"+ rows={3}+ value={internalNote}+ onChange={(e) => setInternalNote(e.target.value)}/></Field></FieldGroup>- )}-- {customer && (- <div className="mt-4 flex items-center gap-3">- <Switch checked={useDefaultAddress} onCheckedChange={setUseDefaultAddress} />- <span className="text-sm">- Use customer's default billing & shipping addresses- </span>- </div>- )}- </CardContent>- </Card>-- <Card>- <CardHeader>- <CardTitle>Items</CardTitle>- </CardHeader>- <CardContent>- <FieldGroup>- <Field>- <FieldLabel>Add a variant</FieldLabel>- <Input- placeholder="Search by name or SKU (3+ chars)…"- value={variantSearch}- onChange={(e) => setVariantSearch(e.target.value)}- />- {variantSearch.length >= 3 && variantResults.length > 0 && (- <div className="mt-1 rounded-lg border bg-white shadow-xs max-h-[280px] overflow-y-auto">- {variantResults.map((v) => (- <button- key={v.id}- type="button"- onClick={() => addItem(v)}- className="block w-full px-3 py-2.5 text-left text-sm hover:bg-muted transition-colors border-b last:border-0"- >- <div className="font-medium">{v.product_name ?? v.sku ?? v.id}</div>- <div className="text-xs text-muted-foreground">- SKU {v.sku} · {v.display_price ?? '—'}- </div>- </button>- ))}- </div>- )}- </Field>- </FieldGroup>-- {items.length > 0 && (- <div className="mt-4 overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="border-b bg-muted/50 text-muted-foreground">- <th className="p-3 pl-5 text-left font-normal">Variant</th>- <th className="p-3 text-left font-normal">SKU</th>- <th className="p-3 text-right font-normal">Qty</th>- <th className="p-3 pr-5 w-10" />- </tr>- </thead>- <tbody>- {items.map(({ variant, quantity }) => (- <tr key={variant.id} className="border-b last:border-b-0">- <td className="p-3 pl-5 font-medium">- {variant.product_name ?? variant.sku ?? variant.id}- </td>- <td className="p-3 text-muted-foreground">{variant.sku}</td>- <td className="p-3 text-right">- <Input- type="number"- min={1}- value={quantity}- onChange={(e) => updateQuantity(variant.id, Number(e.target.value))}- className="w-20 text-right ml-auto"- />- </td>- <td className="p-3 pr-5 text-right">- <Button- type="button"- size="icon-xs"- variant="ghost"- onClick={() => removeItem(variant.id)}- >- <TrashIcon className="size-4" />- </Button>- </td>- </tr>- ))}- </tbody>- </table>- </div>- )}- </CardContent>- </Card>- </div>+ </CardContent>+ </Card>- {/* Sidebar */}- <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">- <Card>- <CardHeader>- <CardTitle>Notes</CardTitle>- </CardHeader>- <CardContent>- <FieldGroup>- <Field>- <FieldLabel htmlFor="customer-note">- Customer note (visible to customer)- </FieldLabel>- <Textarea- id="customer-note"- rows={3}- value={customerNote}- onChange={(e) => setCustomerNote(e.target.value)}- />- </Field>- <Field>- <FieldLabel htmlFor="internal-note">Internal note (staff only)</FieldLabel>- <Textarea- id="internal-note"- rows={3}- value={internalNote}- onChange={(e) => setInternalNote(e.target.value)}- />- </Field>- </FieldGroup>- </CardContent>- </Card>-- <Card>- <CardHeader>- <CardTitle>Discount</CardTitle>- </CardHeader>- <CardContent>- <FieldGroup>- <Field>- <FieldLabel htmlFor="coupon-code">Coupon code</FieldLabel>- <Input- id="coupon-code"- placeholder="Optional"- value={couponCode}- onChange={(e) => setCouponCode(e.target.value)}- />- </Field>- </FieldGroup>- </CardContent>- </Card>+ <Card>+ <CardHeader>+ <CardTitle>Discount</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="coupon-code">Coupon code</FieldLabel>+ <Input+ id="coupon-code"+ placeholder="Optional"+ value={couponCode}+ onChange={(e) => setCouponCode(e.target.value)}+ />+ </Field>+ </FieldGroup>+ </CardContent>+ </Card>- <Card>- <CardContent className="flex flex-col gap-3 pt-6">- <Button type="submit" disabled={!canSubmit}>- {createMutation.isPending ? 'Creating…' : 'Create Order'}- </Button>- {createMutation.error && (- <p className="text-sm text-destructive">- {(createMutation.error as Error).message}+ <Card>+ <CardContent className="flex flex-col gap-3 pt-6">+ <Button type="submit" disabled={!canSubmit}>+ {createMutation.isPending ? 'Creating…' : 'Create Order'}+ </Button>+ {createMutation.error && (+ <p className="text-sm text-destructive">+ {(createMutation.error as Error).message}+ </p>+ )}+ <p className="text-xs text-muted-foreground">+ Creates a draft order. Add payments and complete it after creation.</p>- )}- <p className="text-xs text-muted-foreground">- Creates a draft order. Add payments and complete it after creation.- </p>- </CardContent>- </Card>- </div>- </form>- </div>+ </CardContent>+ </Card>+ </>+ }+ />+ </form>)}diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsxindex 24b0eb2d09..d5284d7675 100644--- a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -15,12 +15,15 @@ type Product = Omit<BaseProduct, 'default_variant' | 'variants'> & {import { zodResolver } from '@hookform/resolvers/zod'import { createFileRoute, useRouter } from '@tanstack/react-router'-import { ImagePlusIcon, Loader2Icon, SaveIcon, TrashIcon, XIcon } from 'lucide-react'+import { ImagePlusIcon, Loader2Icon, SaveIcon, XIcon } from 'lucide-react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { toast } from 'sonner'-import { BackButton } from '@/components/back-button'import { useConfirm } from '@/components/confirm-dialog'+import { PageHeader } from '@/components/spree/page-header'+import { ResourceLayout } from '@/components/spree/resource-layout'+import { ErrorState } from '@/components/spree/route-error-boundary'+import { StickyFormFooter } from '@/components/spree/sticky-form-footer'import { TagCombobox } from '@/components/tag-combobox'import { StatusBadge } from '@/components/ui/badge'import { Button } from '@/components/ui/button'@@ -118,11 +121,17 @@ function productToFormValues(product: Product, currencies: string[]): ProductForfunction ProductDetailPage() {const { productId } = Route.useParams()- const { data: product, isLoading, error } = useProduct(productId)+ const { data: product, isLoading, error, refetch } = useProduct(productId)if (isLoading) return <ProductSkeleton />if (error || !product) {- return <p className="text-destructive p-4">Failed to load product.</p>+ return (+ <ErrorState+ title="Failed to load product"+ error={error as Error | undefined}+ onRetry={() => refetch()}+ />+ )}return <ProductForm product={product as Product} />@@ -180,60 +189,50 @@ function ProductForm({ product }: { product: Product }) {}}- return (- <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">- {/* Header */}- <div className="flex items-center gap-3">- <BackButton fallback="products" />-- <h1 className="text-2xl font-medium truncate">{product.name}</h1>- <StatusBadge status={product.status} />-- <div className="ml-auto flex items-center gap-2">- <Button- type="button"- variant="destructive"- size="sm"- onClick={handleDelete}- disabled={deleteProduct.isPending}- >- <TrashIcon className="size-4" />- Delete- </Button>- <Button- type="submit"- size="sm"- disabled={updateProduct.isPending || !form.formState.isDirty}- >- {updateProduct.isPending ? (- <Loader2Icon className="size-4 animate-spin" />- ) : (- <SaveIcon className="size-4" />- )}- Save- </Button>- </div>- </div>-- {/* Two-column layout */}- <div className="grid grid-cols-12 gap-6">- {/* Left column */}- <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">- <GeneralCard form={form} />- <MediaCard productId={productId} />- {!hasVariants && <PricingCard form={form} />}- {!hasVariants && <InventoryCard form={form} />}- <SEOCard form={form} product={product} />- </div>+ const saveButton = (+ <Button type="submit" size="sm" disabled={updateProduct.isPending || !form.formState.isDirty}>+ {updateProduct.isPending ? (+ <Loader2Icon className="size-4 animate-spin" />+ ) : (+ <SaveIcon className="size-4" />+ )}+ Save+ </Button>+ )- {/* Right column */}- <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">- <StatusCard form={form} />- <CategorizationCard form={form} />- <ShippingCard form={form} hasVariants={hasVariants} />- <TaxCard form={form} />- </div>- </div>+ return (+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <ResourceLayout+ header={+ <PageHeader+ title={product.name}+ backTo="products"+ badges={<StatusBadge status={product.status} />}+ actions={saveButton}+ resource={{ id: product.id }}+ onDelete={handleDelete}+ deleteLabel="Delete product"+ />+ }+ main={+ <>+ <GeneralCard form={form} />+ <MediaCard productId={productId} />+ {!hasVariants && <PricingCard form={form} />}+ {!hasVariants && <InventoryCard form={form} />}+ <SEOCard form={form} product={product} />+ </>+ }+ sidebar={+ <>+ <StatusCard form={form} />+ <CategorizationCard form={form} />+ <ShippingCard form={form} hasVariants={hasVariants} />+ <TaxCard form={form} />+ </>+ }+ />+ <StickyFormFooter form={form} saveLabel="Save product" /></form>)}