Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Fix runtime-breaking errors in the dashboard docs

Damian Legawiec88b71ee0f0f1
diff --git a/docs/developer/dashboard/concepts.mdx b/docs/developer/dashboard/concepts.mdx
index b0a4f396be..ade8b6b765 100644
--- a/docs/developer/dashboard/concepts.mdx
+++ b/docs/developer/dashboard/concepts.mdx
@@ -87,7 +87,7 @@ This is why links work, deep-links restore filter state, and the browser back bu
The dashboard ships with English, German, French, Polish, Arabic, and Simplified Chinese 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)`
+2. Register the bundle: `i18n.addResourceBundle('en', 'translation', bundle, true, true)`
3. Use `useTranslation()` in components and `i18n.t()` at registration sites
[Translations](/developer/dashboard/customization/translations) covers the field-key convention.
diff --git a/docs/developer/dashboard/customization/backend.mdx b/docs/developer/dashboard/customization/backend.mdx
index 0d5e301dd8..48df83876a 100644
--- a/docs/developer/dashboard/customization/backend.mdx
+++ b/docs/developer/dashboard/customization/backend.mdx
@@ -8,19 +8,19 @@ The dashboard never reaches into Rails models or fetches HTML. All data flows th
## The `adminClient`
-The SPA boots a single `adminClient` instance and exposes it from `@spree/dashboard`. Resource methods follow `client.<resource>.<verb>()`:
+The SPA boots a single `adminClient` instance and exposes it from `@spree/dashboard-core`. Resource methods follow `client.<resource>.<verb>()`:
```ts
-import { adminClient } from '@spree/dashboard'
+import { adminClient } from '@spree/dashboard-core'
await adminClient.products.list({ filter: { name_cont: 'shirt' } })
-await adminClient.products.show('prod_86Rf07xd4z', { include: ['variants'] })
+await adminClient.products.get('prod_86Rf07xd4z', { expand: ['variants'] })
await adminClient.products.create({ name: 'New product' })
await adminClient.products.update('prod_86Rf07xd4z', { name: 'Renamed' })
-await adminClient.products.destroy('prod_86Rf07xd4z')
+await adminClient.products.delete('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.
+All IDs are [prefixed](/api-reference/admin-api/querying) — pass them in, get them out. The SDK never coerces to integers.
## Custom endpoints
@@ -50,8 +50,8 @@ Resource methods are just `request<T>()` calls with the right path + types pre-b
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 { adminClient } from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
-import { adminClient } from '@spree/dashboard'
import type { AdminBrand } from './types'
export function useBrands(params?: { search?: string }) {
@@ -73,12 +73,12 @@ export function useUpdateBrand(id: string) {
return useResourceMutation({
mutationFn: (body: Partial<AdminBrand>) =>
adminClient.request<{ data: AdminBrand }>('PATCH', `/brands/${id}`, { body }),
- invalidateQueries: [['brands'], ['brand', id]],
+ invalidate: [['brands'], ['brand', id]],
})
}
```
-The `invalidateQueries` array refetches dependent queries on success.
+The `invalidate` array refetches dependent queries on success.
## Error handling
@@ -100,7 +100,7 @@ try {
In a React Hook Form submit handler, prefer the higher-level helper:
```tsx
-import { mapSpreeErrorsToForm } from '@/lib/form-errors'
+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'
async function handleSubmit(values: FormValues) {
try {
@@ -123,4 +123,4 @@ Pretty much always, for anything non-trivial. If you're filtering, sorting, or a
- [`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)
+- [`mapSpreeErrorsToForm`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/form-errors.ts)
diff --git a/docs/developer/dashboard/customization/permissions.mdx b/docs/developer/dashboard/customization/permissions.mdx
index 5860c932bc..bd08811332 100644
--- a/docs/developer/dashboard/customization/permissions.mdx
+++ b/docs/developer/dashboard/customization/permissions.mdx
@@ -4,7 +4,7 @@ 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`.
+The dashboard exposes the current admin's CanCanCan abilities to every component via the `usePermissions()` hook. The registry surfaces — nav entries, settings entries, custom routes — also accept a `subject` shortcut, and nav entries take a generic `if` predicate that reads from `permissions`.
## Two layers
@@ -21,23 +21,24 @@ UI gating is for **UX**. Backend authorization is for **security**. They are not
```ts
interface Permissions {
- can(action: string, subject: string | object): boolean
- cannot(action: string, subject: string | object): boolean
+ can(action: ActionName, subject: SubjectName): boolean
+ cannot(action: ActionName, subject: SubjectName): boolean
+ /** True when the matching rule has per-record conditions — expect possible 403s. */
+ isConditional(action: ActionName, subject: SubjectName): boolean
}
```
-It mirrors the backend ability:
+It mirrors the backend ability at the **class level**:
```ts
-permissions.can('read', 'Spree::Order') // class-level check
-permissions.can('update', { __typename: 'Spree::Product', id: '...' }) // record-level
+permissions.can('read', 'Spree::Order')
```
-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).
+Subjects are strings (`'Spree::Order'`, `'Spree::Product'`, or your own `'MyApp::Report'`). There is no client-side record-level check — when a rule is conditional on record attributes, `isConditional` returns `true` and the API is the arbiter: render the control and handle a possible 403.
## `subject` shortcut
-Available on `NavEntry`, `SettingsNavEntry`, `RouteEntry`, and table columns. It's sugar for `if: ({ permissions }) => permissions.can('read', subject)`:
+Available on `NavEntry`, `SettingsNavEntry`, and `RouteEntry`. It hides the entry unless the user can `read` the subject:
```ts
nav.add({
@@ -61,31 +62,36 @@ routes: [{
Use `subject` whenever you want a "user can read this resource" check. For anything else, use `if`.
-## `if` predicate
+## `if` predicate (nav entries)
-`if` is the escape hatch. It receives the same merged context as the component would and returns a boolean:
+`if` on a nav entry is the escape hatch. It runs at render with `{ permissions, store, user }` 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 }) => { /* ... */ },
+import type { Store } from '@spree/admin-sdk'
+
+nav.add({
+ key: 'reports',
+ label: 'Reports',
+ path: '/reports',
+ if: ({ permissions, store }) =>
+ permissions.can('read', 'Spree::Order') &&
+ !!(store as Store | null)?.setup_tasks?.every((task) => task.done),
})
```
-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.
+(The `if` context types `store` loosely — cast to the SDK's `Store` for typed access, the same way the built-in Getting Started entry does.)
+
+Use it for combined checks (permission + store state), feature flags, multi-action checks (`can(update) && can(read)`), or anything the `subject` shortcut can't express in one string. It combines with `subject` — both must pass. (Slot entries have an `if` too, but it receives only the slot's own context — see [Slots](/developer/dashboard/customization/slots).)
## Inside components
-Pull from the slot context or, in custom pages, from the dashboard's `usePermissions()` hook:
+Use the `usePermissions()` hook — it returns `{ permissions, rules, isLoading }`:
```tsx
import { usePermissions } from '@spree/dashboard-core'
function ReportsPage() {
- const permissions = usePermissions()
+ const { permissions } = usePermissions()
if (!permissions.can('read', 'Spree::Order')) {
return <Forbidden />
}
@@ -93,7 +99,7 @@ function ReportsPage() {
}
```
-Same hook backs the registry's `if` predicate, so you can move logic between the two without changing behaviour.
+The same `permissions` object backs the nav registry's `if` predicate, so you can move logic between the two without changing behaviour. For declarative gating, `<Can I="update" a="Spree::Order">…</Can>` (also from `@spree/dashboard-core`) renders children only when the check passes.
## Custom abilities
@@ -113,5 +119,5 @@ After that, `permissions.can('read', 'MyApp::Report')` resolves in the dashboard
## Reference
-- [`Permissions` interface](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/permissions.ts)
+- [`Permissions` interface](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/providers/permission-provider.tsx)
- [CanCanCan docs](https://github.com/CanCanCommunity/cancancan) — the Ruby ability definition language
diff --git a/docs/developer/dashboard/customization/slots.mdx b/docs/developer/dashboard/customization/slots.mdx
index b8b6c30cf5..8e8584b191 100644
--- a/docs/developer/dashboard/customization/slots.mdx
+++ b/docs/developer/dashboard/customization/slots.mdx
@@ -34,12 +34,9 @@ defineDashboardPlugin({
## Slot context
-The component receives two pieces of context merged into a single props object:
+The component receives the **slot-specific context** as props — whatever the host page passes via `<Slot name="..." context={{ product, /* etc */ }} />`. The shape varies per slot: `page.actions_dropdown` passes `{ resource }`, `product.form_sidebar` passes `{ product }`, and so on. Each slot's shape is documented in the [Slots catalog](/developer/dashboard/slots-catalog).
-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).
+For anything beyond the slot's own context — permissions, the current store, the signed-in user — call the hooks inside your component: `usePermissions()`, `useStore()`, `useAuth()` from `@spree/dashboard-core`. (A future release may inject these as ambient props, but today the hooks are the way.)
### Why `as never`?
@@ -56,29 +53,26 @@ interface ProductSlotContext {
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} />
- },
+ component: ({ product }) => <BrandCard productId={product.id} brandId={product.brand_id} />,
position: 50,
})
```
## Permission gating
-The `if` predicate runs on every render with the merged context:
+Gate inside the component with `usePermissions()` — return `null` when the user lacks access:
```tsx
-slots: {
- 'page.actions_dropdown': [{
- id: 'admin-only-thing',
- component: AdminOnlyMenuItem as never,
- if: (ctx) => ctx.permissions?.can('manage', 'Spree::User') ?? false,
- }],
+import { usePermissions } from '@spree/dashboard-core'
+
+function AdminOnlyMenuItem() {
+ const { permissions } = usePermissions()
+ if (!permissions.can('manage', 'Spree::User')) return null
+ return <DropdownMenuItem>…</DropdownMenuItem>
}
```
-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.
+The entry-level `if` predicate also exists, but it only receives the slot's own context (the same props your component gets) — use it to skip an entry based on the host page's data, e.g. `if: ({ product }) => !!product.brand_id`. When it returns `false`, the entry is skipped entirely (no DOM nodes mounted).
## Position
diff --git a/docs/developer/dashboard/customization/translations.mdx b/docs/developer/dashboard/customization/translations.mdx
index 98cd3fbcb1..bed368a3f6 100644
--- a/docs/developer/dashboard/customization/translations.mdx
+++ b/docs/developer/dashboard/customization/translations.mdx
@@ -4,37 +4,39 @@ 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.
+The dashboard uses [i18next](https://www.i18next.com/) with the `react-i18next` bindings. All strings live in i18next's default `translation` namespace, with every key under a top-level `admin.` prefix (`admin.nav.orders`, `admin.fields.<resource>.<attribute>.label`, …). You register your strings into the same namespace with the same prefix so they look and feel native.
## Add translations
```ts
-import i18n from 'i18next'
+import { i18n } from '@spree/dashboard-core'
-i18n.addResourceBundle('en', 'admin', {
- reports: {
- title: 'Reports',
- empty: 'No reports yet.',
- },
- fields: {
- report: {
- name: { label: 'Report name', placeholder: 'e.g. Q4 sales by region' },
+i18n.addResourceBundle('en', 'translation', {
+ 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)
+}, /* deep */ true, /* overwrite */ true)
```
-`addResourceBundle` is additive when `deep: true, overwrite: false` — your keys merge into the existing `admin` namespace without clobbering the dashboard's defaults.
+With `deep: true` your keys merge into the existing tree instead of replacing it; `overwrite: true` lets your bundle win where a key genuinely collides (this is what the framework and the official plugins use). Note the `admin` wrapper is part of the **bundle contents** — the namespace argument stays `'translation'`.
Repeat per locale:
```ts
+import de from './locales/de.json'
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)
+ i18n.addResourceBundle(locale, 'translation', bundle, true, true)
}
```
@@ -63,30 +65,18 @@ Note: `i18n.t` resolves at the call site, so the label is a snapshot taken at re
## 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`
+Form labels, placeholders, and help text follow a two-level key convention:
-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`, …).
+1. `admin.fields.<resource>.<attribute>.<facet>` — resource-specific, e.g. `admin.fields.report.name.label`
+2. `admin.fields.<attribute>.<facet>` — cross-resource defaults, e.g. `admin.fields.name.label`
-In dev mode, missing keys log to the console with the chain that was tried.
+Components call `t()` with these keys explicitly — pick the resource-scoped form for labels that differ per resource, and reuse the shared `admin.fields.<attribute>.<facet>` keys the framework already ships for common attributes (`name`, `email`, `created_at`, `storefront_visible`, …).
-## Server-side error mapping
+In dev mode, missing keys log to the console (in production a missing key falls back to a humanized version of the attribute name).
-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"
-```
+## Server-side error messages
-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.
+The `mapSpreeErrorsToForm` helper routes 422 responses onto `form.formState.errors`, but the messages themselves are the **server's strings, verbatim** — `{ "name": ["can't be blank"] }` becomes a field error reading "can't be blank". To localize validation messages, configure the locale on the backend (Rails i18n translates ActiveRecord error messages); the dashboard displays whatever the API returns.
## Order of operations
@@ -97,7 +87,7 @@ Register translations **before** any code that calls `i18n.t()` at module-load t
import { defineDashboardPlugin, i18n } from '@spree/dashboard-core'
import en from './locales/en.json'
-i18n.addResourceBundle('en', 'admin', en, true, false) // ① translations first
+i18n.addResourceBundle('en', 'translation', en, true, true) // ① translations first
defineDashboardPlugin({ /* ② registrations may now use i18n.t(...) */ })
```
diff --git a/docs/developer/dashboard/plugins/overview.mdx b/docs/developer/dashboard/plugins/overview.mdx
index 8f2f65867f..487011cbe6 100644
--- a/docs/developer/dashboard/plugins/overview.mdx
+++ b/docs/developer/dashboard/plugins/overview.mdx
@@ -14,8 +14,8 @@ 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.
+3. **Auto-discovered** — the `"spree": { "dashboard": { "plugin": true } }` marker in your package.json is all the host needs; `spreeDashboardPlugin()` finds every installed dependency carrying it, activates the entry-point, and scans your source for Tailwind classes so you never ship pre-built CSS. (Hosts can pass an explicit `plugins: [...]` array to opt out of discovery and whitelist instead.)
+4. **Translations-aware** — your bundle ships JSON locale files and calls `i18n.addResourceBundle('en', 'translation', bundle, true, true)` on import (keys nested under a top-level `admin` object).
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 `src/plugins.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.
diff --git a/docs/developer/dashboard/plugins/publishing.mdx b/docs/developer/dashboard/plugins/publishing.mdx
index 486a82d7a0..aa2ee2db76 100644
--- a/docs/developer/dashboard/plugins/publishing.mdx
+++ b/docs/developer/dashboard/plugins/publishing.mdx
@@ -13,21 +13,21 @@ Your plugin imports React, the dashboard, Tailwind, i18next, etc., but **you don
```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/admin-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"
+ "react": "^19",
+ "react-dom": "^19",
+ "@spree/dashboard-core": "^0.1.0",
+ "@spree/dashboard-ui": "^0.1.0",
+ "@spree/admin-sdk": "^0.5.0",
+ "i18next": "^26",
+ "react-i18next": "^17",
+ "@tanstack/react-query": "^5",
+ "@tanstack/react-router": "^1",
+ "lucide-react": "^1"
}
}
```
-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.
+Use ranges, not exact versions — pin too tightly and consumers can't upgrade the dashboard without you cutting a release. One Developer Preview caveat: for `0.x` versions, `^` only allows patch-level drift (`^0.1.0` matches `0.1.x`, not `0.2.0`), so expect to bump your `@spree/dashboard-*` peers alongside dashboard releases until 1.0. `spree plugin new` scaffolds these ranges for you, matched to the current release.
`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.
diff --git a/docs/developer/dashboard/plugins/scaffolding.mdx b/docs/developer/dashboard/plugins/scaffolding.mdx
index c0dd545622..84cb36ee68 100644
--- a/docs/developer/dashboard/plugins/scaffolding.mdx
+++ b/docs/developer/dashboard/plugins/scaffolding.mdx
@@ -82,20 +82,27 @@ You now have a buildable plugin. The next page covers what to put in `package.js
## What the entry-point looks like
-`packages/dashboard/src/index.tsx` is where everything starts. The generated version:
+`packages/dashboard/src/index.tsx` is where everything starts. The generated version, trimmed:
```tsx
-import { defineDashboardPlugin } from '@spree/dashboard-core'
+import { defineDashboardPlugin, defineTable, i18n } from '@spree/dashboard-core'
import { PackageIcon } from 'lucide-react'
-import i18n from 'i18next'
import en from './locales/en.json'
import { MyPluginCard } from './slots/product-my-plugin-card'
-i18n.addResourceBundle('en', 'admin', en, true, false)
+// 1. Translations — merge our keys into the shared bundle.
+i18n.addResourceBundle('en', 'translation', en, true, true)
-// Routes are NOT registered here — they ship as file routes in src/routes/
-// (declared via the package.json marker) and compile into the host's typed
-// route tree. See the routes guide.
+// 2. Declare the table our list page renders with <ResourceTable>.
+defineTable('my-plugin', {
+ title: i18n.t('admin.my_plugin.table.title'),
+ defaultSort: { field: 'name', direction: 'asc' },
+ columns: [/* … */],
+})
+
+// 3. Registry extensions. Routes are NOT registered here — they ship as
+// file routes in src/routes/ (declared via the package.json marker) and
+// compile into the host's typed route tree. See the routes guide.
defineDashboardPlugin({
nav: [{
key: 'my-plugin',
@@ -118,7 +125,7 @@ That's the whole entry-point. Edit it to register what your plugin needs and rem
## 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/dashboard/customization/backend).
+The generated `client.ts` calls `adminClient.request()` against `/<name>` (relative to `/api/v3/admin`) — those endpoints don't exist by default. You'd add them on the Rails side (a controller, a model, a serializer) 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 integration docs](/developer/dashboard/customization/backend).
## Reference
diff --git a/docs/developer/dashboard/public-api.mdx b/docs/developer/dashboard/public-api.mdx
index d1ab38eb43..591fcec2fd 100644
--- a/docs/developer/dashboard/public-api.mdx
+++ b/docs/developer/dashboard/public-api.mdx
@@ -96,16 +96,17 @@ import {
```ts
import {
- filtersToRansack, // converts table filter state → Ransack params
+ filtersToRansack, // converts table filter state → Ransack params
mapSpreeErrorsToForm, // 422 response → form.setError
// formatters
- formatMoney,
- formatDate,
- formatRelativeTime,
+ formatPrice, // Price object → display string
+ formatStoreDateTime, // ISO string → wall-clock in the store's timezone
+ getInitials, // full name → avatar initials
// i18n
- i18n, // configured instance
- // form mappers
- mapFormErrors,
+ i18n, // configured instance
+ // form mappers — normalize optional text inputs before submitting
+ blankToNull,
+ blankToUndefined,
} from '@spree/dashboard-core'
```
@@ -159,12 +160,12 @@ import {
Avatar,
Skeleton,
Tooltip, TooltipTrigger, TooltipContent,
- Tabs, TabsList, TabsTrigger, TabsContent,
- Alert, AlertTitle, AlertDescription,
- Toaster, toast,
+ Toaster,
} from '@spree/dashboard-ui'
```
+Toast *notifications* come from [sonner](https://sonner.emilkowal.ski/) directly — `import { toast } from 'sonner'` — while `<Toaster>` (the mount point, already rendered by the app shell) is the only part re-exported here.
+
### Composed components
Higher-level pieces that bundle multiple primitives but still take data via props:
@@ -172,12 +173,14 @@ Higher-level pieces that bundle multiple primitives but still take data via prop
```ts
import {
ResourceLayout, // header + main + sidebar grid
- EmptyState,
+ Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
ColorPicker,
// …more land here as we extract from @spree/dashboard
} from '@spree/dashboard-ui'
```
+`Empty*` composes via children (icon in `<EmptyMedia>`, actions in `<EmptyContent>`) rather than taking `title`/`description` props.
+
### Utilities
```ts
diff --git a/docs/developer/dashboard/recipes/custom-form-field.mdx b/docs/developer/dashboard/recipes/custom-form-field.mdx
index 95d265e65e..ec9a0034d7 100644
--- a/docs/developer/dashboard/recipes/custom-form-field.mdx
+++ b/docs/developer/dashboard/recipes/custom-form-field.mdx
@@ -1,10 +1,14 @@
---
-title: Add a custom form field
+title: Add a custom field to the product page
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.
+description: Surface a custom product attribute on the product detail page — edit it in a sidebar card, validate it, 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.
+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 to edit it on the same page. This recipe adds a **self-contained editor card** to the product page's sidebar: it owns its own small form and saves through the Admin API.
+
+<Note>
+Slot widgets are additive — the built-in product form doesn't expose its internal form instance to slots, so your card manages its own state and its own save. That's a feature: your field can't break the core form, and it works identically from a host app or a distributed plugin.
+</Note>
## Backend prerequisites
@@ -19,22 +23,22 @@ class AddTechSpecsToSpreeProducts < ActiveRecord::Migration[7.2]
end
```
-And declared it as a permitted attribute on the Admin API serializer + controller (see [Admin API conventions](/developer/dashboard/customization/backend)).
+And declared it as a permitted attribute on the Admin API serializer + controller (see [Backend integration](/developer/dashboard/customization/backend)).
-## 1. Register the field
+## 1. Register the card
-Use a slot to inject your field into the product form's sidebar:
+Inject it into the product form's sidebar via a slot:
```tsx
// src/plugins.ts (in your dashboard app)
import { defineDashboardPlugin } from '@spree/dashboard-core'
-import { TechSpecsField } from './fields/tech-specs-field'
+import { TechSpecsCard } from './fields/tech-specs-card'
defineDashboardPlugin({
slots: {
'product.form_sidebar': [{
id: 'tech-specs',
- component: TechSpecsField as never,
+ component: TechSpecsCard as never,
position: 80,
}],
},
@@ -43,25 +47,48 @@ defineDashboardPlugin({
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
+## 2. Build the card
-The slot's context provides the React Hook Form instance for the page's form. Register your input against it:
+The slot's context is `{ product }` — the product being edited. The card seeds its own React Hook Form instance from it and saves with its own button:
```tsx
-// src/fields/tech-specs-field.tsx
+// src/fields/tech-specs-card.tsx
+import { adminClient, mapSpreeErrorsToForm, useResourceMutation } from '@spree/dashboard-core'
import {
- Card, CardContent, CardHeader, CardTitle,
+ Button,
+ Card, CardContent, CardFooter, CardHeader, CardTitle,
Field, FieldError, FieldLabel, Textarea,
} from '@spree/dashboard-ui'
+import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
-import type { UseFormReturn } from 'react-hook-form'
interface Props {
- form: UseFormReturn<{ tech_specs: string }>
+ product: { id: string; tech_specs?: string }
+}
+
+interface FormValues {
+ tech_specs: string
}
-export function TechSpecsField({ form }: Props) {
+export function TechSpecsCard({ product }: Props) {
const { t } = useTranslation()
+ const form = useForm<FormValues>({
+ defaultValues: { tech_specs: product.tech_specs ?? '' },
+ })
+
+ const update = useResourceMutation({
+ mutationFn: (values: FormValues) => adminClient.products.update(product.id, values),
+ invalidate: [['products']],
+ })
+
+ async function onSubmit(values: FormValues) {
+ try {
+ await update.mutateAsync(values)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
const error = form.formState.errors.tech_specs?.message
return (
@@ -69,23 +96,30 @@ export function TechSpecsField({ form }: Props) {
<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>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <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: t('admin.fields.product.tech_specs.too_long') },
+ })}
+ />
+ {error && <FieldError>{error}</FieldError>}
+ </Field>
+ </CardContent>
+ <CardFooter>
+ <Button type="submit" size="sm" disabled={update.isPending || !form.formState.isDirty}>
+ {t('admin.common.save')}
+ </Button>
+ </CardFooter>
+ </form>
</Card>
)
}
@@ -93,54 +127,50 @@ export function TechSpecsField({ form }: Props) {
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.
+- **`invalidate: [['products']]`** refetches the product queries after a save, so the page (and list views) pick up the new value.
+- **`mapSpreeErrorsToForm`** routes a 422 (e.g. a server-side length validation) onto the field as an inline error; `useResourceMutation` already suppresses its toast for validation failures.
+- **Disable save until dirty** — `form.formState.isDirty` keeps the button inert when nothing changed.
+- **Use the field-key i18n convention** — `admin.fields.product.tech_specs.{label,placeholder}`; see [Translations](/developer/dashboard/customization/translations#field-key-convention).
- **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
-// 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
+## 3. Translations
```json
-// src/locales/en.json
+// src/locales/en.json — note the top-level "admin" wrapper
{
- "fields": {
- "product": {
- "tech_specs": {
- "label": "Technical specifications",
- "placeholder": "RAM, CPU, dimensions, weight…"
+ "admin": {
+ "fields": {
+ "product": {
+ "tech_specs": {
+ "label": "Technical specifications",
+ "placeholder": "RAM, CPU, dimensions, weight…",
+ "too_long": "Keep it under 5000 characters"
+ }
}
}
}
}
```
-i18next merges this into the existing `admin` namespace. See [Translations](/developer/dashboard/customization/translations) for the field-key fallback chain.
+```ts
+// src/plugins.ts — before the defineDashboardPlugin call
+import { i18n } from '@spree/dashboard-core'
+import en from './locales/en.json'
+
+i18n.addResourceBundle('en', 'translation', en, true, true)
+```
+
+See [Translations](/developer/dashboard/customization/translations) for locales beyond English.
## 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.
+- **Don't mirror the value into `useState` alongside RHF.** The card's form instance owns it; duplicate state goes out of sync after a save or reset.
+- **Don't write to the core form's fields from your card.** The built-in form saves core attributes; your card saves yours. Two independent submits can't clobber each other.
+- **Don't skip the server-side validation.** The client-side `maxLength` is UX; the Rails validation is the contract.
## Reference
-- [React Hook Form `register`](https://react-hook-form.com/docs/useform/register)
+- [React Hook Form `useForm`](https://react-hook-form.com/docs/useform)
- [`mapSpreeErrorsToForm`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/form-errors.ts) — wires 422 responses to field errors
+- [`useResourceMutation`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/hooks/use-resource-mutation.ts)
- [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.mdx
index 8971bc1fe2..36002f51cf 100644
--- a/docs/developer/dashboard/recipes/page-action-button.mdx
+++ b/docs/developer/dashboard/recipes/page-action-button.mdx
@@ -11,29 +11,30 @@ 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.
+This recipe shows both — and how to gate them by permission + resource state. (Strings are hardcoded for brevity; real buttons should go through i18n — see [Translations](/developer/dashboard/customization/translations).)
## A button in the actions row
```tsx
// src/actions/send-invoice-button.tsx
+import { adminClient, usePermissions, useResourceMutation } from '@spree/dashboard-core'
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 } // Order
}
export function SendInvoiceButton({ resource }: Props) {
+ const { permissions } = usePermissions()
const mutation = useResourceMutation({
mutationFn: () =>
adminClient.request('POST', `/orders/${resource.id}/send_invoice`),
successMessage: 'Invoice sent',
})
- // Only show on completed orders.
+ // Only show to users who can act, and only on completed orders.
+ if (!permissions.can('update', 'Spree::Order')) return null
if (resource.state !== 'complete') return null
return (
@@ -63,21 +64,17 @@ defineDashboardPlugin({
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:
+Two layers of gating, both inside the component:
-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.
+1. **Permission check** — `usePermissions()`; render `null` when the user can't act.
+2. **Resource-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.
+(The slot entry's `if` predicate receives only the slot's own context — `{ resource }` here — so use it for resource-state conditions, and keep permission checks in the component. See [Slots](/developer/dashboard/customization/slots).)
## A dropdown menu item
@@ -85,20 +82,23 @@ For secondary actions, use `page.actions_dropdown` and render `<DropdownMenuItem
```tsx
// src/actions/sync-to-erp-item.tsx
+import { adminClient, usePermissions, useResourceMutation } from '@spree/dashboard-core'
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 { permissions } = usePermissions()
const mutation = useResourceMutation({
mutationFn: () => adminClient.request('POST', `/orders/${resource.id}/sync_to_erp`),
successMessage: 'Synced',
})
+ if (!permissions.can('manage', 'Spree::Order')) return null
+
return (
<DropdownMenuItem
onSelect={(event) => {
@@ -121,7 +121,6 @@ defineDashboardPlugin({
id: 'sync-to-erp',
component: SyncToErpItem as never,
position: 50,
- if: ({ permissions }) => permissions.can('manage', 'Spree::Order'),
}],
},
})
@@ -179,13 +178,9 @@ export function ResetCartItem({ resource }: { resource: { id: string } }) {
## Context
-The `resource` prop is whatever the host page passed to `<PageHeader resource={…} />`. On the order detail page it's an `Order`; on a product page it's an `Product`. 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:
+The `resource` prop is whatever the host page passed to `<PageHeader resource={…} />`. On the order detail page it's an `Order`; on a product page it's a `Product`. The slot doesn't statically know which — see [Slots](/developer/dashboard/customization/slots) for the typing escape hatches.
-```tsx
-export function MyButton({ resource, permissions, store, user }: Props) { … }
-```
+For the current store, user, or permissions, call the hooks inside your component — `useStore()`, `useAuth()`, `usePermissions()` from `@spree/dashboard-core`.
## Reference
diff --git a/docs/developer/dashboard/recipes/sidebar-widget.mdx b/docs/developer/dashboard/recipes/sidebar-widget.mdx
index e4740b0d89..22a633f1db 100644
--- a/docs/developer/dashboard/recipes/sidebar-widget.mdx
+++ b/docs/developer/dashboard/recipes/sidebar-widget.mdx
@@ -15,8 +15,10 @@ This recipe builds a "Loyalty status" card for the customer detail page: read-on
import { useQuery } from '@tanstack/react-query'
import { adminClient, usePermissions, useStore } from '@spree/dashboard-core'
import {
+ Badge,
Card, CardContent, CardHeader, CardTitle,
- Skeleton, Badge, EmptyState,
+ Empty, EmptyDescription,
+ Skeleton,
} from '@spree/dashboard-ui'
import { Trophy } from 'lucide-react'
@@ -62,7 +64,9 @@ export function LoyaltyStatusCard({ customer }: Props) {
{isLoading ? (
<Skeleton className="h-8 w-32" />
) : !data?.data ? (
- <EmptyState size="sm" title="No loyalty record" />
+ <Empty>
+ <EmptyDescription>No loyalty record</EmptyDescription>
+ </Empty>
) : (
<div className="space-y-2">
<Badge variant={tierVariant(data.data.tier)}>{data.data.tier}</Badge>
@@ -83,7 +87,8 @@ 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.
+- **Three states.** Loading (`<Skeleton>`), empty (`<Empty>`), 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.
+- **Strings are hardcoded for brevity.** Real widgets should go through i18n — see [Translations](/developer/dashboard/customization/translations).
## Register the widget
@@ -101,9 +106,9 @@ defineDashboardPlugin({
}],
},
})
+```
The permission gate lives *inside* the component (`usePermissions`) rather than in an `if` predicate on the entry — the predicate only receives the slot context today, not ambient permissions (see the [slots catalog](/developer/dashboard/slots-catalog#ambient-context)).
-```
`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.
@@ -139,4 +144,4 @@ if (!customer) return null // or a <Skeleton> to reserve layout space
- [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 key
+- [`@spree/dashboard` README](https://github.com/spree/spree/blob/main/packages/dashboard/README.md) — the multi-store model and why `storeId` belongs in the key
diff --git a/packages/cli/templates/plugin/packages/dashboard/package.json.tt b/packages/cli/templates/plugin/packages/dashboard/package.json.tt
index 96639dabec..b725db9d07 100644
--- a/packages/cli/templates/plugin/packages/dashboard/package.json.tt
+++ b/packages/cli/templates/plugin/packages/dashboard/package.json.tt
@@ -28,7 +28,7 @@
}
},
"peerDependencies": {
- "@spree/admin-sdk": "^0.1.0",
+ "@spree/admin-sdk": "^0.5.0",
"@spree/dashboard-core": "^0.1.0",
"@spree/dashboard-ui": "^0.1.0",
"@tanstack/react-query": "^5",