Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .changeset/7345-master-detail-outcome-toast.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
'@object-ui/plugin-form': patch
---

A master-detail form no longer ends on a screen asserting both a failure and a success
(objectui#7345).

`MasterDetailForm` raised its two save outcomes — `handleSaved`'s confirmation and
`handleError`'s refusal — under sonner's auto-generated ids, so nothing held a handle on
the previous attempt's toast. A save the server refused left its error toast on screen,
and when the user corrected the input and saved again inside that toast's lifetime the
confirmation landed *beside* the refusal, exactly the objectui#7252 defect on a renderer
that fix did not touch.

Both outcomes now travel under one stable per-form id (`React.useId()`-scoped, the same
spelling the form renderer and the console's `FormPage` publish under), and each save
attempt retires the previous attempt's toast before it starts:

- with no host `onSuccess` (SDUI / embedded hosts), the confirmation supersedes the
refusal instead of stacking beside it;
- with a host `onSuccess` (the console), where the built-in confirmation is deliberately
skipped, the dismissal is what retires the refusal — otherwise it stood over a save
that had succeeded.

Toast durations are unchanged: this is about supersession, not lifetime.
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
/**
* 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 master-detail form never ends on a screen that asserts BOTH outcomes
* (objectui#7345 — the objectui#7252 defect class, on a renderer PR #7342 did
* not touch).
*
* ## Where the two toasts come from here
*
* Unlike the wizard (whose refusal came from the step renderer and whose
* success came from `WizardForm`), BOTH outcomes of a master-detail save are
* raised by `MasterDetailForm` itself, one line apart:
*
* - `handleSaved` -> `toast.success('Created' | '<title> saved')`;
* - `handleError` -> `toast.error(err.message || 'Save failed')`.
*
* Neither carried a sonner id, so each went out under sonner's auto-generated
* one and nothing here held a handle on the previous attempt's toast. A save
* the server refused left its error toast on screen, and the confirmation of
* the corrected retry landed BESIDE it.
*
* ## The two paths, and why both are pinned
*
* 1. **No host `onSuccess`** (SDUI / embedded): the built-in success toast is
* the fallback, so the shared id is what makes the confirmation SUPERSEDE
* the refusal instead of stacking beside it.
* 2. **Host supplies `onSuccess`** (the console): the built-in success toast is
* deliberately skipped, so a shared id alone would retire nothing — the
* refusal would outlive a save that SUCCEEDED. The `toast.dismiss` at the
* start of each attempt is what closes that half, which is why it is part of
* the shape and not decoration.
*
* The parent `<ObjectForm>`'s own renderer also toasts a rejected write, under
* its OWN `form-outcome:` id, and retires it at the top of the next submit
* (objectui#7252). That toast is therefore already superseded and is not what
* this file pins; it is visible in the pre-fix registry below as the second
* error entry.
*
* ## 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 every raiser here reaches — the `toast`
* `MasterDetailForm` pulls from `@object-ui/components` is this module's
* re-export (`src/index.ts` -> `export * from './ui'` -> `./ui/sonner`) — 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.
* A green run here is therefore also the proof that the mock is in the graph.
*/

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<string | number, { type: string; message: string }>();
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<any>();
return { ...actual, toast: fakeToast };
});

import { registerAllFields } from '@object-ui/fields';
import { MasterDetailForm } from './MasterDetailForm';

registerAllFields();

const REFUSAL = 'Line 2 quantity exceeds the remaining allocation.';

const parentObjectSchema = { name: 'po', fields: { ref: { type: 'text', label: 'Ref' } } };

/** Refuses the first save the way the server did, accepts the second. */
const makeDataSource = (overrides: Record<string, unknown> = {}) => {
let saves = 0;
return {
getObjectSchema: vi.fn().mockResolvedValue(parentObjectSchema),
find: vi.fn().mockResolvedValue({ data: [] }),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
bulk: vi.fn(),
batchTransaction: vi.fn(async () => {
saves += 1;
if (saves === 1) {
throw Object.assign(new Error(REFUSAL), { status: 400, code: 'VALIDATION_FAILED' });
}
return { results: [{ id: 'po1' }] };
}),
...overrides,
} as any;
};

