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.

Make the price spreadsheet behave like a spreadsheet

Damian Legawiece33bbac59a8a
diff --git a/packages/dashboard-ui/src/spree/data-grid/cells.tsx b/packages/dashboard-ui/src/spree/data-grid/cells.tsx
index d6fac0b70e..775ccc2aa1 100644
--- a/packages/dashboard-ui/src/spree/data-grid/cells.tsx
+++ b/packages/dashboard-ui/src/spree/data-grid/cells.tsx
@@ -89,6 +89,11 @@ export function NumberCell({
ctx.focusCell(next)
} else if (event.key === 'Escape') {
event.preventDefault()
+ // Base UI's dialog listens for Escape on the document, so preventing
+ // the default is not enough to keep it from closing the sheet behind
+ // this cell: the key has to stop here (docs/plans/6.0-volume-pricing.md).
+ event.stopPropagation()
+ event.nativeEvent.stopImmediatePropagation()
setDraft(value.toString())
ctx.setEditing(null)
} else if (event.key === 'Tab') {
@@ -235,6 +240,11 @@ export function MoneyCell({
ctx.focusCell(next)
} else if (event.key === 'Escape') {
event.preventDefault()
+ // Base UI's dialog listens for Escape on the document, so preventing
+ // the default is not enough to keep it from closing the sheet behind
+ // this cell: the key has to stop here (docs/plans/6.0-volume-pricing.md).
+ event.stopPropagation()
+ event.nativeEvent.stopImmediatePropagation()
setDraft(formatDisplay(value))
ctx.setEditing(null)
} else if (event.key === 'Tab') {
@@ -365,6 +375,11 @@ export function TextCell({ coords, value, onChange, ariaLabel }: TextCellProps)
ctx.focusCell(next)
} else if (event.key === 'Escape') {
event.preventDefault()
+ // Base UI's dialog listens for Escape on the document, so preventing
+ // the default is not enough to keep it from closing the sheet behind
+ // this cell: the key has to stop here (docs/plans/6.0-volume-pricing.md).
+ event.stopPropagation()
+ event.nativeEvent.stopImmediatePropagation()
setDraft(value ?? '')
ctx.setEditing(null)
} else if (event.key === 'Tab') {
diff --git a/packages/dashboard-ui/src/spree/data-grid/data-grid.tsx b/packages/dashboard-ui/src/spree/data-grid/data-grid.tsx
index f64444ecca..0462e9e8b6 100644
--- a/packages/dashboard-ui/src/spree/data-grid/data-grid.tsx
+++ b/packages/dashboard-ui/src/spree/data-grid/data-grid.tsx
@@ -68,6 +68,10 @@ function DataGridShell<T>({
const cellsRef = useRef<Map<CellKey, CellRegistration>>(new Map())
const [bounds, setBounds] = useState<{ maxRow: number; maxCol: number }>({ maxRow: 0, maxCol: 0 })
const [anchor, setAnchor] = useState<CellCoords | null>(null)
+ // Read by the blur handler, which fires from a DOM event and would
+ // otherwise close over a stale anchor.
+ const anchorRef = useRef<CellCoords | null>(null)
+ anchorRef.current = anchor
const [extent, setExtent] = useState<CellCoords | null>(null)
const [editing, setEditing] = useState<CellCoords | null>(null)
@@ -93,11 +97,27 @@ function DataGridShell<T>({
const focusCell = useCallback((coords: CellCoords) => {
const target = cellsRef.current.get(cellKey(coords))
- if (target) {
- target.focus()
- return
- }
+ // Focus now if the cell is already there, but ask again once the render
+ // this commit triggers has settled. Committing an edit re-renders the
+ // row, and React replaces the input we just focused — inside a dialog
+ // the browser then falls back to the dialog itself, which leaves nothing
+ // holding the selection and the arrow keys dead until the merchant
+ // clicks a cell (docs/plans/6.0-volume-pricing.md).
+ target?.focus()
pendingFocusRef.current = coords
+ requestAnimationFrame(() => {
+ const pending = pendingFocusRef.current
+ if (!pending || cellKey(pending) !== cellKey(coords)) return
+ pendingFocusRef.current = null
+ const cell = cellsRef.current.get(cellKey(coords))
+ if (cell) {
+ cell.focus()
+ return
+ }
+ // No cell to focus — keep the keyboard in the grid rather than letting
+ // it fall back to whatever contains it.
+ gridRef.current?.focus()
+ })
}, [])
const registerCell = useCallback(
@@ -160,16 +180,44 @@ function DataGridShell<T>({
<div className="relative overflow-hidden rounded-md">
<table
ref={gridRef}
+ // Focusable so the grid itself can hold the keyboard when a cell's
+ // input goes away. Committing an edit re-renders the row and React
+ // replaces that input; inside a dialog the focus trap then pulls
+ // focus to the dialog, which is outside the grid, and every arrow
+ // key after it lands on nothing (docs/plans/6.0-volume-pricing.md).
+ tabIndex={-1}
className={cn(
- 'w-full border-collapse text-sm [&_td]:border [&_th]:border [&_td]:border-border [&_th]:border-border',
+ 'w-full border-collapse text-sm outline-none [&_td]:border [&_th]:border [&_td]:border-border [&_th]:border-border',
className,
)}
aria-label={ariaLabel}
onBlurCapture={(e) => {
- // If focus leaves the grid entirely, drop the selection so a
- // fresh focus-in starts clean.
+ // A cell unmounting mid-commit is not the merchant leaving the
+ // grid: `relatedTarget` is null there, and the dialog's focus
+ // trap then claims the focus a frame later. Take it back on the
+ // spot and keep the selection, rather than racing that trap on a
+ // timer (docs/plans/6.0-volume-pricing.md).
const next = e.relatedTarget as Node | null
if (next && gridRef.current?.contains(next)) return
+ // Two hops the merchant did not ask for, both caused by a cell
+ // being replaced mid-commit: the browser dropping focus
+ // (`relatedTarget` null), and the surrounding dialog's focus trap
+ // then claiming it. Neither means the grid was left, so keep the
+ // selection and take the keyboard back.
+ const trapped =
+ next === null ||
+ (next instanceof Element &&
+ next.closest('[role="dialog"]')?.contains(gridRef.current ?? null) === true)
+ if (trapped) {
+ // After this event resolves, or the trap that prompted it wins.
+ if (anchorRef.current) {
+ queueMicrotask(() => gridRef.current?.focus({ preventScroll: true }))
+ }
+ return
+ }
+ // Focus moved somewhere real outside the grid — the merchant is
+ // done here, so drop the selection and let a fresh focus-in start
+ // clean.
setAnchor(null)
setExtent(null)
setEditing(null)
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor-dialog.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor-dialog.tsx
index 21cb681e0c..e972b6288a 100644
--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor-dialog.tsx
+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor-dialog.tsx
@@ -87,7 +87,13 @@ export function BulkPriceEditorDialog({
const isSaving = editorState.saving
const handleOpenChange = useCallback(
- async (next: boolean) => {
+ async (next: boolean, reason?: string) => {
+ // Escape belongs to the cell being edited, where it reverts what was
+ // typed. A merchant leaving a cell that way does not expect the sheet
+ // itself to close and take every other unsaved price with it — closing
+ // is the ✕ and the buttons beside it
+ // (docs/plans/6.0-volume-pricing.md).
+ if (!next && reason === 'escape-key') return
if (next) {
onOpenChange(true)
return
@@ -138,7 +144,11 @@ export function BulkPriceEditorDialog({
})
return (
- <Dialog open={open} onOpenChange={(next) => handleOpenChange(next)} modal>
+ <Dialog
+ open={open}
+ onOpenChange={(next, eventDetails) => handleOpenChange(next, eventDetails?.reason)}
+ modal
+ >
<DialogContent
// Edge-to-edge minus a 3-unit (0.75rem) gutter on all sides.
// The primitive ships `top-1/2 left-1/2 -translate-1/2` (centered
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
index e51e900b79..3ce21206f4 100644
--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
@@ -45,6 +45,15 @@ interface CellEdit {
minQuantity?: string
amount: string | null
compareAt: string | null
+ // Set only by the row's remove control. A blank amount is how the bulk
+ // endpoint is told to drop a rung, so it is also what a half-typed row
+ // looks like — this is what tells the two apart.
+ removing?: true
+ // The quantity this rung is stored under, when the merchant has since
+ // changed it. The bulk endpoint keys on the quantity, so a moved rung is an
+ // insert at the new one — the row at the old quantity has to be cleared by
+ // name or the ladder keeps both (docs/plans/6.0-volume-pricing.md).
+ storedMinQuantity?: string
}
// BulkPriceRow extended with the server-side variantId so save can ship the
@@ -416,9 +425,12 @@ export function BulkPriceEditor({
const edit = edits.get(r.priceId ?? r.id)
if (!edit) return r
// A tier row edits the same two things a variant row does, minus the
- // compare-at it has no column for.
+ // compare-at it has no column for. Its quantity comes from the edit
+ // too: a stored rung renders the server's number, so leaving it out
+ // meant a retyped quantity was overwritten by the old one the moment
+ // the cell left edit mode.
return r.kind === 'tier'
- ? { ...r, amount: edit.amount }
+ ? { ...r, minQuantity: edit.minQuantity, amount: edit.amount }
: { ...r, amount: edit.amount, compareAt: edit.compareAt }
}),
[baselineRows, edits],
@@ -472,10 +484,22 @@ export function BulkPriceEditor({
amount: displayBaseAmount,
compareAt: displayBaseCompare,
}
- // Re-read the quantity on every merge: a draft rung's quantity is
- // typed after its price cell may already hold an edit, and the save
- // payload needs whatever it says now.
- const merged = { ...current, minQuantity: baseline.minQuantity, [field]: next }
+ // An edit already holding a quantity keeps it: the merchant may have
+ // typed the quantity first, and the baseline still says what the
+ // server last stored. Only a rung with no edit yet takes its quantity
+ // from the row.
+ const merged = {
+ ...current,
+ minQuantity: prev.get(targetId)?.minQuantity ?? baseline.minQuantity,
+ [field]: next,
+ // Blanking the price of a rung the server already has is how it is
+ // deleted, the same as the row's remove control. On a rung that was
+ // never stored there is nothing to delete — it is simply unfinished,
+ // and the save refuses it rather than reporting a removal.
+ ...(field === 'amount'
+ ? { removing: !next && baseline.priceId ? (true as const) : undefined }
+ : {}),
+ }
if (merged.amount === displayBaseAmount && merged.compareAt === displayBaseCompare) {
const out = new Map(prev)
out.delete(targetId)
@@ -512,6 +536,10 @@ export function BulkPriceEditor({
const existing = prev.get(targetId)
const out = new Map(prev)
+ // The quantity the server has for this rung, remembered from the
+ // first edit so retyping the cell repeatedly still clears the one
+ // original row rather than the previous keystroke's value.
+ const stored = existing?.storedMinQuantity ?? (row.priceId ? row.minQuantity : undefined)
// Moving a stored rung's quantity is an edit in its own right, and a
// draft's quantity is what makes it addressable at all — so either
// way the row joins the sheet's unsaved changes.
@@ -520,6 +548,8 @@ export function BulkPriceEditor({
minQuantity: value,
amount: existing?.amount ?? row.amount ?? null,
compareAt: existing?.compareAt ?? null,
+ // Back at its original quantity there is nothing to clear.
+ ...(stored && stored !== value ? { storedMinQuantity: stored } : {}),
})
return out
})
@@ -551,6 +581,7 @@ export function BulkPriceEditor({
minQuantity: row.minQuantity,
amount: null,
compareAt: null,
+ removing: true,
})
return out
})
@@ -573,6 +604,24 @@ export function BulkPriceEditor({
.filter(([id, edit]) => !(id.startsWith('draft:') && !edit.minQuantity && !edit.amount))
.map(([id]) => id)
if (savedKeys.length === 0) return false
+
+ // A rung with a quantity but no price is unfinished, not a deletion. The
+ // bulk endpoint reads a blank amount as "remove this rung", so sending it
+ // would answer a half-typed row by quietly discarding it — with a success
+ // toast (docs/plans/6.0-volume-pricing.md). Say what is missing instead.
+ const incomplete = savedKeys.find((key) => {
+ const edit = edits.get(key)
+ return edit != null && !edit.removing && Boolean(edit.minQuantity) && !edit.amount
+ })
+ if (incomplete) {
+ toastManager.add({
+ type: 'error',
+ title: t('admin.pages.products.price_lists.edit_prices.tier_needs_price', {
+ quantity: edits.get(incomplete)?.minQuantity ?? '',
+ }),
+ })
+ return false
+ }
// Ship the unique-key triple `(variant_id, currency, price_list_id)`
// — that's what the server upserts on. `id` is not used by the bulk
// endpoint; we already have the lookup columns on screen so there's
@@ -586,9 +635,9 @@ export function BulkPriceEditor({
const normalized = normalizeMoneyInput(v, marketLocale || 'en')
return normalized === '' ? null : normalized
}
- const payload: PriceBulkUpsertRow[] = savedKeys.map((priceId) => {
+ const payload: PriceBulkUpsertRow[] = savedKeys.flatMap((priceId) => {
const edit = edits.get(priceId) as CellEdit
- return {
+ const row: PriceBulkUpsertRow = {
variant_id: edit.variantId,
currency,
...(priceListId ? { price_list_id: priceListId } : {}),
@@ -599,6 +648,20 @@ export function BulkPriceEditor({
// price for a contracted figure.
...(edit.minQuantity ? {} : { compare_at_amount: toCanonical(edit.compareAt) }),
}
+ // A rung whose quantity moved is an insert at the new one, since that
+ // is what the endpoint keys on — so the row it left behind is cleared
+ // in the same batch, or the merchant ends up with the rung twice.
+ if (!edit.storedMinQuantity) return [row]
+ return [
+ row,
+ {
+ variant_id: edit.variantId,
+ currency,
+ ...(priceListId ? { price_list_id: priceListId } : {}),
+ min_quantity: Number(edit.storedMinQuantity),
+ amount: null,
+ },
+ ]
})
try {
const res = await bulkUpsertAsync({ prices: payload })
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index e4835e23ab..020f0c8f19 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -3379,6 +3379,7 @@
"save_success_one": "تم الحفظ {{count}} السعر",
"save_success_other": "تم الحفظ {{count}} الأسعار",
"search_placeholder": "البحث حسب المنتج، SKU، أو الخيار…",
+ "tier_needs_price": "أدخل سعرًا لشريحة الكمية التي تبدأ من {{quantity}}، أو امسح الكمية لإزالتها.",
"title": "تعديل الأسعار — {{name}}",
"variant_default": "تقصير"
},
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 5fa170e730..8ae97f0322 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -3362,6 +3362,7 @@
"save_success_one": "{{count}} Preis gespeichert",
"save_success_other": "{{count}} Preise gespeichert",
"search_placeholder": "Nach Produkt, SKU oder Option suchen…",
+ "tier_needs_price": "Geben Sie einen Preis für die Mengenstaffel ab {{quantity}} ein, oder löschen Sie die Menge, um sie zu entfernen.",
"title": "Preise bearbeiten — {{name}}",
"variant_default": "Standard"
},
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index f9bfaa9576..338ed96b97 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -3362,6 +3362,7 @@
"save_success_one": "Saved {{count}} price",
"save_success_other": "Saved {{count}} prices",
"search_placeholder": "Search by product, SKU, or option…",
+ "tier_needs_price": "Enter a price for the quantity break starting at {{quantity}}, or clear the quantity to remove it.",
"title": "Edit prices — {{name}}",
"variant_default": "Default"
},
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 2f720daddd..a4c32453cb 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -3362,6 +3362,7 @@
"save_success_one": "{{count}} prix enregistré",
"save_success_other": "{{count}} prix enregistrés",
"search_placeholder": "Rechercher par produit, SKU ou option…",
+ "tier_needs_price": "Saisissez un prix pour le palier de quantité à partir de {{quantity}}, ou effacez la quantité pour le supprimer.",
"title": "Modifier les prix — {{name}}",
"variant_default": "Par défaut"
},
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 653e79f592..d3a89660b9 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -3402,6 +3402,7 @@
"save_success_one": "Zapisano {{count}} cenę",
"save_success_other": "Zapisano {{count}} cen",
"search_placeholder": "Szukaj po produkcie, SKU lub opcji…",
+ "tier_needs_price": "Podaj cenę dla progu ilościowego od {{quantity}} lub wyczyść ilość, aby go usunąć.",
"title": "Edytuj ceny — {{name}}",
"variant_default": "Domyślny"
},
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 2000ad944a..d579595b2e 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -3354,6 +3354,7 @@
"save_success_one": "已保存 {{count}} 个价格",
"save_success_other": "已保存 {{count}} 个价格",
"search_placeholder": "按商品、SKU 或选项搜索…",
+ "tier_needs_price": "请为从 {{quantity}} 起的数量阶梯输入价格,或清除数量以将其移除。",
"title": "编辑价格 — {{name}}",
"variant_default": "默认"
},