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.

Universal drag-to-reorder on ResourceTable; drop position field

Damian Legawiec81a2f078ef31
diff --git a/packages/admin/package.json b/packages/admin/package.json
index 032ac9ab48..e4e8f95834 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -17,6 +17,9 @@
},
"dependencies": {
"@base-ui/react": "^1.4.1",
+ "@dnd-kit/core": "^6.3.1",
+ "@dnd-kit/sortable": "^10.0.0",
+ "@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/geist": "^5.2.8",
"@fontsource-variable/geist-mono": "^5.2.7",
"@hookform/resolvers": "^5.2.2",
diff --git a/packages/admin/src/components/spree/resource-table.tsx b/packages/admin/src/components/spree/resource-table.tsx
index bd4a50ff3a..6c05d6f245 100644
--- a/packages/admin/src/components/spree/resource-table.tsx
+++ b/packages/admin/src/components/spree/resource-table.tsx
@@ -1,6 +1,30 @@
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core'
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
-import { type ReactNode, useDeferredValue, useState } from 'react'
+import { GripVerticalIcon } from 'lucide-react'
+import {
+ type CSSProperties,
+ type ReactNode,
+ useCallback,
+ useDeferredValue,
+ useEffect,
+ useState,
+} from 'react'
import { z } from 'zod/v4'
import { EmptyState } from '@/components/spree/empty-state'
import { TableToolbar } from '@/components/spree/table-toolbar'
@@ -25,6 +49,7 @@ import {
getTable,
type SortOption,
} from '@/lib/table-registry'
+import { cn } from '@/lib/utils'
// ============================================================================
// Search schema — shared by all resource table routes
@@ -106,6 +131,20 @@ interface ResourceTableProps<T> {
* 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>
+}
+
+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
}
// ============================================================================
@@ -120,6 +159,7 @@ export function ResourceTable<T extends Record<string, any>>({
title,
defaultParams,
actions,
+ reorder,
}: ResourceTableProps<T>) {
const table = getTable<T>(tableKey)
const { token } = useAuth()
@@ -179,9 +219,55 @@ export function ResourceTable<T extends Record<string, any>>({
enabled: !!token,
})
- const rows = data?.data ?? []
+ const fetchedRows = data?.data ?? []
const meta = data?.meta
+ // Mirror the fetched rows in local state while reordering so we can swap
+ // them optimistically on drop. The mirror tracks the upstream cache by
+ // identity — TanStack returns a new array reference on every refetch, so
+ // this useEffect runs whenever the server data updates.
+ const [localRows, setLocalRows] = useState<T[]>(fetchedRows)
+ useEffect(() => {
+ setLocalRows(fetchedRows)
+ }, [fetchedRows])
+
+ const positionField = reorder?.positionField ?? 'position'
+ const reorderActive = !!reorder && sort === positionField && dir === 'asc'
+ 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 = [...localRows]
+ next.splice(fromIndex, 1)
+ next.splice(toIndex, 0, moved)
+ 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({
@@ -252,6 +338,7 @@ export function ResourceTable<T extends Record<string, any>>({
<Table>
<TableHeader>
<tr>
+ {reorderActive && <TableHead className="w-8" />}
{headerColumns.map((col) => (
<TableHead key={col.key} className={col.headerClassName}>
{col.label}
@@ -259,34 +346,70 @@ export function ResourceTable<T extends Record<string, any>>({
))}
</tr>
</TableHeader>
- <TableBody>
- {isLoading ? (
- <TableEmpty colSpan={visibleColumns.length}>Loading...</TableEmpty>
- ) : rows.length === 0 ? (
- <TableEmpty colSpan={visibleColumns.length}>
- <EmptyState
- compact
- icon={table.emptyIcon}
- title={table.emptyMessage ?? 'No results found'}
- description={
- deferredSearch || (filters as FilterRule[]).length > 0
- ? 'Try adjusting your search or filters'
- : undefined
- }
- />
- </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>
+ {reorderActive ? (
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext
+ items={rows.map((r) => (r as any).id)}
+ strategy={verticalListSortingStrategy}
+ >
+ <TableBody>
+ {isLoading ? (
+ <TableEmpty colSpan={visibleColumns.length + 1}>Loading...</TableEmpty>
+ ) : rows.length === 0 ? (
+ <TableEmpty colSpan={visibleColumns.length + 1}>
+ <EmptyState
+ compact
+ icon={table.emptyIcon}
+ title={table.emptyMessage ?? 'No results found'}
+ description={
+ deferredSearch || (filters as FilterRule[]).length > 0
+ ? 'Try adjusting your search or filters'
+ : undefined
+ }
+ />
+ </TableEmpty>
+ ) : (
+ rows.map((row) => (
+ <SortableRow key={(row as any).id} row={row} columns={visibleColumns} />
+ ))
+ )}
+ </TableBody>
+ </SortableContext>
+ </DndContext>
+ ) : (
+ <TableBody>
+ {isLoading ? (
+ <TableEmpty colSpan={visibleColumns.length}>Loading...</TableEmpty>
+ ) : rows.length === 0 ? (
+ <TableEmpty colSpan={visibleColumns.length}>
+ <EmptyState
+ compact
+ icon={table.emptyIcon}
+ title={table.emptyMessage ?? 'No results found'}
+ description={
+ deferredSearch || (filters as FilterRule[]).length > 0
+ ? 'Try adjusting your search or filters'
+ : undefined
+ }
+ />
+ </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
@@ -299,3 +422,53 @@ export function ResourceTable<T extends Record<string, any>>({
</Card>
)
}
+
+// ============================================================================
+// 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,
+}: {
+ row: T
+ columns: ColumnDef[]
+}) {
+ 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-muted/60 last:*:border-b-0',
+ isDragging && 'relative z-10 opacity-70',
+ )}
+ >
+ <TableCell className="w-8 cursor-grab touch-none text-muted-foreground active:cursor-grabbing">
+ <button
+ type="button"
+ aria-label="Drag to reorder"
+ className="flex size-6 items-center justify-center rounded hover:bg-muted"
+ {...attributes}
+ {...listeners}
+ >
+ <GripVerticalIcon className="size-4" />
+ </button>
+ </TableCell>
+ {columns.map((col) => (
+ <TableCell key={col.key} className={col.className}>
+ {col.render ? col.render(row) : String((row as any)[col.key] ?? '—')}
+ </TableCell>
+ ))}
+ </tr>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
index a23ac72a92..47d289ce89 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
@@ -5,6 +5,7 @@ import type {
PaymentMethodDisplayOn,
PaymentMethodUpdateParams,
} from '@spree/admin-sdk'
+import { useQueryClient } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { PlusIcon } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
@@ -65,6 +66,7 @@ const DISPLAY_ON_OPTIONS: { value: PaymentMethodDisplayOn; label: string }[] = [
function PaymentMethodsPage() {
const search = Route.useSearch() as z.infer<typeof paymentMethodsSearchSchema>
const navigate = useNavigate()
+ const queryClient = useQueryClient()
const editId = search.edit
const isCreating = !!search.new
@@ -100,6 +102,12 @@ function PaymentMethodsPage() {
</Button>
</Can>
}
+ reorder={{
+ onReorder: async (id, position) => {
+ await adminClient.paymentMethods.update(id, { position })
+ queryClient.invalidateQueries({ queryKey: ['payment-methods'] })
+ },
+ }}
/>
{isCreating && <CreatePaymentMethodSheet open onOpenChange={(o) => !o && closeSheet()} />}
@@ -116,7 +124,6 @@ const baseFormSchema = z.object({
display_on: z.enum(['both', 'front_end', 'back_end']),
active: z.boolean(),
auto_capture: z.boolean(),
- position: z.coerce.number().int().nonnegative().optional(),
})
const createFormSchema = baseFormSchema.extend({
@@ -132,7 +139,6 @@ const BASE_DEFAULTS: BaseFormValues = {
display_on: 'both',
active: true,
auto_capture: false,
- position: undefined,
}
const CREATE_DEFAULTS: CreateFormValues = { ...BASE_DEFAULTS, type: '' }
@@ -145,7 +151,6 @@ function valuesToCreateParams(v: CreateFormValues): PaymentMethodCreateParams {
active: v.active,
auto_capture: v.auto_capture,
display_on: v.display_on,
- position: v.position,
}
}
@@ -156,7 +161,6 @@ function valuesToUpdateParams(v: BaseFormValues): PaymentMethodUpdateParams {
active: v.active,
auto_capture: v.auto_capture,
display_on: v.display_on,
- position: v.position,
}
}
@@ -302,7 +306,6 @@ function EditPaymentMethodSheet({
display_on: (paymentMethod.display_on as PaymentMethodDisplayOn) ?? 'both',
active: paymentMethod.active,
auto_capture: paymentMethod.auto_capture ?? false,
- position: paymentMethod.position ?? undefined,
})
const initialPreferences = (paymentMethod.preferences as Record<string, unknown>) ?? {}
setPreferences(initialPreferences)
@@ -459,14 +462,6 @@ function PaymentMethodFormFields({
/>
</Field>
- <Field>
- <FieldLabel htmlFor="position">Position</FieldLabel>
- <Input id="position" type="number" min={0} placeholder="0" {...form.register('position')} />
- <span className="text-xs text-muted-foreground">
- Lower numbers appear first in the checkout list.
- </span>
- </Field>
-
<Field>
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b3646e5b5b..08cc64b05b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -24,6 +24,15 @@ importers:
'@base-ui/react':
specifier: ^1.4.1
+ '@dnd-kit/core':
+ specifier: ^6.3.1
+ '@dnd-kit/sortable':
+ specifier: ^10.0.0
+ '@dnd-kit/utilities':
+ specifier: ^3.2.2
+ version: 3.2.2([email protected])
'@fontsource-variable/geist':
specifier: ^5.2.8
version: 5.2.8
@@ -598,6 +607,28 @@ packages:
'@date-fns/[email protected]':
resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}
+ peerDependencies:
+ react: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==}
+ peerDependencies:
+ react: '>=16.8.0'
+ react-dom: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==}
+ peerDependencies:
+ '@dnd-kit/core': ^6.3.0
+ react: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==}
+ peerDependencies:
+ react: '>=16.8.0'
+
'@dotenvx/[email protected]':
resolution: {integrity: sha512-v4FA/Lw3pTEloLxBqTOaYDX6MNo0Jo7lGBsPZhwnJBqRJp0AzQg1ZZNxrFsh6HVC6QWeWrfIKLn0y2eyIXaVDg==}
hasBin: true
@@ -4382,6 +4413,31 @@ snapshots:
'@date-fns/[email protected]': {}
+ dependencies:
+ react: 19.2.6
+ tslib: 2.8.1
+
+ dependencies:
+ '@dnd-kit/accessibility': 3.1.1([email protected])
+ '@dnd-kit/utilities': 3.2.2([email protected])
+ react: 19.2.6
+ react-dom: 19.2.6([email protected])
+ tslib: 2.8.1
+
+ dependencies:
+ '@dnd-kit/utilities': 3.2.2([email protected])
+ react: 19.2.6
+ tslib: 2.8.1
+
+ dependencies:
+ react: 19.2.6
+ tslib: 2.8.1
+
'@dotenvx/[email protected]':
dependencies:
commander: 11.1.0