const masterDetail = (dataSource: any, extraSchema: Record<string, unknown> = {}) =>
render(
<MasterDetailForm
schema={
{
type: 'object-master-detail-form',
objectName: 'po',
mode: 'create',
fields: ['ref'],
details: [
{
childObject: 'po_line',
relationshipField: 'po',
columns: [{ key: 'qty', label: 'Qty', type: 'number' } as any],
},
],
...extraSchema,
} as any
}
dataSource={dataSource as any}
/>,
);

const headerInput = (container: HTMLElement) =>
waitFor(() => {
const el = container.querySelector('input[name="ref"]') as HTMLInputElement | null;
if (!el) throw new Error('parent form not ready');
return el;
});

/** Drive the bottom action bar's single Save/Create button. */
const save = () => fireEvent.click(screen.getByRole('button', { name: /create/i }));

/** What the user can actually see, in the order sonner holds it. */
const onScreen = (): ToastEntry[] => [...toastRegistry.values()];

/**
* What the screen SAYS, with each distinct statement counted once.
*
* Measured, not assumed: a refused master-detail save currently puts the SAME
* refusal on screen twice — `handleError` here raises one, and the parent
* `<ObjectForm>`'s renderer raises its own for the write it re-threw. That
* duplication is a separate defect from the one this file pins (it is filed
* out of scope), so the assertions below deliberately do not depend on HOW MANY
* raisers reported an outcome — only on WHICH outcomes remain readable.
*/
const distinctOnScreen = (): ToastEntry[] => {
const seen = new Map<string, ToastEntry>();
for (const t of onScreen()) seen.set(`${t.type}:${t.message}`, t);
return [...seen.values()];
};

beforeEach(() => {
toastRegistry.clear();
});

afterEach(() => {
cleanup();
});

describe('MasterDetailForm — a later save outcome supersedes this form’s earlier one', () => {
it('leaves only the success toast after a refused save is retried and accepted', async () => {
const ds = makeDataSource();
const { container } = masterDetail(ds);

fireEvent.change(await headerInput(container), { target: { value: 'PO-1' } });
save();
await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(1));
await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }]));

// The user corrects the input and saves again inside the refusal's lifetime.
fireEvent.change(await headerInput(container), { target: { value: 'PO-1b' } });
save();
await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(2));

// The card's own sentence: one form, one outcome on screen.
await waitFor(() => expect(onScreen()).toEqual([{ type: 'success', message: 'Created' }]));
});

it('retires the refusal even when the host owns confirmation (no built-in success toast)', async () => {
// The console path: `onSuccess` is supplied, so the built-in success toast
// is deliberately skipped. A shared id alone would retire NOTHING here —
// the refusal of the first attempt would outlive a save that succeeded.
// The dismissal at the start of each attempt is what closes this half.
const onSuccess = vi.fn();
const ds = makeDataSource();
const { container } = masterDetail(ds, { onSuccess });

fireEvent.change(await headerInput(container), { target: { value: 'PO-2' } });
save();
await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(1));
await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }]));

fireEvent.change(await headerInput(container), { target: { value: 'PO-2b' } });
save();
await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(2));
await waitFor(() => expect(onSuccess).toHaveBeenCalled());

// Nothing left asserting the save was refused.
await waitFor(() => expect(onScreen()).toEqual([]));
});

it('does not stack a second refusal when the retry is refused too', async () => {
const ds = makeDataSource({
batchTransaction: vi.fn(async () => {
throw Object.assign(new Error(REFUSAL), { status: 400, code: 'VALIDATION_FAILED' });
}),
});
const { container } = masterDetail(ds);

fireEvent.change(await headerInput(container), { target: { value: 'PO-3' } });
save();
await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(1));
await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }]));
// How many raisers reported this refusal is not this file's subject; that
// the SECOND attempt adds none of its own is.
const afterFirstAttempt = onScreen().length;

fireEvent.change(await headerInput(container), { target: { value: 'PO-3b' } });
save();
await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(2));
await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }]));
expect(onScreen()).toHaveLength(afterFirstAttempt);
});
});
6 changes: 5 additions & 1 deletion packages/plugin-form/src/MasterDetailForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import { MasterDetailForm } from './MasterDetailForm';
const { toastSuccess, toastError } = vi.hoisted(() => ({ toastSuccess: vi.fn(), toastError: vi.fn() }));
vi.mock('@object-ui/components', async (orig) => {
const actual = await (orig as any)();
return { ...actual, toast: { success: toastSuccess, error: toastError } };
// Inherit the real toast surface and override only what this file asserts:
// a hand-listed double freezes sonner's methods at whatever was typed that
// day, and the next one the form calls (`dismiss`, objectui#7345) resolves
// to undefined — the `check:vi-mock-inherit` defect, one level down.
return { ...actual, toast: { ...actual.toast, success: toastSuccess, error: toastError } };
});

