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
import {
closestCenter,
DndContext,
type DragEndEvent,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
} from '@dnd-kit/core'
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import {
Card,
Checkbox,
cn,
DragHandle,
Empty,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
Pagination,
type PaginationMeta,
Skeleton,
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableHeaderRow,
TableRow,
Tooltip,
TooltipContent,
TooltipTrigger,
useIsMobile,
} from '@spree/dashboard-ui'
import { InfoIcon } from '@spree/dashboard-ui/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import {
type CSSProperties,
type ReactNode,
useCallback,
useDeferredValue,
useEffect,
useMemo,
useState,
} from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import { runtimeListParams } from '../api-client'
import { useAuth } from '../hooks/use-auth'
import { useVisualViewportOffset } from '../hooks/use-visual-viewport-offset'
import { filtersToRansack } from '../lib/filters-to-ransack'
import { withStoreScope } from '../lib/query-keys'
import {
type ColumnDef,
type FilterRule,
getDefaultColumnKeys,
getTable,
type SortOption,
} from '../lib/table-registry'
import { useTenantId } from '../providers/tenant-provider'
import { type BulkAction, BulkActionBar } from './bulk-action-bar'
import { PageHeader } from './page-header'
import { TableToolbar } from './table-toolbar'
// ============================================================================
// Search schema — shared by all resource table routes
// ============================================================================
const filterSchema = z.object({
id: z.string(),
field: z.string(),
operator: z.string(),
value: z.string(),
})
/**
* A column header, with its explanation behind an info icon when it has one.
*
* Figures whose meaning is a definition rather than a word — available,
* reserved, incoming — need somewhere to say what they count. A tooltip keeps
* that out of the header row until it is asked for.
*/
function ColumnLabel({ column, hideHint }: { column: ColumnDef; hideHint?: boolean }) {
if (!column.labelHint || hideHint) return column.label
return (
<span className="inline-flex items-center gap-1">
{column.label}
<Tooltip>
<TooltipTrigger asChild>
{/* Focusable and named, so the explanation opens on focus as well as
hover and reaches a screen reader the same way. */}
<button
type="button"
className="cursor-help rounded-sm text-muted-foreground focus-visible:outline-2 focus-visible:outline-ring focus-visible:outline-offset-2"
aria-label={column.labelHint}
>
<InfoIcon className="size-3.5" />
</button>
</TooltipTrigger>
<TooltipContent className="max-w-xs font-normal normal-case">
{column.labelHint}
</TooltipContent>
</Tooltip>
</span>
)
}
export const resourceSearchSchema = z.object({
page: z.coerce.number().optional().default(1),
limit: z.coerce.number().optional(),
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
}, z.array(z.string()))
.optional(),
})
export type ResourceSearch = z.infer<typeof resourceSearchSchema>
// ============================================================================
// Props
// ============================================================================
/**
* Per-render context handed to the `actions` render-prop. Gives toolbar
* actions enough state to act on the *current* table view — needed for
* features like "export filtered records" that have to mirror what the user
* is looking at.
*/
export interface ResourceActionsContext {
filters: FilterRule[]
search: string
searchParam: string
/** All columns (incl. filter-only) — needed by `filtersToRansack`. */
columns: ColumnDef[]
/** Total record count for the active filter, or `undefined` while loading. */
totalCount: number | undefined
}
interface ResourceTableProps<T> {
/** Registry key (e.g., 'products') */
tableKey: string
/**
* TanStack Query key prefix. The table auto-injects the current tenant id so
* mutation hooks that invalidate `['<key>', tenantId]` always match — pages
* never need to thread it through themselves. A plain string is
* shorthand for `[string]`; pass an array to add further scope (e.g.
* `[webhookDeliveriesTableKey(endpointId)]`).
*/
queryKey: string | readonly unknown[]
/**
* Function that calls the SDK to fetch data. Its params are built at runtime
* from the table's columns and filters, so any typed SDK list method fits.
*/
queryFn: (params: never) => 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
/**
* Set when the PAGE already renders its own `PageHeader` and this table is a
* panel inside it, so the table renders no heading of its own.
*
* Declared rather than detected. The shell tracks how many headers are
* mounted, but during a route change the outgoing page's header has not
* unregistered by the time the incoming table first renders — so a table
* reading that count saw a header that was on its way out and silently
* dropped its own. Only the page knows this, and it knows it statically.
*/
hideHeader?: boolean
/** One line under the title. Overrides the table definition's description. */
description?: string
/** Docs for the feature, linked after the description. Overrides the table definition's. */
docsPath?: string
/** Default params always sent with every request (e.g., { complete: 1 } for orders) */
defaultParams?: Record<string, unknown>
/**
* Actions to render in the toolbar (e.g., "Add Product" button). Either a
* static node, or a function that receives the current table state — use
* the function form for actions that depend on filters/search (e.g. CSV
* export of the active view).
*/
actions?: ReactNode | ((ctx: ResourceActionsContext) => ReactNode)
/**
* When set, rows can be drag-reordered. The handler receives the moved
* row's id and its new 1-indexed position; the server is expected to
* handle the rest via `acts_as_list` (other rows shift around). Drag
* is only active when the table is sorted ascending by `positionField`
* (default: `position`) — otherwise reordering would be meaningless.
*/
reorder?: ReorderConfig<T>
/**
* Bulk operations available against selected rows. When present, the
* table renders a leading checkbox column and a sticky action bar
* appears once any row is selected. Mutually exclusive with `reorder`
* — the leading column is already taken by the drag handle.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
bulkActions?: BulkAction<any>[]
/**
* Per-row action menu. When set, a trailing cell renders whatever the
* function returns (typically a `<RowActions>` kebab). Works alongside
* `reorder` — the drag handle sits on the leading edge, the actions
* menu on the trailing edge.
*/
rowActions?: (row: T) => ReactNode
/**
* Dynamic per-store columns derived from custom field definitions,
* merged into the registry columns for display (column selector +
* cells), sorting, and filtering. Keys are the definitions'
* `filter_key` (`cf_*`), which the backend accepts as sort and
* filter attributes.
*/
customFieldColumns?: ColumnDef<T>[]
/** @deprecated Use `customFieldColumns` — removed in Spree 6.1. */
metafieldColumns?: ColumnDef<T>[]
}
export interface ReorderConfig<T> {
onReorder: (id: string, position: number, row: T) => Promise<unknown> | unknown
/** Defaults to `'position'`. Override for resources that sort on a different column. */
positionField?: string
}
// ============================================================================
// Component
// ============================================================================
export function ResourceTable<T extends Record<string, any>>({
tableKey,
queryKey,
queryFn,
searchParams,
title,
hideHeader = false,
description,
docsPath,
defaultParams,
actions,
reorder,
bulkActions,
rowActions,
customFieldColumns,
metafieldColumns,
}: ResourceTableProps<T>) {
const table = getTable<T>(tableKey)
const { t } = useTranslation()
const { token } = useAuth()
const navigate = useNavigate()
const queryClient = useQueryClient()
const selectionEnabled = !!bulkActions?.length && !reorder
const rowActionsEnabled = !!rowActions
const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set())
// Whether the bulk bar is covering the column labels.
const bulkActive = selectionEnabled && selectedIds.size > 0
// Only one bulk bar is mounted at a time. Rendering both and hiding one
// with `md:` leaves its text in the accessibility tree, so "2 selected"
// and every action label match twice.
const isMobile = useIsMobile()
const {
page,
limit,
sort: urlSort,
dir: urlDir,
search,
filters,
columns: urlColumns,
} = searchParams
// When the table is reorderable, sort is locked to the position field
// ascending — anything else makes drag-and-drop meaningless. Otherwise
// fall through to the URL params, then the table's declared default,
// then a sensible fallback.
const positionField = reorder?.positionField ?? 'position'
const defaultSort = table.defaultSort ?? {
field: 'updated_at',
direction: 'desc' as const,
}
const sort = reorder ? positionField : (urlSort ?? defaultSort.field)
const dir: 'asc' | 'desc' = reorder ? 'asc' : (urlDir ?? defaultSort.direction)
const [searchInput, setSearchInput] = useState(search ?? '')
const deferredSearch = useDeferredValue(searchInput)
// Registry columns + dynamic custom-field columns. Memoized so the toolbar's
// internal memos (FilterPanel `items` stability) keep stable deps.
const extraColumns = customFieldColumns ?? metafieldColumns
const allColumns = useMemo(
() => [...table.columns, ...(extraColumns ?? [])],
[table, extraColumns],
)
const displayableColumns = useMemo(
() => allColumns.filter((c) => c.displayable !== false),
[allColumns],
)
const defaultColumnKeys = getDefaultColumnKeys(table)
const visibleColumnKeys = urlColumns ?? defaultColumnKeys
const visibleColumns = useMemo(
() => displayableColumns.filter((c) => visibleColumnKeys.includes(c.key)),
[displayableColumns, visibleColumnKeys],
)
// Built from every displayable column, not the visible subset: the column
// picker is a desktop control (it is hidden on a phone), so the card should
// not inherit a selection the merchant cannot see or change there.
// Expands requested by currently-visible columns (e.g. custom field
// columns need `expand=custom_fields` to render their values). Sorted so
// the query key stays stable regardless of column order.
const columnExpand = useMemo(
() => [...new Set(visibleColumns.flatMap((c) => (c.expand ? [c.expand] : [])))].sort(),
[visibleColumns],
)
// Build API params
const sortString = dir === 'desc' ? `-${sort}` : sort
const tenantId = useTenantId()
// Whether the PAGE mounted a header of its own, in which case this table is
// a panel inside it and renders no heading.
//
// Latched from the first render, before this component's own `PageHeader`
// can register: the flag counts every mounted header, so reading it live
// would see the one rendered below, conclude the page already had one, and
// unmount it — which re-clears the flag and mounts it again, forever.
const pageOwnsHeader = hideHeader
// Auto-inject the tenant id so every list query — and the matching mutation
// invalidation — is tenant-scoped without each page re-implementing it.
// Goes through +withStoreScope+ so the slot ordering matches +useResourceKey+
// and +useResourceMutation+'s invalidations (tenant id at position 1).
const userPrefix = Array.isArray(queryKey) ? queryKey : [queryKey]
const queryKeyPrefix = withStoreScope(userPrefix, tenantId)
// Both bulk bars (desktop overlay, mobile bottom bar) reset through here so
// they cannot drift apart.
const visualViewportOffset = useVisualViewportOffset(bulkActive)
const clearSelection = useCallback(() => {
setSelectedIds(new Set())
queryClient.invalidateQueries({ queryKey: queryKeyPrefix })
}, [queryClient, queryKeyPrefix])
const { data, isLoading } = useQuery({
queryKey: [
...queryKeyPrefix,
{ page, limit, sort: sortString, search: deferredSearch, filters, expand: columnExpand },
],
queryFn: () => {
const params: Record<string, unknown> = {
page,
sort: sortString,
...defaultParams,
}
if (limit) {
params.limit = limit
}
if (columnExpand.length) {
const base = defaultParams?.expand
const baseList = Array.isArray(base)
? base
: typeof base === 'string'
? base.split(',')
: []
params.expand = [...new Set([...baseList, ...columnExpand])]
}
if (deferredSearch) {
const searchParam = table.searchParam ?? 'name_cont'
params[searchParam] = deferredSearch
}
Object.assign(params, filtersToRansack(filters as FilterRule[], allColumns))
return queryFn(runtimeListParams(params))
},
enabled: !!token,
})
const fetchedRows = data?.data ?? []
const meta = data?.meta
// Selection is per-page and ephemeral. Wipe it whenever the user pages,
// re-sorts, filters, or searches — keeping IDs from prior pages would let
// them silently apply a bulk op to rows the user can no longer see.
// biome-ignore lint/correctness/useExhaustiveDependencies: intentional reset on visible-set change
useEffect(() => {
if (selectionEnabled) {
setSelectedIds((prev) => (prev.size === 0 ? prev : new Set()))
}
}, [page, sortString, deferredSearch, filters, selectionEnabled])
const reorderActive = !!reorder
// Mirror the fetched rows in local state while reordering so we can swap
// them optimistically on drop. Only allocated when reorder is active —
// otherwise the table reads `fetchedRows` straight through. The mirror
// tracks the upstream cache by identity; TanStack returns a new array
// reference on every refetch, so this useEffect runs whenever data updates.
const [localRows, setLocalRows] = useState<T[]>(fetchedRows)
useEffect(() => {
if (reorderActive) setLocalRows(fetchedRows)
}, [fetchedRows, reorderActive])
const rows = reorderActive ? localRows : fetchedRows
// dnd-kit sensors: pointer for mouse/touch (5px activation distance keeps
// brief clicks on row content from starting a drag), keyboard for a11y.
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
)
const handleDragEnd = useCallback(
async (event: DragEndEvent) => {
const { active, over } = event
if (!over || active.id === over.id || !reorder) return
const fromIndex = localRows.findIndex((r) => r.id === active.id)
const toIndex = localRows.findIndex((r) => r.id === over.id)
if (fromIndex === -1 || toIndex === -1) return
const moved = localRows[fromIndex]
const next = arrayMove(localRows, fromIndex, toIndex)
setLocalRows(next)
try {
// 1-indexed position; acts_as_list shifts the rest server-side.
await reorder.onReorder(String(active.id), toIndex + 1, moved)
} catch {
// Rollback on failure — the next refetch will reconcile anyway.
setLocalRows(localRows)
}
},
[localRows, reorder],
)
// Navigation helpers
function updateSearch(updates: Record<string, unknown>) {
navigate({
search: (prev: Record<string, unknown>) => ({ ...prev, ...updates }) as never,
})
}
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(',') })
}
const pageIds = useMemo(() => (data?.data ?? []).map((r) => String((r as any).id)), [data])
const allPageSelected = pageIds.length > 0 && pageIds.every((id) => selectedIds.has(id))
const somePageSelected = pageIds.some((id) => selectedIds.has(id)) && !allPageSelected
function toggleRow(id: string) {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
function togglePage() {
setSelectedIds((prev) => {
if (allPageSelected) {
const next = new Set(prev)
for (const id of pageIds) next.delete(id)
return next
}
const next = new Set(prev)
for (const id of pageIds) next.add(id)
return next
})
}
// 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,
}
})
const resolvedActions =
typeof actions === 'function'
? actions({
filters: filters as FilterRule[],
search: deferredSearch,
searchParam: table.searchParam ?? 'name_cont',
columns: allColumns,
totalCount: meta?.count,
})
: actions
return (
// Below `sm` the table spans the full width: the page gutter plus the
// card's own border spends ~34px of a 390px screen on chrome, and a table
// is the one place that width is worth reclaiming. Negative margins cancel
// The frame belongs to the ROWS, not to the screen. The toolbar sits above
// it and the pagination below it, both on the sheet itself — so the border
// encloses exactly the tabular data, and the controls that act on it read
// as chrome rather than as its first and last rows.
//
// Below `sm` the table loses its frame and spans the gutter the page
// container applies, so narrow screens spend no width on a box.
//
// No shadow at any width: the sheet under it is already a raised surface,
// so the table is a region drawn on it rather than a second card floating
// above one. Its hairline is `--border`, the same weight as the rules
// between its own rows, so the frame and its contents read as one table.
<div className="flex flex-col gap-3">
{/* The page's own header, not a title bar of the table's own: a list page
IS this table, so its title and actions are the page's. Rendering
`PageHeader` here rather than a parallel implementation means a list
page and a detail page share one heading — the same type, spacing,
sticky behaviour and action slot — and the `page.actions` slot a
plugin registers into reaches both.
Skipped via `hideHeader` when the page already mounts its own
`PageHeader` (a table embedded as a panel), which would otherwise
give the page two. */}
{!pageOwnsHeader && (
<PageHeader
// Not pinned: on a list page the table's own column row is the band
// worth keeping on screen, and stacking a sticky title above it
// spends a third of a short viewport on chrome.
sticky={false}
title={title ?? table.title}
description={description ?? table.description}
docsPath={docsPath ?? table.docsPath}
actions={resolvedActions}
/>
)}
{/* A page that owns its header still passes `actions` here, and they
would otherwise vanish with the suppressed `PageHeader` — taking the
orders export and the policies Add button with them. Render them
above the toolbar so the control keeps a home either way. */}
{pageOwnsHeader && resolvedActions && (
<div className="flex flex-wrap items-center justify-end gap-2">{resolvedActions}</div>
)}
<TableToolbar
columns={displayableColumns}
visibleColumns={visibleColumnKeys}
onVisibleColumnsChange={handleColumnsChange}
search={searchInput}
onSearchChange={handleSearchChange}
searchPlaceholder={table.searchPlaceholder ?? t('admin.common.search_placeholder')}
sort={{ field: sort, direction: dir }}
onSortChange={handleSortChange}
filters={filters as FilterRule[]}
onFiltersChange={handleFiltersChange}
allColumns={allColumns}
hideSort={reorderActive}
/>
{/* `overflow-x-clip`, never `overflow-hidden`: the rows clip to the
rounded frame horizontally, but a `hidden` overflow on either axis
makes this a scroll container, and the pinned column row inside
would then stick to THIS box rather than to the page — which is to
say, scroll away with it. */}
<Card className="-mx-4 gap-0 overflow-x-clip rounded-none border-0 bg-transparent py-0 shadow-none sm:mx-0 sm:rounded-xl sm:border">
{reorderActive ? (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={rows.map((r) => (r as any).id)}
strategy={verticalListSortingStrategy}
>
<Table stickyHeader roundedTop roundedBottom>
<TableHeader>
<TableHeaderRow>
<TableHead className="w-8" />
{headerColumns.map((col) => (
<TableHead key={col.key} className={col.headerClassName}>
<ColumnLabel column={col} />
</TableHead>
))}
{rowActionsEnabled && (
<TableHead className="w-12">
<span className="sr-only">{t('admin.row_actions.menu_label')}</span>
</TableHead>
)}
</TableHeaderRow>
</TableHeader>
<TableBody className="bg-card">
{isLoading ? (
<TableSkeletonRows
colSpan={visibleColumns.length + 1 + (rowActionsEnabled ? 1 : 0)}
/>
) : rows.length === 0 ? (
<TableEmpty colSpan={visibleColumns.length + 1 + (rowActionsEnabled ? 1 : 0)}>
<Empty className="border-0 p-0">
<EmptyHeader>
{table.emptyIcon && (
<EmptyMedia variant="icon">{table.emptyIcon}</EmptyMedia>
)}
<EmptyTitle>
{table.emptyMessage ?? t('admin.common.no_results')}
</EmptyTitle>
{(deferredSearch || (filters as FilterRule[]).length > 0) && (
<EmptyDescription>
{t('admin.common.adjust_search_or_filters')}
</EmptyDescription>
)}
</EmptyHeader>
</Empty>
</TableEmpty>
) : (
rows.map((row) => (
<SortableRow
key={(row as any).id}
row={row}
columns={visibleColumns}
rowActions={rowActions}
/>
))
)}
</TableBody>
</Table>
</SortableContext>
</DndContext>
) : (
<>
{/* The bulk actions overlay the header row but live OUTSIDE the
table's horizontal scroller: out there their width is the
visible card rather than the table's full scroll width, so the
overflow-into-⋯ budget is right and the controls hold still
while the columns scroll sideways. A zero-height wrapper with
the same sticky offset as the pinned header keeps the two
travelling together; the start padding clears the select-all
checkbox, which stays visible and interactive underneath. */}
{bulkActive && !isMobile && (
// `pointer-events-none` on the overlay, re-enabled only on the
// bar itself: the start-padding gutter is part of this div and
// would otherwise swallow every click aimed at the select-all
// checkbox sitting beneath it — checking once, then never
// unchecking.
<div className="pointer-events-none sticky top-header-height z-30 h-0">
<div className="flex h-[2.1875rem] items-center ps-10 pe-4">
<div className="pointer-events-auto min-w-0 flex-1">
<BulkActionBar
selectedIds={Array.from(selectedIds)}
actions={bulkActions!}
onDone={clearSelection}
/>
</div>
</div>
</div>
)}
{/* On a phone the header-row overlay is the wrong home for this: it
scrolls sideways with a wide table and sits at the top, far from
the thumb. A fixed bottom bar stays put and in reach while the
merchant scrolls the list picking rows. */}
{bulkActive &&
isMobile &&
// Portalled to `document.body`: `SidebarInset` is `relative z-0`,
// which opens a stacking context, and a `fixed` child of it can
// only stack against its siblings there — page content painted
// later covered the bar until the merchant scrolled past it.
createPortal(
<section
className="fixed inset-x-0 z-50 border-t border-border bg-card px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] shadow-lg"
// `bottom` anchors to the *layout* viewport. Pinch-zoom (and
// a mobile URL bar) makes the visual viewport a smaller
// window onto it, leaving the bar off-screen until the
// merchant pans down — the offset lifts it back into view.
style={{ bottom: visualViewportOffset }}
aria-label={t('admin.a11y.bulk_actions')}
>
<div className="flex items-center gap-3">
<Checkbox
checked={allPageSelected}
indeterminate={somePageSelected}
onCheckedChange={togglePage}
aria-label={t('admin.a11y.select_all_rows')}
/>
<div className="min-w-0 flex-1">
<BulkActionBar
selectedIds={Array.from(selectedIds)}
actions={bulkActions!}
onDone={clearSelection}
/>
</div>
</div>
</section>,
document.body,
)}
<Table stickyHeader roundedTop roundedBottom>
<TableHeader>
{/* Column headers stay mounted with rows selected, and the bulk
bar is laid over them. Swapping them for one `colSpan` cell
instead would drop the width constraints they impose on an
auto-layout table, and every column would resize the moment a
row was ticked. `bulkActive` only hides the labels. */}
<TableHeaderRow>
{selectionEnabled && (
<TableHead className="w-8">
<Checkbox
checked={allPageSelected}
indeterminate={somePageSelected}
onCheckedChange={togglePage}
aria-label={t('admin.a11y.select_all_rows')}
/>
</TableHead>
)}
{headerColumns.map((col) => (
<TableHead
key={col.key}
className={cn(
col.headerClassName,
'transition-colors duration-150 ease-out',
// Hide the text, not the cell: `opacity-0` would erase
// the cell's muted background and bottom rule too,
// leaving rows visible through the band behind the
// bulk actions overlay. Only where that overlay is
// drawn — on a phone the bar is at the foot of the
// screen and the column labels stay readable.
bulkActive && !isMobile && 'text-transparent select-none',
)}
>
{/* The hint hides with the label: an info icon floating
over the bulk-actions band would be the only thing
left in the row. */}
<ColumnLabel column={col} hideHint={bulkActive && !isMobile} />
</TableHead>
))}
{rowActionsEnabled && (
<TableHead className="w-12">
<span className="sr-only">{t('admin.row_actions.menu_label')}</span>
</TableHead>
)}
</TableHeaderRow>
</TableHeader>
<TableBody className="bg-card">
{isLoading ? (
<TableSkeletonRows
colSpan={
visibleColumns.length +
(selectionEnabled ? 1 : 0) +
(rowActionsEnabled ? 1 : 0)
}
/>
) : rows.length === 0 ? (
<TableEmpty
colSpan={
visibleColumns.length +
(selectionEnabled ? 1 : 0) +
(rowActionsEnabled ? 1 : 0)
}
>
<Empty className="border-0 p-0">
<EmptyHeader>
{table.emptyIcon && (
<EmptyMedia variant="icon">{table.emptyIcon}</EmptyMedia>
)}
<EmptyTitle>
{table.emptyMessage ?? t('admin.common.no_results')}
</EmptyTitle>
{(deferredSearch || (filters as FilterRule[]).length > 0) && (
<EmptyDescription>
{t('admin.common.adjust_search_or_filters')}
</EmptyDescription>
)}
</EmptyHeader>
</Empty>
</TableEmpty>
) : (
rows.map((row, i) => {
const rowId = String((row as any).id ?? i)
const isSelected = selectionEnabled && selectedIds.has(rowId)
return (
<TableRow
key={(row as any).id ?? i}
// Selected rows carry the hover tint so the selection is
// visible at rest; hovering one goes a step deeper so the
// row still answers the pointer.
//
// A row holding an open popover is shaded the same way:
// the panel floats over its neighbours, and without this
// a merchant editing a figure has to count rows to see
// which record they are editing.
className={cn(
'has-data-[popup-open]:bg-accent-strong/40',
isSelected && 'bg-accent-strong/75 hover:bg-accent-strong-hover',
)}
>
{selectionEnabled && (
<TableCell className="w-8">
<Checkbox
checked={isSelected}
onCheckedChange={() => toggleRow(rowId)}
aria-label={t('admin.a11y.select_row')}
/>
</TableCell>
)}
{visibleColumns.map((col) => (
<TableCell key={col.key} className={col.className}>
{col.render ? col.render(row) : String((row as any)[col.key] ?? '—')}
</TableCell>
))}
{rowActionsEnabled && (
<TableCell className="w-12 text-right">{rowActions?.(row)}</TableCell>
)}
</TableRow>
)
})
)}
</TableBody>
</Table>
</>
)}
</Card>
{meta && (
<Pagination
meta={meta}
onPageChange={(p) => updateSearch({ page: p })}
onPageSizeChange={(size) => updateSearch({ limit: size, page: 1 })}
/>
)}
{/* Clears the fixed bottom bar so it can't cover the pagination or the
last row while a selection is active. Carries the same safe-area
inset the bar pads itself by, or the home indicator's worth of bar
still overlaps the last row. Sits after the pagination, which is now
the last thing the bar can cover. */}
{bulkActive && isMobile && (
<div className="h-[calc(4rem+max(0px,env(safe-area-inset-bottom)-0.75rem))]" aria-hidden />
)}
</div>
)
}
// ============================================================================
// TableSkeletonRows — placeholder rows while the first page loads. Rows rather
// than a "Loading…" line so the table keeps its height and the page doesn't
// jump when data lands.
// ============================================================================
function TableSkeletonRows({ colSpan, rows = 8 }: { colSpan: number; rows?: number }) {
return (
<>
{Array.from({ length: rows }, (_, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: fixed-length placeholder list
<tr key={i} className="last:*:border-b-0">
<TableCell colSpan={colSpan}>
<Skeleton className="h-5 w-full" />
</TableCell>
</tr>
))}
</>
)
}
// ============================================================================
// SortableRow — internal row that wires dnd-kit's listeners to a leading
// drag-handle cell. Mirrors the styling of <TableRow> from data-table.tsx.
// ============================================================================
function SortableRow<T extends Record<string, any>>({
row,
columns,
rowActions,
}: {
row: T
columns: ColumnDef[]
rowActions?: (row: T) => ReactNode
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: row.id,
})
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
}
return (
<tr
ref={setNodeRef}
style={style}
className={cn(
'group/row hover:bg-accent-strong/50 last:*:border-b-0',
isDragging && 'relative z-10 opacity-70',
)}
>
<TableCell className="w-8 touch-none">
<DragHandle attributes={attributes} listeners={listeners} />
</TableCell>
{columns.map((col) => (
<TableCell key={col.key} className={col.className}>
{col.render ? col.render(row) : String((row as any)[col.key] ?? '—')}
</TableCell>
))}
{rowActions && <TableCell className="w-12 text-right">{rowActions(row)}</TableCell>}
</tr>
)
}