From 7420bafe49d00e6d9bf6416086ab5c967cfc0f1b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:53:23 +0900 Subject: [PATCH] =?UTF-8?q?fix(form):=20=EB=8B=A4=EC=8B=9C=20=EB=A7=88?= =?UTF-8?q?=EC=9A=B4=ED=8A=B8=ED=95=9C=20=ED=8F=BC=EC=9D=98=20=EC=9E=AC?= =?UTF-8?q?=EC=A0=84=EC=86=A1=EC=9D=B4=20=EB=B3=B4=EB=82=B4=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EC=9D=80=20=ED=99=94=EB=A9=B4=20=EA=B0=92=EC=9D=84=20?= =?UTF-8?q?=EC=A0=80=EC=9E=A5=20=EA=B0=92=EC=9C=BC=EB=A1=9C=20=EC=93=B0?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 저장 결과가 불명인 채 페이지를 떠났다 돌아오면 폼은 새로 마운트되어 보낸 값을 모른다. 그때 resendUnknown은 화면 값을 제출 값으로 썼다 (unknownSubmissionRef ?? values). 재전송이 성공하면 기본 resetOnSuccess가 사용자가 돌아와 입력한, 보낸 적 없는 값을 지우거나 깨끗한 값으로 표시했다. 재전송이 쓰기 전에 거절되어 결과 불명에 남으면 그 화면 값을 보낸 값으로 기억해, 다음 「변경됨으로 확인」이 같은 일을 했다. 같은 상황의 settleApplied는 이미 화면 값과 dirty를 그대로 둔다(1106/08-01). 그 settleApplied 분기를 지키던 시험은 참조 기능 시험과 함께 지워졌다. 고른 방법: 결과 불명 기록을 { values: Values | null }로 바꿔 "보낸 값 모름"을 따로 둔다. 재전송은 그 값만 쓰고, 값을 모르면 성공·적용 확인을 settleApplied의 재마운트 분기와 같은 처리(settleUnsentValues)로 끝낸다. 기록이 남아 있는 동안 새 저장은 그대로 막는다. 버린 대안: 화면 값을 쓰되 성공 뒤 값을 되돌리기(사용자가 친 값을 잃는다). 위험·한계: 다시 마운트한 폼에서 결과 불명이 확인되기 전까지는 폼도 새 저장을 막는다(전에도 재전송이 불명으로 남으면 막았다). 결과 불명 상태를 코디네이터와 폼이 따로 갖는 구조(1112/01-01)는 결정 대기다. 검증: tests/component/form-foundation.test.tsx의 새 describe 셋 중 둘이 고치기 전 코드에서 실패하고 고친 뒤 통과한다(desktop, PR 본문). Refs: 1106/03-01, 1112/01-02, 1112/10-01 --- src/presentation/forms/use-app-form.ts | 64 ++++++++++++++------- tests/component/form-foundation.test.tsx | 73 ++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 21 deletions(-) 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.