diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index 47abaea5..406b7300 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -111,7 +111,10 @@ export function useAppForm< const [result, setResult] = useState("idle"); const [statusFailure, setStatusFailure] = useState(null); const pendingRef = useRef | null> | null>(null); - const unknownSubmissionRef = useRef(null); + // The save whose effect is unknown: what it sent, or `values: null` when + // an earlier mount sent it (a resend from a remounted form). Held, it keeps + // a new save from going out as a new request. + const unknownSubmissionRef = useRef | null>(null); // 1103/08-02. A save that ends in neither a field error nor success shows // its status above the form while the page disables the button that had // focus, so the browser drops focus to the body. The status takes focus @@ -231,22 +234,30 @@ export function useAppForm< [defaultValues, resetOnSuccess], ); + /** + * The save went through, with values this form did not send: an earlier + * mount sent them. 1106/08-01. The confirmed save is shown, and focus, + * lost with the button that confirmed it, goes to the feedback area that + * shows it. The values on screen were never sent, so they and the dirty + * state stay as they are (diff review of 1106/08-01). + */ + const settleUnsentValues = useCallback(() => { + unknownSubmissionRef.current = null; + focusFeedbackRef.current = focusIsLost(); + setFieldErrors({} as FieldErrors); + setFormErrors([]); + setResult("success"); + }, []); + const settleApplied = useCallback(() => { - const submittedValues = unknownSubmissionRef.current; - if (!submittedValues) { - // 1106/08-01. After a remount the form no longer holds the submitted - // values. The confirmed save is shown, and focus, lost with the - // confirm button, goes to the feedback area that shows it. The values - // on screen were never sent, so they and the dirty state stay as they - // are (diff review of 1106/08-01). - focusFeedbackRef.current = focusIsLost(); - setFieldErrors({} as FieldErrors); - setFormErrors([]); - setResult("success"); + const submittedValues = unknownSubmissionRef.current?.values ?? null; + if (submittedValues === null) { + // After a remount the form no longer holds the submitted values. + settleUnsentValues(); return; } settleSuccessfulValues(submittedValues); - }, [settleSuccessfulValues]); + }, [settleSuccessfulValues, settleUnsentValues]); const settleNotApplied = useCallback(() => { if (!unknownSubmissionRef.current) return; @@ -256,10 +267,19 @@ export function useAppForm< setResult("idle"); }, []); + /** + * `submittedValues` is null when this form did not send the request the + * outcome answers (a resend after a remount): a success then keeps the + * values on screen, and a result left unknown holds no values either. + */ const applyOutcome = useCallback( - (outcome: FormResult, submittedValues: Values) => { + (outcome: FormResult, submittedValues: Values | null) => { + const settleSaved = () => + submittedValues === null + ? settleUnsentValues() + : settleSuccessfulValues(submittedValues); if (outcome.ok) { - settleSuccessfulValues(submittedValues); + settleSaved(); return; } const refusal = refusalFor(refusalMessages, outcome.error); @@ -303,13 +323,13 @@ export function useAppForm< setResult("reauth-required"); } else if (outcome.error.effect === "MAYBE_APPLIED") { focusFeedbackRef.current = true; - unknownSubmissionRef.current = submittedValues; + unknownSubmissionRef.current = { values: submittedValues }; setFormErrors([]); // 0929/08-04. Kept for its request id, not shown as a status. setStatusFailure(outcome.error); setResult("effect-unknown"); } else if (outcome.error.effect === "APPLIED_CONFIRMED") { - settleSuccessfulValues(submittedValues); + settleSaved(); } else if (outcome.error.kind === "CONFLICT") { focusFeedbackRef.current = true; unknownSubmissionRef.current = null; @@ -341,6 +361,7 @@ export function useAppForm< focusFirstError, refusalMessages, settleSuccessfulValues, + settleUnsentValues, ], ); @@ -421,15 +442,16 @@ export function useAppForm< send: () => Promise | null>, ): Promise | null> => { if (pendingRef.current) return pendingRef.current; - // After a remount the form no longer holds the submitted values. - const submittedValues = unknownSubmissionRef.current ?? values; + // After a remount the form no longer holds the submitted values, and + // the values on screen were never sent (1106/03-01 diff review FR-03). + const submittedValues = unknownSubmissionRef.current?.values ?? null; const resend = (async () => { setPending(true); try { const outcome = await send(); if (outcome && resendLeftUnknown(outcome)) { focusFeedbackRef.current = true; - unknownSubmissionRef.current = submittedValues; + unknownSubmissionRef.current = { values: submittedValues }; setFieldErrors({} as FieldErrors); setFormErrors(["form.resendLater"]); setResult("effect-unknown"); @@ -446,7 +468,7 @@ export function useAppForm< pendingRef.current = resend; return resend; }, - [applyOutcome, values], + [applyOutcome], ); return Object.freeze({ diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 0b9d18b6..0324f8fd 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -165,6 +165,11 @@ function FormHarness(props: Readonly<{ >; resetOnSuccess?: boolean; onFailureAction?(): void; + /** Resends the save an earlier mount left unknown (`resendUnknown`). */ + resend?(): Promise< + | Readonly<{ ok: true; value: string }> + | Readonly<{ ok: false; error: ReturnType }> + >; }>) { const form = useAppForm({ schema, @@ -179,6 +184,7 @@ function FormHarness(props: Readonly<{ submit: props.submit, resetOnSuccess: props.resetOnSuccess, }); + const resend = props.resend; return (
void form.submitForm(event)}> + {resend ? ( + + ) : null} @@ -632,6 +641,70 @@ describe("local form facade", () => { }); }); +// 1106/08-01, 1106/03-01 (diff review FR-03), 1112/10-01. A page left while +// its save was unknown comes back with a new form: the coordinator still +// holds the unknown save, the form no longer knows the values it sent. The +// values on screen were typed after the save and never sent, so no way out +// of the unknown result may take them as the saved values: they and the +// dirty state stay as they are, and the leave guard still protects them. +describe("a form mounted again while its save is unknown", () => { + const leftUnknown = () => + Promise.resolve({ + ok: false as const, + error: createFailure("RATE_LIMITED", "CREATE_ENTITY", 0, { + effect: "NOT_APPLIED", + httpStatus: 429, + code: "RATE_LIMIT_EXCEEDED", + }), + }); + + it("keeps the values on screen when the earlier save is confirmed applied", async () => { + const user = userEvent.setup(); + const submit = vi.fn(); + render(); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta"); + + await user.click(screen.getByRole("button", { name: "Confirm applied" })); + + expect(screen.getByTestId("result")).toHaveTextContent("success"); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta"); + expect(screen.getByTestId("dirty")).toHaveTextContent("true"); + expect(submit).not.toHaveBeenCalled(); + }); + + it("keeps the values on screen when the resend succeeds", async () => { + const user = userEvent.setup(); + const resend = vi.fn(async () => ({ ok: true as const, value: "saved" })); + render(); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta"); + + await user.click(screen.getByRole("button", { name: "Resend" })); + + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("success"), + ); + expect(resend).toHaveBeenCalledTimes(1); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta"); + expect(screen.getByTestId("dirty")).toHaveTextContent("true"); + }); + + it("keeps the values on screen when a resend left unknown is then confirmed applied", async () => { + const user = userEvent.setup(); + render(); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta"); + await user.click(screen.getByRole("button", { name: "Resend" })); + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"), + ); + + await user.click(screen.getByRole("button", { name: "Confirm applied" })); + + expect(screen.getByTestId("result")).toHaveTextContent("success"); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta"); + expect(screen.getByTestId("dirty")).toHaveTextContent("true"); + }); +}); + // 1101/14.4. Every code the paired backend can put in a field error's // details[].code: clean-architecture-backend-template 5786126c, // ClientSafeValidationDetails.java RULES (18-42) and its INVALID fallback.