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.

Introduce admin table registry

Damian Legawiec85298afc2565
diff --git a/packages/admin/docs/tables.mdx b/packages/admin/docs/tables.mdx
new file mode 100644
index 0000000000..1d62af9f2c
--- /dev/null
+++ b/packages/admin/docs/tables.mdx
@@ -0,0 +1,302 @@
+# Admin Tables
+
+The admin uses a **table registry** to declaratively define resource list pages. This system provides:
+
+- Declarative column, filter, and sort definitions
+- A generic `<ResourceTable>` component that renders any registered table
+- A mutation API for extensions to add, remove, or update columns on existing tables
+
+This is the React equivalent of the Rails admin's `Spree.admin.tables` DSL.
+
+## Quick start
+
+A resource list page requires two things:
+
+1. A **table definition** that declares columns
+2. A **route** that renders `<ResourceTable>`
+
+### 1. Define the table
+
+Create a file in `src/tables/` (e.g., `src/tables/orders.tsx`):
+
+```tsx
+import { defineTable } from '@/lib/table-registry'
+import { StatusBadge } from '@/components/ui/badge'
+import { formatRelativeTime } from '@/lib/formatters'
+
+defineTable('orders', {
+ title: 'Orders',
+ searchParam: 'number_cont',
+ searchPlaceholder: 'Search orders...',
+ defaultSort: { field: 'completed_at', direction: 'desc' },
+ emptyMessage: 'No orders found',
+ columns: [
+ {
+ key: 'number',
+ label: 'Order',
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (order) => (
+ <span className="font-medium text-zinc-950">#{order.number}</span>
+ ),
+ },
+ {
+ key: 'status',
+ label: 'Status',
+ sortable: true,
+ filterable: true,
+ default: true,
+ filterType: 'status',
+ filterOptions: [
+ { value: 'complete', label: 'Complete' },
+ { value: 'canceled', label: 'Canceled' },
+ ],
+ render: (order) => <StatusBadge status={order.status} />,
+ },
+ {
+ key: 'total',
+ label: 'Total',
+ sortable: true,
+ default: true,
+ className: 'text-right tabular-nums',
+ render: (order) => order.display_total,
+ },
+ {
+ key: 'completed_at',
+ label: 'Date',
+ sortable: true,
+ filterable: true,
+ default: true,
+ filterType: 'date',
+ className: 'text-sm text-muted-foreground whitespace-nowrap',
+ render: (order) => order.completed_at ? formatRelativeTime(order.completed_at) : '—',
+ },
+ ],
+})
+```
+
+### 2. Create the route
+
+```tsx
+import { createFileRoute } from '@tanstack/react-router'
+import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+import '@/tables/orders' // registers the table definition
+
+export const Route = createFileRoute('/_authenticated/orders/')({
+ validateSearch: resourceSearchSchema,
+ component: OrdersPage,
+})
+
+function OrdersPage() {
+ const searchParams = Route.useSearch()
+ const { token } = useAuth()
+
+ return (
+ <ResourceTable
+ tableKey="orders"
+ queryKey="orders"
+ queryFn={(params) =>
+ spreeClient.admin.orders.list(params, { token: token! })
+ }
+ searchParams={searchParams}
+ />
+ )
+}
+```
+
+That's it. The `<ResourceTable>` component handles the toolbar (search, filters, sort, column selector), data fetching, pagination, loading states, and empty states automatically.
+
+## Table definition reference
+
+### `defineTable(key, options)`
+
+Registers a table in the global registry.
+
+| Option | Type | Description |
+|---|---|---|
+| `title` | `string` | Title displayed in the toolbar header (e.g., `'Products'`) |
+| `columns` | `ColumnDef[]` | Column definitions (see below) |
+| `searchParam` | `string` | Ransack search parameter name. Defaults to `'name_cont'` |
+| `searchPlaceholder` | `string` | Placeholder text for the search input |
+| `defaultSort` | `{ field, direction }` | Default sort. Defaults to `{ field: 'updated_at', direction: 'desc' }` |
+| `emptyIcon` | `ReactNode` | Icon shown when the table is empty |
+| `emptyMessage` | `string` | Message shown when the table is empty |
+
+### Column definition (`ColumnDef`)
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `key` | `string` | *required* | Unique column identifier, also used as the Ransack attribute for filtering/sorting |
+| `label` | `string` | *required* | Display label in the header and toolbar |
+| `sortable` | `boolean` | `false` | Whether this column can be sorted |
+| `filterable` | `boolean` | `false` | Whether this column appears in the filter drawer |
+| `default` | `boolean` | `false` | Whether this column is visible by default |
+| `filterType` | `'string' \| 'status' \| 'boolean' \| 'number' \| 'date'` | `'string'` | Determines which filter operators are available |
+| `filterOptions` | `{ value, label }[]` | — | Predefined options for `status` filter type |
+| `ransackAttribute` | `string` | — | Override the Ransack attribute name (e.g., `'master_sku'` for a column with `key: 'sku'`) |
+| `render` | `(row: T) => ReactNode` | — | Custom cell renderer. If omitted, renders `row[key]` as plain text |
+| `className` | `string` | — | CSS class applied to the `<td>` element |
+| `displayable` | `boolean` | `true` | Set to `false` for filter-only columns that don't render in the table |
+
+### Filter types and operators
+
+Each `filterType` provides a different set of operators in the filter drawer:
+
+| Type | Operators |
+|---|---|
+| `string` | contains, equals, does not equal, starts with, ends with, is set, is not set |
+| `status` | is, is not, is any of, is none of |
+| `boolean` | is |
+| `number` | equals, greater than, greater than or equal, less than, less than or equal |
+| `date` | is, after, before, on or after, on or before |
+
+## Extending existing tables
+
+Use the `tables` proxy to modify any registered table. Extensions must run **after** the table is registered (i.e., after the table definition file is imported).
+
+### Add a column
+
+```tsx
+import { tables } from '@/lib/table-registry'
+
+tables.products.addColumn({
+ key: 'vendor',
+ label: 'Vendor',
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (product) => product.vendor_name ?? '—',
+})
+```
+
+### Remove a column
+
+```tsx
+tables.products.removeColumn('inventory')
+```
+
+### Update a column
+
+Merges the updates into the existing column definition:
+
+```tsx
+tables.products.updateColumn('sku', {
+ default: true, // make SKU visible by default
+ label: 'Product SKU', // change the header label
+})
+```
+
+### Replace a column's renderer
+
+```tsx
+tables.products.updateColumn('name', {
+ render: (product) => (
+ <div className="flex items-center gap-2">
+ <MyCustomAvatar src={product.thumbnail_url} />
+ <span>{product.name}</span>
+ </div>
+ ),
+})
+```
+
+### Add a filter-only column
+
+Columns with `displayable: false` appear in the filter drawer but not in the table itself:
+
+```tsx
+tables.products.addColumn({
+ key: 'in_stock',
+ label: 'In Stock',
+ filterable: true,
+ filterType: 'boolean',
+ displayable: false,
+})
+```
+
+## `<ResourceTable>` props
+
+| Prop | Type | Description |
+|---|---|---|
+| `tableKey` | `string` | Registry key matching the `defineTable()` call |
+| `queryKey` | `string` | TanStack Query cache key prefix |
+| `queryFn` | `(params) => Promise<{ data: T[], meta }>` | SDK call to fetch data. Receives pre-built Ransack params |
+| `searchParams` | `ResourceSearch` | Current URL search params from the route (use `Route.useSearch()`) |
+| `title` | `string` | Title displayed in the toolbar header. Overrides the table definition's `title` |
+| `actions` | `ReactNode` | Toolbar actions (e.g., "Add Product" button) |
+
+### URL state
+
+`<ResourceTable>` persists all table state in the URL via TanStack Router search params. The shared `resourceSearchSchema` validates these params:
+
+| Param | Type | Description |
+|---|---|---|
+| `page` | `number` | Current page (default: 1) |
+| `sort` | `string` | Sort field |
+| `dir` | `'asc' \| 'desc'` | Sort direction |
+| `search` | `string` | Search query |
+| `filters` | `string` (JSON) | Serialized `FilterRule[]` |
+| `columns` | `string` (comma-separated) | Visible column keys. Omitted when using defaults |
+
+Use `resourceSearchSchema` in your route's `validateSearch`:
+
+```tsx
+import { resourceSearchSchema } from '@/components/resource-table'
+
+export const Route = createFileRoute('/_authenticated/orders/')({
+ validateSearch: resourceSearchSchema,
+ component: OrdersPage,
+})
+```
+
+## How data fetching works
+
+`<ResourceTable>` builds the API params automatically:
+
+1. **Search** — sends `{ [searchParam]: value }` (e.g., `{ multi_search: "widget" }`)
+2. **Sort** — sends `{ sort: "field" }` or `{ sort: "-field" }` for descending
+3. **Filters** — converts each `FilterRule` to a Ransack param: `{ [ransackAttribute]_[operator]: value }` (e.g., `{ status_eq: "active" }`)
+4. **Pagination** — sends `{ page: N }`
+
+These params are passed to your `queryFn`, which forwards them to the SDK.
+
+## File structure
+
+```
+src/
+ lib/
+ table-registry.ts # defineTable, getTable, tables proxy
+ formatters.ts # formatPrice, formatRelativeTime
+ tables/
+ products.tsx # Product table definition
+ orders.tsx # Order table definition (example)
+ components/
+ resource-table.tsx # <ResourceTable> component + resourceSearchSchema
+ table-toolbar.tsx # Search, filters, sort, column selector
+ ui/
+ data-table.tsx # Table primitives (Table, TableRow, etc.)
+ pagination.tsx # Pagination component
+ routes/
+ _authenticated/
+ products/
+ index.tsx # Products list page (~30 lines)
+ orders/
+ index.tsx # Orders list page (~30 lines)
+```
+
+## Comparison with Rails admin
+
+| Rails Admin | React Admin |
+|---|---|
+| `Spree.admin.tables.register(:products, ...)` | `defineTable('products', { ... })` |
+| `Spree.admin.tables.products.add :name, ...` | Column in the `columns` array |
+| `type: :custom, partial: '...'` | `render: (row) => <Component />` |
+| `Spree.admin.tables.products.add :col, ...` (in initializer) | `tables.products.addColumn({ ... })` |
+| `Spree.admin.tables.products.remove :col` | `tables.products.removeColumn('col')` |
+| `Spree.admin.tables.products.update :col, ...` | `tables.products.updateColumn('col', { ... })` |
+| `render_table @collection, :products` | `<ResourceTable tableKey="products" ... />` |
+| `ransack_attribute: 'master_sku'` | `ransackAttribute: 'master_sku'` |
+| `filter_type: :status, value_options: [...]` | `filterType: 'status', filterOptions: [...]` |
+| `displayable: false` (filter-only) | `displayable: false` |
diff --git a/packages/admin/src/components/resource-table.tsx b/packages/admin/src/components/resource-table.tsx
new file mode 100644
index 0000000000..d458920475
--- /dev/null
+++ b/packages/admin/src/components/resource-table.tsx
@@ -0,0 +1,264 @@
+import { useQuery } from "@tanstack/react-query";
+import { useNavigate } from "@tanstack/react-router";
+import { Card, CardContent } from "@/components/ui/card";
+import { Pagination, type PaginationMeta } from "@/components/ui/pagination";
+import {
+ Table,
+ TableHeader,
+ TableBody,
+ TableRow,
+ TableHead,
+ TableCell,
+ TableEmpty,
+} from "@/components/ui/data-table";
+import { TableToolbar } from "@/components/table-toolbar";
+import { useAuth } from "@/hooks/use-auth";
+import {
+ getTable,
+ getDisplayableColumns,
+ getDefaultColumnKeys,
+ type TableDef,
+ type FilterRule,
+ type SortOption,
+} from "@/lib/table-registry";
+import { z } from "zod/v4";
+import { useState, useDeferredValue, type ReactNode } from "react";
+
+// ============================================================================
+// Search schema — shared by all resource table routes
+// ============================================================================
+
+const filterSchema = z.object({
+ id: z.string(),
+ field: z.string(),
+ operator: z.string(),
+ value: z.string(),
+});
+
+export const resourceSearchSchema = z.object({
+ page: z.coerce.number().optional().default(1),
+ sort: z.string().optional(),
+ dir: z.enum(["asc", "desc"]).optional(),
+ search: z.string().optional(),
+ filters: z.preprocess((val) => {
+ if (typeof val === "string") {
+ try {
+ return JSON.parse(val);
+ } catch {
+ return [];
+ }
+ }
+ return val ?? [];
+ }, z.array(filterSchema).optional().default([])),
+ columns: z.preprocess((val) => {
+ if (typeof val === "string") return val.split(",");
+ return val ?? undefined;
+ }, z.array(z.string()).optional()),
+});
+
+export type ResourceSearch = z.infer<typeof resourceSearchSchema>;
+
+// ============================================================================
+// Props
+// ============================================================================
+
+interface ResourceTableProps<T> {
+ /** Registry key (e.g., 'products') */
+ tableKey: string;
+ /** TanStack Query key prefix (e.g., 'products') */
+ queryKey: string;
+ /** Function that calls the SDK to fetch data */
+ queryFn: (
+ params: Record<string, unknown>,
+ ) => Promise<{ data: T[]; meta: PaginationMeta }>;
+ /** Current search params from the route */
+ searchParams: ResourceSearch;
+ /** Title displayed in the toolbar header. Overrides the table definition's title. */
+ title?: string;
+ /** Actions to render in the toolbar (e.g., "Add Product" button) */
+ actions?: ReactNode;
+}
+
+// ============================================================================
+// Component
+// ============================================================================
+
+export function ResourceTable<T extends Record<string, any>>({
+ tableKey,
+ queryKey,
+ queryFn,
+ searchParams,
+ title,
+ actions,
+}: ResourceTableProps<T>) {
+ const table = getTable<T>(tableKey);
+ const { token } = useAuth();
+ const navigate = useNavigate();
+
+ const {
+ page,
+ sort: urlSort,
+ dir: urlDir,
+ search,
+ filters,
+ columns: urlColumns,
+ } = searchParams;
+
+ const defaultSort = table.defaultSort ?? {
+ field: "updated_at",
+ direction: "desc" as const,
+ };
+ const sort = urlSort ?? defaultSort.field;
+ const dir = urlDir ?? defaultSort.direction;
+
+ const [searchInput, setSearchInput] = useState(search ?? "");
+ const deferredSearch = useDeferredValue(searchInput);
+
+ const displayableColumns = getDisplayableColumns(table);
+ const defaultColumnKeys = getDefaultColumnKeys(table);
+ const visibleColumnKeys = urlColumns ?? defaultColumnKeys;
+
+ const visibleColumns = displayableColumns.filter((c) =>
+ visibleColumnKeys.includes(c.key),
+ );
+
+ // Build API params
+ const sortString = dir === "desc" ? `-${sort}` : sort;
+
+ const { data, isLoading } = useQuery({
+ queryKey: [
+ queryKey,
+ { page, sort: sortString, search: deferredSearch, filters },
+ ],
+ queryFn: () => {
+ const params: Record<string, unknown> = { page, sort: sortString };
+
+ if (deferredSearch) {
+ const searchParam = table.searchParam ?? "name_cont";
+ params[searchParam] = deferredSearch;
+ }
+
+ // Convert FilterRule[] to Ransack params
+ for (const filter of filters as FilterRule[]) {
+ const col = table.columns.find((c) => c.key === filter.field);
+ const ransackKey = col?.ransackAttribute ?? filter.field;
+ params[`${ransackKey}_${filter.operator}`] = filter.value;
+ }
+
+ return queryFn(params);
+ },
+ enabled: !!token,
+ });
+
+ const rows = data?.data ?? [];
+ const meta = data?.meta;
+
+ // Navigation helpers
+ function updateSearch(updates: Record<string, unknown>) {
+ navigate({
+ search: (prev: Record<string, unknown>) => ({ ...prev, ...updates }),
+ });
+ }
+
+ function handleSearchChange(value: string) {
+ setSearchInput(value);
+ updateSearch({ search: value || undefined, page: 1 });
+ }
+
+ function handleSortChange(s: SortOption) {
+ updateSearch({ sort: s.field, dir: s.direction, page: 1 });
+ }
+
+ function handleFiltersChange(f: FilterRule[]) {
+ updateSearch({
+ filters: f.length > 0 ? JSON.stringify(f) : undefined,
+ page: 1,
+ });
+ }
+
+ function handleColumnsChange(cols: string[]) {
+ const isDefault =
+ cols.length === defaultColumnKeys.length &&
+ cols.every((c) => defaultColumnKeys.includes(c));
+ updateSearch({ columns: isDefault ? undefined : cols.join(",") });
+ }
+
+ // Header columns for price-like right-aligned columns
+ const headerColumns = visibleColumns.map((col) => {
+ const isRightAligned = col.className?.includes("text-right");
+ return {
+ ...col,
+ headerClassName: isRightAligned ? "text-right" : undefined,
+ };
+ });
+
+ return (
+ <Card className="rounded-2xl">
+ <TableToolbar
+ columns={displayableColumns}
+ visibleColumns={visibleColumnKeys}
+ onVisibleColumnsChange={handleColumnsChange}
+ search={searchInput}
+ onSearchChange={handleSearchChange}
+ searchPlaceholder={table.searchPlaceholder ?? "Search..."}
+ sort={{ field: sort, direction: dir }}
+ onSortChange={handleSortChange}
+ filters={filters as FilterRule[]}
+ onFiltersChange={handleFiltersChange}
+ allColumns={table.columns}
+ title={title ?? table.title}
+ actions={actions}
+ />
+ <CardContent className="p-0">
+ <Table>
+ <TableHeader>
+ <tr>
+ {headerColumns.map((col) => (
+ <TableHead key={col.key} className={col.headerClassName}>
+ {col.label}
+ </TableHead>
+ ))}
+ </tr>
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ <TableEmpty colSpan={visibleColumns.length}>
+ Loading...
+ </TableEmpty>
+ ) : rows.length === 0 ? (
+ <TableEmpty colSpan={visibleColumns.length}>
+ <div className="flex flex-col items-center gap-2">
+ {table.emptyIcon}
+ <p>{table.emptyMessage ?? "No results found"}</p>
+ {(deferredSearch || (filters as FilterRule[]).length > 0) && (
+ <p className="text-xs">
+ Try adjusting your search or filters
+ </p>
+ )}
+ </div>
+ </TableEmpty>
+ ) : (
+ rows.map((row, i) => (
+ <TableRow key={(row as any).id ?? i}>
+ {visibleColumns.map((col) => (
+ <TableCell key={col.key} className={col.className}>
+ {col.render
+ ? col.render(row)
+ : String((row as any)[col.key] ?? "—")}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ {meta && (
+ <Pagination
+ meta={meta}
+ onPageChange={(p) => updateSearch({ page: p })}
+ />
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/admin/src/components/table-toolbar.tsx b/packages/admin/src/components/table-toolbar.tsx
index 7a237580d6..fd7f38d9bc 100644
--- a/packages/admin/src/components/table-toolbar.tsx
+++ b/packages/admin/src/components/table-toolbar.tsx
@@ -1,6 +1,6 @@
-import { Button } from '@/components/ui/button'
-import { Input } from '@/components/ui/input'
-import { Badge } from '@/components/ui/badge'
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Badge } from "@/components/ui/badge";
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,7 +10,7 @@ import {
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
-} from '@/components/ui/dropdown-menu'
+} from "@/components/ui/dropdown-menu";
import {
Sheet,
SheetContent,
@@ -19,7 +19,8 @@ import {
SheetDescription,
SheetFooter,
SheetClose,
-} from '@/components/ui/sheet'
+} from "@/components/ui/sheet";
+import { CardTitle } from "@/components/ui/card";
import {
SearchIcon,
XIcon,
@@ -28,47 +29,27 @@ import {
Columns3Icon,
PlusIcon,
Trash2Icon,
-} from 'lucide-react'
-import { useState, useCallback, useRef, useEffect } from 'react'
-
-// ============================================================================
-// Types
-// ============================================================================
-
-export interface ColumnDef {
- key: string
- label: string
- sortable?: boolean
- filterable?: boolean
- default?: boolean
- filterType?: 'string' | 'status' | 'boolean' | 'number' | 'date'
- filterOptions?: { value: string; label: string }[]
-}
-
-export interface FilterRule {
- id: string
- field: string
- operator: string
- value: string
-}
-
-export interface SortOption {
- field: string
- direction: 'asc' | 'desc'
-}
+} from "lucide-react";
+import { useState, useCallback, useRef, useEffect } from "react";
+import type { ColumnDef, FilterRule, SortOption } from "@/lib/table-registry";
interface TableToolbarProps {
- columns: ColumnDef[]
- visibleColumns: string[]
- onVisibleColumnsChange: (columns: string[]) => void
- search: string
- onSearchChange: (value: string) => void
- searchPlaceholder?: string
- sort: SortOption
- onSortChange: (sort: SortOption) => void
- filters: FilterRule[]
- onFiltersChange: (filters: FilterRule[]) => void
- actions?: React.ReactNode
+ /** Displayable columns (for column selector and table headers) */
+ columns: ColumnDef[];
+ visibleColumns: string[];
+ onVisibleColumnsChange: (columns: string[]) => void;
+ search: string;
+ onSearchChange: (value: string) => void;
+ searchPlaceholder?: string;
+ sort: SortOption;
+ onSortChange: (sort: SortOption) => void;
+ filters: FilterRule[];
+ onFiltersChange: (filters: FilterRule[]) => void;
+ /** All columns including filter-only ones (for the filter drawer). Falls back to `columns` if not provided. */
+ allColumns?: ColumnDef[];
+ /** Title displayed in the toolbar header */
+ title?: string;
+ actions?: React.ReactNode;
}
// ============================================================================
@@ -77,44 +58,42 @@ interface TableToolbarProps {
const operatorsByType: Record<string, { value: string; label: string }[]> = {
string: [
- { value: 'cont', label: 'contains' },
- { value: 'eq', label: 'equals' },
- { value: 'not_eq', label: 'does not equal' },
- { value: 'start', label: 'starts with' },
- { value: 'end', label: 'ends with' },
- { value: 'present', label: 'is set' },
- { value: 'blank', label: 'is not set' },
+ { value: "cont", label: "contains" },
+ { value: "eq", label: "equals" },
+ { value: "not_eq", label: "does not equal" },
+ { value: "start", label: "starts with" },
+ { value: "end", label: "ends with" },
+ { value: "present", label: "is set" },
+ { value: "blank", label: "is not set" },
],
status: [
- { value: 'eq', label: 'is' },
- { value: 'not_eq', label: 'is not' },
- { value: 'in', label: 'is any of' },
- { value: 'not_in', label: 'is none of' },
- ],
- boolean: [
- { value: 'eq', label: 'is' },
+ { value: "eq", label: "is" },
+ { value: "not_eq", label: "is not" },
+ { value: "in", label: "is any of" },
+ { value: "not_in", label: "is none of" },
],
+ boolean: [{ value: "eq", label: "is" }],
number: [
- { value: 'eq', label: 'equals' },
- { value: 'gt', label: 'greater than' },
- { value: 'gteq', label: 'greater than or equal' },
- { value: 'lt', label: 'less than' },
- { value: 'lteq', label: 'less than or equal' },
+ { value: "eq", label: "equals" },
+ { value: "gt", label: "greater than" },
+ { value: "gteq", label: "greater than or equal" },
+ { value: "lt", label: "less than" },
+ { value: "lteq", label: "less than or equal" },
],
date: [
- { value: 'eq', label: 'is' },
- { value: 'gt', label: 'after' },
- { value: 'lt', label: 'before' },
- { value: 'gteq', label: 'on or after' },
- { value: 'lteq', label: 'on or before' },
+ { value: "eq", label: "is" },
+ { value: "gt", label: "after" },
+ { value: "lt", label: "before" },
+ { value: "gteq", label: "on or after" },
+ { value: "lteq", label: "on or before" },
],
-}
+};
function getOperators(type: string) {
- return operatorsByType[type] || operatorsByType.string
+ return operatorsByType[type] || operatorsByType.string;
}
-const noValueOperators = ['present', 'blank']
+const noValueOperators = ["present", "blank"];
// ============================================================================
// TableToolbar
@@ -126,24 +105,28 @@ export function TableToolbar({
onVisibleColumnsChange,
search,
onSearchChange,
- searchPlaceholder = 'Search...',
+ searchPlaceholder = "Search...",
sort,
onSortChange,
filters,
onFiltersChange,
+ allColumns,
+ title,
actions,
}: TableToolbarProps) {
- const [filterOpen, setFilterOpen] = useState(false)
- const searchRef = useRef<HTMLInputElement>(null)
+ const [filterOpen, setFilterOpen] = useState(false);
+ const searchRef = useRef<HTMLInputElement>(null);
- const sortableColumns = columns.filter((c) => c.sortable)
- const filterableColumns = columns.filter((c) => c.filterable)
- const activeFilterCount = filters.length
+ const allCols = allColumns ?? columns;
+ const sortableColumns = allCols.filter((c) => c.sortable);
+ const filterableColumns = allCols.filter((c) => c.filterable);
+ const activeFilterCount = filters.length;
return (
<>
<div className="flex flex-col lg:flex-row gap-3 items-start lg:items-center justify-between p-3 border-b border-gray-200">
- <div className="flex gap-2 items-center flex-wrap">
+ {title && <CardTitle>{title}</CardTitle>}
+ <div className="flex gap-2 items-center flex-wrap ml-auto">
{/* Search */}
<div className="relative lg:w-[300px]">
<SearchIcon className="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-gray-600 pointer-events-none" />
@@ -159,8 +142,8 @@ export function TableToolbar({
type="button"
className="absolute right-2 top-1/2 -translate-y-1/2 p-0.5 text-gray-400 hover:text-gray-600"
onClick={() => {
- onSearchChange('')
- searchRef.current?.focus()
+ onSearchChange("");
+ searchRef.current?.focus();
}}
>
<XIcon className="size-3.5" />
@@ -181,7 +164,9 @@ export function TableToolbar({
<FilterIcon className="size-4" />
Filters
{activeFilterCount > 0 && (
- <Badge className="ml-1 px-1.5 py-0 text-xs">{activeFilterCount}</Badge>
+ <Badge className="ml-1 px-1.5 py-0 text-xs">
+ {activeFilterCount}
+ </Badge>
)}
</Button>
)}
@@ -210,12 +195,16 @@ export function TableToolbar({
{filters.length > 0 && (
<div className="flex gap-2 flex-wrap px-3 py-2 border-b border-gray-200">
{filters.map((filter) => {
- const col = columns.find((c) => c.key === filter.field)
- const ops = getOperators(col?.filterType ?? 'string')
- const opLabel = ops.find((o) => o.value === filter.operator)?.label ?? filter.operator
+ const col = allCols.find((c) => c.key === filter.field);
+ const ops = getOperators(col?.filterType ?? "string");
+ const opLabel =
+ ops.find((o) => o.value === filter.operator)?.label ??
+ filter.operator;
return (
<Badge key={filter.id} className="gap-1.5 pr-1">
- <span className="font-medium">{col?.label ?? filter.field}</span>
+ <span className="font-medium">
+ {col?.label ?? filter.field}
+ </span>
<span className="text-muted-foreground">{opLabel}</span>
{!noValueOperators.includes(filter.operator) && (
<span className="font-medium">{filter.value}</span>
@@ -223,12 +212,14 @@ export function TableToolbar({
<button
type="button"
className="ml-0.5 p-0.5 rounded-sm hover:bg-gray-200"
- onClick={() => onFiltersChange(filters.filter((f) => f.id !== filter.id))}
+ onClick={() =>
+ onFiltersChange(filters.filter((f) => f.id !== filter.id))
+ }
>
<XIcon className="size-3" />
</button>
</Badge>
- )
+ );
})}
<button
type="button"
@@ -249,7 +240,7 @@ export function TableToolbar({
onApply={onFiltersChange}
/>
</>
- )
+ );
}
// ============================================================================
@@ -261,20 +252,20 @@ function SortDropdown({
sort,
onSortChange,
}: {
- columns: ColumnDef[]
- sort: SortOption
- onSortChange: (sort: SortOption) => void
+ columns: ColumnDef[];
+ sort: SortOption;
+ onSortChange: (sort: SortOption) => void;
}) {
- const currentCol = columns.find((c) => c.key === sort.field)
- const currentLabel = currentCol?.label ?? 'Sort'
- const dirLabel = sort.direction === 'asc' ? 'A-Z' : 'Z-A'
+ const currentCol = columns.find((c) => c.key === sort.field);
+ const currentLabel = currentCol?.label ?? "Sort";
+ const dirLabel = sort.direction === "asc" ? "A-Z" : "Z-A";
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-[2.125rem]">
<ArrowUpDownIcon className="size-4" />
- {currentCol ? `${currentLabel} (${dirLabel})` : 'Sort'}
+ {currentCol ? `${currentLabel} (${dirLabel})` : "Sort"}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-48">
@@ -283,8 +274,8 @@ function SortDropdown({
<DropdownMenuRadioGroup
value={`${sort.field}:${sort.direction}`}
onValueChange={(val) => {
- const [field, direction] = val.split(':')
- onSortChange({ field, direction: direction as 'asc' | 'desc' })
+ const [field, direction] = val.split(":");
+ onSortChange({ field, direction: direction as "asc" | "desc" });
}}
>
{columns.map((col) => (
@@ -300,7 +291,7 @@ function SortDropdown({
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
- )
+ );
}
// ============================================================================
@@ -312,11 +303,11 @@ function ColumnSelector({
visibleColumns,
onVisibleColumnsChange,
}: {
- columns: ColumnDef[]
- visibleColumns: string[]
- onVisibleColumnsChange: (columns: string[]) => void
+ columns: ColumnDef[];
+ visibleColumns: string[];
+ onVisibleColumnsChange: (columns: string[]) => void;
}) {
- const defaults = columns.filter((c) => c.default).map((c) => c.key)
+ const defaults = columns.filter((c) => c.default).map((c) => c.key);
return (
<DropdownMenu>
@@ -338,7 +329,7 @@ function ColumnSelector({
checked
? [...visibleColumns, col.key]
: visibleColumns.filter((k) => k !== col.key),
- )
+ );
}}
onSelect={(e) => e.preventDefault()}
>
@@ -358,7 +349,7 @@ function ColumnSelector({
</div>
</DropdownMenuContent>
</DropdownMenu>
- )
+ );
}
// ============================================================================
@@ -372,50 +363,53 @@ function FilterDrawer({
filters: initialFilters,
onApply,
}: {
- open: boolean
- onOpenChange: (open: boolean) => void
- columns: ColumnDef[]
- filters: FilterRule[]
- onApply: (filters: FilterRule[]) => void
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ columns: ColumnDef[];
+ filters: FilterRule[];
+ onApply: (filters: FilterRule[]) => void;
}) {
- const [draft, setDraft] = useState<FilterRule[]>(initialFilters)
+ const [draft, setDraft] = useState<FilterRule[]>(initialFilters);
// Sync draft when opened
useEffect(() => {
- if (open) setDraft(initialFilters)
- }, [open, initialFilters])
+ if (open) setDraft(initialFilters);
+ }, [open, initialFilters]);
const addFilter = useCallback(() => {
- const first = columns[0]
- if (!first) return
+ const first = columns[0];
+ if (!first) return;
setDraft((prev) => [
...prev,
{
id: crypto.randomUUID(),
field: first.key,
- operator: getOperators(first.filterType ?? 'string')[0].value,
- value: '',
+ operator: getOperators(first.filterType ?? "string")[0].value,
+ value: "",
},
- ])
- }, [columns])
-
- const updateFilter = useCallback((id: string, update: Partial<FilterRule>) => {
- setDraft((prev) =>
- prev.map((f) => (f.id === id ? { ...f, ...update } : f)),
- )
- }, [])
+ ]);
+ }, [columns]);
+
+ const updateFilter = useCallback(
+ (id: string, update: Partial<FilterRule>) => {
+ setDraft((prev) =>
+ prev.map((f) => (f.id === id ? { ...f, ...update } : f)),
+ );
+ },
+ [],
+ );
const removeFilter = useCallback((id: string) => {
- setDraft((prev) => prev.filter((f) => f.id !== id))
- }, [])
+ setDraft((prev) => prev.filter((f) => f.id !== id));
+ }, []);
function handleApply() {
// Remove filters with no value (unless operator doesn't need one)
const valid = draft.filter(
- (f) => noValueOperators.includes(f.operator) || f.value.trim() !== '',
- )
- onApply(valid)
- onOpenChange(false)
+ (f) => noValueOperators.includes(f.operator) || f.value.trim() !== "",
+ );
+ onApply(valid);
+ onOpenChange(false);
}
return (
@@ -423,7 +417,9 @@ function FilterDrawer({
<SheetContent side="right" showCloseButton={false}>
<SheetHeader>
<SheetTitle>Filters</SheetTitle>
- <SheetDescription className="sr-only">Build filters for the table</SheetDescription>
+ <SheetDescription className="sr-only">
+ Build filters for the table
+ </SheetDescription>
<SheetClose asChild>
<Button variant="ghost" size="icon-sm">
<XIcon />
@@ -433,9 +429,9 @@ function FilterDrawer({
<div className="flex-1 overflow-y-auto p-4 space-y-3">
{draft.map((filter) => {
- const col = columns.find((c) => c.key === filter.field)
- const type = col?.filterType ?? 'string'
- const ops = getOperators(type)
+ const col = columns.find((c) => c.key === filter.field);
+ const type = col?.filterType ?? "string";
+ const ops = getOperators(type);
return (
<div
@@ -447,13 +443,15 @@ function FilterDrawer({
className="flex-1 rounded-lg border border-border bg-white py-1.5 px-2 text-sm outline-none focus:outline-2 focus:outline-offset-2 focus:outline-blue-500"
value={filter.field}
onChange={(e) => {
- const newCol = columns.find((c) => c.key === e.target.value)
- const newOps = getOperators(newCol?.filterType ?? 'string')
+ const newCol = columns.find(
+ (c) => c.key === e.target.value,
+ );
+ const newOps = getOperators(newCol?.filterType ?? "string");
updateFilter(filter.id, {
field: e.target.value,
operator: newOps[0].value,
- value: '',
- })
+ value: "",
+ });
}}
>
{columns.map((c) => (
@@ -467,7 +465,9 @@ function FilterDrawer({
<select
className="w-[140px] shrink-0 rounded-lg border border-border bg-white py-1.5 px-2 text-sm outline-none focus:outline-2 focus:outline-offset-2 focus:outline-blue-500"
value={filter.operator}
- onChange={(e) => updateFilter(filter.id, { operator: e.target.value })}
+ onChange={(e) =>
+ updateFilter(filter.id, { operator: e.target.value })
+ }
>
{ops.map((op) => (
<option key={op.value} value={op.value}>
@@ -477,12 +477,14 @@ function FilterDrawer({
</select>
{/* Value input */}
- {!noValueOperators.includes(filter.operator) && (
- col?.filterType === 'status' && col.filterOptions ? (
+ {!noValueOperators.includes(filter.operator) &&
+ (col?.filterType === "status" && col.filterOptions ? (
<select
className="flex-1 rounded-lg border border-border bg-white py-1.5 px-2 text-sm outline-none focus:outline-2 focus:outline-offset-2 focus:outline-blue-500"
value={filter.value}
- onChange={(e) => updateFilter(filter.id, { value: e.target.value })}
+ onChange={(e) =>
+ updateFilter(filter.id, { value: e.target.value })
+ }
>
<option value="">Select...</option>
{col.filterOptions.map((opt) => (
@@ -491,11 +493,13 @@ function FilterDrawer({
</option>
))}
</select>
- ) : col?.filterType === 'boolean' ? (
+ ) : col?.filterType === "boolean" ? (
<select
className="flex-1 rounded-lg border border-border bg-white py-1.5 px-2 text-sm outline-none focus:outline-2 focus:outline-offset-2 focus:outline-blue-500"
value={filter.value}
- onChange={(e) => updateFilter(filter.id, { value: e.target.value })}
+ onChange={(e) =>
+ updateFilter(filter.id, { value: e.target.value })
+ }
>
<option value="">Select...</option>
<option value="true">Yes</option>
@@ -503,14 +507,21 @@ function FilterDrawer({
</select>
) : (
<input
- type={col?.filterType === 'number' ? 'number' : col?.filterType === 'date' ? 'date' : 'text'}
+ type={
+ col?.filterType === "number"
+ ? "number"
+ : col?.filterType === "date"
+ ? "date"
+ : "text"
+ }
className="flex-1 rounded-lg border border-border bg-white py-1.5 px-2 text-sm outline-none focus:outline-2 focus:outline-offset-2 focus:outline-blue-500"
placeholder="Enter value..."
value={filter.value}
- onChange={(e) => updateFilter(filter.id, { value: e.target.value })}
+ onChange={(e) =>
+ updateFilter(filter.id, { value: e.target.value })
+ }
/>
- )
- )}
+ ))}
{/* Remove button */}
<button
@@ -521,7 +532,7 @@ function FilterDrawer({
<Trash2Icon className="size-4" />
</button>
</div>
- )
+ );
})}
{draft.length === 0 && (
@@ -530,11 +541,7 @@ function FilterDrawer({
</p>
)}
- <Button
- variant="outline"
- size="sm"
- onClick={addFilter}
- >
+ <Button variant="outline" size="sm" onClick={addFilter}>
<PlusIcon className="size-4" />
Add filter
</Button>
@@ -545,18 +552,13 @@ function FilterDrawer({
<Button variant="outline">Discard</Button>
</SheetClose>
<div className="flex gap-2">
- <Button
- variant="outline"
- onClick={() => setDraft([])}
- >
+ <Button variant="outline" onClick={() => setDraft([])}>
Clear all
</Button>
- <Button onClick={handleApply}>
- Apply filters
- </Button>
+ <Button onClick={handleApply}>Apply filters</Button>
</div>
</SheetFooter>
</SheetContent>
</Sheet>
- )
+ );
}
diff --git a/packages/admin/src/hooks/use-products.ts b/packages/admin/src/hooks/use-products.ts
index 7a108d4e74..a489e42b91 100644
--- a/packages/admin/src/hooks/use-products.ts
+++ b/packages/admin/src/hooks/use-products.ts
@@ -1,7 +1,7 @@
import { useQuery } from '@tanstack/react-query'
import { spreeClient } from '@/client'
import { useAuth } from '@/hooks/use-auth'
-import type { FilterRule } from '@/components/table-toolbar'
+import type { FilterRule } from '@/lib/table-registry'
interface UseProductsParams {
page?: number
diff --git a/packages/admin/src/lib/formatters.ts b/packages/admin/src/lib/formatters.ts
new file mode 100644
index 0000000000..a75efc0da1
--- /dev/null
+++ b/packages/admin/src/lib/formatters.ts
@@ -0,0 +1,24 @@
+export function formatPrice(price: { amount?: string; currency?: string; display?: string } | null) {
+ if (!price) return '—'
+ return price.display ?? `${price.currency} ${price.amount}`
+}
+
+export function formatRelativeTime(iso: string) {
+ const date = new Date(iso)
+ const now = new Date()
+ const diffMs = now.getTime() - date.getTime()
+ const diffMins = Math.floor(diffMs / 60000)
+ const diffHours = Math.floor(diffMins / 60)
+ const diffDays = Math.floor(diffHours / 24)
+
+ if (diffMins < 1) return 'just now'
+ if (diffMins < 60) return `${diffMins}m ago`
+ if (diffHours < 24) return `${diffHours}h ago`
+ if (diffDays < 30) return `${diffDays}d ago`
+
+ return date.toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined,
+ })
+}
diff --git a/packages/admin/src/lib/table-registry.ts b/packages/admin/src/lib/table-registry.ts
new file mode 100644
index 0000000000..f8657b0149
--- /dev/null
+++ b/packages/admin/src/lib/table-registry.ts
@@ -0,0 +1,132 @@
+import type { ReactNode } from 'react'
+
+// ============================================================================
+// Types
+// ============================================================================
+
+export interface ColumnDef<T = any> {
+ key: string
+ label: string
+ sortable?: boolean
+ filterable?: boolean
+ default?: boolean
+ filterType?: 'string' | 'status' | 'boolean' | 'number' | 'date'
+ filterOptions?: { value: string; label: string }[]
+ /** Ransack attribute name if different from key (e.g., 'master_sku' for 'sku') */
+ ransackAttribute?: string
+ /** Custom cell renderer. If omitted, renders `row[key]` as text. */
+ render?: (row: T) => ReactNode
+ /** Cell className */
+ className?: string
+ /** Whether this column is displayable in the table. Set to false for filter-only columns. */
+ displayable?: boolean
+}
+
+export interface FilterRule {
+ id: string
+ field: string
+ operator: string
+ value: string
+}
+
+export interface SortOption {
+ field: string
+ direction: 'asc' | 'desc'
+}
+
+export interface TableDef<T = any> {
+ key: string
+ title?: string
+ columns: ColumnDef<T>[]
+ searchParam?: string
+ searchPlaceholder?: string
+ defaultSort?: SortOption
+ emptyIcon?: ReactNode
+ emptyMessage?: string
+}
+
+// ============================================================================
+// Registry
+// ============================================================================
+
+const registry = new Map<string, TableDef>()
+
+export function defineTable<T = any>(key: string, def: Omit<TableDef<T>, 'key'>): TableDef<T> {
+ const tableDef = { ...def, key } as TableDef<T>
+ registry.set(key, tableDef)
+ return tableDef
+}
+
+export function getTable<T = any>(key: string): TableDef<T> {
+ const table = registry.get(key)
+ if (!table) throw new Error(`Table "${key}" is not registered. Call defineTable("${key}", ...) first.`)
+ return table as TableDef<T>
+}
+
+// ============================================================================
+// Mutation API — allows extensions to modify registered tables
+// ============================================================================
+
+export const tables = new Proxy({} as Record<string, TableMutator>, {
+ get(_target, key: string) {
+ return createMutator(key)
+ },
+})
+
+interface TableMutator {
+ addColumn<T = any>(column: ColumnDef<T>): void
+ removeColumn(key: string): void
+ updateColumn<T = any>(key: string, updates: Partial<ColumnDef<T>>): void
+}
+
+function createMutator(tableKey: string): TableMutator {
+ return {
+ addColumn(column) {
+ const table = registry.get(tableKey)
+ if (!table) throw new Error(`Table "${tableKey}" is not registered.`)
+ // Prevent duplicates
+ if (table.columns.some((c) => c.key === column.key)) {
+ throw new Error(`Column "${column.key}" already exists in table "${tableKey}". Use updateColumn() instead.`)
+ }
+ table.columns.push(column)
+ },
+ removeColumn(key) {
+ const table = registry.get(tableKey)
+ if (!table) throw new Error(`Table "${tableKey}" is not registered.`)
+ table.columns = table.columns.filter((c) => c.key !== key)
+ },
+ updateColumn(key, updates) {
+ const table = registry.get(tableKey)
+ if (!table) throw new Error(`Table "${tableKey}" is not registered.`)
+ const col = table.columns.find((c) => c.key === key)
+ if (!col) throw new Error(`Column "${key}" not found in table "${tableKey}".`)
+ Object.assign(col, updates)
+ },
+ }
+}
+
+// ============================================================================
+// Helpers
+// ============================================================================
+
+/** Get columns that are displayable (not filter-only) */
+export function getDisplayableColumns<T = any>(table: TableDef<T>): ColumnDef<T>[] {
+ return table.columns.filter((c) => c.displayable !== false)
+}
+
+/** Get default visible column keys */
+export function getDefaultColumnKeys(table: TableDef): string[] {
+ return getDisplayableColumns(table)
+ .filter((c) => c.default)
+ .map((c) => c.key)
+}
+
+/** Get columns that can be filtered */
+export function getFilterableColumns(table: TableDef): ColumnDef[] {
+ return table.columns.filter((c) => c.filterable)
+}
+
+/** Get columns that can be sorted */
+export function getSortableColumns(table: TableDef): ColumnDef[] {
+ return table.columns.filter((c) => c.sortable)
+}
diff --git a/packages/admin/src/routes/_authenticated/products/index.tsx b/packages/admin/src/routes/_authenticated/products/index.tsx
index 7738377515..26a0bf9f61 100644
--- a/packages/admin/src/routes/_authenticated/products/index.tsx
+++ b/packages/admin/src/routes/_authenticated/products/index.tsx
@@ -1,345 +1,34 @@
-import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
-import { useProducts } from '@/hooks/use-products'
-import { Card, CardContent } from '@/components/ui/card'
+import { createFileRoute } from '@tanstack/react-router'
import { Button } from '@/components/ui/button'
-import { StatusBadge } from '@/components/ui/badge'
-import { Pagination } from '@/components/ui/pagination'
-import {
- Table,
- TableHeader,
- TableBody,
- TableRow,
- TableHead,
- TableCell,
- TableEmpty,
-} from '@/components/ui/data-table'
-import {
- TableToolbar,
- type ColumnDef,
- type FilterRule,
- type SortOption,
-} from '@/components/table-toolbar'
-import { z } from 'zod/v4'
-import { PlusIcon, PackageIcon } from 'lucide-react'
-import { useState, useDeferredValue } from 'react'
-
-// ============================================================================
-// Column definitions — mirrors the Rails admin spree_admin_tables.rb config
-// ============================================================================
-
-const productColumns: ColumnDef[] = [
- {
- key: 'name',
- label: 'Name',
- sortable: true,
- filterable: true,
- default: true,
- },
- {
- key: 'status',
- label: 'Status',
- sortable: true,
- filterable: true,
- default: true,
- filterType: 'status',
- filterOptions: [
- { value: 'draft', label: 'Draft' },
- { value: 'active', label: 'Active' },
- { value: 'archived', label: 'Archived' },
- ],
- },
- {
- key: 'inventory',
- label: 'Inventory',
- sortable: false,
- filterable: false,
- default: true,
- },
- {
- key: 'price',
- label: 'Price',
- sortable: true,
- filterable: true,
- default: true,
- filterType: 'number',
- },
- {
- key: 'sku',
- label: 'SKU',
- sortable: false,
- filterable: true,
- default: false,
- },
- {
- key: 'created_at',
- label: 'Created at',
- sortable: true,
- filterable: true,
- default: false,
- filterType: 'date',
- },
- {
- key: 'updated_at',
- label: 'Updated at',
- sortable: true,
- filterable: true,
- default: false,
- filterType: 'date',
- },
-]
-
-const defaultColumns = productColumns.filter((c) => c.default).map((c) => c.key)
-
-// ============================================================================
-// Route
-// ============================================================================
-
-const filterSchema = z.object({
- id: z.string(),
- field: z.string(),
- operator: z.string(),
- value: z.string(),
-})
-
-const searchSchema = z.object({
- page: z.coerce.number().optional().default(1),
- sort: z.string().optional().default('updated_at'),
- dir: z.enum(['asc', 'desc']).optional().default('desc'),
- search: z.string().optional(),
- filters: z.preprocess(
- (val) => {
- if (typeof val === 'string') {
- try { return JSON.parse(val) } catch { return [] }
- }
- return val ?? []
- },
- z.array(filterSchema).optional().default([]),
- ),
- columns: z.preprocess(
- (val) => {
- if (typeof val === 'string') return val.split(',')
- return val ?? undefined
- },
- z.array(z.string()).optional(),
- ),
-})
+import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+import { PlusIcon } from 'lucide-react'
+import '@/tables/products'
export const Route = createFileRoute('/_authenticated/products/')({
- validateSearch: searchSchema,
+ validateSearch: resourceSearchSchema,
component: ProductsPage,
})
-// ============================================================================
-// Page
-// ============================================================================
-
function ProductsPage() {
- const { page, sort, dir, search, filters, columns: urlColumns } = Route.useSearch()
- const navigate = useNavigate({ from: Route.fullPath })
-
- const [searchInput, setSearchInput] = useState(search ?? '')
- const deferredSearch = useDeferredValue(searchInput)
- const visibleColumns = urlColumns ?? defaultColumns
-
- const sortString = dir === 'desc' ? `-${sort}` : sort
-
- const { data, isLoading } = useProducts({
- page,
- sort: sortString,
- search: deferredSearch || undefined,
- filters: filters as FilterRule[],
- })
-
- const products = data?.data ?? []
- const meta = data?.meta
-
- // Navigation helpers
- function updateSearch(updates: Record<string, unknown>) {
- navigate({ search: (prev) => ({ ...prev, ...updates }) })
- }
-
- function handleSearchChange(value: string) {
- setSearchInput(value)
- updateSearch({ search: value || undefined, page: 1 })
- }
-
- function handleSortChange(s: SortOption) {
- updateSearch({ sort: s.field, dir: s.direction, page: 1 })
- }
-
- function handleFiltersChange(f: FilterRule[]) {
- updateSearch({
- filters: f.length > 0 ? JSON.stringify(f) : undefined,
- page: 1,
- })
- }
-
- function handleColumnsChange(cols: string[]) {
- const isDefault = cols.length === defaultColumns.length && cols.every((c) => defaultColumns.includes(c))
- updateSearch({ columns: isDefault ? undefined : cols.join(',') })
- }
-
- const showSku = visibleColumns.includes('sku')
- const showCreatedAt = visibleColumns.includes('created_at')
- const showUpdatedAt = visibleColumns.includes('updated_at')
-
- const colCount = 2 + // name is always shown, price is always shown
- (visibleColumns.includes('status') ? 1 : 0) +
- (visibleColumns.includes('inventory') ? 1 : 0) +
- (showSku ? 1 : 0) +
- (showCreatedAt ? 1 : 0) +
- (showUpdatedAt ? 1 : 0)
+ const searchParams = Route.useSearch()
+ const { token } = useAuth()
return (
- <Card className="rounded-2xl">
- <TableToolbar
- columns={productColumns}
- visibleColumns={visibleColumns}
- onVisibleColumnsChange={handleColumnsChange}
- search={searchInput}
- onSearchChange={handleSearchChange}
- searchPlaceholder="Search products..."
- sort={{ field: sort, direction: dir }}
- onSortChange={handleSortChange}
- filters={filters as FilterRule[]}
- onFiltersChange={handleFiltersChange}
- actions={
- <Button size="sm" className="h-[2.125rem]">
- <PlusIcon className="size-4" />
- Add Product
- </Button>
- }
- />
- <CardContent className="p-0">
- <Table>
- <TableHeader>
- <tr>
- <TableHead>Name</TableHead>
- {visibleColumns.includes('status') && <TableHead>Status</TableHead>}
- {visibleColumns.includes('inventory') && <TableHead>Inventory</TableHead>}
- {showSku && <TableHead>SKU</TableHead>}
- <TableHead className="text-right">Price</TableHead>
- {showCreatedAt && <TableHead>Created</TableHead>}
- {showUpdatedAt && <TableHead>Updated</TableHead>}
- </tr>
- </TableHeader>
- <TableBody>
- {isLoading ? (
- <TableEmpty colSpan={colCount}>Loading products...</TableEmpty>
- ) : products.length === 0 ? (
- <TableEmpty colSpan={colCount}>
- <div className="flex flex-col items-center gap-2">
- <PackageIcon className="size-8 text-muted-foreground/50" />
- <p>No products found</p>
- {(deferredSearch || (filters as FilterRule[]).length > 0) && (
- <p className="text-xs">
- Try adjusting your search or filters
- </p>
- )}
- </div>
- </TableEmpty>
- ) : (
- products.map((product: any) => (
- <TableRow key={product.id}>
- <TableCell>
- <Link
- to="/products/$productId"
- params={{ productId: product.id }}
- className="flex items-center gap-3 no-underline"
- >
- <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-gray-200 bg-gray-50 overflow-hidden">
- {product.thumbnail_url ? (
- <img
- src={product.thumbnail_url}
- alt={product.name}
- className="size-full object-cover"
- />
- ) : (
- <PackageIcon className="size-4 text-gray-400" />
- )}
- </div>
- <div className="min-w-0">
- <div className="truncate font-medium text-zinc-950">
- {product.name}
- </div>
- </div>
- </Link>
- </TableCell>
- {visibleColumns.includes('status') && (
- <TableCell>
- <StatusBadge status={product.status} />
- </TableCell>
- )}
- {visibleColumns.includes('inventory') && (
- <TableCell>
- <InventoryCell product={product} />
- </TableCell>
- )}
- {showSku && (
- <TableCell className="text-sm text-muted-foreground">
- {product.sku ?? '—'}
- </TableCell>
- )}
- <TableCell className="text-right tabular-nums whitespace-nowrap">
- {product.price ? formatPrice(product.price) : '—'}
- </TableCell>
- {showCreatedAt && (
- <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
- {formatRelativeTime(product.created_at)}
- </TableCell>
- )}
- {showUpdatedAt && (
- <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
- {formatRelativeTime(product.updated_at)}
- </TableCell>
- )}
- </TableRow>
- ))
- )}
- </TableBody>
- </Table>
- {meta && (
- <Pagination
- meta={meta}
- onPageChange={(p) => updateSearch({ page: p })}
- />
- )}
- </CardContent>
- </Card>
+ <ResourceTable
+ tableKey="products"
+ queryKey="products"
+ queryFn={(params) =>
+ spreeClient.admin.products.list(params, { token: token! })
+ }
+ searchParams={searchParams}
+ actions={
+ <Button size="sm" className="h-[2.125rem]">
+ <PlusIcon className="size-4" />
+ Add Product
+ </Button>
+ }
+ />
)
}
-
-// ============================================================================
-// Helpers
-// ============================================================================
-
-function InventoryCell({ product }: { product: any }) {
- if (!product.in_stock && !product.backorderable) {
- return <span className="text-sm text-destructive">Out of stock</span>
- }
- if (product.backorderable && !product.in_stock) {
- return <span className="text-sm text-muted-foreground">On backorder</span>
- }
- return <span className="text-sm text-muted-foreground">In stock</span>
-}
-
-function formatPrice(price: { amount?: string; currency?: string; display?: string } | null) {
- if (!price) return '—'
- return price.display ?? `${price.currency} ${price.amount}`
-}
-
-function formatRelativeTime(iso: string) {
- const date = new Date(iso)
- const now = new Date()
- const diffMs = now.getTime() - date.getTime()
- const diffMins = Math.floor(diffMs / 60000)
- const diffHours = Math.floor(diffMins / 60)
- const diffDays = Math.floor(diffHours / 24)
-
- if (diffMins < 1) return 'just now'
- if (diffMins < 60) return `${diffMins}m ago`
- if (diffHours < 24) return `${diffHours}h ago`
- if (diffDays < 30) return `${diffDays}d ago`
-
- return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined })
-}
diff --git a/packages/admin/src/tables/products.tsx b/packages/admin/src/tables/products.tsx
new file mode 100644
index 0000000000..22eb891988
--- /dev/null
+++ b/packages/admin/src/tables/products.tsx
@@ -0,0 +1,126 @@
+import { Link } from '@tanstack/react-router'
+import { PackageIcon } from 'lucide-react'
+import { StatusBadge } from '@/components/ui/badge'
+import { defineTable } from '@/lib/table-registry'
+import { formatPrice, formatRelativeTime } from '@/lib/formatters'
+
+defineTable('products', {
+ title: 'Products',
+ searchParam: 'multi_search',
+ searchPlaceholder: 'Search products...',
+ defaultSort: { field: 'updated_at', direction: 'desc' },
+ emptyIcon: <PackageIcon className="size-8 text-muted-foreground/50" />,
+ emptyMessage: 'No products found',
+ columns: [
+ {
+ key: 'name',
+ label: 'Name',
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (product) => (
+ <Link
+ to="/products/$productId"
+ params={{ productId: product.id }}
+ className="flex items-center gap-3 no-underline"
+ >
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-gray-200 bg-gray-50 overflow-hidden">
+ {product.thumbnail_url ? (
+ <img
+ src={product.thumbnail_url}
+ alt={product.name}
+ className="size-full object-cover"
+ />
+ ) : (
+ <PackageIcon className="size-4 text-gray-400" />
+ )}
+ </div>
+ <div className="min-w-0">
+ <div className="truncate font-medium text-zinc-950">
+ {product.name}
+ </div>
+ </div>
+ </Link>
+ ),
+ },
+ {
+ key: 'status',
+ label: 'Status',
+ sortable: true,
+ filterable: true,
+ default: true,
+ filterType: 'status',
+ filterOptions: [
+ { value: 'draft', label: 'Draft' },
+ { value: 'active', label: 'Active' },
+ { value: 'archived', label: 'Archived' },
+ ],
+ render: (product) => <StatusBadge status={product.status} />,
+ },
+ {
+ key: 'inventory',
+ label: 'Inventory',
+ sortable: false,
+ filterable: false,
+ default: true,
+ render: (product) => {
+ if (!product.in_stock && !product.backorderable) {
+ return <span className="text-sm text-destructive">Out of stock</span>
+ }
+ if (product.backorderable && !product.in_stock) {
+ return <span className="text-sm text-muted-foreground">On backorder</span>
+ }
+ return <span className="text-sm text-muted-foreground">In stock</span>
+ },
+ },
+ {
+ key: 'sku',
+ label: 'SKU',
+ sortable: false,
+ filterable: true,
+ default: false,
+ ransackAttribute: 'master_sku',
+ className: 'text-sm text-muted-foreground',
+ render: (product) => product.sku ?? '—',
+ },
+ {
+ key: 'price',
+ label: 'Price',
+ sortable: true,
+ filterable: true,
+ default: true,
+ filterType: 'number',
+ ransackAttribute: 'master_price',
+ className: 'text-right tabular-nums whitespace-nowrap',
+ render: (product) => (product.price ? formatPrice(product.price) : '—'),
+ },
+ {
+ key: 'created_at',
+ label: 'Created at',
+ sortable: true,
+ filterable: true,
+ default: false,
+ filterType: 'date',
+ className: 'text-sm text-muted-foreground whitespace-nowrap',
+ render: (product) => formatRelativeTime(product.created_at),
+ },
+ {
+ key: 'updated_at',
+ label: 'Updated at',
+ sortable: true,
+ filterable: true,
+ default: false,
+ filterType: 'date',
+ className: 'text-sm text-muted-foreground whitespace-nowrap',
+ render: (product) => formatRelativeTime(product.updated_at),
+ },
+ {
+ key: 'in_stock',
+ label: 'In Stock',
+ filterable: true,
+ filterType: 'boolean',
+ displayable: false,
+ default: false,
+ },
+ ],
+})