registerAllFields();
Expand Down
41 changes: 36 additions & 5 deletions packages/plugin-form/src/MasterDetailForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,31 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
const [saving, setSaving] = useState(false);
const savingRef = useRef(false);
const saveGuardTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
/**
* The sonner id BOTH save outcomes of THIS form are published under.
*
* `handleSaved` and `handleError` below each raised their toast under
* sonner's auto-generated id, so nothing here held a handle on the previous
* attempt's. A save the server refused left its error toast on screen, and
* when the user corrected the input and saved again inside that toast's
* lifetime the confirmation landed BESIDE the refusal — the form ending on a
* screen that asserted both outcomes at once (objectui#7345, the
* objectui#7252 defect class).
*
* One stable id closes both halves. Reusing an id sonner already holds
* UPDATES that toast rather than stacking a second one, so the later outcome
* supersedes the earlier; and the dismissal at the top of `handleSave`
* retires it the moment a new attempt starts — which is the half that matters
* when a host supplies `onSuccess`, because the built-in confirmation is then
* skipped and a shared id alone would leave the stale refusal standing over a
* save that succeeded.
*
* Scoped to this form instance (`React.useId()`) on purpose: a blanket
* `toast.dismiss()` would take unrelated toasts down with it. Same spelling
* the form renderer and the console's `FormPage` publish under (#7342).
*/
const formInstanceId = React.useId();
const outcomeToastId = `form-outcome:${formInstanceId}`;
const releaseSave = useCallback(() => {
savingRef.current = false;
setSaving(false);
Expand Down Expand Up @@ -828,7 +853,9 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
async (parent: any) => {
releaseSave();
if (!schema.onSuccess) {
toast.success(isEdit ? (schema.title ? `${schema.title} saved` : 'Saved') : 'Created');
toast.success(isEdit ? (schema.title ? `${schema.title} saved` : 'Saved') : 'Created', {
id: outcomeToastId,
});
}
if (!isEdit) {
// Every collection back to empty for the next entry. Dropping the whole
Expand All @@ -840,17 +867,17 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
await schema.onSuccess?.(parent);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isEdit, schema.onSuccess, schema.title, entries.length, releaseSave],
[isEdit, schema.onSuccess, schema.title, entries.length, releaseSave, outcomeToastId],
);

/** Surface failures (validation / network / atomic rollback) to the user. */
const handleError = useCallback(
(err: Error) => {
releaseSave();
toast.error(err?.message || 'Save failed');
toast.error(err?.message || 'Save failed', { id: outcomeToastId });
schema.onError?.(err);
},
[schema, releaseSave],
[schema, releaseSave, outcomeToastId],
);

// Persistence ALWAYS goes through dataSource.batchTransaction: the parent and
Expand Down Expand Up @@ -950,6 +977,10 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
if (!form) return;
savingRef.current = true;
setSaving(true);
// The previous attempt's outcome belongs to the previous attempt: retire it
// the moment a new one starts, so no host can confirm a success while this
// form's last refusal is still on screen (objectui#7345).
toast.dismiss(outcomeToastId);
// IMPORTANT: defer the submit out of this click's React dispatch AND
// re-query the <form> inside the timer. Calling requestSubmit()
// synchronously inside the onClick (or on a form reference captured before
Expand All @@ -965,7 +996,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
// onSuccess/onError, which would otherwise leave the button stuck. Release
// the guard after a beat so the user can correct fields and retry.
saveGuardTimer.current = setTimeout(() => releaseSave(), 1500);
}, [releaseSave]);
}, [releaseSave, outcomeToastId]);

useEffect(() => () => { if (saveGuardTimer.current) clearTimeout(saveGuardTimer.current); }, []);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ import './index';

vi.mock('@object-ui/components', async (orig) => {
const actual = await (orig as any)();
return { ...actual, toast: { success: vi.fn(), error: vi.fn() } };
// Inherit the real toast surface (see MasterDetailForm.test.tsx): a
// hand-listed double leaves every other sonner method undefined.
return { ...actual, toast: { ...actual.toast, success: vi.fn(), error: vi.fn() } };
});

registerAllFields();
Expand Down
Loading
Loading