Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added real life dashboard plugin example
Damian Legawiec3cc20874dd3c
diff --git a/docs/developer/customization/dashboard-plugins.mdx b/docs/developer/customization/dashboard-plugins.mdxnew file mode 100644index 0000000000..e6fc0faae4--- /dev/null+++ b/docs/developer/customization/dashboard-plugins.mdx@@ -0,0 +1,350 @@+---+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. This guide walks through its structure; copy the package shape for your own plugin.++## Anatomy of a plugin++```+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/docs.json b/docs/docs.jsonindex 838cadeb08..c0e6900ee4 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -323,7 +323,8 @@"developer/customization/model-preferences","developer/customization/metadata","developer/customization/routes",- "developer/customization/api"+ "developer/customization/api",+ "developer/customization/dashboard-plugins"]}]diff --git a/packages/dashboard-plugin-example/README.md b/packages/dashboard-plugin-example/README.mdnew file mode 100644index 0000000000..ec16668905--- /dev/null+++ b/packages/dashboard-plugin-example/README.md@@ -0,0 +1,88 @@+# @spree/dashboard-plugin-example++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.++## What it demonstrates++Five extension points, all in one plugin:++1. **Nav entry** — adds "Brands" to the main sidebar between Products and Customers+2. **Custom route** — `/$storeId/brands` renders a list page using `<ResourceTable>`+3. **Table definition** — `defineTable('brands', ...)` declares columns, default sort, search params+4. **Slot widget** — the product detail page's right sidebar shows a "Brand" card via the `product.form_sidebar` slot+5. **Table column extension** — adds a "Brand" column to the existing core Products table+6. **Translations** — `admin.brands_plugin.*` keys deep-merged into the framework's i18next namespace++## Backend assumption++The plugin calls `adminClient.request('GET', '/brands')` etc. against a hypothetical Brands Admin API. **This package does not ship that backend** — a real Brands plugin would publish a Rails engine (`spree_brands`) alongside this dashboard plugin that registers:++- `Spree::Brand` model+- `Spree::Api::V3::Admin::BrandsController` (a `ResourceController` subclass)+- `Spree::Api::V3::Admin::BrandSerializer` (Alba)+- Routes under `/api/v3/admin/brands`+- CanCanCan ability for `Spree::Brand`++The dashboard plugin is the front end; the gem is the back end. They ship together but live in separate packages.++For the request layer pattern (`adminClient.request<T>` against custom endpoints), see [Custom Admin Endpoints](../../docs/developer/sdk/admin/extending.mdx) in the Spree docs.++## Activate this plugin in the dashboard++Add a side-effect import to your dashboard app's entry (`packages/dashboard/src/main.tsx` for the bundled dashboard, your own `main.tsx` for a custom admin app):++```ts+import '@spree/dashboard-plugin-example'+```++The import must run **before the router mounts** so the route registry is populated when the catch-all dispatcher reads it. The single side-effect import triggers everything: nav entry registers, `/brands` route mounts, slot widget appears on product pages, table column lands on the products table.++## File layout++```+src/+├── index.tsx ← plugin entry — defineDashboardPlugin call+├── types.ts ← Brand interface (would be Typelizer-generated in a real plugin)+├── client.ts ← adminClient.request wrappers+├── routes/+│ └── brands-list.tsx ← /brands page using <ResourceTable>+├── slots/+│ └── product-brand-card.tsx ← product.form_sidebar widget+└── locales/+ └── en.json ← plugin translations+```++## Per-extension-point notes++### `defineTable` runs at import time++The table definition (`defineTable('brands', ...)`) is declared at module scope so it's registered as soon as the plugin's entry is imported — before `<ResourceTable tableKey="brands">` ever mounts. The catch-all route dispatcher reads from the route registry on every navigation, so plugin registration before first render isn't strictly required, but mountain-then-register patterns make for fragile UX. Always register at module top-level.++### Nav `subject` gates visibility++`subject: 'Spree::Brand'` on the nav entry hides the sidebar item for admins without `read` permission on brands. The catch-all route checks the same subject and renders a 403 fallback if a user reaches `/brands` via a direct URL despite not having permission. Server-side enforcement still runs — this is UX, not authorization.++### Slot context shape is typed by the slot, not the plugin++`product.form_sidebar` slots receive `{ product, permissions, store, user }`. The plugin's `<ProductBrandCard>` types only the fields it reads (`{ product: { id, brand_id } }`); a slot author should never assume more than what's documented in the dashboard's slot catalogue. Slot names and their context shapes are documented per-page in `@spree/dashboard`.++### Translation collisions++`addResourceBundle` deep-merges, so two plugins both writing `admin.actions.share` would race — last write wins. Put plugin-specific text under your own namespace (`admin.brands_plugin.*`) to stay clear of the framework and other plugins. See the dashboard-core README for the full convention.++## Development workflow++This package lives in the Spree monorepo but mirrors the shape of a real external plugin. Build it with the rest of the workspace:++```bash+pnpm install+pnpm -F @spree/dashboard-plugin-example typecheck+```++The dashboard imports it via the workspace symlink (`@spree/dashboard-plugin-example` in `packages/dashboard/package.json` once added). Run the dashboard with `pnpm dev` and the plugin's nav entry, slot widget, table column, and `/brands` route all light up.++## License++MIT. Copy this package shape for your own plugin; it's intended as a template.diff --git a/packages/dashboard-plugin-example/biome.json b/packages/dashboard-plugin-example/biome.jsonnew file mode 100644index 0000000000..ccae8ce9b7--- /dev/null+++ b/packages/dashboard-plugin-example/biome.json@@ -0,0 +1,8 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",+ "root": false,+ "extends": ["../../biome.json"],+ "files": {+ "includes": ["src/**", "!src/**/*.css"]+ }+}diff --git a/packages/dashboard-plugin-example/package.json b/packages/dashboard-plugin-example/package.jsonnew file mode 100644index 0000000000..77ea0f26fb--- /dev/null+++ b/packages/dashboard-plugin-example/package.json@@ -0,0 +1,42 @@+{+ "name": "@spree/dashboard-plugin-example",+ "private": true,+ "license": "MIT",+ "version": "0.0.0",+ "description": "Example Spree dashboard plugin — adds a Brands feature to the admin via defineDashboardPlugin. Reference implementation for the dashboard plugin authoring docs.",+ "type": "module",+ "main": "./src/index.tsx",+ "module": "./src/index.tsx",+ "types": "./src/index.tsx",+ "exports": {+ ".": "./src/index.tsx"+ },+ "files": [+ "src",+ "README.md"+ ],+ "scripts": {+ "lint": "biome check src",+ "lint:fix": "biome check --fix src",+ "format": "biome format --write src",+ "typecheck": "tsc --noEmit"+ },+ "peerDependencies": {+ "@spree/admin-sdk": "workspace:^",+ "@spree/dashboard-core": "workspace:^",+ "@spree/dashboard-ui": "workspace:^",+ "@tanstack/react-query": "^5.100.9",+ "@tanstack/react-router": "^1.169.2",+ "i18next": "^26.2.0",+ "lucide-react": "^1.14.0",+ "react": "^19.2.6",+ "react-dom": "^19.2.6",+ "react-i18next": "^17.0.8"+ },+ "devDependencies": {+ "@types/react": "^19.2.14",+ "@types/react-dom": "^19.2.3",+ "typescript": "~6.0.3",+ "vite": "^8.0.11"+ }+}diff --git a/packages/dashboard-plugin-example/src/client.ts b/packages/dashboard-plugin-example/src/client.tsnew file mode 100644index 0000000000..85d71c975b--- /dev/null+++ b/packages/dashboard-plugin-example/src/client.ts@@ -0,0 +1,40 @@+/**+ * Thin SDK wrapper for the Brands Admin API.+ *+ * Pattern: plugins that ship a backend they own (a `spree_brands` gem,+ * for instance) wrap `adminClient.request<T>(...)` here in a small client+ * module. The wrappers add no logic — they're just typed signatures for+ * the endpoints the plugin's backend exposes. The dashboard's hooks and+ * components consume these wrappers, not `adminClient.request` directly,+ * so the plugin can rename, version, or swap backends in one place.+ *+ * See the `Custom Admin Endpoints` guide in the Spree docs for the+ * `adminClient.request` API.+ */++import type { PaginatedResponse } from '@spree/admin-sdk'+import { adminClient } from '@spree/dashboard-core'+import type { Brand, BrandCreateParams, BrandUpdateParams } from './types'++/**+ * Query-param shape accepted by the brands list endpoint. Wider than+ * @spree/admin-sdk's `ListParams` because `adminClient.request` only knows+ * the runtime shape (string-keyed) and `ListParams` is a closed interface.+ * In practice, callers pass the same `{ page, limit, sort, search, … }`+ * keys built-in resources accept.+ */+type BrandsListParams = Record<string, string | number | boolean | (string | number)[] | undefined>++export const brandsClient = {+ list: (params?: BrandsListParams) =>+ adminClient.request<PaginatedResponse<Brand>>('GET', '/brands', { params }),++ get: (id: string) => adminClient.request<Brand>('GET', `/brands/${id}`),++ create: (body: BrandCreateParams) => adminClient.request<Brand>('POST', '/brands', { body }),++ update: (id: string, body: BrandUpdateParams) =>+ adminClient.request<Brand>('PATCH', `/brands/${id}`, { body }),++ delete: (id: string) => adminClient.request<void>('DELETE', `/brands/${id}`),+}diff --git a/packages/dashboard-plugin-example/src/index.tsx b/packages/dashboard-plugin-example/src/index.tsxnew file mode 100644index 0000000000..fa8f0fe14c--- /dev/null+++ b/packages/dashboard-plugin-example/src/index.tsx@@ -0,0 +1,181 @@+/**+ * @spree/dashboard-plugin-example — Brands plugin.+ *+ * Reference implementation of a Spree dashboard plugin. Adds a "Brands"+ * feature to the admin:+ *+ * - **Nav entry** in the main sidebar at `/$storeId/brands`.+ * - **Custom route** at `/$storeId/brands` rendering a Brands list page+ * built on `<ResourceTable>`.+ * - **Table definition** for `'brands'`, declared via `defineTable` so+ * ResourceTable can read column metadata, filters, default sort, etc.+ * - **Slot widget** on the product detail page (`product.form_sidebar`)+ * showing the brand assigned to the product.+ * - **Column extension** on the core Products table — adds a "Brand"+ * column that joins the product's `brand_id` against the brands client.+ * - **Translations** under `admin.brands_plugin.*`, deep-merged into the+ * dashboard's i18next namespace.+ *+ * A real plugin would also ship a Rails-side Brands engine (model, controller,+ * Alba serializer); this package only contains the dashboard half. See+ * `README.md` for the full setup story.+ *+ * To activate this plugin in the dashboard, the app's `main.tsx` imports+ * `@spree/dashboard-plugin-example` once as a side-effect (before the+ * router mounts):+ *+ * import '@spree/dashboard-plugin-example'+ *+ * That single import triggers the `defineDashboardPlugin` call below.+ */+import { defineDashboardPlugin, defineTable, i18n } from '@spree/dashboard-core'+import { RelativeTime } from '@spree/dashboard-ui'+import { useQuery } from '@tanstack/react-query'+import { Link } from '@tanstack/react-router'+import { PackageIcon } from 'lucide-react'+import { brandsClient } from './client'+import en from './locales/en.json'+import { BrandsListPage } from './routes/brands-list'+import { ProductBrandCard } from './slots/product-brand-card'+import type { Brand } from './types'++// ---------------------------------------------------------------------------+// 1. Register translations+// ---------------------------------------------------------------------------+// `deep: true` + `overwrite: true` merge our `admin.brands_plugin.*` keys+// into the framework's existing `admin.*` namespace without dropping anything.+// See @spree/dashboard-core's README → "Translations".+i18n.addResourceBundle('en', 'translation', en, true, true)++// ---------------------------------------------------------------------------+// 2. Declare the Brands table+// ---------------------------------------------------------------------------+// Must run before `<ResourceTable tableKey="brands" />` mounts. defineTable+// is idempotent on the same key, but its initial declaration is the source+// of truth for which columns/filters/sort exist. Plugins can add columns+// after the fact via `tables.brands.addColumn`.+defineTable<Brand>('brands', {+ title: i18n.t('admin.brands_plugin.table.title'),+ searchParam: 'search',+ searchPlaceholder: i18n.t('admin.brands_plugin.table.search_placeholder'),+ defaultSort: { field: 'name', direction: 'asc' },+ emptyMessage: i18n.t('admin.brands_plugin.table.empty'),+ columns: [+ {+ key: 'name',+ label: i18n.t('admin.brands_plugin.fields.name'),+ sortable: true,+ filterable: true,+ default: true,+ render: (b) => (+ <Link+ to={'/$storeId/brands/$brandId' as string}+ params={{ brandId: b.id }}+ className="font-medium text-foreground no-underline"+ >+ {b.name}+ </Link>+ ),+ },+ {+ key: 'slug',+ label: i18n.t('admin.brands_plugin.fields.slug'),+ sortable: true,+ filterable: true,+ default: true,+ render: (b) => b.slug,+ },+ {+ key: 'products_count',+ label: i18n.t('admin.brands_plugin.fields.products_count'),+ default: true,+ className: 'text-right tabular-nums',+ render: (b) => b.products_count,+ },+ {+ key: 'created_at',+ label: i18n.t('admin.brands_plugin.fields.created_at'),+ sortable: true,+ default: false,+ render: (b) => <RelativeTime iso={b.created_at} />,+ },+ ],+})++// ---------------------------------------------------------------------------+// 3. Wire everything into defineDashboardPlugin+// ---------------------------------------------------------------------------+defineDashboardPlugin({+ nav: [+ {+ key: 'brands',+ label: i18n.t('admin.brands_plugin.nav'),+ path: '/brands',+ icon: PackageIcon,+ // Position 35 puts "Brands" between Products (30) and Customers (40)+ // in core's default sidebar ordering.+ position: 35,+ // Hide the entry for admins who can't read brands. Permission-aware+ // navigation matches core's behavior.+ subject: 'Spree::Brand',+ },+ ],+ routes: [+ {+ key: 'brands',+ path: '/brands',+ component: BrandsListPage,+ subject: 'Spree::Brand',+ },+ ],+ slots: {+ 'product.form_sidebar': [+ {+ id: 'brand-card',+ // Cast because `defineDashboardPlugin`'s `slots` is typed as a+ // generic-erased `Record<string, SlotEntry[]>` — the host page knows+ // its slot context shape, but the plugin facade doesn't. The slot+ // catalogue in the dashboard's source documents which context each+ // named slot provides (`product.form_sidebar` → `{ product }`).+ component: ProductBrandCard as never,+ // Render below core's first-party cards (which use 100, 200, …).+ position: 250,+ },+ ],+ },+ tables: {+ // Add a "Brand" column to the existing core Products table. Plugin+ // authors extending built-in resources rarely need more than a column+ // or two; for richer integrations, register a slot on the product form.+ products: {+ add: [+ {+ key: 'brand',+ label: i18n.t('admin.brands_plugin.products_column.label'),+ default: false,+ render: (product: { brand_id?: string | null }) =>+ product.brand_id ? <BrandNameCell brandId={product.brand_id} /> : '—',+ },+ ],+ },+ },+})++// ---------------------------------------------------------------------------+// Internal: render a brand name by ID for the products-table column. Looks+// up via brandsClient; the dashboard's TanStack Query cache de-dupes+// requests across rows.+// ---------------------------------------------------------------------------+function BrandNameCell({ brandId }: { brandId: string }) {+ const { data } = useQuery({+ queryKey: ['plugin-brands', 'brand', brandId],+ queryFn: () => brandsClient.get(brandId),+ staleTime: 5 * 60_000,+ })+ return <span>{data?.name ?? '…'}</span>+}++// Re-export the public API of this plugin in case the host app wants to+// reach into it (e.g. to invalidate brand queries from outside).+export { brandsClient } from './client'+export type { Brand, BrandCreateParams, BrandUpdateParams } from './types'diff --git a/packages/dashboard-plugin-example/src/locales/en.json b/packages/dashboard-plugin-example/src/locales/en.jsonnew file mode 100644index 0000000000..26d8e85756--- /dev/null+++ b/packages/dashboard-plugin-example/src/locales/en.json@@ -0,0 +1,30 @@+{+ "admin": {+ "brands_plugin": {+ "nav": "Brands",+ "page": {+ "title": "Brands",+ "subtitle": "Manage product brands",+ "new_cta": "New brand"+ },+ "table": {+ "title": "Brands",+ "search_placeholder": "Search by name…",+ "empty": "No brands yet"+ },+ "fields": {+ "name": "Name",+ "slug": "Slug",+ "products_count": "Products",+ "created_at": "Created"+ },+ "products_column": {+ "label": "Brand"+ },+ "product_card": {+ "title": "Brand",+ "empty": "No brand assigned."+ }+ }+ }+}diff --git a/packages/dashboard-plugin-example/src/routes/brands-list.tsx b/packages/dashboard-plugin-example/src/routes/brands-list.tsxnew file mode 100644index 0000000000..f9bc5952c5--- /dev/null+++ b/packages/dashboard-plugin-example/src/routes/brands-list.tsx@@ -0,0 +1,60 @@+/**+ * Brands index page. Mounted at `/$storeId/brands` via the plugin's route+ * registration in `index.tsx`. Uses the dashboard's `<ResourceTable>` for+ * filtering, sorting, pagination, and bulk-action chrome — the same UX as+ * core's Products/Customers/Orders pages.+ *+ * The table's columns and filters are declared via `defineTable('brands', ...)`+ * in `../index.tsx` (alongside the plugin entry); ResourceTable reads from+ * that registry by tableKey.+ *+ * Plugin route components receive `{ params, storeId, searchParams }` from+ * the catch-all dispatcher. We forward `searchParams` straight to+ * ResourceTable so filter/sort/pagination round-trip through the URL.+ */+import { PageHeader, type ResourceSearch, ResourceTable } from '@spree/dashboard-core'+import { Button, ResourceLayout } from '@spree/dashboard-ui'+import { PlusIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { brandsClient } from '../client'+import type { Brand } from '../types'++interface BrandsListPageProps {+ searchParams: Record<string, unknown>+}++export function BrandsListPage({ searchParams }: BrandsListPageProps) {+ const { t } = useTranslation()++ return (+ <ResourceLayout+ header={+ <PageHeader+ title={t('admin.brands_plugin.page.title')}+ subtitle={t('admin.brands_plugin.page.subtitle')}+ actions={+ <Button size="sm">+ <PlusIcon className="size-4" />+ {t('admin.brands_plugin.page.new_cta')}+ </Button>+ }+ />+ }+ main={+ <ResourceTable<Brand>+ tableKey="brands"+ queryKey="brands"+ // ResourceTable hands `params` to queryFn as `Record<string, unknown>`+ // (its internal builder doesn't know what each table's API accepts).+ // We narrow to our client's known param shape at the boundary.+ queryFn={(params) => brandsClient.list(params as Record<string, never>)}+ // The catch-all dispatcher passes searchParams as a generic record+ // because it can't know each plugin's parsed shape. ResourceTable+ // expects a Zod-validated `ResourceSearch`; defaults fill in any+ // missing fields, so the cast is safe at the boundary.+ searchParams={searchParams as ResourceSearch}+ />+ }+ />+ )+}diff --git a/packages/dashboard-plugin-example/src/slots/product-brand-card.tsx b/packages/dashboard-plugin-example/src/slots/product-brand-card.tsxnew file mode 100644index 0000000000..3246c70a1d--- /dev/null+++ b/packages/dashboard-plugin-example/src/slots/product-brand-card.tsx@@ -0,0 +1,45 @@+/**+ * Widget rendered inside the product detail page's right-hand sidebar via the+ * `product.form_sidebar` slot. Shows the currently-assigned brand (if any),+ * with a button to clear or change it.+ *+ * The slot's context (typed by the dashboard as `{ product }`) gives us the+ * product being edited. The widget is purely additive — the host page knows+ * nothing about brands, the plugin contributes this card via `registerSlot`.+ */+import { Card, CardContent, CardHeader, CardTitle } from '@spree/dashboard-ui'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { brandsClient } from '../client'++interface ProductBrandCardProps {+ // The host product page's slot context. We type only what we read.+ product: { id: string; brand_id?: string | null }+}++export function ProductBrandCard({ product }: ProductBrandCardProps) {+ const { t } = useTranslation()++ const { data: brand } = useQuery({+ queryKey: ['plugin-brands', 'brand', product.brand_id],+ queryFn: () => (product.brand_id ? brandsClient.get(product.brand_id) : null),+ enabled: Boolean(product.brand_id),+ })++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.brands_plugin.product_card.title')}</CardTitle>+ </CardHeader>+ <CardContent>+ {brand ? (+ <p className="text-sm">{brand.name}</p>+ ) : (+ <p className="text-sm text-muted-foreground">+ {t('admin.brands_plugin.product_card.empty')}+ </p>+ )}+ </CardContent>+ </Card>+ )+}diff --git a/packages/dashboard-plugin-example/src/types.ts b/packages/dashboard-plugin-example/src/types.tsnew file mode 100644index 0000000000..69bcb280bb--- /dev/null+++ b/packages/dashboard-plugin-example/src/types.ts@@ -0,0 +1,24 @@+/**+ * Shape of a Brand record as returned by the (hypothetical) Brands Admin API.+ * A real plugin would generate this from its serializer via the Typelizer+ * pipeline (see CLAUDE.md → Type Generation Pipeline); we hand-write it here+ * to keep the example self-contained.+ */+export interface Brand {+ id: string+ name: string+ slug: string+ description: string | null+ logo_url: string | null+ products_count: number+ created_at: string+ updated_at: string+}++export interface BrandCreateParams {+ name: string+ slug?: string+ description?: string | null+}++export type BrandUpdateParams = Partial<BrandCreateParams>diff --git a/packages/dashboard-plugin-example/tsconfig.json b/packages/dashboard-plugin-example/tsconfig.jsonnew file mode 100644index 0000000000..fbb2ea3e56--- /dev/null+++ b/packages/dashboard-plugin-example/tsconfig.json@@ -0,0 +1,25 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "ignoreDeprecations": "6.0",+ "useDefineForClassFields": true,+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "types": ["vite/client"],+ "skipLibCheck": true,+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,+ "jsx": "react-jsx",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true,+ "resolveJsonModule": true+ },+ "include": ["src"]+}