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.

Replace the shipping card with a full-page bulk variant editor

Damian Legawiec6d9b41d00c9e
diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.ts
index 5939ff275f..ed3f795051 100644
--- a/packages/dashboard-ui/src/index.ts
+++ b/packages/dashboard-ui/src/index.ts
@@ -27,7 +27,7 @@ export * from './spree/address-block'
export * from './spree/back-button'
export * from './spree/bulk-dialog'
export * from './spree/bulk-price-table'
-export * from './spree/bulk-shipping-table'
+export * from './spree/bulk-variants-table'
export * from './spree/calculator-summary'
export * from './spree/color-picker'
export * from './spree/confirm-dialog'
diff --git a/packages/dashboard-ui/src/spree/bulk-shipping-table.tsx b/packages/dashboard-ui/src/spree/bulk-shipping-table.tsx
deleted file mode 100644
index 7370e1c5c4..0000000000
--- a/packages/dashboard-ui/src/spree/bulk-shipping-table.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import type { ColumnDef } from '@tanstack/react-table'
-import { useMemo } from 'react'
-import { DataGrid, DecimalCell, ReadOnlyCell } from './data-grid'
-
-export interface BulkShippingRow {
- id: string
- variantLabel?: string | null
- sku?: string | null
- // Display strings — decimal weight/dimension values, or null for unset.
- weight?: string | null
- height?: string | null
- width?: string | null
- depth?: string | null
-}
-
-export type BulkShippingField = 'weight' | 'height' | 'width' | 'depth'
-
-export interface BulkShippingTableLabels {
- /** Column header for the variant label column. */
- variant: string
- /** Column header for the SKU column. */
- sku: string
- /** Column headers for the editable measurement columns. */
- weight: string
- height: string
- width: string
- depth: string
- /** Placeholder for a variant row with no options text (e.g. "Default"). */
- variantDefault: string
- /** Shown when rows.length === 0. */
- emptyMessage?: string
- /** Aria label on the DataGrid for screen readers. */
- gridAriaLabel?: string
-}
-
-export interface BulkShippingTableProps {
- rows: BulkShippingRow[]
- /** Localized strings — the caller owns translations. */
- labels: BulkShippingTableLabels
- /** Called when the user commits a value to a cell. The id is the row id. */
- onChange: (rowId: string, field: BulkShippingField, value: string | null) => void
-}
-
-// Editable columns in grid order; the +2 offset skips the two read-only
-// leading columns when assigning keyboard-navigation coordinates.
-const FIELDS: BulkShippingField[] = ['weight', 'height', 'width', 'depth']
-
-/**
- * Presentational primitive for a "spreadsheet of variant shipping fields" UI.
- * Owns the DataGrid columns and decimal-cell wiring; selection, copy/paste,
- * and drag-fill come from the DataGrid. Owns NO data fetching, edit tracking,
- * or save logic — the caller projects its rows into BulkShippingRow shape and
- * writes edits back through `onChange`.
- */
-export function BulkShippingTable({ rows, labels, onChange }: BulkShippingTableProps) {
- const columns = useMemo<ColumnDef<BulkShippingRow>[]>(
- () => [
- {
- id: 'variant',
- header: labels.variant,
- cell: ({ row }) => (
- <ReadOnlyCell className="text-muted-foreground">
- {row.original.variantLabel ?? labels.variantDefault}
- </ReadOnlyCell>
- ),
- },
- {
- id: 'sku',
- header: labels.sku,
- cell: ({ row }) => (
- <ReadOnlyCell className="font-mono text-xs text-muted-foreground">
- {row.original.sku ?? '—'}
- </ReadOnlyCell>
- ),
- },
- ...FIELDS.map<ColumnDef<BulkShippingRow>>((field, fieldIndex) => ({
- id: field,
- header: () => <span className="block text-right">{labels[field]}</span>,
- cell: ({ row }) => {
- const r = row.original
- // No section-header rows in this grid, so the table row index IS
- // the keyboard-navigation row coordinate.
- const coords = { row: row.index, col: fieldIndex + 2 }
- const label = r.variantLabel ?? labels.variantDefault
- return (
- <DecimalCell
- coords={coords}
- value={r[field] ?? null}
- onChange={(next) => onChange(r.id, field, next)}
- ariaLabel={`${labels[field]} — ${label}`}
- />
- )
- },
- })),
- ],
- [onChange, labels],
- )
-
- if (rows.length === 0) {
- return <p className="text-sm text-muted-foreground">{labels.emptyMessage ?? ''}</p>
- }
-
- return (
- <DataGrid<BulkShippingRow>
- rows={rows}
- columns={columns}
- getRowId={(row) => row.id}
- aria-label={labels.gridAriaLabel}
- />
- )
-}
diff --git a/packages/dashboard-ui/src/spree/bulk-variants-table.tsx b/packages/dashboard-ui/src/spree/bulk-variants-table.tsx
new file mode 100644
index 0000000000..5e1b735ffc
--- /dev/null
+++ b/packages/dashboard-ui/src/spree/bulk-variants-table.tsx
@@ -0,0 +1,257 @@
+import type { ColumnDef } from '@tanstack/react-table'
+import { useMemo } from 'react'
+import { DataGrid, DecimalCell, ReadOnlyCell, SelectCell, SwitchCell, TextCell } from './data-grid'
+
+export interface BulkVariantsRow {
+ id: string
+ variantLabel?: string | null
+ sku?: string | null
+ barcode?: string | null
+ // Display strings — decimal weight/dimension values, or null for unset.
+ weight?: string | null
+ weightUnit?: string | null
+ height?: string | null
+ width?: string | null
+ depth?: string | null
+ dimensionsUnit?: string | null
+ preorderable?: boolean
+ backorderLimit?: string | null
+ taxCategoryId?: string | null
+}
+
+export type BulkVariantsField =
+ | 'sku'
+ | 'barcode'
+ | 'weight'
+ | 'weightUnit'
+ | 'height'
+ | 'width'
+ | 'depth'
+ | 'dimensionsUnit'
+ | 'preorderable'
+ | 'backorderLimit'
+ | 'taxCategoryId'
+
+export type BulkVariantsChange =
+ | { field: Exclude<BulkVariantsField, 'preorderable'>; value: string | null }
+ | { field: 'preorderable'; value: boolean }
+
+export interface BulkVariantsTableLabels {
+ /** Column headers. */
+ variant: string
+ sku: string
+ barcode: string
+ weight: string
+ weightUnit: string
+ height: string
+ width: string
+ depth: string
+ dimensionsUnit: string
+ preorderable: string
+ backorderLimit: string
+ taxCategory: string
+ /** Placeholder for a variant row with no options text (e.g. "Default"). */
+ variantDefault: string
+ /** Shown in unit cells with no explicit value ("inherit the default"). */
+ unitDefault: string
+ /** Shown in the tax-category cell when none is set. */
+ taxCategoryNone: string
+ /** Aria label on the DataGrid for screen readers. */
+ gridAriaLabel?: string
+}
+
+export interface BulkVariantsTableProps {
+ rows: BulkVariantsRow[]
+ /** Localized strings — the caller owns translations. */
+ labels: BulkVariantsTableLabels
+ weightUnitOptions: ReadonlyArray<{ value: string; label: string }>
+ dimensionUnitOptions: ReadonlyArray<{ value: string; label: string }>
+ /** Omit to hide the tax-category column (no tax categories configured). */
+ taxCategoryOptions?: ReadonlyArray<{ value: string; label: string }>
+ /** Called when the user commits a value to a cell. The id is the row id. */
+ onChange: (rowId: string, change: BulkVariantsChange) => void
+}
+
+// Decimal columns in grid order, paired with their fixed keyboard column
+// coordinate (see the coordinate map in the component body).
+const DECIMAL_COLUMNS: ReadonlyArray<{
+ field: 'weight' | 'height' | 'width' | 'depth'
+ col: number
+}> = [
+ { field: 'weight', col: 3 },
+ { field: 'height', col: 5 },
+ { field: 'width', col: 6 },
+ { field: 'depth', col: 7 },
+]
+
+/**
+ * Presentational primitive for a "spreadsheet of variant fields" UI: SKU,
+ * barcode, shipping measurements + units, availability, tax category.
+ * Selection, copy/paste, and drag-fill come from the DataGrid. Owns NO data
+ * fetching, edit tracking, or save logic — the caller projects its rows into
+ * BulkVariantsRow shape and writes edits back through `onChange`.
+ */
+export function BulkVariantsTable({
+ rows,
+ labels,
+ weightUnitOptions,
+ dimensionUnitOptions,
+ taxCategoryOptions,
+ onChange,
+}: BulkVariantsTableProps) {
+ const columns = useMemo<ColumnDef<BulkVariantsRow>[]>(() => {
+ // Keyboard column coordinates, fixed per column: variant label is
+ // read-only (unregistered), then sku=1, barcode=2, weight=3, unit=4,
+ // height=5, width=6, depth=7, unit=8, preorderable=9, backorder=10,
+ // tax=11.
+ const numericHeader = (label: string) => () => <span className="block text-right">{label}</span>
+ const rowLabel = (r: BulkVariantsRow) => r.variantLabel ?? labels.variantDefault
+
+ const defs: ColumnDef<BulkVariantsRow>[] = [
+ {
+ id: 'variant',
+ header: labels.variant,
+ cell: ({ row }) => (
+ <ReadOnlyCell className="whitespace-nowrap text-muted-foreground">
+ {rowLabel(row.original)}
+ </ReadOnlyCell>
+ ),
+ },
+ {
+ id: 'sku',
+ header: labels.sku,
+ cell: ({ row }) => (
+ <TextCell
+ coords={{ row: row.index, col: 1 }}
+ value={row.original.sku ?? null}
+ onChange={(next) => onChange(row.original.id, { field: 'sku', value: next })}
+ ariaLabel={`${labels.sku} — ${rowLabel(row.original)}`}
+ />
+ ),
+ },
+ {
+ id: 'barcode',
+ header: labels.barcode,
+ cell: ({ row }) => (
+ <TextCell
+ coords={{ row: row.index, col: 2 }}
+ value={row.original.barcode ?? null}
+ onChange={(next) => onChange(row.original.id, { field: 'barcode', value: next })}
+ ariaLabel={`${labels.barcode} — ${rowLabel(row.original)}`}
+ />
+ ),
+ },
+ ...DECIMAL_COLUMNS.map<ColumnDef<BulkVariantsRow>>(({ field, col }) => ({
+ id: field,
+ header: numericHeader(labels[field]),
+ cell: ({ row }) => (
+ <DecimalCell
+ coords={{ row: row.index, col }}
+ value={row.original[field] ?? null}
+ onChange={(next) => onChange(row.original.id, { field, value: next })}
+ ariaLabel={`${labels[field]} — ${rowLabel(row.original)}`}
+ />
+ ),
+ })),
+ {
+ id: 'weight_unit',
+ header: labels.weightUnit,
+ cell: ({ row }) => (
+ <SelectCell
+ coords={{ row: row.index, col: 4 }}
+ value={row.original.weightUnit ?? null}
+ options={weightUnitOptions}
+ nullLabel={labels.unitDefault}
+ onChange={(next) => onChange(row.original.id, { field: 'weightUnit', value: next })}
+ ariaLabel={`${labels.weightUnit} — ${rowLabel(row.original)}`}
+ />
+ ),
+ },
+ {
+ id: 'dimensions_unit',
+ header: labels.dimensionsUnit,
+ cell: ({ row }) => (
+ <SelectCell
+ coords={{ row: row.index, col: 8 }}
+ value={row.original.dimensionsUnit ?? null}
+ options={dimensionUnitOptions}
+ nullLabel={labels.unitDefault}
+ onChange={(next) => onChange(row.original.id, { field: 'dimensionsUnit', value: next })}
+ ariaLabel={`${labels.dimensionsUnit} — ${rowLabel(row.original)}`}
+ />
+ ),
+ },
+ {
+ id: 'preorderable',
+ header: labels.preorderable,
+ cell: ({ row }) => (
+ <SwitchCell
+ coords={{ row: row.index, col: 9 }}
+ value={row.original.preorderable ?? false}
+ onChange={(next) => onChange(row.original.id, { field: 'preorderable', value: next })}
+ ariaLabel={`${labels.preorderable} — ${rowLabel(row.original)}`}
+ />
+ ),
+ },
+ {
+ id: 'backorder_limit',
+ header: numericHeader(labels.backorderLimit),
+ cell: ({ row }) => (
+ <DecimalCell
+ coords={{ row: row.index, col: 10 }}
+ value={row.original.backorderLimit ?? null}
+ onChange={(next) => onChange(row.original.id, { field: 'backorderLimit', value: next })}
+ ariaLabel={`${labels.backorderLimit} — ${rowLabel(row.original)}`}
+ />
+ ),
+ },
+ ]
+
+ if (taxCategoryOptions) {
+ defs.push({
+ id: 'tax_category',
+ header: labels.taxCategory,
+ cell: ({ row }) => (
+ <SelectCell
+ coords={{ row: row.index, col: 11 }}
+ value={row.original.taxCategoryId ?? null}
+ options={taxCategoryOptions}
+ nullLabel={labels.taxCategoryNone}
+ onChange={(next) => onChange(row.original.id, { field: 'taxCategoryId', value: next })}
+ ariaLabel={`${labels.taxCategory} — ${rowLabel(row.original)}`}
+ />
+ ),
+ })
+ }
+
+ // Reorder to visual sequence: the coordinate map above is stable, but
+ // the defs array built column groups out of order for concision.
+ const order = [
+ 'variant',
+ 'sku',
+ 'barcode',
+ 'weight',
+ 'weight_unit',
+ 'height',
+ 'width',
+ 'depth',
+ 'dimensions_unit',
+ 'preorderable',
+ 'backorder_limit',
+ 'tax_category',
+ ]
+ return defs.sort((a, b) => order.indexOf(a.id as string) - order.indexOf(b.id as string))
+ }, [onChange, labels, weightUnitOptions, dimensionUnitOptions, taxCategoryOptions])
+
+ return (
+ <div className="overflow-x-auto">
+ <DataGrid<BulkVariantsRow>
+ rows={rows}
+ columns={columns}
+ getRowId={(row) => row.id}
+ className="min-w-[1100px]"
+ aria-label={labels.gridAriaLabel}
+ />
+ </div>
+ )
+}
diff --git a/packages/dashboard-ui/src/spree/data-grid/cells.tsx b/packages/dashboard-ui/src/spree/data-grid/cells.tsx
index bcf38b7351..510d0b2069 100644
--- a/packages/dashboard-ui/src/spree/data-grid/cells.tsx
+++ b/packages/dashboard-ui/src/spree/data-grid/cells.tsx
@@ -298,6 +298,116 @@ export function DecimalCell(props: Omit<MoneyCellProps, 'symbol'>) {
return <MoneyCell {...props} />
}
+interface TextCellProps extends BaseCellProps {
+ value: string | null
+ /** Receives the user's raw input; `null` when the field is blanked. */
+ onChange: (next: string | null) => void
+}
+
+/** Editable free-text cell (SKU, barcode, …). Left-aligned; ships the raw
+ * input on commit, `null` when blanked. */
+export function TextCell({ coords, value, onChange, ariaLabel }: TextCellProps) {
+ const ctx = useDataGridContext()
+ const inputRef = useRef<HTMLInputElement | null>(null)
+ const [draft, setDraft] = useState(value ?? '')
+ const isSelected = ctx.isSelected(coords)
+ const mode = modeFor(ctx.editing, coords)
+ const isEditing = mode === 'edit'
+ const isFocused = ctx.anchor?.row === coords.row && ctx.anchor?.col === coords.col
+
+ // Resync draft with external value when not editing.
+ useEffect(() => {
+ if (!isEditing) setDraft(value ?? '')
+ }, [value, isEditing])
+
+ // Auto-focus + select when entering edit mode.
+ useEffect(() => {
+ if (isEditing) {
+ const el = inputRef.current
+ if (el) {
+ el.focus()
+ el.select()
+ }
+ }
+ }, [isEditing])
+
+ const wrapRef = useRef<HTMLDivElement | null>(null)
+ useStableCellRegistration(coords, {
+ focus: () => inputRef.current?.focus(),
+ read: () => value ?? '',
+ write: (next) => onChange(next.trim() ? next : null),
+ canWrite: () => true,
+ getElement: () => wrapRef.current,
+ })
+
+ function commit() {
+ onChange(draft.trim() ? draft : null)
+ }
+
+ function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {
+ if (!isEditing) return
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ commit()
+ ctx.setEditing(null)
+ const next = { row: coords.row + 1, col: coords.col }
+ ctx.setAnchor(next)
+ ctx.setExtent(next)
+ ctx.cells.get(`${next.row}.${next.col}`)?.focus()
+ } else if (event.key === 'Escape') {
+ event.preventDefault()
+ setDraft(value ?? '')
+ ctx.setEditing(null)
+ } else if (event.key === 'Tab') {
+ event.preventDefault()
+ commit()
+ ctx.setEditing(null)
+ const dx = event.shiftKey ? -1 : 1
+ const next = { row: coords.row, col: coords.col + dx }
+ ctx.setAnchor(next)
+ ctx.setExtent(next)
+ ctx.cells.get(`${next.row}.${next.col}`)?.focus()
+ }
+ }
+
+ return (
+ <div
+ ref={wrapRef}
+ className={cn(
+ 'flex h-9 w-full items-center transition-colors',
+ isSelected && 'bg-blue-500/10',
+ isFocused && !isEditing && 'ring-2 ring-blue-500 ring-inset',
+ isEditing && 'bg-card ring-2 ring-blue-500 ring-inset',
+ )}
+ >
+ <input
+ ref={inputRef}
+ type="text"
+ value={isEditing ? draft : (value ?? '')}
+ readOnly={!isEditing}
+ onChange={(e) => setDraft(e.target.value)}
+ onFocus={() => {
+ ctx.setAnchor(coords)
+ ctx.setExtent(coords)
+ }}
+ onDoubleClick={() => ctx.setEditing(coords)}
+ onKeyDown={onKeyDown}
+ onBlur={() => {
+ if (isEditing) {
+ commit()
+ ctx.setEditing(null)
+ }
+ }}
+ aria-label={ariaLabel}
+ className={cn(
+ 'block h-9 w-full cursor-cell border-0 bg-transparent px-3 outline-none',
+ isEditing && 'cursor-text',
+ )}
+ />
+ </div>
+ )
+}
+
interface SwitchCellProps extends BaseCellProps {
value: boolean
onChange: (next: boolean) => void
@@ -354,18 +464,23 @@ export function SwitchCell({ coords, value, onChange, ariaLabel }: SwitchCellPro
}
interface SelectCellProps<V extends string> extends BaseCellProps {
- value: V
- onChange: (next: V) => void
+ value: V | null
+ /** `null` when the cell is cleared (Delete key, or pasting a blank). */
+ onChange: (next: V | null) => void
options: ReadonlyArray<{ value: V; label: string }>
+ /** Shown when value is null — e.g. "—" for "inherit the default". */
+ nullLabel?: string
}
/** Cell for fixed-option pickers. Enter opens the Select; arrow keys inside
- * the open Select navigate options (Base UI default). Esc closes. */
+ * the open Select navigate options (Base UI default). Esc closes. Pasted
+ * values match by option value or label; blanks clear to null. */
export function SelectCell<V extends string>({
coords,
value,
onChange,
options,
+ nullLabel,
ariaLabel,
}: SelectCellProps<V>) {
const ctx = useDataGridContext()
@@ -374,17 +489,27 @@ export function SelectCell<V extends string>({
const isFocused = ctx.anchor?.row === coords.row && ctx.anchor?.col === coords.col
const id = useId()
+ const matchOption = (raw: string) => {
+ const needle = raw.trim()
+ return options.find((o) => o.value === needle || o.label === needle)
+ }
+
useStableCellRegistration(coords, {
focus: () => triggerRef.current?.focus(),
- read: () => value,
+ read: () => value ?? '',
write: (next) => {
- if (options.some((o) => o.value === next)) onChange(next as V)
+ if (next.trim() === '') {
+ onChange(null)
+ return
+ }
+ const match = matchOption(next)
+ if (match) onChange(match.value)
},
- canWrite: (next) => options.some((o) => o.value === next) || next === '',
+ canWrite: (next) => next.trim() === '' || matchOption(next) !== undefined,
})
return (
- <Select items={options} value={value} onValueChange={(v) => onChange(v as V)}>
+ <Select items={options} value={value ?? ''} onValueChange={(v) => onChange((v || null) as V)}>
<SelectTrigger
ref={triggerRef}
id={id}
@@ -401,7 +526,9 @@ export function SelectCell<V extends string>({
isFocused && 'ring-2 ring-blue-500',
)}
>
- <SelectValue />
+ <SelectValue>
+ {(v) => options.find((o) => o.value === v)?.label ?? nullLabel ?? ''}
+ </SelectValue>
</SelectTrigger>
<SelectContent>
{options.map((opt) => (
diff --git a/packages/dashboard-ui/src/spree/data-grid/index.ts b/packages/dashboard-ui/src/spree/data-grid/index.ts
index 6c219c02df..3781b07f0f 100644
--- a/packages/dashboard-ui/src/spree/data-grid/index.ts
+++ b/packages/dashboard-ui/src/spree/data-grid/index.ts
@@ -1,4 +1,12 @@
-export { DecimalCell, MoneyCell, NumberCell, ReadOnlyCell, SelectCell, SwitchCell } from './cells'
+export {
+ DecimalCell,
+ MoneyCell,
+ NumberCell,
+ ReadOnlyCell,
+ SelectCell,
+ SwitchCell,
+ TextCell,
+} from './cells'
export { useDataGridContext } from './context'
export { DataGrid } from './data-grid'
export { editableRowIndex } from './helpers'
diff --git a/packages/dashboard/src/components/spree/products/bulk-variants-dialog.tsx b/packages/dashboard/src/components/spree/products/bulk-variants-dialog.tsx
new file mode 100644
index 0000000000..0a1d85f690
--- /dev/null
+++ b/packages/dashboard/src/components/spree/products/bulk-variants-dialog.tsx
@@ -0,0 +1,212 @@
+import {
+ type BulkVariantsChange,
+ type BulkVariantsRow,
+ BulkVariantsTable,
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@spree/dashboard-ui'
+import { useCallback, useEffect, useMemo, useRef } from 'react'
+import { type UseFormReturn, useWatch } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useOptionTypes } from '../../../hooks/use-option-types'
+import { useTaxCategories } from '../../../hooks/use-tax-categories'
+import type { ProductFormValues, VariantFormValues } from '../../../schemas/product'
+import { composeOptionsText } from './variants-matrix'
+
+const WEIGHT_UNITS = ['g', 'kg', 'lb', 'oz'] as const
+const DIMENSION_UNITS = ['mm', 'cm', 'in'] as const
+
+interface Props {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form: UseFormReturn<ProductFormValues, any, any>
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}
+
+/**
+ * Full-page bulk variant editor: a spreadsheet of every per-variant field
+ * from the variant edit sheet (SKU, barcode, shipping measurements + units,
+ * availability, tax category) across all of a product's variants at once.
+ * Selection, copy/paste, and drag-fill come from the shared DataGrid.
+ *
+ * Form-backed like the edit sheet: cells read from and write to the parent
+ * product form's `variants[]`, so Done keeps the edits in form state (the
+ * product Save button commits them) and Cancel restores the snapshot taken
+ * when the dialog opened. Closing via Esc/overlay/X cancels, mirroring the
+ * sheet.
+ */
+export function BulkVariantsDialog({ form, open, onOpenChange }: Props) {
+ const { t } = useTranslation()
+ const variants = useWatch({ control: form.control, name: 'variants' }) ?? []
+ const { data: optionTypesData } = useOptionTypes({ limit: 100 })
+ const optionTypes = useMemo(() => optionTypesData?.data ?? [], [optionTypesData])
+ const { data: taxCategoriesResponse } = useTaxCategories()
+ const taxCategories = taxCategoriesResponse?.data ?? []
+
+ // Snapshot the variants when the dialog opens so Cancel can restore them.
+ // Deep-clone — `form.getValues` returns references into RHF's internal
+ // state, and cell edits mutate them in place (same trap the edit sheet
+ // documents).
+ const snapshotRef = useRef<VariantFormValues[] | null>(null)
+ useEffect(() => {
+ if (!open) return
+ snapshotRef.current = structuredClone(form.getValues('variants') ?? []) as VariantFormValues[]
+ }, [open, form])
+
+ const handleCancel = useCallback(() => {
+ const snapshot = snapshotRef.current
+ if (snapshot) {
+ // Restore element-by-element via resetField so each variant's dirty
+ // bit clears too (the edit sheet's Cancel does the same). The bulk
+ // editor never adds or removes rows, so indices are stable.
+ snapshot.forEach((value, index) => {
+ form.resetField(`variants.${index}`, { defaultValue: value })
+ })
+ }
+ snapshotRef.current = null
+ onOpenChange(false)
+ }, [form, onOpenChange])
+
+ const handleDone = useCallback(() => {
+ snapshotRef.current = null
+ onOpenChange(false)
+ }, [onOpenChange])
+
+ const rows = useMemo<BulkVariantsRow[]>(
+ () =>
+ variants.map((v, idx) => ({
+ id: `variant:${idx}`,
+ variantLabel: v.options.length > 0 ? composeOptionsText(v.options, optionTypes) : null,
+ sku: v.sku ?? null,
+ barcode: v.barcode ?? null,
+ weight: v.weight != null ? String(v.weight) : null,
+ weightUnit: v.weight_unit ?? null,
+ height: v.height != null ? String(v.height) : null,
+ width: v.width != null ? String(v.width) : null,
+ depth: v.depth != null ? String(v.depth) : null,
+ dimensionsUnit: v.dimensions_unit ?? null,
+ preorderable: !!v.preorderable,
+ backorderLimit: v.backorder_limit != null ? String(v.backorder_limit) : null,
+ taxCategoryId: v.tax_category_id ?? null,
+ })),
+ [variants, optionTypes],
+ )
+
+ const handleChange = useCallback(
+ (rowId: string, change: BulkVariantsChange) => {
+ if (!rowId.startsWith('variant:')) return
+ const idx = Number.parseInt(rowId.slice('variant:'.length), 10)
+ if (Number.isNaN(idx)) return
+ const set = (path: Parameters<typeof form.setValue>[0], value: unknown) =>
+ form.setValue(path, value as never, { shouldDirty: true })
+
+ switch (change.field) {
+ case 'sku':
+ set(`variants.${idx}.sku`, change.value)
+ break
+ case 'barcode':
+ set(`variants.${idx}.barcode`, change.value)
+ break
+ case 'weightUnit':
+ set(`variants.${idx}.weight_unit`, change.value)
+ break
+ case 'dimensionsUnit':
+ set(`variants.${idx}.dimensions_unit`, change.value)
+ break
+ case 'taxCategoryId':
+ set(`variants.${idx}.tax_category_id`, change.value)
+ break
+ case 'preorderable':
+ set(`variants.${idx}.preorderable`, change.value)
+ break
+ case 'backorderLimit': {
+ if (change.value == null || change.value.trim() === '') {
+ set(`variants.${idx}.backorder_limit`, null)
+ break
+ }
+ const parsed = Number(change.value.trim().replace(',', '.'))
+ if (!Number.isFinite(parsed) || parsed < 0) break
+ set(`variants.${idx}.backorder_limit`, Math.trunc(parsed))
+ break
+ }
+ default: {
+ // weight / height / width / depth — decimals. Accept a comma
+ // decimal (the cell ships raw input); ignore anything that doesn't
+ // parse to a non-negative number rather than mangling it.
+ if (change.value == null || change.value.trim() === '') {
+ set(`variants.${idx}.${change.field}`, null)
+ break
+ }
+ const parsed = Number(change.value.trim().replace(',', '.'))
+ if (!Number.isFinite(parsed) || parsed < 0) break
+ set(`variants.${idx}.${change.field}`, parsed)
+ break
+ }
+ }
+ },
+ [form],
+ )
+
+ const unitOptions = (units: readonly string[]) => units.map((u) => ({ value: u, label: u }))
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => (next ? onOpenChange(true) : handleCancel())} modal>
+ <DialogContent
+ // Edge-to-edge minus a 3-unit gutter, same overrides as the bulk
+ // price dialog (see BulkPriceEditorDialog for why each is needed).
+ className="!inset-3 !w-auto !max-w-none !translate-x-0 !translate-y-0 flex flex-col p-0"
+ style={{ maxHeight: 'none' }}
+ showCloseButton={false}
+ >
+ <DialogHeader className="flex flex-row items-center justify-between gap-3 space-y-0 border-b p-3">
+ <DialogTitle className="truncate">
+ {t('admin.products.variants.bulk_edit.title')}
+ </DialogTitle>
+ <div className="flex items-center gap-2">
+ <Button type="button" size="sm" variant="ghost" onClick={handleCancel}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="button" size="sm" onClick={handleDone}>
+ {t('admin.actions.done')}
+ </Button>
+ </div>
+ </DialogHeader>
+ <DialogBody className="min-h-0 flex-1 overflow-auto p-3">
+ <BulkVariantsTable
+ rows={rows}
+ onChange={handleChange}
+ weightUnitOptions={unitOptions(WEIGHT_UNITS)}
+ dimensionUnitOptions={unitOptions(DIMENSION_UNITS)}
+ taxCategoryOptions={
+ taxCategories.length > 0
+ ? taxCategories.map((c) => ({ value: c.id, label: c.name }))
+ : undefined
+ }
+ labels={{
+ variant: t('admin.pages.products.price_lists.edit_prices.columns.variant'),
+ sku: t('admin.fields.variant.sku.label'),
+ barcode: t('admin.fields.variant.barcode.label'),
+ weight: t('admin.fields.variant.weight.label'),
+ weightUnit: t('admin.fields.variant.weight_unit.label'),
+ height: t('admin.fields.variant.height.label'),
+ width: t('admin.fields.variant.width.label'),
+ depth: t('admin.fields.variant.depth.label'),
+ dimensionsUnit: t('admin.fields.variant.dimensions_unit.label'),
+ preorderable: t('admin.fields.variant.preorderable.label'),
+ backorderLimit: t('admin.fields.variant.backorder_limit.label'),
+ taxCategory: t('admin.fields.tax_category_id.label'),
+ variantDefault: t('admin.products.variants.default_variant'),
+ unitDefault: '—',
+ taxCategoryNone: t('admin.products.variants.sheet.tax_category_placeholder'),
+ gridAriaLabel: t('admin.products.variants.bulk_edit.grid_aria'),
+ }}
+ />
+ </DialogBody>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/products/product-bulk-shipping-editor.tsx b/packages/dashboard/src/components/spree/products/product-bulk-shipping-editor.tsx
deleted file mode 100644
index bb4f385c57..0000000000
--- a/packages/dashboard/src/components/spree/products/product-bulk-shipping-editor.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import {
- type BulkShippingField,
- type BulkShippingRow,
- BulkShippingTable,
-} from '@spree/dashboard-ui'
-import { useCallback, useMemo } from 'react'
-import { type UseFormReturn, useWatch } from 'react-hook-form'
-import { useTranslation } from 'react-i18next'
-import { useOptionTypes } from '../../../hooks/use-option-types'
-import type { ProductFormValues } from '../../../schemas/product'
-import { composeOptionsText } from './variants-matrix'
-
-interface Props {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: UseFormReturn<ProductFormValues, any, any>
-}
-
-/**
- * Form-backed shipping spreadsheet for ONE product's variants: weight,
- * height, width, depth. Reads from and writes to the parent product form's
- * `variants[]` array — works equally for persisted and unsaved variants —
- * so edits ride the product form's Save like the prices grid. Units are
- * deliberately not columns here: they rarely vary per variant and stay
- * editable in the variant edit sheet.
- */
-export function ProductBulkShippingEditor({ form }: Props) {
- const { t } = useTranslation()
- const variants = useWatch({ control: form.control, name: 'variants' }) ?? []
- const { data: optionTypesData } = useOptionTypes({ limit: 100 })
- const optionTypes = useMemo(() => optionTypesData?.data ?? [], [optionTypesData])
-
- // Row id is the variant's array index so onChange can write back
- // unambiguously, even for variants without a persisted id.
- const rows = useMemo<BulkShippingRow[]>(
- () =>
- variants.map((v, idx) => ({
- id: `variant:${idx}`,
- variantLabel: v.options.length > 0 ? composeOptionsText(v.options, optionTypes) : null,
- sku: v.sku ?? null,
- weight: v.weight != null ? String(v.weight) : null,
- height: v.height != null ? String(v.height) : null,
- width: v.width != null ? String(v.width) : null,
- depth: v.depth != null ? String(v.depth) : null,
- })),
- [variants, optionTypes],
- )
-
- const handleChange = useCallback(
- (rowId: string, field: BulkShippingField, next: string | null) => {
- if (!rowId.startsWith('variant:')) return
- const idx = Number.parseInt(rowId.slice('variant:'.length), 10)
- if (Number.isNaN(idx)) return
-
- const path = `variants.${idx}.${field}` as const
- if (next == null || next.trim() === '') {
- form.setValue(path, null, { shouldDirty: true })
- return
- }
- // Accept a comma decimal (the cell ships raw input); ignore anything
- // that doesn't parse to a non-negative number rather than mangling it.
- const parsed = Number(next.trim().replace(',', '.'))
- if (!Number.isFinite(parsed) || parsed < 0) return
- form.setValue(path, parsed, { shouldDirty: true })
- },
- [form],
- )
-
- return (
- <BulkShippingTable
- rows={rows}
- onChange={handleChange}
- labels={{
- variant: t('admin.pages.products.price_lists.edit_prices.columns.variant'),
- sku: t('admin.fields.variant.sku.label'),
- weight: t('admin.fields.variant.weight.label'),
- height: t('admin.fields.variant.height.label'),
- width: t('admin.fields.variant.width.label'),
- depth: t('admin.fields.variant.depth.label'),
- variantDefault: t('admin.pages.products.price_lists.edit_prices.variant_default'),
- emptyMessage: t('admin.pages.products.edit.bulk_shipping.no_variants'),
- gridAriaLabel: t('admin.pages.products.edit.bulk_shipping.grid_aria'),
- }}
- />
- )
-}
diff --git a/packages/dashboard/src/components/spree/products/product-form-cards.tsx b/packages/dashboard/src/components/spree/products/product-form-cards.tsx
index ae25a40ec4..9612626bf0 100644
--- a/packages/dashboard/src/components/spree/products/product-form-cards.tsx
+++ b/packages/dashboard/src/components/spree/products/product-form-cards.tsx
@@ -54,7 +54,6 @@ import type { ProductFormValues } from '../../../schemas/product'
import { ProductBulkPriceEditor } from '../bulk-price-editor/product-bulk-price-editor'
import { InventorySection } from './inventory-section'
import { MediaEditSheet } from './media-edit-sheet'
-import { ProductBulkShippingEditor } from './product-bulk-shipping-editor'
import { VariantsSection } from './variants-section'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -153,27 +152,6 @@ export function PricesCard({ form, productName }: FormCardProps & { productName:
)
}
-// ---------------------------------------------------------------------------
-// Shipping — inline form-backed spreadsheet of per-variant weight and
-// dimensions. Same model as PricesCard: edits ride the parent product
-// form's Save.
-// ---------------------------------------------------------------------------
-
-export function ShippingCard({ form }: FormCardProps) {
- const { t } = useTranslation()
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.fields.shipping.label')}</CardTitle>
- </CardHeader>
- <CardContent>
- <ProductBulkShippingEditor form={form} />
- </CardContent>
- </Card>
- )
-}
-
// ---------------------------------------------------------------------------
// Media — edit-only. On create, render a "save first" empty state so the
// merchant sees where uploads will go but can't trigger them.
diff --git a/packages/dashboard/src/components/spree/products/variants-section.tsx b/packages/dashboard/src/components/spree/products/variants-section.tsx
index efe0c4fca3..436a745360 100644
--- a/packages/dashboard/src/components/spree/products/variants-section.tsx
+++ b/packages/dashboard/src/components/spree/products/variants-section.tsx
@@ -38,6 +38,7 @@ import { useTranslation } from 'react-i18next'
import { useOptionTypes, useOptionTypesByIds } from '../../../hooks/use-option-types'
import { useProductType } from '../../../hooks/use-product-types'
import type { ProductFormValues, VariantFormValues } from '../../../schemas/product'
+import { BulkVariantsDialog } from './bulk-variants-dialog'
import { VariantEditSheet } from './variant-edit-sheet'
import {
generateVariantCombinations,
@@ -137,6 +138,7 @@ export function VariantsSection({ form, seedFromType = false }: Props) {
const [editingIndex, setEditingIndex] = useState<number | null>(null)
const [sheetOpen, setSheetOpen] = useState(false)
+ const [bulkOpen, setBulkOpen] = useState(false)
const [orphanedKeys, setOrphanedKeys] = useState<string[]>([])
// `selected` is fully derived from the current variants array + the global
@@ -324,8 +326,13 @@ export function VariantsSection({ form, seedFromType = false }: Props) {
return (
<Card>
- <CardHeader>
+ <CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
<CardTitle>{t('admin.products.variants.title')}</CardTitle>
+ {fields.length > 0 && (
+ <Button type="button" variant="outline" size="sm" onClick={() => setBulkOpen(true)}>
+ {t('admin.products.variants.bulk_edit.trigger')}
+ </Button>
+ )}
</CardHeader>
<CardContent className="flex flex-col gap-6">
<VariantsOptionsBuilder
@@ -409,6 +416,8 @@ export function VariantsSection({ form, seedFromType = false }: Props) {
)}
</CardContent>
+ <BulkVariantsDialog form={form} open={bulkOpen} onOpenChange={setBulkOpen} />
+
{editingIndex !== null && (
<VariantEditSheet
form={form}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 506c724445..b068b42cd5 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2029,10 +2029,6 @@
"edit": {
"bulk_prices": {
"no_variants": "أضف متغيرًا واحدًا على الأقل لبدء تعديل الأسعار."
- },
- "bulk_shipping": {
- "no_variants": "أضف متغيرًا واحدًا على الأقل لبدء تعديل بيانات الشحن.",
- "grid_aria": "جدول شحن المتغيرات"
}
},
"inventory": {
@@ -2833,7 +2829,12 @@
"tax_category_placeholder": "ترث من المنتج"
},
"title": "المتغيرات",
- "variant_label": "البديل"
+ "variant_label": "البديل",
+ "bulk_edit": {
+ "trigger": "تحرير جماعي",
+ "title": "تحرير المتغيرات جماعيًا",
+ "grid_aria": "جدول التحرير الجماعي للمتغيرات"
+ }
}
},
"promotions": {
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 73ea620a68..fc6d71b21d 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2029,10 +2029,6 @@
"edit": {
"bulk_prices": {
"no_variants": "Fügen Sie mindestens eine Variante hinzu, um die Preisbearbeitung zu starten."
- },
- "bulk_shipping": {
- "no_variants": "Füge mindestens eine Variante hinzu, um Versanddaten zu bearbeiten.",
- "grid_aria": "Versandtabelle der Varianten"
}
},
"inventory": {
@@ -2827,7 +2823,12 @@
"tax_category_placeholder": "Vom Produkt übernehmen"
},
"title": "Varianten",
- "variant_label": "Variante"
+ "variant_label": "Variante",
+ "bulk_edit": {
+ "trigger": "Massenbearbeitung",
+ "title": "Varianten massenbearbeiten",
+ "grid_aria": "Tabelle zur Massenbearbeitung der Varianten"
+ }
}
},
"promotions": {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 3bb6b68c71..74c3a91d05 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2029,10 +2029,6 @@
"edit": {
"bulk_prices": {
"no_variants": "Add at least one variant to start editing prices."
- },
- "bulk_shipping": {
- "no_variants": "Add at least one variant to start editing shipping.",
- "grid_aria": "Variant shipping spreadsheet"
}
},
"inventory": {
@@ -2827,7 +2823,12 @@
"tax_category_placeholder": "Inherit from product"
},
"title": "Variants",
- "variant_label": "Variant"
+ "variant_label": "Variant",
+ "bulk_edit": {
+ "trigger": "Bulk edit",
+ "title": "Bulk edit variants",
+ "grid_aria": "Variant bulk edit spreadsheet"
+ }
}
},
"promotions": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 76c4d4538d..73ebb045aa 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2029,10 +2029,6 @@
"edit": {
"bulk_prices": {
"no_variants": "Ajoutez au moins une variante pour commencer à modifier les prix."
- },
- "bulk_shipping": {
- "no_variants": "Ajoutez au moins une variante pour modifier les données d'expédition.",
- "grid_aria": "Tableau d'expédition des variantes"
}
},
"inventory": {
@@ -2827,7 +2823,12 @@
"tax_category_placeholder": "Hériter du produit"
},
"title": "Variantes",
- "variant_label": "Variante"
+ "variant_label": "Variante",
+ "bulk_edit": {
+ "trigger": "Édition groupée",
+ "title": "Modifier les variantes en masse",
+ "grid_aria": "Tableau d'édition groupée des variantes"
+ }
}
},
"promotions": {
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 91755596be..8a54ec6b45 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2041,10 +2041,6 @@
"edit": {
"bulk_prices": {
"no_variants": "Dodaj co najmniej jeden wariant, aby rozpocząć edycję cen."
- },
- "bulk_shipping": {
- "no_variants": "Dodaj co najmniej jeden wariant, aby edytować dane wysyłki.",
- "grid_aria": "Arkusz wysyłki wariantów"
}
},
"inventory": {
@@ -2869,7 +2865,12 @@
"tax_category_placeholder": "Dziedzicz z produktu"
},
"title": "Warianty",
- "variant_label": "Wariant"
+ "variant_label": "Wariant",
+ "bulk_edit": {
+ "trigger": "Edycja zbiorcza",
+ "title": "Edytuj warianty zbiorczo",
+ "grid_aria": "Arkusz zbiorczej edycji wariantów"
+ }
}
},
"promotions": {
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 1202cb3336..69567df658 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2029,10 +2029,6 @@
"edit": {
"bulk_prices": {
"no_variants": "至少添加一个变体以开始编辑价格。"
- },
- "bulk_shipping": {
- "no_variants": "请至少添加一个变体以编辑运输信息。",
- "grid_aria": "变体运输表格"
}
},
"inventory": {
@@ -2827,7 +2823,12 @@
"tax_category_placeholder": "继承自商品"
},
"title": "变体",
- "variant_label": "变体"
+ "variant_label": "变体",
+ "bulk_edit": {
+ "trigger": "批量编辑",
+ "title": "批量编辑变体",
+ "grid_aria": "变体批量编辑表格"
+ }
}
},
"promotions": {
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
index 1391fb90e9..6002019645 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -33,7 +33,6 @@ import {
MediaCard,
PricesCard,
SEOCard,
- ShippingCard,
StatusCard,
TaxCard,
VariantsCard,
@@ -444,7 +443,6 @@ function ProductForm({ product }: { product: Product }) {
<VariantsCard form={form} />
<MediaCard productId={productId} variants={assignableVariants} form={form} />
<PricesCard form={form} productName={product.name} />
- <ShippingCard form={form} />
<InventoryCard form={form} storeId={storeId} />
<ProductCustomFieldsProvider form={form} productTypeId={selectedProductTypeId}>
<CustomFieldsInlineCard />
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
index e96a22e09b..fdbc263bb3 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
@@ -20,7 +20,6 @@ import {
MediaCard,
PricesCard,
SEOCard,
- ShippingCard,
StatusCard,
TaxCard,
VariantsCard,
@@ -185,7 +184,6 @@ function NewProductPage() {
form={form}
productName={form.watch('name') || t('admin.pages.products.new.title')}
/>
- <ShippingCard form={form} />
<InventoryCard form={form} storeId={storeId} />
<ProductCustomFieldsProvider
form={form}