diff --git a/.changeset/7252-form-outcome-toast-supersede.md b/.changeset/7252-form-outcome-toast-supersede.md new file mode 100644 index 0000000000..07abcf2c6c --- /dev/null +++ b/.changeset/7252-form-outcome-toast-supersede.md @@ -0,0 +1,28 @@ +--- +'@object-ui/components': patch +'@object-ui/console': patch +--- + +A form no longer ends on a screen asserting both a failure and a success (objectui#7252). + +A refused submit raised an error toast that nothing ever retired, so when the user +fixed the input and submitted again the confirmation of that second attempt appeared +*beside* the refusal of the first — a wizard's last step showing "Invalid project +status transition." and "Your new project is ready…" at the same time. + +Every outcome toast a form raises now travels under one stable per-form id, so the +later outcome supersedes the earlier one instead of stacking beside it: + +- `@object-ui/components`' form renderer publishes its three outcome toasts (the + field-level rejection, an `onAction` error, and a rejected write) under that id, and + retires the previous attempt's toast in the same place it already cleared the + previous attempt's in-form banner. This is what fixes the reported wizard flow: the + refusal comes from this renderer while the success toast is raised by the host + (`WizardForm` / `ObjectForm`), so no single raiser could supersede the other before. +- the console's own `FormPage` publishes its confirmation and its submit failure under + one id, for the same reason. + +Toast durations are unchanged — this is about supersession, not lifetime. The +objectui#4190 arm is deliberately excluded: a refused redirect *destination* still gets +its own toast, because the write succeeded and that refusal has to stay readable beside +the confirmation it qualifies. diff --git a/apps/console/src/components/FormPage.outcomeToast.test.tsx b/apps/console/src/components/FormPage.outcomeToast.test.tsx new file mode 100644 index 0000000000..274f17e1fc --- /dev/null +++ b/apps/console/src/components/FormPage.outcomeToast.test.tsx @@ -0,0 +1,180 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectui#7252 — a form never ends on a screen that asserts BOTH outcomes. + * + * The card was filed against the console's WIZARD path, where the refusal and + * the confirmation are raised by two different modules (`@object-ui/components`' + * form renderer and `@object-ui/plugin-form`'s `WizardForm`); that end-to-end + * flow is pinned in + * `packages/plugin-form/src/WizardForm.outcomeToastSupersede.test.tsx`. + * + * This page carried the SAME defect in a single function. `handleSubmit` clears + * the `error` banner at the top of every attempt but published its toast under + * sonner's auto-generated id, so nothing here could retire it: a refused submit + * left its toast up, and the confirmation of the retry landed beside it. Both + * outcomes now travel under one per-form id, so the later one supersedes the + * earlier in place. + * + * ## Why the assertion is a registry rather than a call count + * + * `toast.error` was called and `toast.success` was called is true both before + * and after the fix — it is exactly the reading under which the defect looks + * fine. What the card is about is what remains ON SCREEN, so `sonner` is + * replaced by a registry modelling the one behaviour the fix relies on: raising + * a toast under an id the registry already holds REPLACES that entry. + * + * ## Reverse verification — predicted, then measured + * + * Dropping `{ id: outcomeToastId }` from the two submit-outcome toasts turns + * the first test RED (two entries on screen: the refusal and the confirmation) + * and leaves the second one — which asserts that the redirect refusal is NOT + * folded into that id — green, since it never depended on the id at all. + */ + +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { FormPage } from './FormPage'; + +type ToastEntry = { type: string; message: string }; + +const { toastRegistry, fakeToast } = vi.hoisted(() => { + const toastRegistry = new Map(); + let auto = 0; + const raise = + (type: string) => + (message: unknown, options?: { id?: string | number }) => { + // No id is sonner's auto-id — a NEW toast every time, which is precisely + // the pre-fix behaviour that let two outcomes share the screen. + const id = options?.id ?? `auto:${(auto += 1)}`; + toastRegistry.set(id, { type, message: String(message) }); + return id; + }; + const fakeToast = { + success: raise('success'), + error: raise('error'), + info: raise('info'), + warning: raise('warning'), + dismiss: (id?: string | number) => { + if (id === undefined) toastRegistry.clear(); + else toastRegistry.delete(id); + return id; + }, + }; + return { toastRegistry, fakeToast }; +}); + +vi.mock('sonner', () => ({ toast: fakeToast })); + +/** What the submitter can actually see, in the order sonner holds it. */ +const onScreen = (): ToastEntry[] => [...toastRegistry.values()]; + +const publicPayload = (submitBehavior?: unknown) => ({ + slug: 'contact-us', + object: 'showcase_inquiry', + label: 'Contact us', + form: { + type: 'simple', + sections: [{ fields: ['title'] }], + ...(submitBehavior ? { submitBehavior } : {}), + }, + objectSchema: { name: 'showcase_inquiry', fields: { title: { type: 'text', label: 'Title' } } }, +}); + +/** + * Answers the form resolver, then refuses the first N submits with a 400 the + * way the reported flow was refused, and accepts every one after that. + */ +function stubFetchRefusingFirst(refusals: number, payload: Record) { + let posts = 0; + return vi.fn(async (url: string, init?: RequestInit) => { + if (init?.method === 'POST') { + posts += 1; + if (posts <= refusals) { + return { + ok: false, + status: 400, + statusText: 'Bad Request', + text: async () => 'Invalid project status transition.', + json: async () => ({ error: 'Invalid project status transition.' }), + } as unknown as Response; + } + return { + ok: true, + status: 201, + statusText: 'Created', + json: async () => ({ object: 'showcase_inquiry', id: 'inq-1', record: { id: 'inq-1' } }), + text: async () => '{}', + } as unknown as Response; + } + if (!String(url).includes('/forms/')) throw new Error(`unstubbed fetch: ${url}`); + return { + ok: true, + status: 200, + statusText: 'OK', + json: async () => payload, + text: async () => JSON.stringify(payload), + } as unknown as Response; + }); +} + +const renderPublic = () => + render( + + + } /> + + , + ); + +beforeEach(() => { + toastRegistry.clear(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('FormPage — the later submit outcome supersedes the earlier one', () => { + it('leaves only the confirmation after a refused submit is retried and accepted', async () => { + vi.stubGlobal('fetch', stubFetchRefusingFirst(1, publicPayload())); + renderPublic(); + + await screen.findByLabelText(/Title/); + await userEvent.type(screen.getByLabelText(/Title/), 'Ship it'); + + await userEvent.click(screen.getByRole('button', { name: /Submit/ })); + await waitFor(() => expect(onScreen()).toHaveLength(1)); + expect(onScreen()[0].type).toBe('error'); + expect(onScreen()[0].message).toContain('Invalid project status transition.'); + + // The retry the card describes: same form, same page, and it is accepted. + await userEvent.click(screen.getByRole('button', { name: /Submit/ })); + expect(await screen.findByText('Your submission has been received.')).toBeInTheDocument(); + + await waitFor(() => expect(onScreen()).toEqual([{ type: 'success', message: 'Submitted' }])); + }); + + /** + * The objectui#4190 arm is NOT a submit outcome: the write succeeded and only + * the declared destination is out of contract, so its refusal has to stay + * readable BESIDE the confirmation. It therefore keeps its own toast — folding + * it into the shared id would silently delete the confirmation of a write that + * really happened. + */ + it('keeps a refused redirect destination beside the confirmation it qualifies', async () => { + vi.stubGlobal( + 'fetch', + stubFetchRefusingFirst(0, publicPayload({ kind: 'redirect', url: 'https://evil.example/x' })), + ); + renderPublic(); + + await screen.findByLabelText(/Title/); + await userEvent.click(screen.getByRole('button', { name: /Submit/ })); + + await waitFor(() => expect(onScreen()).toHaveLength(2)); + expect(onScreen().map((e) => e.type)).toEqual(['success', 'error']); + }); +}); diff --git a/apps/console/src/components/FormPage.tsx b/apps/console/src/components/FormPage.tsx index b284c40cb7..2de9ac8193 100644 --- a/apps/console/src/components/FormPage.tsx +++ b/apps/console/src/components/FormPage.tsx @@ -103,7 +103,7 @@ * sibling of `@object-ui/plugin-form`'s `omitServerResolvedDefaults`. */ -import { useEffect, useMemo, useState, type FormEvent } from 'react'; +import { useEffect, useId, useMemo, useState, type FormEvent } from 'react'; import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { toast } from 'sonner'; import { @@ -1578,6 +1578,23 @@ export function FormPage({ mode, recordPath }: FormPageProps) { const [loaded, setLoaded] = useState(null); const [values, setValues] = useState>({}); const [submitting, setSubmitting] = useState(false); + /** + * The sonner id this form's submit OUTCOME is published under — one id for + * the confirmation and for the refusal, so the later of the two SUPERSEDES + * the earlier instead of stacking beside it (objectui#7252). + * + * The `error` banner above is already cleared at the top of every attempt; + * its toast was not, because it went out under sonner's auto-generated id and + * nothing here held a handle on it. A refused submit therefore left its toast + * on screen, and the success toast of the retry landed next to it — the form + * ending on a screen that asserted both outcomes at once. + * + * ⚠️ The redirect REFUSAL below deliberately does NOT share this id. That one + * is not a submit outcome: the write succeeded and only the declared + * destination is out of contract, so it has to be readable BESIDE the + * confirmation this id carries, exactly as objectui#4190 ruled. + */ + const outcomeToastId = `form-outcome:${useId()}`; const [submitted, setSubmitted] = useState(false); /** * The outcome of a `redirect` submit behaviour: the in-app route to go to @@ -1681,7 +1698,7 @@ export function FormPage({ mode, recordPath }: FormPageProps) { mode === 'public' ? await submitPublic(identifier, payload) : await submitInternal(loaded.object, payload, editingId); - toast.success('Submitted'); + toast.success('Submitted', { id: outcomeToastId }); // Behaviour after submit switch (behavior.kind) { case 'created-record': { @@ -1766,7 +1783,7 @@ export function FormPage({ mode, recordPath }: FormPageProps) { } catch (err: any) { const msg = err?.message ?? String(err); setError(msg); - toast.error(msg); + toast.error(msg, { id: outcomeToastId }); } finally { setSubmitting(false); } diff --git a/packages/components/src/renderers/form/form.tsx b/packages/components/src/renderers/form/form.tsx index af6f4bc309..5d01245f79 100644 --- a/packages/components/src/renderers/form/form.tsx +++ b/packages/components/src/renderers/form/form.tsx @@ -1130,6 +1130,29 @@ ComponentRegistry.register('form', const [isSubmitting, setIsSubmitting] = React.useState(false); const [submitError, setSubmitError] = React.useState(null); + /** + * The sonner id every OUTCOME toast of THIS form is published under. + * + * The in-form banner (`submitError`) and its toast are raised together at + * each of the three points below, but only the banner was ever retired + * together: the toast went out under sonner's auto-generated id, so nothing + * here held a handle on it and a refused submit's toast outlived the + * attempt that raised it. A later SUCCESSFUL submit — whose success toast a + * host raises (`WizardForm`, `ObjectForm`), not this renderer — then landed + * BESIDE that stale refusal, and the form ended on a screen asserting both + * outcomes at once (objectui#7252). + * + * One stable id closes both halves. Reusing an id sonner already holds + * UPDATES that toast rather than stacking a second one, so every outcome + * this form reports supersedes the one before it; and the dismissal beside + * `setSubmitError(null)` retires it the moment a new attempt starts, so by + * the time any host can confirm a success this form's last refusal is gone. + * + * Scoped to this form instance (`React.useId()`) on purpose: a blanket + * `toast.dismiss()` would take unrelated toasts down with it. + */ + const formInstanceId = React.useId(); + const outcomeToastId = `form-outcome:${formInstanceId}`; // Active `fieldTabs` panel. Undefined until something picks one — the // effective tab falls back to `defaultFieldTab`, then to the first tab. // Which tab of an in-progress form is showing is presentational and dies @@ -1912,7 +1935,7 @@ ComponentRegistry.register('form', const fieldsText = labels.slice(0, MAX).join(t('validation.formInvalidJoiner')) + (labels.length > MAX ? '…' : ''); - toast.error(t('validation.formInvalid', { fields: fieldsText })); + toast.error(t('validation.formInvalid', { fields: fieldsText }), { id: outcomeToastId }); const errored = new Set(names); const firstName = @@ -1948,6 +1971,10 @@ ComponentRegistry.register('form', const handleSubmit = form.handleSubmit(async (data) => { setIsSubmitting(true); setSubmitError(null); + // …and the toast twin of that banner (objectui#7252). Both belong to the + // previous attempt and both are stale now; the toast outliving it is what + // let an earlier refusal share the screen with the success that followed. + toast.dismiss(outcomeToastId); // This attempt cleared client validation — drop the previous attempt's // tab markers (the server may re-add its own below). setRejectedFieldNames([]); @@ -1999,7 +2026,7 @@ ComponentRegistry.register('form', setSubmitError(result.error); // Also surface as a toast so the message is visible even when the // in-form banner has scrolled out of view (long forms in modals/drawers). - toast.error(result.error); + toast.error(result.error, { id: outcomeToastId }); return; } } @@ -2069,7 +2096,7 @@ ComponentRegistry.register('form', setSubmitError(errorMessage); // Also surface as a toast so the message is visible even when the // in-form banner has scrolled out of view (long forms in modals/drawers). - toast.error(errorMessage); + toast.error(errorMessage, { id: outcomeToastId }); // Log errors for debugging (dev environment only) // process may not be defined in all environments diff --git a/packages/plugin-form/src/WizardForm.outcomeToastSupersede.test.tsx b/packages/plugin-form/src/WizardForm.outcomeToastSupersede.test.tsx new file mode 100644 index 0000000000..3e6816345d --- /dev/null +++ b/packages/plugin-form/src/WizardForm.outcomeToastSupersede.test.tsx @@ -0,0 +1,225 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * A form never ends on a screen that asserts BOTH outcomes (objectui#7252). + * + * ## The reported flow, and where the two toasts actually come from + * + * Showcase -> Workspace -> New Project (wizard): the last step's Create was + * refused (400 `VALIDATION_FAILED`, "Invalid project status transition."), the + * user went back a step, changed the status, hit Create again and got a 201 — + * and the refusal was STILL on screen beside the success. + * + * The two toasts are raised by two different modules, which is why neither + * could supersede the other on its own: + * + * - the REFUSAL comes from the step form renderer, `@object-ui/components`'s + * `renderers/form/form.tsx`. `WizardForm` hands it `onSubmit: + * handleStepSubmit`; that handler rethrows a rejected write after calling + * `schema.onError`, so the rejection surfaces in the renderer's own catch, + * which sets the in-form banner AND toasts; + * - the SUCCESS comes from `WizardForm` itself (`toast.success(successMessage + * || 'Created')`). + * + * ## What was actually measured, not assumed + * + * The refusal toast is NOT sticky by configuration. `ConsoleToaster` sets + * `toastOptions.duration: 4000` for every severity, `@object-ui/components`' + * own `Toaster` sets none (sonner's default `TOAST_LIFETIME` is also 4000), and + * `duration: Infinity` appears nowhere on any form path in this repo. So the + * durations are left exactly as they are here: the defect this file pins is + * SUPERSESSION, and it is reproducible inside any lifetime — the two toasts are + * simply unrelated, so nothing retires the first when the second arrives. + * + * ## Why the pin models sonner rather than counting calls + * + * Asserting `toast.error` was called and `toast.success` was called says + * nothing about what is on SCREEN — that is exactly the reading under which the + * defect looks fine. So the module is replaced by a registry modelling the one + * sonner behaviour the fix relies on: a toast raised under an id the registry + * already holds REPLACES that entry, and `dismiss(id)` removes exactly that + * one. The assertion is then the card's own sentence — what remains on screen. + * + * ⚠️ The mock target is `@object-ui/components/ui/sonner`, NOT bare `'sonner'`. + * That wrapper is the single module BOTH raisers reach — the renderer imports + * it as `../../ui/sonner`, and the `toast` `WizardForm` pulls from + * `@object-ui/components` is this module's re-export — and it is the only one + * of the two spellings that resolves from here: `plugin-form` does not depend + * on `sonner`, so `vi.mock('sonner')` in this package registers against an id + * nothing resolves to and intercepts NOTHING (measured: the run went red with + * an EMPTY registry while the in-form banner rendered the refusal, i.e. the + * real sonner had taken both toasts). A green run here is therefore also the + * proof that the mock is in the graph at all. + */ + +import React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; + +type ToastEntry = { type: string; message: string }; + +const { toastRegistry, fakeToast } = vi.hoisted(() => { + const toastRegistry = new Map(); + let auto = 0; + const raise = + (type: string) => + (message: unknown, options?: { id?: string | number }) => { + // No id supplied is sonner's auto-id: a NEW toast every time, which is + // precisely the pre-fix behaviour that let two outcomes coexist. + const id = options?.id ?? `auto:${(auto += 1)}`; + toastRegistry.set(id, { type, message: String(message) }); + return id; + }; + const fakeToast: any = Object.assign(raise('message'), { + success: raise('success'), + error: raise('error'), + info: raise('info'), + warning: raise('warning'), + loading: raise('loading'), + custom: raise('custom'), + promise: (p: unknown) => p, + dismiss: (id?: string | number) => { + if (id === undefined) toastRegistry.clear(); + else toastRegistry.delete(id); + return id; + }, + }); + return { toastRegistry, fakeToast }; +}); + +vi.mock('@object-ui/components/ui/sonner', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, toast: fakeToast }; +}); + +import { registerAllFields } from '@object-ui/fields'; +import { WizardForm } from './WizardForm'; + +registerAllFields(); + +const REFUSAL = 'Invalid project status transition.'; +const SUCCESS = 'Your new project is ready.'; + +const objectSchema = { + name: 'showcase_project', + fields: { + name: { type: 'text', label: 'Name' }, + status: { type: 'text', label: 'Status' }, + }, +}; + +/** Refuses the first create the way the server did, accepts the second. */ +const makeDataSource = () => { + let creates = 0; + return { + getObjectSchema: vi.fn().mockResolvedValue(objectSchema), + create: vi.fn(async (_object: string, data: Record) => { + creates += 1; + if (creates === 1) { + throw Object.assign(new Error(REFUSAL), { status: 400, code: 'VALIDATION_FAILED' }); + } + return { id: 'proj-1', ...data }; + }), + update: vi.fn(), + findOne: vi.fn(), + }; +}; + +const wizard = (dataSource: any) => + render( + , + ); + +const inputNamed = (container: HTMLElement, name: string) => + waitFor(() => { + const el = container.querySelector(`input[name="${name}"]`) as HTMLInputElement | null; + if (!el) throw new Error(`input ${name} not ready`); + return el; + }); + +const submitStep = (container: HTMLElement) => + fireEvent.submit(container.querySelector('form') as HTMLFormElement); + +/** What the user can actually see, in the order sonner holds it. */ +const onScreen = (): ToastEntry[] => [...toastRegistry.values()]; + +beforeEach(() => { + toastRegistry.clear(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('WizardForm — a later outcome supersedes this form’s earlier one', () => { + it('leaves only the success toast after a refused submit is retried and accepted', async () => { + const ds = makeDataSource(); + const { container } = wizard(ds); + + // Step 1 -> Step 2. + fireEvent.change(await inputNamed(container, 'name'), { target: { value: 'Apollo' } }); + submitStep(container); + + // Step 2: Create, refused. + fireEvent.change(await inputNamed(container, 'status'), { target: { value: 'archived' } }); + submitStep(container); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(onScreen()).toEqual([{ type: 'error', message: REFUSAL }])); + + // Back to step 2 of the reported flow, change the status, and Create again. + // The navigation matters: it is what proves the id survives step changes — + // the renderer instance is reused across steps, so the attempt that + // succeeds is the one that must retire the refusal. + fireEvent.click(screen.getByRole('button', { name: /Back/i })); + await inputNamed(container, 'name'); + submitStep(container); + fireEvent.change(await inputNamed(container, 'status'), { target: { value: 'active' } }); + submitStep(container); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(2)); + + // The card's own sentence: one form, one outcome on screen. + await waitFor(() => expect(onScreen()).toEqual([{ type: 'success', message: SUCCESS }])); + }); + + it('does not stack a second refusal when the retry is refused too', async () => { + const ds = makeDataSource(); + // Refuse every attempt this time. + ds.create = vi.fn(async () => { + throw Object.assign(new Error(REFUSAL), { status: 400, code: 'VALIDATION_FAILED' }); + }); + const { container } = wizard(ds); + + fireEvent.change(await inputNamed(container, 'name'), { target: { value: 'Apollo' } }); + submitStep(container); + fireEvent.change(await inputNamed(container, 'status'), { target: { value: 'archived' } }); + + submitStep(container); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(onScreen()).toHaveLength(1)); + + submitStep(container); + await waitFor(() => expect(ds.create).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(onScreen()).toEqual([{ type: 'error', message: REFUSAL }])); + }); +});