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
Restructure dashboard docs + auto-discover plugin packages
Damian Legawiec5f5d1eec9278
diff --git a/docs/developer/customization/dashboard-plugins.mdx b/docs/developer/customization/dashboard-plugins.mdxdeleted file mode 100644index cc985ddde7..0000000000--- a/docs/developer/customization/dashboard-plugins.mdx+++ /dev/null@@ -1,390 +0,0 @@-----title: Dashboard Plugins-sidebarTitle: Dashboard Plugins-description: Extend the Spree 6.0 admin dashboard with a redistributable npm plugin — nav entries, custom routes, slot widgets, table columns, translations.------<Info>-The dashboard plugin API ships in **Spree 5.5** as part of the new Vite-based admin dashboard (currently developer preview).-For the stable admin dashboard refer to the [extension model](/developer/admin/extending-ui).-</Info>--A dashboard plugin is an npm package that extends the Spree admin without forking it. Plugins can:--- Add **sidebar entries** that link to plugin-owned pages-- Mount **custom routes** under `/$storeId/...`-- Inject **slot widgets** into core pages (e.g. a card on the product detail page)-- Add **columns to existing tables** (Products, Orders, Customers, …)-- Register **their own resource tables** for use with `<ResourceTable>`-- Contribute **translations** that merge into the framework's i18next namespace--A working reference implementation lives in [`packages/dashboard-plugin-example/`](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) in the Spree monorepo — a Brands plugin that exercises every extension point. The Spree CLI scaffolds the same shape for any new plugin.--## Quick start: scaffold with `@spree/cli`--```bash-npx @spree/cli plugin new brands-```--The CLI walks you through the prompts (plugin name, npm scope, author, license) and produces a monorepo with the dashboard plugin pre-wired. It picks the npm package name, peer dependencies, and `defineDashboardPlugin` skeleton based on your answers.--```bash-brands/-├── package.json # workspace root (e.g. "@acme/brands")-├── pnpm-workspace.yaml-├── README.md-├── LICENSE-└── packages/- └── dashboard/ # the dashboard plugin (e.g. "@acme/brands-dashboard")- ├── package.json- ├── tsconfig.json- ├── biome.json- └── src/- ├── index.tsx # entry — defineDashboardPlugin call- ├── types.ts # TypeScript shapes for your records- ├── client.ts # adminClient.request wrappers- ├── routes/- │ └── brands-list.tsx # custom route mounted at /$storeId/brands- ├── slots/- │ └── product-brands-card.tsx- └── locales/- └── en.json-```--Flags:-- `--no-dashboard` — skip the dashboard plugin half-- `--no-install` — don't run `pnpm install` after scaffolding-- `--force` — overwrite a non-empty destination directory--The CLI also reserves `--no-engine` for the upcoming Rails-engine scaffolding (the Ruby half that ships your Admin API endpoints). For now, generate the Ruby side with the existing [`spree-extension`](https://github.com/spree/spree_extension) gem alongside the CLI's dashboard output.--## Anatomy of a plugin--If you're not using the CLI, the minimum layout is:--```-my-spree-plugin/-├── package.json # peer deps + version-├── tsconfig.json-└── src/- ├── index.tsx # entry — defineDashboardPlugin call- ├── types.ts # TypeScript shapes for your records- ├── client.ts # adminClient.request wrappers- ├── routes/- │ └── my-list-page.tsx # custom route(s)- ├── slots/- │ └── my-widget.tsx # slot widget(s)- └── locales/- └── en.json # translations-```--### package.json — peer dependencies--```jsonc-{- "name": "spree-brands-plugin",- "version": "0.1.0",- "type": "module",- "main": "./src/index.tsx",- "exports": { ".": "./src/index.tsx" },- "peerDependencies": {- "@spree/admin-sdk": "^0.1.0",- "@spree/dashboard-core": "^0.1.0",- "@spree/dashboard-ui": "^0.1.0",- "@tanstack/react-query": "^5",- "@tanstack/react-router": "^1",- "i18next": "^26",- "react": "^19",- "react-i18next": "^17"- }-}-```--**Always declare these as peer deps, not regular deps.** The dashboard's four registries (nav, route, slot, table) are module singletons — if your plugin bundles its own copy of `@spree/dashboard-core`, your `nav.add()` call writes to a different Map than the dashboard reads. pnpm/yarn dedupe peer deps to a single instance and that's the only setup that works.--### src/index.tsx — the entry--The plugin's entry calls `defineDashboardPlugin` once at module load. The dashboard imports the plugin as a side-effect:--```tsx-// my-spree-plugin/src/index.tsx-import { defineDashboardPlugin, i18n } from '@spree/dashboard-core'-import { PackageIcon } from 'lucide-react'-import en from './locales/en.json'-import { BrandsListPage } from './routes/brands-list'-import { ProductBrandCard } from './slots/product-brand-card'--// 1. Merge translations into the dashboard's existing `admin.*` namespace.-i18n.addResourceBundle('en', 'translation', en, true, true)--// 2. Register everything else.-defineDashboardPlugin({- nav: [{- key: 'brands',- label: i18n.t('admin.brands_plugin.nav'),- path: '/brands',- icon: PackageIcon,- position: 35,- subject: 'Spree::Brand', // hide from admins without read permission- }],- routes: [{- key: 'brands',- path: '/brands',- component: BrandsListPage,- subject: 'Spree::Brand',- }],- slots: {- 'product.form_sidebar': [- { id: 'brand-card', component: ProductBrandCard, position: 250 },- ],- },- tables: {- products: { add: [- { key: 'brand', label: 'Brand', render: (p) => p.brand_id ?? '—' },- ]},- },-})-```--The app activates the plugin with a single side-effect import in `main.tsx`, **before the router mounts**:--```tsx-// packages/dashboard/src/main.tsx-import 'spree-brands-plugin' // registers everything above-// ...rest of the dashboard bootstrap-```--## Extension points in detail--### 1. Navigation (`nav`)--Add a sidebar entry. The dashboard prefixes `path` with `/$storeId` automatically:--```ts-nav: [{- key: 'brands',- label: 'Brands',- path: '/brands',- icon: PackageIcon,- position: 35, // 100/200/300 = built-ins; pick a number between- subject: 'Spree::Brand', // CanCanCan subject; omit for always-visible-}]-```--The `subject` field hides the entry for admins who can't `read` the subject. Server-side enforcement still applies — this is UX, not authorization.--`children` lets you nest entries under a top-level parent:--```ts-{ key: 'brands', label: 'Brands', children: [- { key: 'all-brands', label: 'All brands', path: '/brands' },- { key: 'featured-brands', label: 'Featured', path: '/brands?featured=1' },-]}-```--### 2. Routes (`routes`)--Mount a page under `/$storeId/...`. The dashboard's catch-all dispatcher reads from the route registry on every navigation:--```tsx-routes: [{- key: 'brands',- path: '/brands',- component: BrandsListPage,- subject: 'Spree::Brand', // 403 fallback when permission denied-}]-```--Path patterns support TanStack-Router-style params:--```ts-{ key: 'brand-detail', path: '/brands/$brandId', component: BrandDetailPage }-```--Your component receives `{ params, storeId, searchParams }`:--```tsx-function BrandDetailPage({ params, storeId }: {- params: Record<string, string>- storeId: string- searchParams: Record<string, unknown>-}) {- const brandId = params.brandId- // ...-}-```--### 3. Slots (`slots`)--Slots are named injection points the dashboard exposes on built-in pages. The full catalogue lives in `@spree/dashboard`'s source — common slots include:--- `product.form_sidebar` — right sidebar on the product detail page-- `product.actions` — primary action buttons on the product page-- `order.page_body` — main column of the order detail page-- `customer.tabs` — additional tabs on the customer detail page--Register a component for a slot:--```tsx-slots: {- 'product.form_sidebar': [{- id: 'brand-card',- component: ProductBrandCard,- position: 250,- if: (ctx) => ctx.permissions?.can('read', 'Spree::Brand'),- }],-}-```--The slot's context (`product`, `permissions`, `store`, `user`, …) is passed to the component as props. Each slot documents its context shape.--### 4. Tables — extend existing (`tables.<key>.add`)--Add columns to the dashboard's built-in resource tables:--```ts-tables: {- products: {- add: [{- key: 'brand',- label: 'Brand',- sortable: false,- filterable: false,- default: false, // off by default; admin can toggle on- render: (product) => product.brand_id ? <BrandName id={product.brand_id} /> : '—',- }],- // Or remove/update existing columns:- remove: ['legacy_field'],- update: { total_price: { label: 'Net total' } },- },-}-```--If the target table isn't registered yet (route hasn't loaded), the mutation is queued and replayed when `defineTable('products', ...)` runs. You don't need to know the order.--### 4b. Tables — register your own--For plugin-owned tables (used by your custom routes), use `defineTable`:--```tsx-import { defineTable } from '@spree/dashboard-core'--defineTable<Brand>('brands', {- title: 'Brands',- searchParam: 'search',- searchPlaceholder: 'Search by name…',- defaultSort: { field: 'name', direction: 'asc' },- columns: [- { key: 'name', label: 'Name', sortable: true, default: true,- render: (b) => <Link to={`/$storeId/brands/${b.id}`}>{b.name}</Link> },- { key: 'products_count', label: 'Products', default: true,- render: (b) => b.products_count },- ],-})-```--Then mount `<ResourceTable tableKey="brands">` from your route page. See [`packages/dashboard-plugin-example/src/routes/brands-list.tsx`](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example/src/routes/brands-list.tsx) for a runnable example.--### 5. Translations--Merge your keys into the framework's namespace via `i18n.addResourceBundle`:--```tsx-import { i18n } from '@spree/dashboard-core'-import en from './locales/en.json'--i18n.addResourceBundle('en', 'translation', en, true, true)-```--```jsonc-// src/locales/en.json-{- "admin": {- "brands_plugin": { // namespace under admin.<your-plugin>.*- "nav": "Brands",- "page": { "title": "Brands", "subtitle": "Manage product brands" }- }- }-}-```--**Always put plugin text under your own namespace** (`admin.<your-plugin>.*`). Writing to `admin.actions.save` would overwrite the framework's translation — two plugins doing that would race. The dashboard's base namespace (`admin.actions.*`, `admin.common.*`, `admin.fields.<simple>.*`, `admin.validation.*`) is available for you to read but should not be extended.--## Talking to a backend--Your plugin needs a backend to talk to. The dashboard's pre-built SDK methods (`adminClient.products.list()`, `adminClient.orders.get(id)`, etc.) only cover Spree's first-party resources. For your own endpoints, use the SDK's `request` escape hatch:--```ts-// my-spree-plugin/src/client.ts-import { adminClient } from '@spree/dashboard-core'-import type { PaginatedResponse } from '@spree/admin-sdk'-import type { Brand } from './types'--export const brandsClient = {- list: (params?: Record<string, unknown>) =>- adminClient.request<PaginatedResponse<Brand>>('GET', '/brands', { params }),- get: (id: string) =>- adminClient.request<Brand>('GET', `/brands/${id}`),- create: (body: { name: string; slug?: string }) =>- adminClient.request<Brand>('POST', '/brands', { body }),-}-```--Paths are relative to `/api/v3/admin`. The request method uses the same auth (secret key or JWT), retry logic, and 401-refresh handshake as the built-in resources.--The backend half is a normal Spree extension gem: a model, a Rails controller subclassing `Spree::Api::V3::Admin::ResourceController`, an Alba serializer. See [Custom Admin Endpoints](/developer/sdk/admin/extending) and the [Admin API customization](/developer/admin/admin) guide.--## Order-of-operations--Three things must happen at boot, in this order:--1. **i18n bootstrap** — `@spree/dashboard-core`'s `i18n.ts` runs (via the dashboard's `i18n-setup.ts` side-effect import) and registers the base translation namespace.-2. **Plugin imports** — each `import 'my-plugin'` runs `defineDashboardPlugin`, populating registries.-3. **Router mounts** — the dashboard's `RouterProvider` reads the route registry on first navigation.--If a plugin runs before i18n, `i18n.t(...)` returns the literal key string instead of a translation. If a plugin runs after the router mounts, route registration still works (the catch-all reads on every navigation), but nav entries appear "for new visitors only" rather than from boot. **Always import plugins right after `@/i18n-setup` in `main.tsx`.**--## Permission gating--Three places to declare permissions:--- **Nav entry** `subject`: hides the sidebar entry-- **Route entry** `subject`: 403 fallback at the route-- **Slot entry** `if`: visibility predicate, receives the merged context--```ts-nav: [{ key: 'brands', subject: 'Spree::Brand', /* ... */ }],-routes: [{ key: 'brands', subject: 'Spree::Brand', /* ... */ }],-slots: {- 'product.form_sidebar': [{- id: 'brand-card',- component: ProductBrandCard,- if: (ctx) => ctx.permissions?.can('read', 'Spree::Brand'),- }],-}-```--All three are UX-only. The backend's CanCanCan rules still gate the actual API responses — the plugin should treat permission checks as a hint about what to render, not a security boundary.--## Distributing--Publish to npm under your own scope (e.g. `@my-org/spree-brands-plugin`). Document the install:--```bash-pnpm add @my-org/spree-brands-plugin-```--Plus the side-effect import in the dashboard's `main.tsx`:--```tsx-import '@my-org/spree-brands-plugin'-```--Pair the npm package with your Rails-side extension gem so consumers install both. Once both are in place, every store running your customers' dashboards picks up your feature.--## Reference--- [Example plugin source](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) — runnable Brands plugin in the Spree monorepo-- [`@spree/dashboard-core` README](https://github.com/spree/spree/tree/main/packages/dashboard-core) — full extension-API reference-- [Custom Admin Endpoints](/developer/sdk/admin/extending) — `adminClient.request<T>` API-- [Admin API guide](/developer/admin/admin) — adding new Admin API endpointsdiff --git a/docs/developer/dashboard/concepts.mdx b/docs/developer/dashboard/concepts.mdxnew file mode 100644index 0000000000..057feb4ef7--- /dev/null+++ b/docs/developer/dashboard/concepts.mdx@@ -0,0 +1,103 @@+---+title: Concepts+sidebarTitle: Concepts+description: The mental model — what the dashboard is built on, how the pieces fit together, and what you need to know about each layer before you start customizing.+---++This page is a five-minute orientation for the dashboard's technology choices and how they cooperate. If you're already familiar with React + TanStack + Tailwind, skim it for the Spree-specific bits and move on.++## Tech stack at a glance++| Layer | What we use | Why it matters |+|---|---|---|+| Build | [Vite](https://vitejs.dev/) | Fast HMR, dev server, source consumption of TS/TSX |+| UI runtime | [React 19](https://react.dev/) | Components, hooks, suspense |+| Routing | [TanStack Router](https://tanstack.com/router) (file-based) | Type-safe URLs, nested layouts, search params |+| Data | [TanStack Query v5](https://tanstack.com/query) | Caching, refetch, mutation tracking |+| Forms | [React Hook Form](https://react-hook-form.com/) + [Zod](https://zod.dev/) | Uncontrolled inputs + schema validation |+| Styling | [Tailwind v4](https://tailwindcss.com/) + [shadcn/ui](https://ui.shadcn.com/) + [Base UI](https://base-ui.com/) | Utility classes + headless primitives |+| i18n | [i18next](https://www.i18next.com/) | Translations, fallback chains |+| Lint/format | [Biome](https://biomejs.dev/) | ESLint + Prettier in one tool |+| HTTP | [`@spree/dashboard-sdk`](https://www.npmjs.com/package/@spree/dashboard-sdk) | Typed Admin API client |++The dashboard is a **Single Page Application**: one HTML page, all routing client-side. No Rails views, no Turbo, no server-rendered partials. Everything the user sees comes from React components fetching JSON from `/api/v3/admin/*`.++## The three-package split++```+@spree/dashboard-ui ─ design system: shadcn primitives + headless compounds + tokens+@spree/dashboard-core ─ framework: registries + providers + hooks + SDK client + plugin facade+@spree/dashboard ─ app shell: routes, resource hooks, locales, vite config+```++[Overview](/developer/dashboard/overview) covers the split in more detail. The short version: **`-ui`** has no providers or hooks (data comes via props); **`-core`** is the extension API and runtime services; **`-dashboard`** is the deployable app shell. Plugins and customizations consume `-core` and `-ui`, never the app shell.++## How customization plugs in++Five global, in-memory registries hold the things you add or modify:++| Registry | Adds | Surfaced by |+|---|---|---|+| `nav` | Sidebar entries | `<AppSidebar>` |+| `settingsNav` | Settings sub-shell entries | `<SettingsSidebar>` |+| Route registry | Custom pages mounted under `/$storeId/*` | Catch-all dispatcher route |+| Slot registry | Components injected into named slots in built-in pages | `<Slot name="...">` |+| Table registry | Columns, filters, row actions, bulk actions on built-in tables | `<ResourceTable>` |++Each is a module singleton with `add`/`remove`/`update`/`insertBefore`/`insertAfter` mutators. The consumer components subscribe via `useSyncExternalStore`, so registering late still updates the UI on the next render.++The facade `defineDashboardPlugin({ nav, routes, slots, … })` groups all five into one declarative call — convenient for plugins, optional for in-app customizations (you can call `nav.add()` directly).++## Auth, context, providers++The signed-in admin's identity and abilities are exposed via three providers wrapping the app:++- `<AuthProvider>` — the current admin user; `useAuth()` returns `{ user, signIn, signOut, … }`+- `<PermissionProvider>` — CanCanCan abilities; `usePermissions()` returns `{ can, cannot }`+- `<StoreProvider>` — current store + timezone + currency; `useStore()` returns `{ storeId, store, … }`++When you write a custom page or hook, pull from these. **Never reach into local state for identity** — it changes on store switch or session refresh, and the providers wire all that for you.++## Data fetching++Every screen in the dashboard follows the same pattern:++```+adminClient (SDK)+ ↓ called inside+useFoo (custom hook wrapping useQuery)+ ↓ consumed by+<FooList /> (component renders cached data, owns no fetching logic)+```++Wrap SDK calls in custom hooks under `src/hooks/`, never call `adminClient` directly from components. See [Backend integration](/developer/dashboard/customization/backend) for the full pattern, error mapping, and the `useResourceMutation` helper that wires up 422 handling.++## URL = state++The dashboard treats the URL as the single source of truth for page state:++- Filters, sort, page number → URL search params+- Selected row → URL path param+- "Sheet open?" → URL search param (`?edit=prod_xxx`)++This is why links work, deep-links restore filter state, and the browser back button does the right thing. When you build a custom page, follow the same rule — don't stash filter state in React state where it's invisible to bookmarks and analytics.++## i18n is not optional++The dashboard ships with English, German, French, Spanish, Portuguese, and a few more out of the box. Every label, placeholder, error message goes through `i18n.t()`. When you add a feature:++1. Add the keys to your customization's `locales/en.json`+2. Register the bundle: `i18n.addResourceBundle('en', 'admin', bundle, true, false)`+3. Use `useTranslation()` in components and `i18n.t()` at registration sites++[Translations](/developer/dashboard/customization/translations) covers the field-key convention.++## Prefixed IDs everywhere++The Admin API uses [Stripe-style prefixed IDs](/developer/api-reference/admin/overview#prefixed-ids): `prod_86Rf07xd4z`, `cust_k5nR8xLq`. The dashboard does too — URLs, hook params, table rows, SDK calls. Never coerce IDs to integers. Never strip the prefix. Pass them around as opaque strings.++## Where to go next++- [Public API](/developer/dashboard/public-api) — what's importable from `@spree/dashboard-core` / `-ui` / `-dashboard`+- [Customization Quickstart](/developer/dashboard/customization/quickstart) — first nav entry in 30 seconds+- [Recipes](/developer/dashboard/recipes/custom-form-field) — focused walkthroughs for common extension shapesdiff --git a/docs/developer/dashboard/customization/backend.mdx b/docs/developer/dashboard/customization/backend.mdxnew file mode 100644index 0000000000..c10b551a9b--- /dev/null+++ b/docs/developer/dashboard/customization/backend.mdx@@ -0,0 +1,126 @@+---+title: Backend integration+sidebarTitle: Backend integration+description: Talk to your own (or Spree's) Admin API from the dashboard — typed SDK calls, custom endpoints, prefixed IDs, error handling, and React-Query hooks.+---++The dashboard never reaches into Rails models or fetches HTML. All data flows through `@spree/dashboard-sdk` — a typed Admin API client. This page covers the patterns: calling existing endpoints, adding new ones, handling errors, and wrapping it all in React-Query hooks for caching.++## The `adminClient`++The SPA boots a single `adminClient` instance and exposes it from `@spree/dashboard`. Resource methods follow `client.<resource>.<verb>()`:++```ts+import { adminClient } from '@spree/dashboard'++await adminClient.products.list({ filter: { name_cont: 'shirt' } })+await adminClient.products.show('prod_86Rf07xd4z', { include: ['variants'] })+await adminClient.products.create({ name: 'New product' })+await adminClient.products.update('prod_86Rf07xd4z', { name: 'Renamed' })+await adminClient.products.destroy('prod_86Rf07xd4z')+```++All IDs are [prefixed](/developer/api-reference/admin/overview#prefixed-ids) — pass them in, get them out. The SDK never coerces to integers.++## Custom endpoints++When you've added an endpoint to `spree/api` that the SDK doesn't model yet (host-app routes, an in-development feature, a custom controller), use the public `request<T>()` escape hatch:++```ts+import type { AdminBrand } from './types'++const data = await adminClient.request<{ data: AdminBrand[] }>(+ 'GET',+ '/brands',+ { params: { 'filter[name_cont]': 'nike' } },+)+```++It accepts:++- `method` — `'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'`+- `path` — relative to `/api/v3/admin` (so `/brands` hits `/api/v3/admin/brands`)+- `body` — JSON-stringified for non-GET requests+- `params` — query string++Resource methods are just `request<T>()` calls with the right path + types pre-bound. When you publish your customization or generate types from your serializer, you can promote the inline call to a typed wrapper.++## React-Query hooks++The dashboard's data layer is React-Query — every `useFoo` hook is `useQuery({ queryKey, queryFn })` over an SDK call. Follow the same pattern for your own data:++```ts+import { useQuery } from '@tanstack/react-query'+import { adminClient } from '@spree/dashboard'+import type { AdminBrand } from './types'++export function useBrands(params?: { search?: string }) {+ return useQuery({+ queryKey: ['brands', params],+ queryFn: () =>+ adminClient.request<{ data: AdminBrand[] }>('GET', '/brands', { params }),+ staleTime: 30_000,+ })+}+```++For mutations, prefer the existing `useResourceMutation` helper — it wires up the SDK's error shape, the 422 silencer, and the toast for non-validation errors:++```ts+import { useResourceMutation } from '@spree/dashboard-core'++export function useUpdateBrand(id: string) {+ return useResourceMutation({+ mutationFn: (body: Partial<AdminBrand>) =>+ adminClient.request<{ data: AdminBrand }>('PATCH', `/brands/${id}`, { body }),+ invalidateQueries: [['brands'], ['brand', id]],+ })+}+```++The `invalidateQueries` array refetches dependent queries on success.++## Error handling++The SDK throws `SpreeError` for non-2xx responses. The error carries `status`, `code`, and `details` — the last contains the Rails error hash for 422s.++```ts+import { SpreeError } from '@spree/dashboard-sdk'++try {+ await adminClient.products.update(id, payload)+} catch (err) {+ if (err instanceof SpreeError && err.status === 422) {+ console.log(err.details) // { name: ["can't be blank"] }+ }+ throw err+}+```++In a React Hook Form submit handler, prefer the higher-level helper:++```tsx+import { mapSpreeErrorsToForm } from '@/lib/form-errors'++async function handleSubmit(values: FormValues) {+ try {+ await mutation.mutateAsync(values)+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+}+```++`mapSpreeErrorsToForm` routes flat field errors onto `aria-invalid` `<FieldError>` blocks and `:base` errors onto `errors.root.message` for a destructive banner. Returns `true` if it handled the error; otherwise re-throw so the global toast catches it.++## When to add a new endpoint++Pretty much always, for anything non-trivial. If you're filtering, sorting, or aggregating across multiple resources, do it on the backend — the API can join, scope, and serialize correctly in one round-trip, whereas the dashboard would have to fan out N requests and stitch them together. See the backend customization docs for adding controllers, serializers, and authorization.++## Reference++- [Admin API conventions](https://github.com/spree/spree/blob/main/docs/plans/6.0-admin-api.md)+- [`AdminClient.request`](https://github.com/spree/spree/blob/main/packages/admin-sdk/src/admin-client.ts) — full type+- [`SpreeError`](https://github.com/spree/spree/blob/main/packages/sdk-core/src/errors.ts)+- [`useResourceMutation`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/hooks/use-resource-mutation.ts)+- [`mapSpreeErrorsToForm`](https://github.com/spree/spree/blob/main/packages/dashboard/src/lib/form-errors.ts)diff --git a/docs/developer/dashboard/customization/navigation.mdx b/docs/developer/dashboard/customization/navigation.mdxnew file mode 100644index 0000000000..f7f798dedc--- /dev/null+++ b/docs/developer/dashboard/customization/navigation.mdx@@ -0,0 +1,154 @@+---+title: Navigation+sidebarTitle: Navigation+description: Add, modify, and remove items from the dashboard's main sidebar and settings sub-nav.+---++The dashboard has two navigation registries: **main sidebar** (`nav`) and **settings sub-shell** (`settingsNav`). Both are module singletons exposed from `@spree/dashboard-core` and consumed by `<AppSidebar>` and `<SettingsSidebar>` via `useSyncExternalStore`, so late registration re-renders the sidebars automatically.++## Main sidebar (`nav`)++### Add an entry++```ts+import { nav } from '@spree/dashboard-core'+import { BarChartIcon } from 'lucide-react'++nav.add({+ key: 'reports',+ label: 'Reports',+ path: '/reports', // prefixed with /$storeId at render time+ icon: BarChartIcon,+ position: 80,+ subject: 'Spree::Order', // optional CanCanCan subject — hides item without read permission+})+```++`position` controls ordering — built-ins use 100/200/300 to leave gaps. The default is 100.++### Add via `defineDashboardPlugin`++The facade groups multiple registry calls:++```ts+import { defineDashboardPlugin } from '@spree/dashboard-core'++defineDashboardPlugin({+ nav: [+ { key: 'reports', label: 'Reports', path: '/reports', icon: BarChartIcon, position: 80 },+ { key: 'segments', label: 'Segments', path: '/segments', icon: UsersIcon, position: 85 },+ ],+})+```++### Nest children under a parent++```ts+nav.add({+ key: 'reports',+ label: 'Reports',+ icon: BarChartIcon,+ children: [+ { key: 'reports-sales', label: 'Sales', path: '/reports/sales' },+ { key: 'reports-inventory', label: 'Inventory', path: '/reports/inventory' },+ ],+})+```++Children declare their own `subject` independently — the parent doesn't auto-gate them.++### Insert relative to an existing entry++```ts+nav.insertBefore('customers', { key: 'segments', label: 'Segments', path: '/segments' })+nav.insertAfter('orders', { key: 'returns', label: 'Returns', path: '/returns' })+```++The new entry inherits the target's `position` ± 1 unless you specify your own.++### Modify or remove++```ts+nav.update('orders', { label: 'All orders' })+nav.remove('legacy-thing')+```++### Bottom-pinned entries++`section: 'bottom'` pins to the sidebar footer (where "Settings" lives by default):++```ts+nav.add({+ key: 'help',+ label: 'Help',+ path: '/help',+ icon: HelpCircleIcon,+ section: 'bottom',+})+```++## Settings sub-nav (`settingsNav`)++The settings page has its own sub-shell sidebar with grouped entries (Store, Localization, Team & Access, …). Entries cluster under groups defined separately.++### Register a group++```ts+import { settingsNav } from '@spree/dashboard-core'++settingsNav.addGroup({+ key: 'integrations',+ label: 'Integrations',+ position: 500,+})+```++### Add entries to a group++```ts+settingsNav.add({+ key: 'stripe-tax',+ label: 'Stripe Tax',+ path: '/integrations/stripe-tax', // prefixed with /$storeId/settings+ group: 'integrations',+ position: 100,+ subject: 'Spree::TaxRate',+})+```++### `comingSoon` badge++Disabled entries with a "Soon" badge — useful for staging the rollout:++```ts+settingsNav.add({+ key: 'reports',+ label: 'Reports',+ path: '/reports',+ group: 'analytics',+ comingSoon: true,+})+```++## Permission gating++`subject` on a nav entry checks `permissions.can('read', subject)` — when it fails, the sidebar item is hidden. **This is UX, not authorization.** The backend still enforces CanCanCan via `authorize!` on every API call. Hiding the link is a hint, not a security boundary.++## Order of operations++Nav registrations run at module-load time. The sidebar reads via `useSyncExternalStore`, so:++- Registering before the sidebar mounts: works (the snapshot picks it up on first render)+- Registering after the sidebar mounts: also works (the store notifies subscribers)++The only ordering rule is **i18n**: if you use `i18n.t('admin.foo.label')` for `label`, the i18n bootstrap must run first. Import order in `main.tsx`:++```tsx+import '@/i18n-setup' // base translations registered+import '@/customizations' // your nav.add calls run; i18n.t resolves+```++## Reference++- [`NavEntry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/nav-registry.ts) — the full shape including types for `children`, `position`, `subject`, `section`+- [`SettingsNavEntry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/settings-nav-registry.ts) — settings sub-nav typesdiff --git a/docs/developer/dashboard/customization/permissions.mdx b/docs/developer/dashboard/customization/permissions.mdxnew file mode 100644index 0000000000..fab4696fda--- /dev/null+++ b/docs/developer/dashboard/customization/permissions.mdx@@ -0,0 +1,118 @@+---+title: Permissions+sidebarTitle: Permissions+description: How to hide UI behind CanCanCan permissions in your customisations — and why hiding is never the same as authorising.+---++The dashboard exposes the current admin's CanCanCan abilities to every component via the `permissions` context. Most customisation surfaces — nav entries, settings entries, slots, columns, row actions, custom routes — accept either a `subject` shortcut or a generic `if` predicate that reads from `permissions`.++## Two layers++UI gating is for **UX**. Backend authorization is for **security**. They are not the same:++| Layer | Where | What it does |+|---|---|---|+| UI gating | Dashboard registries (`subject`, `if`) | Hides menu items, columns, buttons — keeps the interface tidy |+| Authorization | Rails API controllers (CanCanCan, scopes) | Refuses the request when the user doesn't have permission |++**Always rely on the backend for security.** Hiding a button is a hint to the user, not a wall. A user with browser dev tools (or the API token) can always hit the endpoint directly — your `authorize!` call is what stops them.++## The `permissions` object++```ts+interface Permissions {+ can(action: string, subject: string | object): boolean+ cannot(action: string, subject: string | object): boolean+}+```++It mirrors the backend ability:++```ts+permissions.can('read', 'Spree::Order') // class-level check+permissions.can('update', { __typename: 'Spree::Product', id: '...' }) // record-level+```++The string `subject` form is what you'll usually use in registry entries — the class is enough because hiding a list entry is class-scoped (you don't have a specific row in hand).++## `subject` shortcut++Available on `NavEntry`, `SettingsNavEntry`, `RouteEntry`, and table columns. It's sugar for `if: ({ permissions }) => permissions.can('read', subject)`:++```ts+nav.add({+ key: 'reports',+ label: 'Reports',+ path: '/reports',+ subject: 'Spree::Order', // hides nav item without read:Spree::Order+})+```++For routes, `subject` also renders a 403 page if the user navigates directly:++```ts+routes: [{+ key: 'reports',+ path: '/reports',+ component: ReportsPage,+ subject: 'Spree::Order',+}],+```++Use `subject` whenever you want a "user can read this resource" check. For anything else, use `if`.++## `if` predicate++`if` is the escape hatch. It receives the same merged context as the component would and returns a boolean:++```tsx+tables.products.bulkActions.add({+ key: 'bulk-archive',+ label: 'Archive',+ if: ({ permissions, rows }) =>+ permissions.can('update', 'Spree::Product') && rows.every((r) => r.status !== 'archived'),+ onSelect: async ({ rows }) => { /* ... */ },+})+```++Use it for combined checks (permission + row state), feature flags, multi-action checks (`can(update) && can(read)`), or anything the `subject` shortcut can't express in one string.++## Inside components++Pull from the slot context or, in custom pages, from the dashboard's `usePermissions()` hook:++```tsx+import { usePermissions } from '@spree/dashboard-core'++function ReportsPage() {+ const permissions = usePermissions()+ if (!permissions.can('read', 'Spree::Order')) {+ return <Forbidden />+ }+ return <ReportsList />+}+```++Same hook backs the registry's `if` predicate, so you can move logic between the two without changing behaviour.++## Custom abilities++If your customization introduces a new model on the backend, extend the CanCanCan ability there (typically a decorator on `Spree::PermissionSets::DefaultCustomer` or `Spree::PermissionSets::DashboardManagement`):++```ruby+# config/initializers/spree.rb (host app)+Spree::PermissionSets::DashboardManagement.class_eval do+ def activate!+ super+ can :manage, MyApp::Report+ end+end+```++After that, `permissions.can('read', 'MyApp::Report')` resolves in the dashboard exactly like a first-party check — the abilities ship to the SPA via the `/api/v3/platform/users/me/permissions` endpoint at sign-in.++## Reference++- [`Permissions` interface](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/permissions.ts)+- [CanCanCan docs](https://github.com/CanCanCommunity/cancancan) — the Ruby ability definition language+- [`6.0-admin-spa.md` permission section](https://github.com/spree/spree/blob/main/docs/plans/6.0-admin-spa.md) — the design that backs the SPA's permission systemdiff --git a/docs/developer/dashboard/customization/quickstart.mdx b/docs/developer/dashboard/customization/quickstart.mdxnew file mode 100644index 0000000000..c90ea34a7e--- /dev/null+++ b/docs/developer/dashboard/customization/quickstart.mdx@@ -0,0 +1,106 @@+---+title: Quickstart+sidebarTitle: Quickstart+description: Add your first customization to a Spree dashboard in under 5 minutes — no npm publishing, no Vite plugin, just a new file in your host app.+---++This guide assumes you have a Spree 6.0 store already running. If not, scaffold one first:++```bash+npx create-spree-app my-store+cd my-store+```++The scaffolded host has a dashboard app at `packages/dashboard/`. That's where customizations live. **You don't need to scaffold a plugin** — you're editing the host's own code.++## The 30-second example++Add a "Reports" item to the dashboard sidebar.++**Step 1.** Create `packages/dashboard/src/customizations.ts`:++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { BarChartIcon } from 'lucide-react'++defineDashboardPlugin({+ nav: [{+ key: 'reports',+ label: 'Reports',+ path: '/reports',+ icon: BarChartIcon,+ position: 80,+ }],+})+```++**Step 2.** Import it from `packages/dashboard/src/main.tsx`, **before** the router mounts:++```tsx+import '@/i18n-setup'+import '@/nav/default'+import '@/nav/settings'+import '@/customizations' // ← add this line+// ...rest of bootstrap+```++**Step 3.** Restart the dev server. The sidebar now shows "Reports".++Clicking it goes to a "Page not found" screen — we registered the nav entry but no route. Let's fix that.++## Add the page++**Step 4.** Create the page component at `packages/dashboard/src/pages/reports.tsx`:++```tsx+import { PageHeader } from '@spree/dashboard-core'+import { ResourceLayout } from '@spree/dashboard-ui'++export function ReportsPage() {+ return (+ <ResourceLayout+ header={<PageHeader title="Reports" subtitle="Store performance over time" />}+ main={<p>Coming soon.</p>}+ />+ )+}+```++**Step 5.** Register the route in `customizations.ts`:++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { BarChartIcon } from 'lucide-react'+import { ReportsPage } from './pages/reports'++defineDashboardPlugin({+ nav: [{+ key: 'reports',+ label: 'Reports',+ path: '/reports',+ icon: BarChartIcon,+ position: 80,+ }],+ routes: [{+ key: 'reports',+ path: '/reports',+ component: ReportsPage,+ }],+})+```++Save. The dev server hot-reloads. Click "Reports" — your page renders.++## What just happened++`defineDashboardPlugin` registers extensions against five module-singleton registries in `@spree/dashboard-core`: `nav`, `routes`, `slots`, `tables`, `settingsNav`. Because you imported `customizations.ts` from `main.tsx`, the registration runs at boot — before the router reads from the registry. Same APIs the marketplace plugins use.++The custom route mounts under `/$storeId/reports`. The dashboard's catch-all dispatcher matches the URL splat against the route registry on every navigation, so late registration (lazy-imported features) still works without reconfiguring the router.++## Next steps++- [Navigation](/developer/dashboard/customization/navigation) — sidebar entries, settings sub-nav, children, permissions gating+- [Routes](/developer/dashboard/customization/routes) — path patterns, params, permission fallback+- [Slots](/developer/dashboard/customization/slots) — inject widgets into core pages without forking them+- [Tables](/developer/dashboard/customization/tables) — define your own list page or extend core tables+- [Translations](/developer/dashboard/customization/translations) — add i18n keys without colliding with the frameworkdiff --git a/docs/developer/dashboard/customization/routes.mdx b/docs/developer/dashboard/customization/routes.mdxnew file mode 100644index 0000000000..a5302ff4b6--- /dev/null+++ b/docs/developer/dashboard/customization/routes.mdx@@ -0,0 +1,121 @@+---+title: Routes+sidebarTitle: Routes+description: Mount custom pages under your dashboard's `/$storeId/...` path. Supports path params, permission gating, and works alongside the dashboard's built-in routes.+---++The dashboard's first-party routes (`customers/`, `orders/`, `products/`, …) are file-based via TanStack Router and live in `@spree/dashboard/src/routes/`. Custom routes from host customizations or plugins go through a **route registry** in `@spree/dashboard-core`. A catch-all dispatcher mounted at `/_authenticated/$storeId/$` reads the registry on every navigation and renders the matched component.++## Add a route++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { ReportsPage } from './pages/reports'++defineDashboardPlugin({+ routes: [{+ key: 'reports',+ path: '/reports',+ component: ReportsPage,+ }],+})+```++`path` is **relative** to `/$storeId` — the dispatcher prepends the prefix at match time. So `/reports` matches the URL `/store_xyz/reports`. The leading `/` is required.++## Path parameters++TanStack-Router-style `$name` tokens match a single non-empty segment:++```tsx+routes: [+ { key: 'report-detail', path: '/reports/$reportId', component: ReportDetailPage },+ { key: 'report-export', path: '/reports/$reportId/export', component: ReportExportPage },+],+```++## Receiving params++Your component receives three props from the dispatcher:++```tsx+interface PluginRouteProps {+ /** Path params extracted from the URL. Keys match the `$name` tokens in your path. */+ params: Record<string, string>+ /** Always set — every route is scoped to a store. */+ storeId: string+ /** URL search-state. Pass to `<ResourceTable searchParams={searchParams} />` so filters+ * round-trip through the URL. */+ searchParams: Record<string, unknown>+}++function ReportDetailPage({ params, storeId, searchParams }: PluginRouteProps) {+ const reportId = params.reportId+ // ...+}+```++`searchParams` is typed as `Record<string, unknown>` because the dispatcher can't statically know your page's shape. If you're handing it to `<ResourceTable>`, cast to `ResourceSearch`:++```tsx+import type { ResourceSearch } from '@spree/dashboard-core'++<ResourceTable searchParams={searchParams as ResourceSearch} ... />+```++## Permission gating++A `subject` on the route entry renders a 403 fallback (instead of the page) when the user lacks `read` permission:++```tsx+routes: [{+ key: 'reports',+ path: '/reports',+ component: ReportsPage,+ subject: 'Spree::Order',+}],+```++Always pair this with a matching `subject` on the **nav entry** so users without permission never see the link in the first place. The route subject is the defensive layer for direct URLs.++## Layout++Custom routes inherit the dashboard's `_authenticated` + `$storeId` layout (auth guard, sidebar, top bar, etc.) — your component renders inside the `<Outlet />`. Use `<ResourceLayout>` from `@spree/dashboard-ui` to get the same header/main/sidebar grid as core pages:++```tsx+import { PageHeader } from '@spree/dashboard-core'+import { ResourceLayout } from '@spree/dashboard-ui'++function ReportsPage() {+ return (+ <ResourceLayout+ header={<PageHeader title="Reports" backTo="dashboard" />}+ main={<ReportsList />}+ sidebar={<ReportsFilters />}+ />+ )+}+```++## Linking to a custom route++Use TanStack Router's `<Link>`. The dashboard's link API expects a path template + params object:++```tsx+import { Link } from '@tanstack/react-router'++<Link to={'/$storeId/reports/$reportId' as string} params={{ storeId, reportId }}>+ View report+</Link>+```++The `as string` cast bypasses TanStack Router's static type-checking for the path (because custom routes aren't in the generated route tree). Params are passed positionally.++## Order of operations++Routes register at module-load time. The dispatcher reads from the registry on **every navigation**, so route registration is much more forgiving than nav: even a route registered after first render works as soon as the user navigates to it. That said, follow the same import order as everything else — `@/i18n-setup` first, then your customizations — so labels and i18n keys resolve correctly.++## Reference++- [`RouteEntry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/route-registry.ts) — full type+- [Catch-all dispatcher source](https://github.com/spree/spree/blob/main/packages/dashboard/src/routes/_authenticated/$storeId/$.tsx) — see how matching worksdiff --git a/docs/developer/dashboard/customization/slots.mdx b/docs/developer/dashboard/customization/slots.mdxnew file mode 100644index 0000000000..b8b6c30cf5--- /dev/null+++ b/docs/developer/dashboard/customization/slots.mdx@@ -0,0 +1,105 @@+---+title: Slots+sidebarTitle: Slots+description: Inject your own widgets into existing dashboard pages without forking them. Slots are named injection points the dashboard exposes on built-in pages.+---++A slot is a named injection point in a built-in page. Components registered against a slot render inside it, sorted by `position`, gated by an optional `if` predicate. The host page knows nothing about your widget — it just renders `<Slot name="..." context={...} />` and the slot registry handles the rest.++## Quick example++Render a card with the current user's email in every page's actions dropdown:++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { DropdownMenuItem } from '@spree/dashboard-ui'++function UserBadge({ user }: { user?: { email: string } }) {+ if (!user) return null+ return <DropdownMenuItem>{user.email}</DropdownMenuItem>+}++defineDashboardPlugin({+ slots: {+ 'page.actions_dropdown': [{+ id: 'my-user-badge',+ component: UserBadge as never,+ position: 50,+ }],+ },+})+```++`page.actions_dropdown` is one of the slots exposed by `<PageHeader>`. See the [Slots catalog](/developer/dashboard/slots-catalog) for the full list and the context shape each slot provides.++## Slot context++The component receives two pieces of context merged into a single props object:++1. **Slot-specific context** — what the host page passes via `<Slot name="..." context={{ product, /* etc */ }} />`. The shape varies per slot — `page.actions_dropdown` passes `{ resource }`, the order-detail page might pass `{ order }`, and so on.+2. **Ambient context** — `{ permissions, store, user }` injected by the providers, available to every slot. Useful for the `if` predicate and for components that only need the current user.++Both shapes are documented per slot in the [Slots catalog](/developer/dashboard/slots-catalog).++### Why `as never`?++`defineDashboardPlugin`'s `slots` field is typed as a generic-erased `Record<string, SlotEntry[]>` — the facade can't statically know your slot's context shape, only the host page does. Cast your component to `as never` to satisfy the registry's signature. Your component still receives the right props at runtime; the cast only suppresses the type-system noise.++If you'd rather have full type safety, call `registerSlot` directly with the explicit type parameter:++```tsx+import { registerSlot } from '@spree/dashboard-core'++interface ProductSlotContext {+ product: { id: string; brand_id?: string | null }+}++registerSlot<ProductSlotContext>('product.form_sidebar', {+ id: 'brand-card',+ component: ({ product, permissions }) => {+ if (!permissions?.can('read', 'Spree::Brand')) return null+ return <BrandCard productId={product.id} brandId={product.brand_id} />+ },+ position: 50,+})+```++## Permission gating++The `if` predicate runs on every render with the merged context:++```tsx+slots: {+ 'page.actions_dropdown': [{+ id: 'admin-only-thing',+ component: AdminOnlyMenuItem as never,+ if: (ctx) => ctx.permissions?.can('manage', 'Spree::User') ?? false,+ }],+}+```++When it returns `false`, the entry is skipped entirely (no DOM nodes mounted). Useful for entries that should depend on dynamic state — feature flags, A/B buckets, or context the user can change without reloading.++## Position++`position` controls render order within the slot. Built-in entries (when the dashboard ships any) use 100/200/300 to leave gaps. Default is 100, so two entries with no explicit position render in registration order.++## Removing or updating an entry++```ts+import { removeSlot, updateSlot } from '@spree/dashboard-core'++removeSlot('product.form_sidebar', 'brand-card')+updateSlot('product.form_sidebar', 'brand-card', { position: 999 })+```++These mirror the registry's mutator pattern — useful for development-mode toggles, or for unregistering a third-party slot entry from your host.++## Order of operations++Like nav, slot entries register at module-load time and the `<Slot>` consumer re-renders via `useSyncExternalStore` when entries change. Late registration works; the slot just lights up the next render.++## Reference++- [Slots catalog](/developer/dashboard/slots-catalog) — every named slot the dashboard exposes+- [`SlotEntry`, `SlotAmbientContext`, `registerSlot`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/slot-registry.ts) — full registry sourcediff --git a/docs/developer/dashboard/customization/tables.mdx b/docs/developer/dashboard/customization/tables.mdxnew file mode 100644index 0000000000..49e5f788ba--- /dev/null+++ b/docs/developer/dashboard/customization/tables.mdx@@ -0,0 +1,153 @@+---+title: Tables+sidebarTitle: Tables+description: Add columns, bulk actions, row actions, and filters to built-in list tables (products, orders, customers, …) without forking them.+---++Every list table in the dashboard is rendered by `<ResourceTable>` against a **table registry**. Built-in tables register their default columns and filters at boot; you can append to, modify, or remove entries from any table by its key (`products`, `orders`, `customers`, etc.).++## Tour of the registry++```ts+import { tables } from '@spree/dashboard-core'++tables.products.columns.add(...) // append a column+tables.products.columns.insertAfter('name', ...) // place explicitly+tables.products.columns.remove('cost_price')+tables.products.filters.add(...)+tables.products.bulkActions.add(...)+tables.products.rowActions.add(...)+```++Each entry has a `key` so it can be referenced later for `update` or `remove`. Like nav, the registry is a singleton consumed via `useSyncExternalStore`, so late registration re-renders the table.++## Add a column++```tsx+import { tables } from '@spree/dashboard-core'+import type { AdminProduct } from '@spree/dashboard-sdk'++tables.products.columns.add({+ key: 'brand',+ header: 'Brand',+ cell: ({ row }) => row.brand?.name ?? '—',+ position: 250,+})+```++`cell` is a TanStack-Table `ColumnDef` cell renderer — `row` is fully typed as the resource (`AdminProduct`, `AdminOrder`, …) when you reach it from a typed registry key.++### Sort + filter on a column++```tsx+tables.products.columns.add({+ key: 'brand',+ header: 'Brand',+ cell: ({ row }) => row.brand?.name ?? '—',+ sortable: true,+ sortKey: 'brand_name', // becomes ?sort=brand_name when toggled+})+```++For Ransack-backed filters, register against `filters` separately so the filter chip lives in the toolbar instead of the column header:++```tsx+tables.products.filters.add({+ key: 'brand',+ label: 'Brand',+ type: 'multi-resource',+ resource: 'brands',+ ransackKey: 'brand_id_in',+})+```++## Add a row action++```tsx+import { ArchiveIcon } from 'lucide-react'++tables.products.rowActions.add({+ key: 'archive',+ label: 'Archive',+ icon: ArchiveIcon,+ onSelect: async ({ row }) => {+ await adminClient.products.update(row.id, { status: 'archived' })+ },+ if: ({ row, permissions }) =>+ permissions.can('update', 'Spree::Product') && row.status !== 'archived',+})+```++`if` runs per row — useful for hiding actions that don't apply (already archived, can't be deleted, etc.). When omitted, the action shows for every row.++## Add a bulk action++Bulk actions appear in the toolbar above the table when rows are selected:++```tsx+tables.products.bulkActions.add({+ key: 'bulk-archive',+ label: 'Archive selected',+ icon: ArchiveIcon,+ variant: 'destructive',+ confirm: { title: 'Archive products?', description: 'You can restore them later.' },+ onSelect: async ({ rows }) => {+ await Promise.all(+ rows.map((row) => adminClient.products.update(row.id, { status: 'archived' })),+ )+ },+})+```++The `confirm` config opens a dialog before `onSelect` runs. Skip it for non-destructive actions.++## Order columns explicitly++`position` controls render order. Built-in columns leave gaps (100, 200, …) so you can slot in:++```tsx+tables.products.columns.add({ key: 'brand', position: 150, /* ... */ })+```++Or pick a neighbour:++```tsx+tables.products.columns.insertAfter('name', { key: 'brand', /* ... */ })+tables.products.columns.insertBefore('price', { key: 'tier', /* ... */ })+```++## Remove or modify a default column++```ts+tables.products.columns.remove('cost_price')++tables.products.columns.update('price', {+ header: 'Retail price',+})+```++The `update` patch is shallow — pass only the keys you want to change.++## Permission-gating columns++`if` on a column skips it for users without the matching permission:++```tsx+tables.products.columns.add({+ key: 'cost_price',+ header: 'Cost',+ cell: ({ row }) => formatMoney(row.cost_price),+ if: ({ permissions }) => permissions.can('manage', 'Spree::Product'),+})+```++This complements the backend, which omits `cost_price` from the serializer when the user can't see it.++## Order of operations++Same as nav: registry runs at module-load time, consumers re-render via `useSyncExternalStore`, late registration works. Make sure your `defineDashboardPlugin` call runs once — multiple calls add entries multiple times, which the dev-mode warning will catch.++## Reference++- [`TableRegistry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/table-registry.ts) — full type including bulk-action and filter shapes+- [`<ResourceTable>`](https://github.com/spree/spree/blob/main/packages/dashboard-ui/src/components/resource-table.tsx) — host component that reads from the registrydiff --git a/docs/developer/dashboard/customization/translations.mdx b/docs/developer/dashboard/customization/translations.mdxnew file mode 100644index 0000000000..637cfb7c95--- /dev/null+++ b/docs/developer/dashboard/customization/translations.mdx@@ -0,0 +1,104 @@+---+title: Translations+sidebarTitle: Translations+description: Add your own i18n strings to the dashboard so labels, validation messages, and notifications respect the admin's chosen locale.+---++The dashboard uses [i18next](https://www.i18next.com/) with the `react-i18next` bindings. The base bundle ships in `@spree/dashboard` under the `admin` namespace. You add your strings to the same `admin` namespace so they look and feel native — same `admin.fields.<resource>.<attribute>.{label,placeholder,help}` convention, same fallback chain.++## Add translations++```ts+import i18n from 'i18next'++i18n.addResourceBundle('en', 'admin', {+ reports: {+ title: 'Reports',+ empty: 'No reports yet.',+ },+ fields: {+ report: {+ name: { label: 'Report name', placeholder: 'e.g. Q4 sales by region' },+ },+ },+}, /* deep */ true, /* overwrite */ false)+```++`addResourceBundle` is additive when `deep: true, overwrite: false` — your keys merge into the existing `admin` namespace without clobbering the dashboard's defaults.++Repeat per locale:++```ts+import en from './locales/en.json'+import fr from './locales/fr.json'+import de from './locales/de.json'++for (const [locale, bundle] of Object.entries({ en, fr, de })) {+ i18n.addResourceBundle(locale, 'admin', bundle, true, false)+}+```++## Use them++```tsx+import { useTranslation } from 'react-i18next'++function ReportsHeader() {+ const { t } = useTranslation()+ return <h1>{t('admin.reports.title')}</h1>+}+```++In a registry entry, pass the key directly:++```ts+nav.add({+ key: 'reports',+ label: i18n.t('admin.reports.title'),+ path: '/reports',+})+```++Note: `i18n.t` resolves at the call site, so it's snapshot at registration time. If the user changes language without a reload, sidebar labels updates automatically because the sidebar re-renders on locale change. If you stash the resolved string elsewhere, refresh it on the i18n `languageChanged` event.++## Field-key convention++Form labels, placeholders, and help text resolve via this fallback chain (defined in `@spree/dashboard-core`):++1. `admin.fields.<resource>.<attribute>.<facet>` — e.g., `admin.fields.report.name.label`+2. `admin.fields.<attribute>.<facet>` — e.g., `admin.fields.name.label`++The form helpers (`<Field>`, `<Input>`, `<FieldError>`) walk this chain automatically — you only pass the attribute name. Define keys under `fields.<resource>` for resource-specific labels and rely on `fields.<attribute>` shared defaults for everything else (`name`, `email`, `created_at`, …).++In dev mode, missing keys log to the console with the chain that was tried.++## Server-side error mapping++The dashboard's `mapSpreeErrorsToForm` helper translates 422 responses onto `form.formState.errors`. Backend `errors` come back as `{ "name": ["can't be blank"] }`, and the helper sets the field error using the **translated** version of the same key chain:++```ts+// Spree returns:+// { "errors": { "name": ["can't be blank"] } }++// The helper looks up these keys in order, taking the first one that resolves:+// 1. admin.errors.report.name.cant_be_blank+// 2. admin.errors.name.cant_be_blank+// 3. The raw server string "can't be blank"+```++Provide the localised string in `admin.errors.<resource>.<attribute>.<message_key>` if you want the user to see something other than the raw English message.++## Order of operations++Register translations **before** any code that calls `i18n.t()` at module-load time (registry labels, default nav items, etc.). The simplest pattern: do all i18n setup in a single `i18n-setup.ts` module, import it at the top of `main.tsx` before your customizations:++```tsx+// main.tsx+import './i18n-setup' // i18n initialised + bundles added+import './customizations' // nav.add, defineDashboardPlugin, …+```++## Reference++- [i18next docs](https://www.i18next.com/) — full API+- The dashboard's own bundle: [`packages/dashboard/src/locales/en.json`](https://github.com/spree/spree/blob/main/packages/dashboard/src/locales/en.json) — copy keys for forms, status badges, validation messages, etc.diff --git a/docs/developer/dashboard/overview.mdx b/docs/developer/dashboard/overview.mdxnew file mode 100644index 0000000000..15fb626669--- /dev/null+++ b/docs/developer/dashboard/overview.mdx@@ -0,0 +1,82 @@+---+title: Dashboard Overview+sidebarTitle: Overview+description: How the Spree 6.0 admin dashboard is structured, when to customize in-app, and when to ship a redistributable plugin.+---++<Info>+The Vite-based admin dashboard ships in **Spree 6.0** as a developer preview. If you're on Spree 5.x today, the Rails admin extension model is documented at [`/developer/admin/extending-ui`](/developer/admin/extending-ui).+</Info>++The Spree 6.0 admin is a React single-page application built on three packages:++| Package | What it contains | When you touch it |+|---|---|---|+| `@spree/dashboard-ui` | Design system: shadcn primitives + headless composed components (`PageHeader`, `ResourceLayout`, `ResourceTable`'s rendering layer, etc.) + design tokens | Building custom UI — primitives + compounds you can drop anywhere |+| `@spree/dashboard-core` | Framework: registries (nav, route, slot, table, settings-nav), providers (auth, permission, store), admin SDK client, infra hooks, the `defineDashboardPlugin` API | Extending the admin — every customization API lives here |+| `@spree/dashboard` | The deployable SPA: routes, resource hooks, schemas, locale strings, app shell | Replacing or restyling specific routes (rare) |++Most customization happens via `@spree/dashboard-core`. You import its registries from your own host-app code (or from a separate plugin package) to add nav entries, routes, slot widgets, table columns, and translations.++## Choose your path++There are two ways to customize the dashboard. **Both use the same APIs** — the only difference is packaging.++### 1. Customize in your host app++You're building a Spree store and want a "Featured products" page or a custom card on every product detail. Edit your host app's dashboard package directly:++```tsx+// packages/dashboard/src/main.tsx (your host app, scaffolded by create-spree-app)+import './my-customizations' // ← your own file+```++```tsx+// packages/dashboard/src/my-customizations.ts+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { MyAnalyticsPage } from './pages/analytics'++defineDashboardPlugin({+ nav: [{ key: 'analytics', label: 'Analytics', path: '/analytics' }],+ routes: [{ key: 'analytics', path: '/analytics', component: MyAnalyticsPage }],+})+```++That's the entire setup. No npm publishing, no peer-deps, no Vite plugin registration — you're already inside the host's Vite build, so Tailwind already scans your source. Most teams stop here.++→ Start at the [**customization quickstart**](/developer/dashboard/customization/quickstart).++### 2. Ship a redistributable plugin++You're building a feature that multiple Spree stores will install — a Brands gem, a Wishlists integration, a Stripe Tax connector. Package the customization as an npm module so any host app can `pnpm add my-plugin` + flip two switches in their host config.++This adds three concerns on top of in-app customization:++- **Peer-dependency rules** so your plugin's `@spree/dashboard-core` resolves to the host's instance (registries are module singletons — see [Publishing](/developer/dashboard/plugins/publishing))+- **Host-side activation** — the host side-effect-imports your package in `main.tsx`. Tailwind scanning happens automatically: `spreeDashboardPlugin()` discovers plugins by reading the host's `package.json` deps and picking up any with the `spree.dashboard.plugin` marker. See [Distributing](/developer/dashboard/plugins/distributing) for the auto-discovery details and the manual-whitelist escape hatch.+- **A backend half** — a Rails extension gem that ships the API endpoints your dashboard plugin calls++The `@spree/cli` scaffolds the dashboard half for you:++```bash+npx @spree/cli plugin new my-feature+```++→ Start at the [**plugin scaffolding guide**](/developer/dashboard/plugins/scaffolding).++## Which one should I pick?++Use this rule of thumb:++- **Customize in-app** if the feature is store-specific (your branding, your team's workflow, your custom domain logic) or you don't yet know whether others would want it. The cost to "promote" it to a plugin later is small.+- **Ship a plugin** if you're certain others will install it (you're publishing to the marketplace, your agency is rolling it out across clients, the feature has a clear standalone identity).++When in doubt, customize in-app first. The migration path to a plugin is mechanical — same APIs, just wrapped in their own package.++## Reference++- [Customization quickstart](/developer/dashboard/customization/quickstart)+- [Plugin scaffolding](/developer/dashboard/plugins/scaffolding)+- [Slots catalog](/developer/dashboard/slots-catalog) — every named slot the dashboard exposes+- [`@spree/dashboard-core` README](https://github.com/spree/spree/tree/main/packages/dashboard-core) — full extension API reference+- [Rails admin extension model](/developer/admin/extending-ui) — for Spree 5.xdiff --git a/docs/developer/dashboard/plugins/distributing.mdx b/docs/developer/dashboard/plugins/distributing.mdxnew file mode 100644index 0000000000..732aaee81e--- /dev/null+++ b/docs/developer/dashboard/plugins/distributing.mdx@@ -0,0 +1,140 @@+---+title: Distributing+sidebarTitle: Distributing+description: What consumers do to install your plugin — the wiring on the host side, what to document, and how to keep upgrades painless.+---++This page is the *consumer's* perspective on installing your plugin. Cover it in your README so users have a one-page reference.++## The three steps++A consumer installing your plugin needs to:++1. **Install the npm package** — `pnpm add @your-scope/your-plugin`+2. **Import it in `main.tsx`** — so its side-effects (`defineDashboardPlugin`) run+3. **Apply any backend changes** — usually adding a Rails gem, running migrations++In code:++```tsx+// packages/dashboard/src/main.tsx+import '@/i18n-setup'+import '@your-scope/your-plugin' // ⬅ step 2+import '@/customizations'+// rest of bootstrap+```++```bash+# Rails side, if your plugin has a backend+bundle add your_plugin+bin/rails generate your_plugin:install+bin/rails db:migrate+```++**No `vite.config.ts` edit.** As long as your plugin's `package.json` declares the `spree.dashboard.plugin` marker (the CLI scaffold does this for you — see [Publishing](/developer/dashboard/publishing#tell-the-vite-plugin-where-to-find-you)), `spreeDashboardPlugin()` walks the host's dependencies at build time and finds it automatically. Tailwind picks up the plugin's class names without any extra wiring.++### Manual whitelist (advanced)++For tightly controlled environments (a host that wants explicit allowlist semantics, or a plugin you want to load conditionally), pass the names explicitly:++```ts+// packages/dashboard/vite.config.ts+spreeDashboardPlugin({+ plugins: ['@your-scope/your-plugin'], // disables auto-discovery+})+```++Passing `plugins: []` disables auto-discovery entirely — useful if you want to ship a vanilla dashboard with zero third-party Tailwind sources.++## Dev-mode banner++If the consumer registers your plugin explicitly but it's not installed (or the spelling is off), `@spree/dashboard-core/vite` shows a Vite error overlay during dev with the package name and a fix-it checklist. The same overlay fires if a discovered plugin can't be resolved on disk. That replaces the older silent-failure mode where missing plugins emitted unstyled HTML.++## What to put in your README++A README that gets users to "working in five minutes" has:++- A one-paragraph "what this does"+- Screenshots or a short clip of the dashboard UI it adds+- The four install steps (literally copy-paste blocks)+- A "configuration" section if the plugin has runtime config+- A "compatibility" table (`@spree/dashboard >=6.0.0`, `Spree >=6.0.0`, etc.)+- Links to the source for slots/components the plugin overrides++Skip the "philosophy" and the "alternative approaches" sections. Get users to working in minutes.++## Configuration patterns++Plugins occasionally need runtime config — API endpoints, feature toggles, custom permissions. Two patterns:++### Module-level `configure` call++```ts+// in your plugin+let _config = { endpoint: '/default' }+export function configure(opts: { endpoint?: string }) {+ _config = { ..._config, ...opts }+}+export function getConfig() { return _config }+```++```ts+// consumer+import { configure } from '@your-scope/your-plugin'+configure({ endpoint: '/custom' })+import '@your-scope/your-plugin'+```++Simple, no dependencies. The consumer has to call `configure` **before** importing the plugin (or the plugin's `defineDashboardPlugin` runs with defaults).++### `definePlugin(config)` factory++```ts+// in your plugin+export function definePlugin(config: PluginConfig) {+ // call defineDashboardPlugin inside, closing over config+}+```++```ts+// consumer+import { definePlugin } from '@your-scope/your-plugin'+definePlugin({ endpoint: '/custom' })+```++A bit more boilerplate but easier to test, and the order is unambiguous — no side-effect-at-import-time. If you go this route, drop the auto-registering entry-point and document `definePlugin` as *the* way to install.++## Upgrades++When you cut a major version of your plugin, the breaking-changes section of your changelog needs to call out:++- Renamed registry keys (`nav.add({ key: ... })` changes are user-visible — their URLs depend on it)+- Locale-key renames (consumers may have overrides keyed off old names)+- Slot ID changes (consumers extending your slots break)+- `peerDependencies` range bumps (consumers may need to upgrade Spree first)++Treat the plugin's public surface as: nav keys, route paths, slot IDs, locale keys, and the exported `configure` / `definePlugin` API. Everything else is internal.++## Coexistence with other plugins++The registries are global singletons, so a key collision is the consumer's problem to debug. Mitigations:++- **Namespace your keys** — `key: 'acme-brands'` not `key: 'brands'`.+- **Namespace locale keys** — `admin.acme_brands.title` not `admin.brands.title`.+- **Namespace API paths** — your Rails engine should mount under `/api/v3/admin/acme/...`, not `/api/v3/admin/brands` (which collides with core Brands if it ever ships).++The dashboard logs a warning in dev mode when two registry entries share a key. That's the consumer's signal that two plugins are stepping on each other — and it falls back to "last-registered wins", which is rarely what either plugin wanted.++## Distribution channels++- **npm public** — what most plugins want. `pnpm publish --access public`.+- **npm private (paid)** — for commercial plugins; combine with a license key checked at runtime.+- **GitHub Package Registry** — internal-only; consumers add `@your-scope:registry=https://npm.pkg.github.com` to `.npmrc`.+- **Git tarball** — `pnpm add github:your-org/your-plugin#main` works for unpublished plugins, useful while iterating against a single consumer.++For pre-1.0 plugins, ship under the `next` dist-tag (`pnpm publish --tag next`) so `pnpm add @your-scope/your-plugin` resolves to the stable line and `pnpm add @your-scope/your-plugin@next` opts in.++## Reference++- [Example consumer wiring](https://github.com/spree/spree/blob/main/packages/dashboard/vite.config.ts) — what `spreeDashboardPlugin` looks like in production+- [Plugins reference (`brands` example)](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) — what a finished plugin looks like end-to-enddiff --git a/docs/developer/dashboard/plugins/overview.mdx b/docs/developer/dashboard/plugins/overview.mdxnew file mode 100644index 0000000000..333d79897f--- /dev/null+++ b/docs/developer/dashboard/plugins/overview.mdx@@ -0,0 +1,46 @@+---+title: Plugin overview+sidebarTitle: Overview+description: Package dashboard customizations as a redistributable npm plugin. Read this if you're shipping a feature for *other* people's Spree projects — not your own.+---++If you're customizing the dashboard for your own project, you don't need a plugin. Drop the same code into `packages/dashboard/src/customizations.ts` in your host app and skip this section entirely — start with the [Customization](/developer/dashboard/customization/quickstart) docs.++This section is for the ~10% of cases where you want to **distribute** dashboard extensions: as an open-source integration, an internal package shared across multiple host apps, or a SaaS-style commercial add-on.++## What "plugin" means here++A dashboard plugin is:++1. **An npm package** — published, versioned, installed via `pnpm add @your-scope/your-plugin`.+2. **One side-effecting entry-point** — `import '@your-scope/your-plugin'` calls `defineDashboardPlugin({ ... })` at module-load time, which registers nav entries, routes, slots, columns, etc.+3. **Tailwind-aware** — the host's `vite.config.ts` lists your package name in the `spreeDashboardPlugin` plugins array; the dashboard's Tailwind config picks up your class names without you having to ship pre-built CSS.+4. **Translations-aware** — your bundle ships JSON locale files and calls `i18n.addResourceBundle('en', 'admin', bundle, true, false)` on import.+5. **Possibly Rails-aware** — many plugins also ship a Rails engine alongside the dashboard package (new models, new API endpoints) so the dashboard has something to talk to.++That's it. **Plugins use the exact same registries as in-app customizations.** Everything you can do in `packages/dashboard/src/customizations.ts` you can also do from inside a plugin entry-point. The split between "in-app" and "plugin" is about packaging and distribution, not capability.++## When to choose plugin over in-app++| Scenario | Approach |+|---|---|+| Single project, your own team | In-app customization |+| Two-three internal projects sharing the same extension | Internal npm package (still a plugin) |+| Open-source integration distributed via npm | Plugin |+| Commercial add-on with versioning + changelog | Plugin |+| One-off prototype, even at a client | In-app (you can extract later) |++If you're not sure: start in-app. Lifting `customizations.ts` into a plugin package later is a half-hour refactor — moving in the other direction is more painful.++## What's in this section++- [Scaffolding](/developer/dashboard/plugins/scaffolding) — `spree plugin new <name>` generates the monorepo+- [Publishing](/developer/dashboard/plugins/publishing) — package metadata, semver, the npm bits+- [Distributing](/developer/dashboard/plugins/distributing) — what consumers do to install it++If you haven't yet, read the [Customization](/developer/dashboard/customization/quickstart) section first. It's where the registry API is documented; the plugin pages mostly cover *packaging* concerns.++## Reference++- [Reference: Plugin example (`brands` repo)](https://github.com/spree/spree/tree/main/packages/dashboard-plugin-example) — vendored reference implementation+- [`defineDashboardPlugin` source](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/plugin.ts)diff --git a/docs/developer/dashboard/plugins/publishing.mdx b/docs/developer/dashboard/plugins/publishing.mdxnew file mode 100644index 0000000000..b5b6c378b7--- /dev/null+++ b/docs/developer/dashboard/plugins/publishing.mdx@@ -0,0 +1,139 @@+---+title: Publishing+sidebarTitle: Publishing+description: Get a dashboard plugin onto npm — package metadata, peer dependencies, TypeScript builds, versioning with Changesets.+---++`@spree/cli plugin new` scaffolds the npm package shape, but you still need to fill in publishing-specific metadata before `pnpm publish`. This page covers what to set and why.++## Set the right `peerDependencies`++Your plugin imports React, the dashboard, Tailwind, i18next, etc., but **you don't bundle them** — the host app has those, and bundling them twice causes either duplicate module instances or a tree-shaken nightmare. Use `peerDependencies`:++```json+{+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0",+ "@spree/dashboard-core": ">=6.0.0-0",+ "@spree/dashboard-ui": ">=6.0.0-0",+ "@spree/dashboard-sdk": ">=6.0.0-0",+ "i18next": "^25.0.0",+ "react-i18next": "^16.0.0",+ "@tanstack/react-query": "^5.0.0",+ "@tanstack/react-router": "^1.0.0",+ "lucide-react": "^0.477.0"+ }+}+```++Use ranges, not exact versions — pin too tightly and consumers can't upgrade the dashboard without you cutting a release. The dashboard's own packages follow strict semver from 6.0.0 onward; tracking `>=6.0.0-0` covers prereleases (`6.0.0-rc.1`) too.++`dependencies` is for things your plugin *uses* that the host *doesn't* — small utilities (e.g., `clsx`, `date-fns` if you need a specific version, your own helper packages). When in doubt, peer-dep it. The trade-off is "user has to install one more thing" vs. "user has two copies of React" — always pay the first cost.++## Choose what to publish++The scaffold's `package.json` ships TS source by default. Two options:++### Option A — Ship pre-built JS++Run `tsup` on publish, ship `dist/`:++```json+{+ "main": "./dist/index.cjs",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "files": ["dist", "src/locales"],+ "scripts": {+ "build": "tsup src/index.tsx --format cjs,esm --dts --external react",+ "prepublishOnly": "pnpm build"+ }+}+```++Pre-built JS is friendlier to consumers using non-Vite bundlers and means your code runs regardless of the host's TS config.++### Option B — Ship source++```json+{+ "main": "./src/index.tsx",+ "types": "./src/index.tsx",+ "files": ["src"]+}+```++Vite + tsup can consume TSX directly. Simpler builds, hot reload across the boundary in dev, but only works for Vite-host consumers. Spree dashboards always use Vite, so this is safe in practice.++Pick A if you're going to npm in earnest. Pick B for internal-only packages used inside a known-Vite setup.++## Side-effects flag++The plugin's whole purpose is side effects (`defineDashboardPlugin` registers stuff at module-load time). **Tell bundlers not to tree-shake it:**++```json+{+ "sideEffects": ["./src/index.tsx", "./dist/index.js", "./dist/index.cjs"]+}+```++Without this, a bundler can decide that `import '@your-scope/your-plugin'` does nothing useful and drop it. The list is what's allowed to have effects; everything else still tree-shakes.++## Tell the Vite plugin where to find you++Declare your package as a dashboard plugin in its own `package.json`:++```json+{+ "spree": {+ "dashboard": {+ "plugin": true+ }+ }+}+```++This marker is what powers **auto-discovery**: when a host calls `spreeDashboardPlugin()` without an explicit `plugins` array (the default), the Vite plugin walks the host's `package.json` deps + devDeps, reads each one's manifest, and picks up anything with `spree.dashboard.plugin: true`. The host doesn't have to know your plugin's name — `pnpm add @your-scope/your-plugin` is the entire installation step.++The CLI scaffold (`spree plugin new`) writes this field for you. If you're hand-rolling a plugin, add it before publishing — without it, hosts that rely on auto-discovery won't find your plugin and Tailwind won't pick up your class names.++## Export the Tailwind source++`spreeDashboardPlugin` uses `require.resolve(...)` to find your package, then walks `src/` for Tailwind class scanning. As long as you ship `src/`, it works — Tailwind picks up `className="..."` strings from your built code without you publishing CSS.++If you only ship `dist/` and your built code mangles class names (Tailwind can't see `text-${variant}-500`), use static class names or expose a `tailwind.config.js` content array.++## Versioning with Changesets++The Spree monorepo uses [Changesets](https://github.com/changesets/changesets); plugin authors don't have to, but it pairs well with peer-dep ranges. Workflow:++```bash+pnpm changeset # describe what changed → writes a markdown file+git commit -am "feat: x"+pnpm changeset version # bumps package versions + writes CHANGELOG+pnpm install # resolve workspace versions+git commit -am "Release"+pnpm publish -r # publish updated packages+```++Standalone plugin repos can run Changesets the same way; the CLI scaffold doesn't pre-configure it.++## Publishing the npm package++```bash+pnpm build+pnpm publish --access public+```++Set `"private": false` and remove the `"publishConfig.access": "restricted"` if your scaffold has it.++## Avoiding lock-step releases++Your plugin should compile against a **range** of dashboard versions. Run the build against the lowest supported version locally (`pnpm add -D @spree/[email protected]`) and add a CI matrix job that bumps to the next minor and rebuilds. That's the cheapest way to catch "I depended on something that doesn't exist in 6.0.0".++## Reference++- [npm `peerDependencies` docs](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#peerdependencies)+- [Changesets](https://github.com/changesets/changesets)+- [tsup docs](https://tsup.egoist.dev/)diff --git a/docs/developer/dashboard/plugins/scaffolding.mdx b/docs/developer/dashboard/plugins/scaffolding.mdxnew file mode 100644index 0000000000..185bc04661--- /dev/null+++ b/docs/developer/dashboard/plugins/scaffolding.mdx@@ -0,0 +1,119 @@+---+title: Scaffolding+sidebarTitle: Scaffolding+description: Generate a new dashboard plugin monorepo with `@spree/cli` in one command. Includes TypeScript, biome, tsup, a working example entry-point, and translations.+---++`@spree/cli` ships a `plugin new` command that scaffolds the whole plugin monorepo for you. Generated layout:++```+your-plugin/+├── package.json # workspace root+├── pnpm-workspace.yaml+├── LICENSE+├── README.md+├── .gitignore+└── packages/+ └── dashboard/+ ├── package.json # @your-scope/dashboard-your-plugin+ ├── tsconfig.json+ ├── biome.json+ └── src/+ ├── index.tsx # defineDashboardPlugin entry+ ├── client.ts # adminClient request wrappers+ ├── types.ts # plugin-specific TS types+ ├── routes/+ │ └── <name>-list.tsx+ ├── slots/+ │ └── product-<name>-card.tsx+ └── locales/+ └── en.json+```++You get a working "Brands"-style plugin out of the box: nav entry, a list page wired through React Query, a product-detail slot card, and English translations.++## Run it++```bash+npx @spree/cli plugin new my-plugin+```++The CLI prompts for:++- **Plugin name** — slug (kebab-case), used for package names and i18n keys+- **Ruby gem name** — only matters if you later add a Rails engine+- **Module name** — PascalCase, used as the React component prefix (`MyPluginCard`)+- **npm scope** — e.g., `@acme` (no leading `@` required)+- **Author + email** — for `package.json` and `LICENSE`+- **License** — MIT by default; the CLI fills in the standard text++Skip prompts with flags:++```bash+npx @spree/cli plugin new my-plugin \+ --module-name MyPlugin \+ --npm-scope @acme \+ --author "Ada Lovelace" \+ --author-email "[email protected]" \+ --no-install # skip pnpm install+```++`--force` overwrites an existing directory. `--no-dashboard` skips the dashboard package (Rails-engine-only plugins). `--no-engine` is reserved — engine scaffolding lands later.++## After scaffolding++```bash+cd my-plugin+pnpm install # runs by default unless --no-install+pnpm build+```++You now have a buildable plugin. The next page covers what to put in `package.json` for publishing — but if you're using it internally and importing by path, you can stop here and skip [Publishing](/developer/dashboard/plugins/publishing).++## What the entry-point looks like++`packages/dashboard/src/index.tsx` is where everything starts. The generated version:++```tsx+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { PackageIcon } from 'lucide-react'+import i18n from 'i18next'+import en from './locales/en.json'+import { MyPluginList } from './routes/my-plugin-list'+import { MyPluginCard } from './slots/product-my-plugin-card'++i18n.addResourceBundle('en', 'admin', en, true, false)++defineDashboardPlugin({+ nav: [{+ key: 'my-plugin',+ label: i18n.t('admin.my_plugin.title'),+ path: '/my-plugin',+ icon: PackageIcon,+ position: 250,+ }],+ routes: [{+ key: 'my-plugin-list',+ path: '/my-plugin',+ component: MyPluginList,+ }],+ slots: {+ 'product.form_sidebar': [{+ id: 'my-plugin-card',+ component: MyPluginCard as never,+ position: 50,+ }],+ },+})+```++That's the whole entry-point. Edit it to register what your plugin needs and remove what it doesn't.++## The example endpoints++The generated `client.ts` calls `adminClient.request()` against `/api/v3/admin/<name>s` — those endpoints don't exist by default. You'd add them on the Rails side (a `BrandsController`, a Brand model, etc.) for the plugin to do anything end-to-end. The CLI doesn't scaffold the Rails engine today; for now, write that part by hand using the [backend customization docs](/developer/customization/extending-backend).++## Reference++- [`@spree/cli` source](https://github.com/spree/spree/tree/main/packages/cli)+- [Template tree](https://github.com/spree/spree/tree/main/packages/cli/templates/plugin) — what gets copied (`.tt` files are template-substituted)diff --git a/docs/developer/dashboard/public-api.mdx b/docs/developer/dashboard/public-api.mdxnew file mode 100644index 0000000000..d806b7db34--- /dev/null+++ b/docs/developer/dashboard/public-api.mdx@@ -0,0 +1,227 @@+---+title: Public API+sidebarTitle: Public API+description: Every importable symbol the dashboard exposes — components, hooks, registries, providers, and the SDK client. Treat this as the surface you can safely depend on.+---++The dashboard is structured as three packages, each with a documented public surface. **Anything not listed here is internal** — don't import it via `@spree/dashboard-core/src/internal/...`, because we'll move or rename it without a deprecation cycle.++## `@spree/dashboard-core`++Default-import surface for plugins and customizations.++### Plugin facade++```ts+import { defineDashboardPlugin } from '@spree/dashboard-core'+```++Single declarative entry-point for all five registries. See [Customization Quickstart](/developer/dashboard/customization/quickstart) for the full shape.++### Registries++```ts+import {+ nav,+ settingsNav,+ // route registry+ pluginRoutes,+ matchPluginRoute,+ usePluginRoutes,+ // slot registry+ registerSlot,+ removeSlot,+ updateSlot,+ useSlotEntries,+ // table registry+ tables,+} from '@spree/dashboard-core'+```++Each registry exposes `add`/`remove`/`update`/`insertBefore`/`insertAfter` mutators. See the per-feature pages for examples.++### Components++```ts+import {+ // Page chrome+ PageHeader,+ PageTabs,+ TopBar,+ AppSidebar,+ SettingsSidebar,+ Slot,+ StoreSwitcher,+ // Tables+ ResourceTable,+ TableToolbar,+ BulkActionBar,+ // Form widgets+ StoreDatePicker,+ CountryCombobox,+ CountryStateFields,+ CurrencySelect,+ LocaleSelect,+ MarketCombobox,+ ResourceCombobox,+ ResourceMultiAutocomplete,+ TagCombobox,+ PreferencesForm,+ AddressFormDialog,+ // Permission+ Can,+ // Export+ ExportButton,+} from '@spree/dashboard-core'+```++### Hooks++```ts+import {+ useAuth, // current admin user+ usePermissions, // CanCanCan abilities+ useStore, // current store+ useCommandPalette, // ⌘K palette open/close state+ useGlobalSearch, // global search query state+ useCountries,+ useCustomFields,+ useDirectUpload, // ActiveStorage direct uploads+ useExport, // CSV export job lifecycle+ useResourceMutation, // useMutation wrapper with 422 handling+} from '@spree/dashboard-core'+```++### Helpers++```ts+import {+ filtersToRansack, // converts table filter state → Ransack params+ mapSpreeErrorsToForm, // 422 response → form.setError+ // formatters+ formatMoney,+ formatDate,+ formatRelativeTime,+ // i18n+ i18n, // configured instance+ // form mappers+ mapFormErrors,+} from '@spree/dashboard-core'+```++### SDK client++```ts+import { adminClient } from '@spree/dashboard-core'+```++The shared `@spree/dashboard-sdk` instance configured for the host's API URL. Use this everywhere instead of constructing your own.++### Providers++```ts+import {+ AuthProvider,+ PermissionProvider,+ StoreProvider,+} from '@spree/dashboard-core'+```++Mount these at the root of your app shell. The shipped app shell does this for you — re-export only if you're composing a custom shell (vendor panel, etc.).++### Vite plugin++```ts+import { spreeDashboardPlugin } from '@spree/dashboard-core/vite'+```++Vite plugin that resolves third-party dashboard plugins and injects Tailwind `@source` directives for their CSS. See [Distributing](/developer/dashboard/plugins/distributing) for the host wiring.++## `@spree/dashboard-ui`++Design system primitives. Headless — accept data via props, never reach for providers or hooks.++### shadcn-style primitives++```ts+import {+ Button,+ Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter,+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,+ Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter,+ DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem,+ Input, Textarea, Checkbox, RadioGroup, Switch,+ Select, SelectTrigger, SelectContent, SelectItem, SelectValue,+ Combobox,+ Field, FieldLabel, FieldError, FieldDescription,+ Table, TableHeader, TableBody, TableRow, TableCell,+ Badge,+ Avatar,+ Skeleton,+ Tooltip, TooltipTrigger, TooltipContent,+ Tabs, TabsList, TabsTrigger, TabsContent,+ Alert, AlertTitle, AlertDescription,+ Toaster, toast,+} from '@spree/dashboard-ui'+```++### Composed components++Higher-level pieces that bundle multiple primitives but still take data via props:++```ts+import {+ ResourceLayout, // header + main + sidebar grid+ EmptyState,+ ColorPicker,+ // …more land here as we extract from @spree/dashboard+} from '@spree/dashboard-ui'+```++### Utilities++```ts+import { cn } from '@spree/dashboard-ui' // clsx + tailwind-merge+```++## `@spree/dashboard`++The deployable app. **You normally don't import from here in a plugin.** The exception is when you're composing a custom dashboard variant (e.g., a vendor portal) and want to reuse a resource hook:++```ts+import {+ useOrders,+ useProducts,+ useCustomers,+ // …per-resource hooks+} from '@spree/dashboard'+```++Importing from `@spree/dashboard` pins your code to the deployable app's version. If you only need the underlying primitives, prefer `@spree/dashboard-core`.++## What about `@spree/dashboard-sdk`?++The SDK is a separate package and a public dependency. Import types and `SpreeError` from it directly:++```ts+import {+ type AdminProduct,+ type AdminOrder,+ type AdminCustomer,+ SpreeError,+} from '@spree/dashboard-sdk'+```++The `adminClient` instance, by contrast, comes from `@spree/dashboard-core` so the host owns the configured singleton.++## Stability++Anything on this page is covered by semver from `@spree/dashboard-core` 1.0.0 onward. Pre-1.0 we may rename, but we'll call breaking moves out in the changelog.++Anything not listed here is internal. If you find yourself wanting it, open a discussion — it's a sign we should promote it to the public surface.++## Reference++- [`packages/dashboard-core/src/index.ts`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/index.ts) — canonical export list+- [`packages/dashboard-ui/src/index.ts`](https://github.com/spree/spree/blob/main/packages/dashboard-ui/src/index.ts)+- [`packages/dashboard-sdk/src/index.ts`](https://github.com/spree/spree/blob/main/packages/dashboard-sdk/src/index.ts)diff --git a/docs/developer/dashboard/recipes/custom-form-field.mdx b/docs/developer/dashboard/recipes/custom-form-field.mdxnew file mode 100644index 0000000000..e2976d2260--- /dev/null+++ b/docs/developer/dashboard/recipes/custom-form-field.mdx@@ -0,0 +1,146 @@+---+title: Add a custom form field+sidebarTitle: Custom form field+description: Add a field to the product (or any built-in) form, validate it client-side and server-side, and persist via the Admin API.+---++The dashboard's product form lives in `@spree/dashboard` and renders core attributes (name, description, price, …). When you've added a custom column to `spree_products` or a custom field through a [metafield definition](/developer/customization/metadata), you'll want it to surface in the same form. This recipe walks the four pieces end-to-end.++## Backend prerequisites++This recipe assumes you've added the column or metafield on the Rails side:++```ruby+# A migration:+class AddTechSpecsToSpreeProducts < ActiveRecord::Migration[7.2]+ def change+ add_column :spree_products, :tech_specs, :text, null: false, default: ''+ end+end+```++And declared it as a permitted attribute on the Admin API serializer + controller (see [Admin API conventions](/developer/dashboard/customization/backend)).++## 1. Register the field++Use a slot to inject your field into the product form's sidebar:++```tsx+// packages/dashboard/src/customizations.ts+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { TechSpecsField } from './fields/tech-specs-field'++defineDashboardPlugin({+ slots: {+ 'product.form_sidebar': [{+ id: 'tech-specs',+ component: TechSpecsField as never,+ position: 80,+ }],+ },+})+```++If you don't see a slot at the right spot in the form, see [Slots catalog](/developer/dashboard/slots-catalog) — if one's missing, open a PR adding it.++## 2. Build the field component++The slot's context provides the React Hook Form instance for the page's form. Register your input against it:++```tsx+// packages/dashboard/src/fields/tech-specs-field.tsx+import {+ Card, CardContent, CardHeader, CardTitle,+ Field, FieldError, FieldLabel, Textarea,+} from '@spree/dashboard-ui'+import { useTranslation } from 'react-i18next'+import type { UseFormReturn } from 'react-hook-form'++interface Props {+ form: UseFormReturn<{ tech_specs: string }>+}++export function TechSpecsField({ form }: Props) {+ const { t } = useTranslation()+ const error = form.formState.errors.tech_specs?.message++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.fields.product.tech_specs.label')}</CardTitle>+ </CardHeader>+ <CardContent>+ <Field>+ <FieldLabel className="sr-only" htmlFor="tech_specs">+ {t('admin.fields.product.tech_specs.label')}+ </FieldLabel>+ <Textarea+ id="tech_specs"+ rows={6}+ placeholder={t('admin.fields.product.tech_specs.placeholder')}+ aria-invalid={Boolean(error)}+ {...form.register('tech_specs', {+ maxLength: { value: 5000, message: 'Too long' },+ })}+ />+ {error && <FieldError>{error}</FieldError>}+ </Field>+ </CardContent>+ </Card>+ )+}+```++A few patterns worth flagging:++- **Use `form.register('tech_specs')`** — the parent form's `defaultValues` already includes `tech_specs` from the API response, so RHF wires up the initial value.+- **Use the field-key i18n convention** — `admin.fields.product.tech_specs.{label,placeholder}` falls back to `admin.fields.tech_specs.*` if you want to share the label across resources.+- **Apply `aria-invalid`** when the field has an error so screen readers announce it.++## 3. Extend the Zod schema (optional)++If your customization adds client-side validation, extend the product form schema in the host app:++```ts+// packages/dashboard/src/schemas/product.ts+import { z } from 'zod'++export const productFormSchema = z+ .object({+ name: z.string().min(1),+ // …existing core fields…+ tech_specs: z.string().max(5000).default(''),+ })+```++The form already uses `zodResolver(productFormSchema)`, so adding the key automatically runs validation. If the field has no client-side constraints, skip this step — server-side validation will round-trip through `mapSpreeErrorsToForm`.++## 4. Translations++```json+// packages/dashboard/src/locales/en.json+{+ "fields": {+ "product": {+ "tech_specs": {+ "label": "Technical specifications",+ "placeholder": "RAM, CPU, dimensions, weight…"+ }+ }+ }+}+```++i18next merges this into the existing `admin` namespace. See [Translations](/developer/dashboard/customization/translations) for the field-key fallback chain.++## What you should *not* do++- **Don't add a separate `useState` for the value.** The form's RHF instance owns it; a duplicate state goes out of sync on submit/reset.+- **Don't call `adminClient.products.update()` from inside the field.** The parent form's submit handler already does that — your job is to register the value.+- **Don't add a `useEffect` that copies `props.product.tech_specs` to local state.** RHF's `defaultValues` from the parent already handles the initial value.++## Reference++- [React Hook Form `register`](https://react-hook-form.com/docs/useform/register)+- [`mapSpreeErrorsToForm`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/form-errors.ts) — wires 422 responses to field errors+- [Field-key i18n convention](/developer/dashboard/customization/translations#field-key-convention)diff --git a/docs/developer/dashboard/recipes/page-action-button.mdx b/docs/developer/dashboard/recipes/page-action-button.mdxnew file mode 100644index 0000000000..c3dc5f2f91--- /dev/null+++ b/docs/developer/dashboard/recipes/page-action-button.mdx@@ -0,0 +1,194 @@+---+title: Add a page action button+sidebarTitle: Page action button+description: Add a primary action (e.g., "Send invoice", "Sync to ERP") to a built-in detail page's header — both as a top-right button and as a dropdown item.+---++Built-in detail pages render `<PageHeader>` at the top with primary action buttons on the right and a more-actions (`⋯`) dropdown next to them. Both are slot-based — you can inject your own buttons or menu items without touching the host page.++Two slots cover the surface:++- `page.actions` — the right-aligned action zone (buttons, badges)+- `page.actions_dropdown` — the dropdown menu++This recipe shows both — and how to gate them by permission + resource state.++## A button in the actions row++```tsx+// packages/dashboard/src/actions/send-invoice-button.tsx+import { Button } from '@spree/dashboard-ui'+import { Send } from 'lucide-react'+import { useResourceMutation } from '@spree/dashboard-core'+import { adminClient } from '@spree/dashboard-core'++interface Props {+ resource: { id: string; state: string } // AdminOrder+}++export function SendInvoiceButton({ resource }: Props) {+ const mutation = useResourceMutation({+ mutationFn: () =>+ adminClient.request('POST', `/orders/${resource.id}/send_invoice`),+ successMessage: 'Invoice sent',+ })++ // Only show on completed orders.+ if (resource.state !== 'complete') return null++ return (+ <Button+ variant="outline"+ size="sm"+ onClick={() => mutation.mutate()}+ disabled={mutation.isPending}+ >+ <Send className="size-4" />+ Send invoice+ </Button>+ )+}+```++Register it:++```ts+// packages/dashboard/src/customizations.ts+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { SendInvoiceButton } from './actions/send-invoice-button'++defineDashboardPlugin({+ slots: {+ 'page.actions': [{+ id: 'send-invoice',+ component: SendInvoiceButton as never,+ position: 50,+ // Permission gate at the slot level — the button is also hidden by+ // its own `state !== 'complete'` check, but the slot gate runs first+ // and avoids mounting at all when the user can't trigger the action.+ if: ({ permissions }) => permissions.can('update', 'Spree::Order'),+ }],+ },+})+```++Two layers of gating:++1. **Slot `if`** — coarse permission check; component never mounts if the user can't act.+2. **In-component `return null`** — fine-grained state check; the user *can* send invoices, but this specific order isn't ready yet.++Keep both. The `if` check is cheap; the resource-state check needs the actual record.++## A dropdown menu item++For secondary actions, use `page.actions_dropdown` and render `<DropdownMenuItem>`:++```tsx+// packages/dashboard/src/actions/sync-to-erp-item.tsx+import { DropdownMenuItem } from '@spree/dashboard-ui'+import { RefreshCw } from 'lucide-react'+import { useResourceMutation, adminClient } from '@spree/dashboard-core'++interface Props {+ resource: { id: string }+}++export function SyncToErpItem({ resource }: Props) {+ const mutation = useResourceMutation({+ mutationFn: () => adminClient.request('POST', `/orders/${resource.id}/sync_to_erp`),+ successMessage: 'Synced',+ })++ return (+ <DropdownMenuItem+ onSelect={(event) => {+ event.preventDefault()+ mutation.mutate()+ }}+ disabled={mutation.isPending}+ >+ <RefreshCw className="size-4" />+ Sync to ERP+ </DropdownMenuItem>+ )+}+```++```ts+defineDashboardPlugin({+ slots: {+ 'page.actions_dropdown': [{+ id: 'sync-to-erp',+ component: SyncToErpItem as never,+ position: 50,+ if: ({ permissions }) => permissions.can('manage', 'Spree::Order'),+ }],+ },+})+```++The `event.preventDefault()` keeps the dropdown open if the mutation fails — without it, the menu closes on click and the toast appears with no context.++## Confirm before acting++For destructive or expensive actions, wrap the click in a `<Dialog>`:++```tsx+import { useState } from 'react'+import {+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,+ DropdownMenuItem, Button,+} from '@spree/dashboard-ui'++export function ResetCartItem({ resource }: { resource: { id: string } }) {+ const [open, setOpen] = useState(false)+ const mutation = useResourceMutation({+ mutationFn: () => adminClient.request('POST', `/orders/${resource.id}/reset_cart`),+ successMessage: 'Cart reset',+ onSuccess: () => setOpen(false),+ })++ return (+ <>+ <DropdownMenuItem+ onSelect={(event) => {+ event.preventDefault()+ setOpen(true)+ }}+ >+ Reset cart+ </DropdownMenuItem>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Reset this cart?</DialogTitle>+ </DialogHeader>+ <p>All line items will be cleared. This cannot be undone.</p>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>+ <Button variant="destructive" onClick={() => mutation.mutate()}>+ Reset+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ )+}+```++## Context++The `resource` prop is whatever the host page passed to `<PageHeader resource={…} />`. On the order detail page it's an `AdminOrder`; on a product page it's an `AdminProduct`. The slot doesn't statically know which — see [Slots](/developer/dashboard/customization/slots) for the typing escape hatches.++If you need the current store/user/permissions, they're also merged into the props bag:++```tsx+export function MyButton({ resource, permissions, store, user }: Props) { … }+```++## Reference++- [`page.actions` / `page.actions_dropdown`](/developer/dashboard/slots-catalog#page-header-slots) in the slots catalog+- [`useResourceMutation`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/hooks/use-resource-mutation.ts) — 422-aware mutation hook+- [Slots](/developer/dashboard/customization/slots) — registry primerdiff --git a/docs/developer/dashboard/recipes/sidebar-widget.mdx b/docs/developer/dashboard/recipes/sidebar-widget.mdxnew file mode 100644index 0000000000..6c28690392--- /dev/null+++ b/docs/developer/dashboard/recipes/sidebar-widget.mdx@@ -0,0 +1,141 @@+---+title: Add a sidebar widget+sidebarTitle: Sidebar widget+description: Add an info card to a built-in detail page's sidebar — pulling its own data, gated by permissions, with loading and empty states.+---++The product, order, and customer detail pages each render a `<Slot>` in their right-hand sidebar — typically named `<resource>.form_sidebar`. Widgets rendered into these slots see the current record and can fetch their own data without disturbing the host page.++This recipe builds a "Loyalty status" card for the customer detail page: read-only, fetches the customer's points + tier, shows a spinner while loading, an empty state when there's no data, and hides itself for staff without the right permission.++## The component++```tsx+// packages/dashboard/src/widgets/loyalty-status-card.tsx+import { useQuery } from '@tanstack/react-query'+import { adminClient, useStore } from '@spree/dashboard-core'+import {+ Card, CardContent, CardHeader, CardTitle,+ Skeleton, Badge, EmptyState,+} from '@spree/dashboard-ui'+import { Trophy } from 'lucide-react'++interface LoyaltyRecord {+ customer_id: string+ points: number+ tier: 'bronze' | 'silver' | 'gold'+}++interface Props {+ resource: { id: string }+}++export function LoyaltyStatusCard({ resource }: Props) {+ const { storeId } = useStore()+ const { data, isLoading } = useQuery({+ queryKey: ['loyalty', storeId, resource.id],+ queryFn: () =>+ adminClient.request<{ data: LoyaltyRecord | null }>(+ 'GET',+ `/customers/${resource.id}/loyalty`,+ ),+ staleTime: 30_000,+ })++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Trophy className="size-4" />+ Loyalty status+ </CardTitle>+ </CardHeader>+ <CardContent>+ {isLoading ? (+ <Skeleton className="h-8 w-32" />+ ) : !data?.data ? (+ <EmptyState size="sm" title="No loyalty record" />+ ) : (+ <div className="space-y-2">+ <Badge variant={tierVariant(data.data.tier)}>{data.data.tier}</Badge>+ <p className="text-sm text-muted-foreground">{data.data.points} points</p>+ </div>+ )}+ </CardContent>+ </Card>+ )+}++function tierVariant(tier: LoyaltyRecord['tier']) {+ return tier === 'gold' ? 'default' : 'secondary'+}+```++Worth noting:++- **`storeId` in the query key.** The dashboard is multi-store; without this, switching stores leaves stale data on screen.+- **`staleTime: 30_000`** keeps the data fresh enough for a sidebar widget without re-fetching on every focus event.+- **Three states.** Loading (`<Skeleton>`), empty (`<EmptyState>`), and loaded. Skipping the empty state ships a card that says "0 points" when really the customer has never been enrolled — different meaning, different UX.++## Register the widget++```ts+// packages/dashboard/src/customizations.ts+import { defineDashboardPlugin } from '@spree/dashboard-core'+import { LoyaltyStatusCard } from './widgets/loyalty-status-card'++defineDashboardPlugin({+ slots: {+ 'customer.form_sidebar': [{+ id: 'loyalty-status',+ component: LoyaltyStatusCard as never,+ position: 50,+ if: ({ permissions }) => permissions.can('read', 'MyApp::LoyaltyRecord'),+ }],+ },+})+```++`position: 50` puts the card near the top of the sidebar (built-in cards typically use 100/200/300). Pick a number based on whether your widget is more or less important than the others — for a "status" card, near the top is right.++## When to fetch in the widget vs. read from the host++The pattern above fetches its own data. The alternative is to read it from the resource the host passes:++```tsx+function MyCard({ resource }: { resource: AdminCustomer }) {+ return <div>{resource.loyalty_points}</div> // host already loaded it+}+```++Choose based on **whether the data is hot path for the rest of the page**:++| Data | Approach |+|---|---|+| Already on the host's serializer (e.g., `customer.tags`) | Read from `resource` — no extra HTTP |+| Conditional, expensive, or owned by your plugin | Fetch in the widget |+| Sometimes-needed (e.g., gated by feature flag) | Fetch in the widget |++A widget that always fetches is wasteful when the host already has the data. A widget that reads from the host but the host doesn't serialize is broken. Match the pattern to the source of truth.++## Loading states for the host page++The host page renders the sidebar slot before its own data is ready — your widget receives `resource: undefined` briefly during initial load. Either:++```tsx+if (!resource) return <Skeleton className="h-24" />+```++…or skip rendering altogether and let the slot register no DOM at all:++```tsx+if (!resource) return null+```++Skeleton when you want to reserve layout space; null when the widget is small enough that pop-in is acceptable.++## Reference++- [Slots catalog → form sidebars](/developer/dashboard/slots-catalog) — every page-level sidebar slot+- [`useQuery`](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) — query key conventions+- [Memory: query keys are store-scoped](https://github.com/spree/spree/blob/main/packages/dashboard/README.md) — why `storeId` belongs in the keydiff --git a/docs/developer/dashboard/slots-catalog.mdx b/docs/developer/dashboard/slots-catalog.mdxnew file mode 100644index 0000000000..5afc04e7a5--- /dev/null+++ b/docs/developer/dashboard/slots-catalog.mdx@@ -0,0 +1,130 @@+---+title: Slots catalog+sidebarTitle: Slots catalog+description: Every named slot the dashboard renders today. Each entry lists the host page, the slot name, and the context the slot's components receive.+---++This is the canonical list of slots the dashboard currently exposes. To rebuild it locally: `grep -rn '<Slot name=' packages/dashboard/src packages/dashboard-core/src` and cross-reference each call site for its `context` prop.++If you need a new injection point in a built-in page, open a PR adding `<Slot name="..." context={...} />` and a documentation entry here — that's the contract for new slots.++## Ambient context++Every slot component receives this in addition to the slot-specific context (merged into the same props object):++```ts+interface SlotAmbientContext {+ permissions: Permissions // CanCanCan abilities+ store: Store // the current store+ user: AdminUser // the signed-in admin+}+```++Pull them from the merged props bag:++```tsx+function MyWidget({ permissions, store, resource }: { permissions: Permissions; store: Store; resource: any }) {+ // ...+}+```++## Page header slots++Rendered by `<PageHeader>` (`@spree/dashboard-core/components/page-header.tsx`) at the top of every detail and list page that uses the shared chrome.++### `page.actions`++| Where | Top-right of `<PageHeader>`, left of any explicit `actions` prop |+|---|---|+| Use | Add primary action buttons (e.g., a "Refund" button on the order detail page) |+| Context | `{ resource, ...slotContext }` — `resource` is the current page's primary record, when the host passed one to `<PageHeader resource={...} />`. May be `undefined` on list pages. |++### `page.actions_dropdown`++| Where | Inside the more-actions (`⋯`) dropdown menu, above the auto-rendered Copy ID / Delete items |+|---|---|+| Use | Add menu items (`<DropdownMenuItem>`) for secondary actions |+| Context | `{ resource, ...slotContext }` — same as `page.actions` |++## Page tabs slot++### `page.tabs` (default)++Rendered by `<PageTabs>` at the right edge of any tabbed sub-nav.++| Where | After the built-in tab strip |+|---|---|+| Use | Append your own tab(s) to a sub-route — typically for plugin-owned views inside an existing resource (e.g., "Returns" tab on the order detail) |+| Context | `{ tabs, ...slotContext }` — `tabs` is the array of built-in tabs (so you can inspect or filter by them) |++Some pages override `slotName` to scope tabs to a single resource (e.g., `slotName="order.tabs"`). The catalog will grow these as we wire them up; today only the default `page.tabs` name is in production use.++## Payment method editor slots (dynamic)++Used by `<PaymentMethodForm>` to let payment-provider plugins replace pieces of the editor sheet. The slot names are computed per provider type (`stripe`, `bogus`, …), so registering against the right name is what hooks your editor in.++### `payment_method.guide.<providerType>`++| Where | Above the preferences form |+|---|---|+| Use | Banner explaining what the integration does, what credentials to use, links to provider docs |+| Context | `PaymentMethodEditorContext` (see below) |++### `payment_method.form.<providerType>`++| Where | In place of the auto-generated preferences form |+|---|---|+| Use | Render a custom React form when the provider's preferences are too complex for the generated UI (multi-step OAuth, environment switchers, …) |+| Context | `PaymentMethodEditorContext` |++### `payment_method.actions.<providerType>`++| Where | Sheet footer, before Save/Cancel |+|---|---|+| Use | Provider-specific action buttons — "Test connection", "Rotate keys", "Open dashboard in provider" |+| Context | `PaymentMethodEditorContext` |++### `PaymentMethodEditorContext`++```ts+interface PaymentMethodEditorContext {+ mode: 'create' | 'edit'+ type: string // STI shorthand (`stripe`, `bogus`, …)+ paymentMethod: PaymentMethod | null // null in create mode+ preferenceSchema: PreferenceField[]+ preferences: Record<string, unknown>+ onPreferencesChange: (next: Record<string, unknown>) => void+ form: UseFormReturn<PaymentMethodFormValues> // RHF instance for top-level fields+}+```++Helpers for building the slot name:++```ts+import {+ paymentMethodGuideSlot,+ paymentMethodFormSlot,+ paymentMethodActionsSlot,+} from '@spree/dashboard/components/spree/payment-method-editors/types'++paymentMethodFormSlot('stripe') // → "payment_method.form.stripe"+```++Use these instead of constructing the string yourself, so a rename in one place doesn't silently break your registration.++## Adding a new slot++If a built-in page should expose a new injection point:++1. Pick a name (`<resource>.<area>`, e.g., `order.timeline`)+2. Add `<Slot name="..." context={{ resource: order, /* ... */ }} />` at the call site+3. Document the slot here — host, intent, context shape+4. Open the PR++The slot is not "live" until the docs land — without an entry here, no plugin author knows it exists.++## Reference++- [`<Slot>` source](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/components/slot.tsx)+- [`slot-registry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/slot-registry.ts) — `registerSlot`, `removeSlot`, `updateSlot`, `useSlotEntries`+- [Slots customization page](/developer/dashboard/customization/slots) — how to register against a slotdiff --git a/docs/developer/sdk/admin/extending.mdx b/docs/developer/sdk/admin/extending.mdxindex ace7f9d208..15327605ec 100644--- a/docs/developer/sdk/admin/extending.mdx+++ b/docs/developer/sdk/admin/extending.mdx@@ -67,4 +67,4 @@ The SDK transforms `filter`/`sort` into the Ransack-flavored query string the Ad- The [Store SDK extending guide](/developer/sdk/extending) covers the same pattern for storefront endpoints — the API is identical, only the base path (`/api/v3/store`) and auth header differ.- The [Store API](/developer/tutorial/store-api) and [SDK](/developer/tutorial/sdk) tutorials walk through creating new Spree endpoints end-to-end (Rails controller, serializer, TypeScript types). Everything they show for the Store API applies equivalently for the Admin API.-- For building dashboard UI on top of your custom endpoint, see the [Dashboard Plugins](/developer/customization/dashboard-plugins) guide.+- For building dashboard UI on top of your custom endpoint, see the [Dashboard](/developer/dashboard/overview) section — start with [Customization Quickstart](/developer/dashboard/customization/quickstart) for in-app changes or [Plugin Overview](/developer/dashboard/plugins/overview) for redistributable packages.diff --git a/docs/docs.json b/docs/docs.jsonindex c0e6900ee4..e4f71fc1fa 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -43,6 +43,10 @@"source": "/developer/admin/permissions","destination": "/developer/customization/permissions"},+ {+ "source": "/developer/customization/dashboard-plugins",+ "destination": "/developer/dashboard/overview"+ },{"source": "/developer/customization/event-subscribers","destination": "/developer/core-concepts/events"@@ -294,8 +298,48 @@]},{- "group": "Admin Dashboard",+ "group": "React Dashboard","icon": "gauge",+ "pages": [+ "developer/dashboard/overview",+ "developer/dashboard/concepts",+ "developer/dashboard/public-api",+ {+ "group": "Customization",+ "pages": [+ "developer/dashboard/customization/quickstart",+ "developer/dashboard/customization/navigation",+ "developer/dashboard/customization/routes",+ "developer/dashboard/customization/slots",+ "developer/dashboard/customization/tables",+ "developer/dashboard/customization/translations",+ "developer/dashboard/customization/permissions",+ "developer/dashboard/customization/backend"+ ]+ },+ {+ "group": "Recipes",+ "pages": [+ "developer/dashboard/recipes/custom-form-field",+ "developer/dashboard/recipes/page-action-button",+ "developer/dashboard/recipes/sidebar-widget"+ ]+ },+ {+ "group": "Plugins",+ "pages": [+ "developer/dashboard/plugins/overview",+ "developer/dashboard/plugins/scaffolding",+ "developer/dashboard/plugins/publishing",+ "developer/dashboard/plugins/distributing"+ ]+ },+ "developer/dashboard/slots-catalog"+ ]+ },+ {+ "group": "Admin",+ "icon": "ruby","pages": ["developer/admin/admin","developer/admin/extending-ui",@@ -323,8 +367,7 @@"developer/customization/model-preferences","developer/customization/metadata","developer/customization/routes",- "developer/customization/api",- "developer/customization/dashboard-plugins"+ "developer/customization/api"]}]diff --git a/packages/cli/src/commands/plugin.ts b/packages/cli/src/commands/plugin.tsindex f122393c9a..5df8866552 100644--- a/packages/cli/src/commands/plugin.ts+++ b/packages/cli/src/commands/plugin.ts@@ -295,7 +295,7 @@ function printNextSteps(answers: Answers, dst: string, installed: boolean): void` Edit ${pc.cyan('packages/dashboard/src/index.tsx')} to wire your nav/route/slot extensions.`,)lines.push(- ` See ${pc.cyan('https://docs.spreecommerce.org/developer/customization/dashboard-plugins')}`,+ ` See ${pc.cyan('https://docs.spreecommerce.org/developer/dashboard/plugins/overview')}`,)}if (answers.includeEngine) {diff --git a/packages/cli/templates/plugin/README.md.tt b/packages/cli/templates/plugin/README.md.ttindex a43c36476d..7ae7539705 100644--- a/packages/cli/templates/plugin/README.md.tt+++ b/packages/cli/templates/plugin/README.md.tt@@ -28,17 +28,24 @@ The engine needs to live alongside a Spree host (typically scaffolded via `creatgem '{{ruby_name}}', path: '../path/to/{{plugin_name}}/engine'```-Activate the dashboard plugin by adding a side-effect import to your dashboard's `main.tsx`, **before the router mounts**:+Activate the dashboard plugin with a side-effect import in the host's `main.tsx`, before the router mounts. This runs `defineDashboardPlugin` so the nav entry, route, slot widget, and table column register:```tsximport '{{npm_dashboard_package}}'```+That's it — no `vite.config.ts` edit. This plugin's `package.json` declares `"spree": { "dashboard": { "plugin": true } }`, which `@spree/dashboard-core/vite`'s auto-discovery picks up so Tailwind v4 scans the plugin's source files for utility classes automatically.++If you'd rather opt out of auto-discovery and register manually, pass an explicit `plugins` array to `spreeDashboardPlugin` in the host's `vite.config.ts`.+## Documentation-- [Dashboard Plugins guide](https://docs.spreecommerce.org/developer/customization/dashboard-plugins)-- [Custom Admin Endpoints](https://docs.spreecommerce.org/developer/sdk/admin/extending)-- [Spree Extensions guide](https://docs.spreecommerce.org/developer/customization/extensions)+- [Dashboard overview](https://docs.spreecommerce.org/developer/dashboard/overview) — three-package split + when to plug-in vs. customize in-app+- [Customization quickstart](https://docs.spreecommerce.org/developer/dashboard/customization/quickstart) — the registries this plugin uses+- [Plugin overview](https://docs.spreecommerce.org/developer/dashboard/plugins/overview) — packaging + publishing your plugin to npm+- [Slots catalog](https://docs.spreecommerce.org/developer/dashboard/slots-catalog) — every named slot the dashboard exposes+- [Custom Admin Endpoints](https://docs.spreecommerce.org/developer/sdk/admin/extending) — adding your own API endpoints+- [Spree Extensions guide](https://docs.spreecommerce.org/developer/customization/extensions) — the Rails-engine side## Licensediff --git a/packages/cli/templates/plugin/packages/dashboard/package.json.tt b/packages/cli/templates/plugin/packages/dashboard/package.json.ttindex 3993fd9ef8..e5b9627360 100644--- a/packages/cli/templates/plugin/packages/dashboard/package.json.tt+++ b/packages/cli/templates/plugin/packages/dashboard/package.json.tt@@ -21,6 +21,11 @@"lint:fix": "biome check --fix src","typecheck": "tsc --noEmit"},+ "spree": {+ "dashboard": {+ "plugin": true+ }+ },"peerDependencies": {"@spree/admin-sdk": "^0.1.0","@spree/dashboard-core": "^0.1.0",diff --git a/packages/dashboard-core/package.json b/packages/dashboard-core/package.jsonindex 8724c02f46..e79b715935 100644--- a/packages/dashboard-core/package.json+++ b/packages/dashboard-core/package.json@@ -12,6 +12,7 @@".": "./src/index.ts","./plugin": "./src/plugin.ts","./vite": "./src/vite/index.ts",+ "./vite/discover": "./src/vite/discover.ts","./providers/*": "./src/providers/*.tsx","./hooks/*": "./src/hooks/*.ts","./hooks/use-command-palette": "./src/hooks/use-command-palette.tsx",@@ -26,7 +27,8 @@"lint": "biome check src","lint:fix": "biome check --fix src","format": "biome format --write src",- "typecheck": "tsc --noEmit"+ "typecheck": "tsc --noEmit",+ "test": "vitest run"},"peerDependencies": {"@hookform/resolvers": "^5.2.2",@@ -60,6 +62,7 @@"@types/react-dom": "^19.2.3","@types/spark-md5": "^3.0.5","typescript": "~6.0.3",- "vite": "^8.0.16"+ "vite": "^8.0.16",+ "vitest": "^4.1.5"}}diff --git a/packages/dashboard-core/src/vite/discover.ts b/packages/dashboard-core/src/vite/discover.tsnew file mode 100644index 0000000000..81c1c20b7c--- /dev/null+++ b/packages/dashboard-core/src/vite/discover.ts@@ -0,0 +1,119 @@+import fs from 'node:fs'+import { createRequire } from 'node:module'+import path from 'node:path'++/**+ * Walk a host project's `package.json` dependencies and return the names of+ * packages that opt-in as dashboard plugins by declaring+ * `"spree": { "dashboard": { "plugin": true } }` in their own `package.json`.+ *+ * Auto-discovery is what makes `pnpm add @acme/foo-plugin` a one-step install+ * for host-app developers — no manual edit of `vite.config.ts` to register+ * the plugin name. Plugin authors opt-in by adding the marker field; hosts+ * never have to know it exists.+ *+ * Order is deterministic — the order packages appear in the host's combined+ * `dependencies` + `devDependencies` maps. Tailwind class scanning is+ * order-insensitive, so this only matters for the dev-mode banner's listing.+ *+ * The function does not throw on missing files or malformed JSON — failures+ * are reported via the `onWarn` callback and the offending package is+ * skipped. A missing host `package.json` returns an empty array.+ */+export interface DiscoverOptions {+ /** Project root to scan. Usually Vite's `config.root`. */+ root: string+ /** Optional callback for per-package warnings (malformed JSON, missing dep). */+ onWarn?: (message: string) => void+}++export function discoverDashboardPlugins({ root, onWarn }: DiscoverOptions): string[] {+ const hostPkgPath = path.join(root, 'package.json')+ if (!fs.existsSync(hostPkgPath)) return []++ let hostPkg: HostManifest+ try {+ hostPkg = JSON.parse(fs.readFileSync(hostPkgPath, 'utf8')) as HostManifest+ } catch (err) {+ onWarn?.(`Could not parse ${hostPkgPath}: ${(err as Error).message}`)+ return []+ }++ const deps = [+ ...Object.keys(hostPkg.dependencies ?? {}),+ ...Object.keys(hostPkg.devDependencies ?? {}),+ ]++ // Resolve from the host's own root so workspace symlinks and `pnpm`'s+ // `.pnpm/` hoisting both work. createRequire wants a file path, not a+ // directory, so synthesize one.+ const require = createRequire(path.join(root, 'package.json'))++ const discovered: string[] = []+ const seen = new Set<string>()++ for (const name of deps) {+ if (seen.has(name)) continue+ seen.add(name)++ const manifestPath = resolveManifest(name, require)+ if (!manifestPath) continue++ let depPkg: PluginManifest+ try {+ depPkg = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as PluginManifest+ } catch (err) {+ onWarn?.(`Could not parse ${manifestPath}: ${(err as Error).message}`)+ continue+ }++ if (depPkg.spree?.dashboard?.plugin === true) {+ discovered.push(name)+ }+ }++ return discovered+}++interface HostManifest {+ dependencies?: Record<string, string>+ devDependencies?: Record<string, string>+}++interface PluginManifest {+ spree?: {+ dashboard?: {+ plugin?: boolean+ }+ }+}++/**+ * Resolve `<pkg>/package.json` to its filesystem path. We can't always do+ * `require.resolve('<pkg>/package.json')` because many packages don't expose+ * it in their `exports` map. Fall back to walking up from the resolved entry+ * point — same pattern as the source-dir resolver in `index.ts`.+ */+function resolveManifest(pkg: string, require: NodeJS.Require): string | null {+ try {+ return require.resolve(`${pkg}/package.json`)+ } catch {+ // exports map didn't include package.json; walk up from the main entry.+ }++ let entry: string+ try {+ entry = require.resolve(pkg)+ } catch {+ return null+ }++ let current = path.dirname(entry.startsWith('file:') ? entry.slice(7) : entry)+ const { root } = path.parse(current)+ while (current !== root) {+ const candidate = path.join(current, 'package.json')+ if (fs.existsSync(candidate)) return candidate+ current = path.dirname(current)+ }+ return null+}diff --git a/packages/dashboard-core/src/vite/index.ts b/packages/dashboard-core/src/vite/index.tsindex 6b2adbc839..8dc976c979 100644--- a/packages/dashboard-core/src/vite/index.ts+++ b/packages/dashboard-core/src/vite/index.ts@@ -2,6 +2,11 @@ import fs from 'node:fs'import { createRequire } from 'node:module'import path from 'node:path'import { fileURLToPath } from 'node:url'+// Self-referencing package import (not a relative path): this entry is loaded+// raw by Node when a host's vite.config.ts imports `@spree/dashboard-core/vite`,+// and Node's TS type-stripping can't resolve extensionless relative specifiers.+// The exports-map path resolves to the real file name everywhere.+import { discoverDashboardPlugins } from '@spree/dashboard-core/vite/discover'import tailwindcss from '@tailwindcss/vite'import type { Plugin, PluginOption } from 'vite'@@ -23,6 +28,13 @@ export interface SpreeDashboardPluginOptions {* to `import()`. The plugin resolves each one via Node module resolution* and tells Tailwind v4 to scan its source files for class usage.*+ * When omitted (the typical case), the plugin auto-discovers installed+ * dashboard plugins by walking the host's `package.json` dependencies and+ * picking up anything that declares+ * `"spree": { "dashboard": { "plugin": true } }`. Pass an explicit array+ * to opt out of auto-discovery — useful for whitelisting in tightly+ * controlled environments.+ ** Example: `['@my-store/orders-plugin', '@my-store/wishlists-plugin']`.*/plugins?: string[]@@ -73,7 +85,7 @@ export function spreeDashboardPlugin(options: SpreeDashboardPluginOptions = {}):}function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): Plugin {- const pluginPackages = options.plugins ?? []+ const explicitPlugins = options.pluginsconst cssEntry = options.cssEntry ?? './src/styles.css'// Resolution roots from this file's location. Wherever@@ -84,6 +96,7 @@ function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): Pllet resolvedSources: string[] = []let resolvedCssEntry = ''+ let pluginErrors: PluginError[] = []return {name: 'spree:dashboard-tailwind-source',@@ -92,11 +105,28 @@ function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): PlconfigResolved(config) {resolvedCssEntry = path.resolve(config.root, cssEntry).split(path.sep).join('/')+ // `plugins: []` is an explicit empty whitelist; only `plugins` omitted+ // triggers discovery. Discovery walks the host's package.json deps and+ // returns names that opt-in via the `spree.dashboard.plugin` marker.+ const pluginPackages =+ explicitPlugins ??+ discoverDashboardPlugins({+ root: config.root,+ onWarn: (msg) => console.warn(`[@spree/dashboard-core/vite] ${msg}`),+ })+const packagesToScan = ['@spree/dashboard-core', '@spree/dashboard-ui', ...pluginPackages]- resolvedSources = packagesToScan- .map((pkg) => resolvePackageSourceDir(pkg, fromHere))- .filter((dir): dir is string => dir !== null)+ pluginErrors = []+ resolvedSources = []+ for (const pkg of packagesToScan) {+ const dir = resolvePackageSourceDir(pkg, fromHere)+ if (dir) {+ resolvedSources.push(dir)+ } else {+ pluginErrors.push({ pkg, kind: 'unresolved' })+ }+ }},transform(code, id) {@@ -110,9 +140,50 @@ function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): Plmap: null,}},++ configureServer(server) {+ // Surface unresolved plugins as a Vite error overlay in dev so the+ // failure mode is loud. Without this, a missing plugin silently emits+ // unstyled HTML when the host imports it.+ if (pluginErrors.length === 0) return+ const message = formatPluginErrorOverlay(pluginErrors)+ server.middlewares.use((_req, _res, next) => {+ server.ws.send({+ type: 'error',+ err: {+ message,+ stack: '',+ plugin: 'spree:dashboard-tailwind-source',+ },+ })+ next()+ })+ },}}+interface PluginError {+ pkg: string+ kind: 'unresolved'+}++function formatPluginErrorOverlay(errors: PluginError[]): string {+ const lines = [+ 'Spree dashboard plugin(s) could not be resolved:',+ '',+ ...errors.map(({ pkg }) => ` - ${pkg}`),+ '',+ 'For each one, check:',+ ' 1. The package is installed (`pnpm add <package>`)',+ ' 2. Its package.json declares the dashboard marker:',+ ' { "spree": { "dashboard": { "plugin": true } } }',+ '',+ 'If you registered it explicitly via spreeDashboardPlugin({ plugins: [...] }),',+ 'verify the name matches the installed package exactly.',+ ]+ return lines.join('\n')+}+/*** Resolve `<package>/src` on disk. Resolves the package's main entry point* (defined by its `exports` map or `main` field) and walks upwards looking@@ -128,11 +199,6 @@ function resolvePackageSourceDir(pkg: string, require: NodeJS.Require): string |if (!packageRoot) return nullreturn path.join(packageRoot, 'src')} catch {- console.warn(- `[@spree/dashboard-core/vite] Could not resolve '${pkg}'. ` +- `Tailwind classes from this package won't be generated. ` +- `Make sure the package is installed.`,- )return null}}diff --git a/packages/dashboard-core/tests/discover.test.ts b/packages/dashboard-core/tests/discover.test.tsnew file mode 100644index 0000000000..76832f06e2--- /dev/null+++ b/packages/dashboard-core/tests/discover.test.ts@@ -0,0 +1,156 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { discoverDashboardPlugins } from '../src/vite/discover'++/**+ * Each test builds a tiny fixture project on disk:+ *+ * <tmp>/+ * package.json+ * node_modules/+ * <dep>/package.json+ *+ * That lets us exercise the real `require.resolve` resolution path the+ * production code uses, without mocking Node's module system.+ */++interface Fixture {+ root: string+ cleanup: () => void+ writeHost: (deps: Record<string, string>, devDeps?: Record<string, string>) => void+ writeDep: (name: string, pkg: Record<string, unknown>) => void+}++function makeFixture(): Fixture {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-discover-'))+ fs.mkdirSync(path.join(root, 'node_modules'), { recursive: true })++ return {+ root,+ cleanup: () => fs.rmSync(root, { recursive: true, force: true }),+ writeHost(deps, devDeps = {}) {+ fs.writeFileSync(+ path.join(root, 'package.json'),+ JSON.stringify({ name: 'host', dependencies: deps, devDependencies: devDeps }),+ )+ },+ writeDep(name, pkg) {+ // Support scoped names by splitting on `/`.+ const dir = path.join(root, 'node_modules', ...name.split('/'))+ fs.mkdirSync(dir, { recursive: true })+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({ name, version: '0.0.0', main: 'index.js', ...pkg }),+ )+ // require.resolve(pkg) needs `main` to point at an existing file.+ fs.writeFileSync(path.join(dir, 'index.js'), '')+ },+ }+}++describe('discoverDashboardPlugins', () => {+ let fixture: Fixture++ beforeEach(() => {+ fixture = makeFixture()+ })++ afterEach(() => {+ fixture.cleanup()+ })++ it('discovers deps that declare the marker', () => {+ fixture.writeHost({ '@acme/foo': '^1', '@acme/bar': '^1' })+ fixture.writeDep('@acme/foo', { spree: { dashboard: { plugin: true } } })+ fixture.writeDep('@acme/bar', {})++ const discovered = discoverDashboardPlugins({ root: fixture.root })+ expect(discovered).toEqual(['@acme/foo'])+ })++ it('walks both dependencies and devDependencies', () => {+ fixture.writeHost({ '@acme/prod-plugin': '^1' }, { '@acme/dev-plugin': '^1' })+ fixture.writeDep('@acme/prod-plugin', { spree: { dashboard: { plugin: true } } })+ fixture.writeDep('@acme/dev-plugin', { spree: { dashboard: { plugin: true } } })++ expect(discoverDashboardPlugins({ root: fixture.root })).toEqual([+ '@acme/prod-plugin',+ '@acme/dev-plugin',+ ])+ })++ it('ignores deps with the marker set to false or missing', () => {+ fixture.writeHost({ '@acme/foo': '^1', '@acme/bar': '^1', '@acme/baz': '^1' })+ fixture.writeDep('@acme/foo', { spree: { dashboard: { plugin: false } } })+ fixture.writeDep('@acme/bar', { spree: { dashboard: {} } })+ fixture.writeDep('@acme/baz', { spree: {} })++ expect(discoverDashboardPlugins({ root: fixture.root })).toEqual([])+ })++ it('returns deterministic order (deps before devDeps, manifest order within each)', () => {+ fixture.writeHost({ '@acme/a': '^1', '@acme/c': '^1' }, { '@acme/b': '^1' })+ fixture.writeDep('@acme/a', { spree: { dashboard: { plugin: true } } })+ fixture.writeDep('@acme/b', { spree: { dashboard: { plugin: true } } })+ fixture.writeDep('@acme/c', { spree: { dashboard: { plugin: true } } })++ expect(discoverDashboardPlugins({ root: fixture.root })).toEqual([+ '@acme/a',+ '@acme/c',+ '@acme/b',+ ])+ })++ it('returns an empty array when the host package.json is missing', () => {+ // Brand-new tmp dir, no package.json written.+ expect(discoverDashboardPlugins({ root: fixture.root })).toEqual([])+ })++ it('warns and skips malformed host package.json', () => {+ fs.writeFileSync(path.join(fixture.root, 'package.json'), '{ not json')+ const warnings: string[] = []++ const result = discoverDashboardPlugins({+ root: fixture.root,+ onWarn: (msg) => warnings.push(msg),+ })++ expect(result).toEqual([])+ expect(warnings).toHaveLength(1)+ expect(warnings[0]).toMatch(/Could not parse/)+ })++ it('skips deps with malformed package.json without crashing the whole walk', () => {+ // Node's `require.resolve` itself throws when it can't parse a dep's+ // package.json, so the dep is treated as unresolvable and silently+ // skipped — same behavior as a dep that's declared but uninstalled. The+ // important contract here is "the walk doesn't crash on a bad dep."+ fixture.writeHost({ '@acme/good': '^1', '@acme/bad': '^1' })+ fixture.writeDep('@acme/good', { spree: { dashboard: { plugin: true } } })+ const badDir = path.join(fixture.root, 'node_modules', '@acme/bad')+ fs.mkdirSync(badDir, { recursive: true })+ fs.writeFileSync(path.join(badDir, 'package.json'), '{ bogus')+ fs.writeFileSync(path.join(badDir, 'index.js'), '')++ const result = discoverDashboardPlugins({ root: fixture.root })+ expect(result).toEqual(['@acme/good'])+ })++ it('skips deps that cannot be resolved (e.g. declared but not installed)', () => {+ fixture.writeHost({ '@acme/foo': '^1', '@acme/ghost': '^1' })+ fixture.writeDep('@acme/foo', { spree: { dashboard: { plugin: true } } })+ // Note: no writeDep for @acme/ghost — declared but not installed.++ const result = discoverDashboardPlugins({ root: fixture.root })+ expect(result).toEqual(['@acme/foo'])+ })++ it('deduplicates a dep listed in both dependencies and devDependencies', () => {+ fixture.writeHost({ '@acme/foo': '^1' }, { '@acme/foo': '^1' })+ fixture.writeDep('@acme/foo', { spree: { dashboard: { plugin: true } } })++ expect(discoverDashboardPlugins({ root: fixture.root })).toEqual(['@acme/foo'])+ })+})diff --git a/packages/dashboard-core/vitest.config.ts b/packages/dashboard-core/vitest.config.tsnew file mode 100644index 0000000000..9eef0e8a80--- /dev/null+++ b/packages/dashboard-core/vitest.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ environment: 'node',+ include: ['tests/**/*.test.ts'],+ },+})diff --git a/packages/dashboard-plugin-example/README.md b/packages/dashboard-plugin-example/README.mdindex ec16668905..3c6b292809 100644--- a/packages/dashboard-plugin-example/README.md+++ b/packages/dashboard-plugin-example/README.md@@ -2,7 +2,7 @@Reference implementation of a Spree dashboard plugin. Adds a "Brands" feature to the admin via `defineDashboardPlugin` from `@spree/dashboard-core`.-This package is the runnable companion to the [Dashboard Plugins guide](../../docs/developer/customization/dashboard-plugins.mdx). Read that for the conceptual walkthrough; read the source here for a concrete template you can copy.+This package is the runnable companion to the [Dashboard section](../../docs/developer/dashboard/) of the developer docs. Start with [`overview.mdx`](../../docs/developer/dashboard/overview.mdx) for the lay of the land, then [`plugins/overview.mdx`](../../docs/developer/dashboard/plugins/overview.mdx) for the packaging story. Read the source here for a concrete template you can copy.## What it demonstratesdiff --git a/packages/dashboard-plugin-example/package.json b/packages/dashboard-plugin-example/package.jsonindex 77ea0f26fb..23d67c09ba 100644--- a/packages/dashboard-plugin-example/package.json+++ b/packages/dashboard-plugin-example/package.json@@ -21,6 +21,11 @@"format": "biome format --write src","typecheck": "tsc --noEmit"},+ "spree": {+ "dashboard": {+ "plugin": true+ }+ },"peerDependencies": {"@spree/admin-sdk": "workspace:^","@spree/dashboard-core": "workspace:^",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8b97015ac0..4599e415b8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -389,6 +389,9 @@ importers:vite:specifier: ^8.0.16version: 8.0.16(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^4.1.5+ version: 4.1.5(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))packages/dashboard-plugin-example:dependencies:@@ -433,8 +436,8 @@ importers:specifier: ~6.0.3version: 6.0.3vite:- specifier: ^8.0.11- version: 8.0.11(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: ^8.0.16+ version: 8.0.16(@types/[email protected])([email protected])([email protected])([email protected])([email protected])packages/dashboard-ui:dependencies: