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.

Ask before a wizard is dismissed with work in it (#14546)

Damian Legawiecba896cfb43db
diff --git a/packages/dashboard-core/src/components/import-wizard-dialog.tsx b/packages/dashboard-core/src/components/import-wizard-dialog.tsx
index 04a8572499..bc910b41ce 100644
--- a/packages/dashboard-core/src/components/import-wizard-dialog.tsx
+++ b/packages/dashboard-core/src/components/import-wizard-dialog.tsx
@@ -25,6 +25,7 @@ import {
TableHead,
TableHeader,
TableRow,
+ useConfirm,
WizardProgress,
} from '@spree/dashboard-ui'
import {
@@ -74,8 +75,39 @@ interface ImportWizardDialogProps {
* and reopens from the history page (or the same `?import=` URL).
*/
export function ImportWizardDialog({ importId, onClose, onViewRecords }: ImportWizardDialogProps) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ // Only the mapping step holds anything unsaved. Once the import is running
+ // the work is server-side, so closing then is safe and asking would nag.
+ const [mappingUnsaved, setMappingUnsaved] = useState(false)
+
+ async function requestClose() {
+ if (mappingUnsaved) {
+ const discard = await confirm({
+ title: t('admin.components.wizard.discard_title'),
+ message: t('admin.components.wizard.discard_message'),
+ confirmLabel: t('admin.components.wizard.discard_confirm'),
+ cancelLabel: t('admin.components.wizard.discard_cancel'),
+ variant: 'destructive',
+ })
+ if (!discard) return
+ }
+ onClose()
+ }
+
return (
- <Dialog open={!!importId} onOpenChange={(next) => !next && onClose()} modal>
+ <Dialog
+ open={!!importId}
+ onOpenChange={(next, details) => {
+ if (next) return
+ if (details?.reason === 'escape-key' || details?.reason === 'outside-press') {
+ void requestClose()
+ return
+ }
+ onClose()
+ }}
+ modal
+ >
<DialogContent
// Edge-to-edge minus a 3-unit gutter — see BulkPriceEditorDialog for
// why every inset/translate/max is overridden.
@@ -84,7 +116,12 @@ export function ImportWizardDialog({ importId, onClose, onViewRecords }: ImportW
showCloseButton={false}
>
{importId && (
- <ImportWizard importId={importId} onClose={onClose} onViewRecords={onViewRecords} />
+ <ImportWizard
+ importId={importId}
+ onClose={requestClose}
+ onViewRecords={onViewRecords}
+ onMappingDirtyChange={setMappingUnsaved}
+ />
)}
</DialogContent>
</Dialog>
@@ -95,10 +132,13 @@ function ImportWizard({
importId,
onClose,
onViewRecords,
+ onMappingDirtyChange,
}: {
importId: string
onClose: () => void
onViewRecords?: (type: string | null) => void
+ /** Reports whether the mapping has edits the dialog should protect. */
+ onMappingDirtyChange?: (dirty: boolean) => void
}) {
const { t } = useTranslation()
const { data: imp, isLoading, isError, refetch } = useImport(importId)
@@ -121,6 +161,17 @@ function ImportWizard({
}, [imp])
const isMapping = imp?.status === 'mapping'
+
+ useEffect(() => {
+ if (!onMappingDirtyChange) return
+ const edited =
+ !!imp &&
+ imp.status === 'mapping' &&
+ Object.entries(initialAssignments(imp)).some(
+ ([field, column]) => (assignments[field] ?? null) !== (column ?? null),
+ )
+ onMappingDirtyChange(edited)
+ }, [imp, assignments, onMappingDirtyChange])
const isCompleted = imp?.status === 'completed'
const missingRequired = imp && isMapping ? missingRequiredFields(imp, assignments) : []
const retryMutation = useRetryFailedRows(importId)
diff --git a/packages/dashboard-core/src/components/wizard-close-guard.test.ts b/packages/dashboard-core/src/components/wizard-close-guard.test.ts
new file mode 100644
index 0000000000..dbf7ef4428
--- /dev/null
+++ b/packages/dashboard-core/src/components/wizard-close-guard.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from 'vitest'
+
+// The decision table both wizards close by: which reasons ask before
+// discarding and which pass straight through. The components wire this to Base
+// UI's `onOpenChange` reason; `catalogs.spec.ts` covers that wiring in a
+// browser, and this pins the rules themselves.
+function makeHandler(
+ hasUnsavedChanges: boolean,
+ confirm: () => Promise<boolean>,
+ close: () => void,
+) {
+ return async (next: boolean, details?: { reason?: string }) => {
+ if (next) return
+ if (details?.reason === 'escape-key' || details?.reason === 'outside-press') {
+ if (hasUnsavedChanges && !(await confirm())) return
+ close()
+ return
+ }
+ close()
+ }
+}
+
+describe('wizard close guard', () => {
+ it('asks before Escape discards unsaved work', async () => {
+ const confirm = vi.fn().mockResolvedValue(false)
+ const close = vi.fn()
+ await makeHandler(true, confirm, close)(false, { reason: 'escape-key' })
+ expect(confirm).toHaveBeenCalledOnce()
+ expect(close).not.toHaveBeenCalled()
+ })
+
+ it('closes on Escape once discarding is confirmed', async () => {
+ const confirm = vi.fn().mockResolvedValue(true)
+ const close = vi.fn()
+ await makeHandler(true, confirm, close)(false, { reason: 'escape-key' })
+ expect(close).toHaveBeenCalledOnce()
+ })
+
+ it('guards a click outside the wizard too', async () => {
+ const confirm = vi.fn().mockResolvedValue(false)
+ const close = vi.fn()
+ await makeHandler(true, confirm, close)(false, { reason: 'outside-press' })
+ expect(confirm).toHaveBeenCalledOnce()
+ expect(close).not.toHaveBeenCalled()
+ })
+
+ it('does not nag when nothing has been entered', async () => {
+ const confirm = vi.fn()
+ const close = vi.fn()
+ await makeHandler(false, confirm, close)(false, { reason: 'escape-key' })
+ expect(confirm).not.toHaveBeenCalled()
+ expect(close).toHaveBeenCalledOnce()
+ })
+})
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index eff118e048..e6a2066135 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -462,6 +462,12 @@
"label": "المظهر",
"light": "فاتح",
"system": "النظام"
+ },
+ "wizard": {
+ "discard_cancel": "متابعة التحرير",
+ "discard_confirm": "تجاهل",
+ "discard_message": "سيُفقد كل ما أدخلته حتى الآن، ولا يمكن التراجع عن ذلك.",
+ "discard_title": "تجاهل هذه المسودة؟"
}
},
"custom_field_definitions": {
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 83cb4b6312..eb15397857 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -462,6 +462,12 @@
"label": "Design",
"light": "Hell",
"system": "System"
+ },
+ "wizard": {
+ "discard_cancel": "Weiter bearbeiten",
+ "discard_confirm": "Verwerfen",
+ "discard_message": "Alles bisher Eingegebene geht verloren. Das lässt sich nicht rückgängig machen.",
+ "discard_title": "Entwurf verwerfen?"
}
},
"custom_field_definitions": {
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 9771ba56a6..85090239de 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -464,6 +464,12 @@
"label": "Theme",
"light": "Light",
"system": "System"
+ },
+ "wizard": {
+ "discard_cancel": "Keep editing",
+ "discard_confirm": "Discard",
+ "discard_message": "Everything you have filled in so far will be lost. This cannot be undone.",
+ "discard_title": "Discard this draft?"
}
},
"custom_field_definitions": {
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index 4a32b9206f..73e6ee3537 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -462,6 +462,12 @@
"label": "Thème",
"light": "Clair",
"system": "Système"
+ },
+ "wizard": {
+ "discard_cancel": "Continuer",
+ "discard_confirm": "Abandonner",
+ "discard_message": "Tout ce que vous avez saisi sera perdu. Cette action est irréversible.",
+ "discard_title": "Abandonner ce brouillon ?"
}
},
"custom_field_definitions": {
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 1a003c6a3f..2abfe17e47 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -462,6 +462,12 @@
"label": "Motyw",
"light": "Jasny",
"system": "Systemowy"
+ },
+ "wizard": {
+ "discard_cancel": "Wróć do edycji",
+ "discard_confirm": "Odrzuć",
+ "discard_message": "Wszystko, co zostało wprowadzone, zostanie utracone. Nie można tego cofnąć.",
+ "discard_title": "Odrzucić szkic?"
}
},
"custom_field_definitions": {
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index fb2853baad..064fa579e5 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -462,6 +462,12 @@
"label": "主题",
"light": "浅色",
"system": "系统"
+ },
+ "wizard": {
+ "discard_cancel": "继续编辑",
+ "discard_confirm": "放弃",
+ "discard_message": "已填写的内容将全部丢失,且无法恢复。",
+ "discard_title": "放弃此草稿?"
}
},
"custom_field_definitions": {
diff --git a/packages/dashboard-ui/src/spree/wizard.tsx b/packages/dashboard-ui/src/spree/wizard.tsx
index 3439b2af1c..8087d21948 100644
--- a/packages/dashboard-ui/src/spree/wizard.tsx
+++ b/packages/dashboard-ui/src/spree/wizard.tsx
@@ -10,6 +10,7 @@ import {
DialogHeader,
DialogTitle,
} from '../ui/dialog'
+import { useConfirm } from './confirm-dialog'
import { CheckIcon, XIcon } from './icons'
/** One step in a wizard: what it is called, and how far in it sits. */
@@ -128,6 +129,7 @@ export function Wizard({
children,
back,
forward,
+ hasUnsavedChanges = false,
}: {
open: boolean
onOpenChange: (open: boolean) => void
@@ -148,11 +150,44 @@ export function Wizard({
back: ReactNode
/** Next, or the submit on the last step. */
forward: ReactNode
+ /**
+ * Whether closing now would discard the merchant's work. The host decides,
+ * since only it knows what its steps have collected.
+ */
+ hasUnsavedChanges?: boolean
}) {
const { t } = useTranslation()
+ const confirm = useConfirm()
+
+ async function requestClose() {
+ if (hasUnsavedChanges) {
+ const discard = await confirm({
+ title: t('admin.components.wizard.discard_title'),
+ message: t('admin.components.wizard.discard_message'),
+ confirmLabel: t('admin.components.wizard.discard_confirm'),
+ cancelLabel: t('admin.components.wizard.discard_cancel'),
+ variant: 'destructive',
+ })
+ if (!discard) return
+ }
+ onOpenChange(false)
+ }
return (
- <Dialog open={open} onOpenChange={onOpenChange} modal>
+ <Dialog
+ open={open}
+ onOpenChange={(next, details) => {
+ if (next) return onOpenChange(true)
+ // A wizard holds several steps of work, so a stray Escape or a click
+ // past its edge must not throw that away without asking.
+ if (details?.reason === 'escape-key' || details?.reason === 'outside-press') {
+ void requestClose()
+ return
+ }
+ onOpenChange(false)
+ }}
+ modal
+ >
<DialogContent
// Edge-to-edge minus a gutter, like the import wizard and the bulk
// price editor — every inset/translate/max is overridden.
@@ -176,7 +211,7 @@ export function Wizard({
type="button"
size="icon-sm"
variant="ghost"
- onClick={() => onOpenChange(false)}
+ onClick={() => void requestClose()}
aria-label={t('admin.actions.close')}
>
<XIcon />
diff --git a/packages/dashboard/e2e/catalogs.spec.ts b/packages/dashboard/e2e/catalogs.spec.ts
index 6b11128305..e57cbe01f8 100644
--- a/packages/dashboard/e2e/catalogs.spec.ts
+++ b/packages/dashboard/e2e/catalogs.spec.ts
@@ -59,6 +59,51 @@ test.describe('catalogs', () => {
await expect(page.getByText(name)).toBeVisible({ timeout: 15_000 })
})
+ // A wizard holds several steps of work, so dismissing it is not the cheap
+ // action it is for an ordinary dialog.
+ test('confirms before Escape discards a part-filled wizard', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, CATALOGS_PATH(creds.store_id), CTA)
+ await page.getByRole('button', { name: CTA }).click()
+
+ await expect(page.getByRole('heading', { name: /new catalog/i })).toBeVisible()
+ const draftName = `Escape guard ${Date.now()}`
+ await page.locator('#catalog-name').fill(draftName)
+
+ // Escape asks rather than closing, and keeping the draft leaves the work
+ // exactly where it was.
+ await page.keyboard.press('Escape')
+ const confirmDialog = page
+ .getByRole('dialog')
+ .filter({ has: page.getByRole('heading', { name: /discard this draft/i }) })
+ await expect(confirmDialog).toBeVisible()
+ await confirmDialog.getByRole('button', { name: /keep editing/i }).click()
+ await expect(page.getByRole('heading', { name: /new catalog/i })).toBeVisible()
+ // Keeping the draft has to keep the draft, not just the dialog.
+ await expect(page.locator('#catalog-name')).toHaveValue(draftName)
+
+ // Discarding is still one Escape and one confirmation away.
+ await page.keyboard.press('Escape')
+ await confirmDialog.getByRole('button', { name: /^discard$/i }).click()
+ await expect(page.getByRole('heading', { name: /new catalog/i })).toBeHidden({
+ timeout: 15_000,
+ })
+ })
+
+ // Nothing typed, nothing to lose: the wizard should not nag on the way out.
+ test('closes an untouched wizard without asking', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, CATALOGS_PATH(creds.store_id), CTA)
+ await page.getByRole('button', { name: CTA }).click()
+
+ await expect(page.getByRole('heading', { name: /new catalog/i })).toBeVisible()
+
+ await page.keyboard.press('Escape')
+ await expect(page.getByRole('heading', { name: /new catalog/i })).toBeHidden({
+ timeout: 15_000,
+ })
+ })
+
test('stages product membership and persists it on Save', async ({ page }) => {
const creds = await login(page)
await gotoIndex(page, CATALOGS_PATH(creds.store_id), CTA)
diff --git a/packages/dashboard/src/components/spree/catalog-wizard-dialog.tsx b/packages/dashboard/src/components/spree/catalog-wizard-dialog.tsx
index b1d4d6743e..72c97b5293 100644
--- a/packages/dashboard/src/components/spree/catalog-wizard-dialog.tsx
+++ b/packages/dashboard/src/components/spree/catalog-wizard-dialog.tsx
@@ -160,6 +160,9 @@ function CatalogWizard({
steps={steps}
current={step}
onStepSelect={(key: string) => setStep(key as StepKey)}
+ // The assortment is picked outside the form, so a merchant who has only
+ // added products is still part-way through something.
+ hasUnsavedChanges={form.formState.isDirty || products.length > 0}
onSubmit={form.handleSubmit(handleCreate, () =>
form.setError('root', { message: t('admin.catalogs.wizard.fix_this_step') }),
)}