diff --git a/docs/adr/VD-04-native-form-facade.md b/docs/adr/VD-04-native-form-facade.md index 91a263e4..083dcc87 100644 --- a/docs/adr/VD-04-native-form-facade.md +++ b/docs/adr/VD-04-native-form-facade.md @@ -4,7 +4,7 @@ - 상태: 채택(보완) - 작성일: 2026-07-26 - 요약: 폼은 외부 폼 라이브러리 대신 native form 이벤트를 쓰는 local `useAppForm` facade로 처리하고 검증 오류·충돌·저장 실패를 구분해 보여 준다는 결정이다. -- 현재 정본: `src/presentation/forms/`, `src/presentation/templates/`. 결정 5(409를 입력 오류로 바꾸지 않음)는 기능이 선언하지 않은 409에 적용된다. 기능이 `refusalMessages`로 선언한 쓰기 전 거절(409 포함)은 필드 오류로 보인다(1103/03-01, `docs/manual/02-decision-tables.md` 4절의 `refusalMessages` 문단) +- 현재 정본: `src/presentation/forms/`, `src/presentation/templates/` # VD-04: Native form controller와 local facade @@ -73,3 +73,7 @@ React Hook Form과 Zod resolver를 평가한다. rollback 시 reference page는 이전 직접 form/layout으로 돌아갈 수 있다. application input과 outbound gateway 계약은 유지되며, form facade와 template commit은 독립적으로 되돌릴 수 있다. + +## 보완 + +- 2026-11-12: 결정 5(409 conflict는 validation으로 바꾸지 않는다)는 기능이 선언하지 않은 409에 적용된다. 기능이 `useAppForm`의 `refusalMessages`로 선언한 쓰기 전 거절은 409라도 기능의 문구로 필드나 오류 요약에 보이고, 폼은 다음 저장을 받는다(1103/03-01, 매뉴얼 02 결정표 4절). 그 밖의 409는 그대로 충돌이고, `mutation` 옵션을 준 폼은 그 안내를 입력 오류 요약이 아니라 `FormSaveFeedback`에 보인다(1112/04-02). diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index d298aeb7..289bb3e5 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -578,6 +578,7 @@ export function useInvoiceListFilters(): InvoiceListSearch { - 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿) - 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 다시 보내도 되는 요청(`KEYED`, `IDEMPOTENT`. 뮤테이션 정책의 `resendSafe`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. 폼 밖에서 `mutation.submit`을 부르는 화면도 `NEVER` 쓰기의 같은 입력을 다시 보낼 수 없다. 훅이 `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)로 거절한다. `AsyncSurface`에 손으로 만든 상태를 넘기면 재전송 버튼은 그려지지 않는다(코디네이터의 `state`를 넘긴다). +- 폼으로 저장하면 결과 불명 화면을 직접 잇지 않는다. `useAppForm`에 `mutation`과 저장 뒤 할 일(`onSaved`)을 주고 피드백 자리에 `FormSaveFeedback`을 둔다. 확인·재전송, 결과 불명 동안 새 저장 막기, 페이지를 떠난 뒤 끝난 저장이 아무 데도 옮기지 않는 것을 폼이 맡는다. - 폼이면 서버 필드 오류를 받을 필드(`useAppForm`의 `allowedServerFields`). 짝 백엔드는 필드 검증 거절을 400 `VALIDATION_FAILED`와 `details[{field, code}]`로 보낸다(422가 아니다). 공유 MSW 시나리오에는 짝 백엔드가 보내지 않는 `validation-422`만 있고, Envelope operation에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`-create-page.test.tsx`)처럼 400 본문을 손으로 적는다. ② **기준** diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index d8ef76a8..69c1b92a 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -96,7 +96,7 @@ const search = (q: string) => | 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 | | 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) | | 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/-contract-contribution.ts`, `presentation/use--create.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 | -| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/-create-page.tsx` | 기능 테스트만(쓰기 slice는 `-create-page.test.tsx`) | +| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect`. 폼으로 저장하면 아래 「폼」 행의 `FormSaveFeedback`이 이 둘을 잇는다 | 쓰기 slice `presentation/-create-page.tsx` | 기능 테스트(쓰기 slice는 `-create-page.test.tsx`), `tests/component/form-foundation.test.tsx` | | 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (쓰기 slice는 작성 명령만 만든다) | — | | 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 | | 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (생성 뼈대 목록은 첫 페이지와 `meta.page.total`만 읽는다) | 런타임 테스트만 | @@ -108,7 +108,7 @@ const search = (q: string) => |---|---|---|---| | 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 쓰기 slice `DetailPage`·`FormPage` | `page-templates-own-layout-only` | | 비동기 상태 화면 | `src/presentation/components/async-surface.tsx`의 `AsyncSurface` | 생성 뼈대 목록 페이지 | 페이지 테스트 | -| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm`. mutation으로 저장하는 폼은 `mutation` 옵션을 주고 피드백 자리에 `FormSaveFeedback`(`src/presentation/forms/form-components.tsx`)을 둔다. 결과 불명 동안 새 저장 막기, 「변경됨으로 확인」, 같은 키 재전송, 다른 저장이 도는 동안의 표시를 폼이 맡는다 | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인), `tests/component/form-foundation.test.tsx` | +| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm`. mutation으로 저장하는 폼은 `mutation` 옵션을 주고 피드백 자리에 `FormSaveFeedback`(`src/presentation/forms/form-components.tsx`)을 둔다. 결과 불명 동안 새 저장 막기, 「변경됨으로 확인」, 같은 키 재전송, 다른 저장이 도는 동안의 표시, 마운트된 동안만 저장 뒤 이동(`onSaved`, `FormSaveFeedback`의 `onConfirmed`)을 폼이 맡는다 | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인), `tests/component/form-foundation.test.tsx` | | 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) | | 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 코드 조각: [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 403 페이지 테스트 `tests/features//-forbidden.test.tsx` | 가드 테스트. 역할·권한 힌트 예제는 없음 | diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index 2ac3cb93..50d6b944 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -589,10 +589,8 @@ export default function ${pascal}DetailPage() { export function renderCreatePage({ names, routeId, write }: SliceShape): string { const { base, camel, pascal, upper } = names; - return `import { useCallback, useEffect, useRef } from "react"; -import { Link, useNavigate } from "react-router-dom"; + return `import { Link, useNavigate } from "react-router-dom"; -import type { Result } from "../../../contracts/result.ts"; import { Button, DirtyNavigationDialog, @@ -606,8 +604,6 @@ import { useDirtyNavigationGuard, } from "../../../presentation/design-system/index.ts"; import { useLocale } from "../../../presentation/i18n/index.ts"; -import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; -import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; import { ${upper}_FORM_DEFAULTS, ${camel}FormSchema, @@ -633,46 +629,24 @@ export default function ${pascal}CreatePage() { name: message("${camel}.form.name"), } satisfies Record; const mutation = use${pascal}Create(); - // A save outlives this page when the user leaves while it runs. Ending - // then, it does not take them to its item or the list (1106/08-02). - const mounted = useRef(false); - useEffect(() => { - mounted.current = true; - return () => { - mounted.current = false; - }; - }, []); - const openSaved = useCallback( - (outcome: Result<${pascal}ItemView> | null) => { - if (outcome?.ok && mounted.current) { - void navigate( - ${camel}RouteUrl("${write.detail.routeId}", { - params: { ${write.idParam}: outcome.value.itemId }, - }), - ); - } - return outcome; - }, - [navigate], - ); - const submit = useCallback( - async (command: ${pascal}CreateCommand) => { - const outcome = await mutation.submit(command); - openSaved(outcome); - return outcome; - }, - [mutation, openSaved], - ); // The form holds the rules of a save through the mutation: no new save // while one is unknown or another runs, confirm and resend of an unknown - // one (useAppForm \`mutation\`, FormSaveFeedback). + // one, and what the page does after a save only while it is still open + // (useAppForm \`mutation\` and \`onSaved\`, FormSaveFeedback). const form = useAppForm({ schema: ${camel}FormSchema, defaultValues: ${upper}_FORM_DEFAULTS, allowedServerFields: ["name"], mapToCommand: to${pascal}CreateCommand, - submit, + submit: mutation.submit, mutation, + onSaved: (item) => { + void navigate( + ${camel}RouteUrl("${write.detail.routeId}", { + params: { ${write.idParam}: item.itemId }, + }), + ); + }, }); const guard = useDirtyNavigationGuard(form.dirty && !form.pending); @@ -714,10 +688,8 @@ export default function ${pascal}CreatePage() { // The list shows whether the item is there; the form alone // would show nothing but an emptied input (1105/08-02). onConfirmed={() => { - if (mounted.current) void navigate(${camel}RouteUrl("${routeId}")); + void navigate(${camel}RouteUrl("${routeId}")); }} - // The resend is drawn only for a request with a key (a KEYED command). - onResent={openSaved} /> } guard={} diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 5837e348..65c9e950 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -280,6 +280,13 @@ type ApplicationMutationController = Readonly<{ * `state.unknownEffectResendable` carries the same answer to `AsyncSurface`. */ canResendUnknownEffect: boolean; + /** + * 1112/01-01. Whether the oldest request is unknown now, read at the + * call, not from the last render: a form asks it when a resend has ended + * (`useAppForm` `mutation`). `state.indicator` says the same once the + * hook renders again. + */ + holdsUnknownEffect(): boolean; }>; type MutationExecution = @@ -869,6 +876,11 @@ export function useApplicationMutation( return submit(head.input as Input); }, [submit, unknownEffectChannel]); + const holdsUnknownEffect = useCallback( + () => unknownEffectChannel?.admissions[0]?.state === "UNKNOWN", + [unknownEffectChannel], + ); + const unknownEffectHead = unknownEffectChannel?.admissions[0]; const canResendUnknownEffect = unknownEffectChannel !== null && @@ -891,6 +903,7 @@ export function useApplicationMutation( reconcileUnknownEffect, resendUnknownEffect, canResendUnknownEffect, + holdsUnknownEffect, }); } diff --git a/src/presentation/forms/form-components.tsx b/src/presentation/forms/form-components.tsx index b7a98b0c..3f3fb912 100644 --- a/src/presentation/forms/form-components.tsx +++ b/src/presentation/forms/form-components.tsx @@ -140,55 +140,56 @@ export type FormSaveFeedbackForm = Readonly<{ notice: ParameterlessMessageKey | null; supportReference: string | undefined; submitForm(): Promise; - confirmUnknownEffect(): Promise; - resendUnknownEffect( - then?: (outcome: FormResult | null) => FormResult | null, - ): Promise | null>; + confirmUnknownEffect(then?: () => void): Promise; + resendUnknownEffect(): Promise | null>; }>; /** * 1112/01-01. The feedback of a form that saves through a mutation * (`useAppForm` with `mutation`), in the order a page used to write out by - * hand: the unknown result (confirm it was applied, or resend it with the - * same key), then a save failure that is not an input error, then a - * conflict, then a save of the mutation this form did not start. Put it in - * the page template's feedback area (`FormPage` `feedback`, `feedbackId`). + * hand: signing in again (D-2, whatever the effect), the unknown result + * (confirm it was applied, or resend it with the same key), then another + * save failure that is not an input error, then a conflict, then a save of + * the mutation this form did not start. Put it in the page template's + * feedback area (`FormPage` `feedback`, `feedbackId`). What a resend saved + * goes to the form's `onSaved`. */ export function FormSaveFeedback(props: Readonly<{ form: FormSaveFeedbackForm; - /** After "it was applied" has settled the request (a page opens the list). */ + /** + * After "it was applied" has settled the request, while the form is + * mounted (a page opens the list). + */ onConfirmed?: () => void; - /** Sees a resend's outcome first (a page opens what was saved). */ - onResent?: (outcome: FormResult | null) => FormResult | null; /** The action of a failure that is not "try again" (sign in, for example). */ onFailureAction?: () => void; }>) { const { message } = useLocale(); - const { form, onConfirmed, onResent, onFailureAction } = props; + const { form, onConfirmed, onFailureAction } = props; const notice = form.notice ? message(form.notice) : undefined; + const failureStatus = form.failure ? ( + void form.submitForm() : onFailureAction} + /> + ) : null; + if (form.failure?.action === "reauth") return failureStatus; if (form.effectUnknown && form.mutationState) { return ( { - void form.confirmUnknownEffect().then(() => onConfirmed?.()); + void form.confirmUnknownEffect(onConfirmed); }} onResendUnknownEffect={() => { - void form.resendUnknownEffect(onResent); + void form.resendUnknownEffect(); }} state={form.mutationState} supportReference={form.supportReference} /> ); } - if (form.failure) { - return ( - void form.submitForm() : onFailureAction} - /> - ); - } + if (failureStatus) return failureStatus; if (form.result === "conflict" && notice) { return

{notice}

; } diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index eefb38ba..e4aff105 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -48,6 +48,11 @@ export type FormSaveMutation = Readonly<{ state: AsyncState; reconcileUnknownEffect(resolution: "APPLIED"): Promise; resendUnknownEffect(): Promise | null>; + /** + * Whether the mutation holds an unknown result now. The form reads it + * when a resend has ended instead of judging the outcome itself. + */ + holdsUnknownEffect(): boolean; }>; type AppFormOptions< @@ -81,6 +86,14 @@ type AppFormOptions< * `FormSaveFeedback`, not to the input error summary. */ mutation?: FormSaveMutation; + /** + * 1106/08-02, 1112/01-01. A save this form shows ended with a value (a + * submit or a resend): a page opens what was saved here. Called while the + * form is mounted only, after the form shows the outcome and is no longer + * pending, so a leave guard reads the values left on screen (values a + * remounted form never sent stay guarded). + */ + onSaved?(value: Output): void; }>; export function useAppForm< @@ -98,6 +111,7 @@ export function useAppForm< resetOnSuccess = true, refusalMessages, mutation, + onSaved, } = options; const generatedId = useId().replaceAll(":", ""); const formId = `app-form-${generatedId}`; @@ -152,6 +166,15 @@ export function useAppForm< // focus, so the browser drops focus to the body. The status takes focus // once it has rendered (`feedbackId`). const focusFeedbackRef = useRef(false); + // 1106/08-02. A save outlives the form when the user leaves while it runs. + // Ending then, it opens nothing and changes no state. + const mountedRef = useRef(false); + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); // 1105/08-01. The recovery actions (confirm applied, resend, retry) sit in // that status and go away with it once they have done their work, so the // browser drops focus to the body again. A success that replaces a status @@ -417,6 +440,20 @@ export function useAppForm< ], ); + /** + * The end of a save the form shows: no longer pending, committed before + * `onSaved` runs, so a page that navigates there meets the form's own leave + * guard. Nothing runs once the form is gone. + */ + const finishSave = useCallback( + (outcome: FormResult | null) => { + if (!mountedRef.current) return; + flushSync(() => setPending(false)); + if (outcome?.ok) onSaved?.(outcome.value); + }, + [onSaved], + ); + const validateAndSubmit = useCallback( async (): Promise | null> => { setFieldErrors({} as FieldErrors); @@ -446,17 +483,19 @@ export function useAppForm< const command = mapToCommand(parsed.data); setPending(true); + let outcome: FormResult | null = null; try { - const outcome = await submit(command); + outcome = await submit(command); applyOutcome(outcome, parsed.data); return outcome; } finally { - setPending(false); + finishSave(outcome); } }, [ allowedServerFields, applyOutcome, + finishSave, focusFirstError, mapToCommand, schema, @@ -503,9 +542,10 @@ export function useAppForm< const submittedValues = unknownSubmissionRef.current?.values ?? null; const resend = (async () => { setPending(true); + let outcome: FormResult | null = null; try { - const outcome = await send(); - if (outcome && resendLeftUnknown(outcome)) { + outcome = await send(); + if (outcome && resendLeftUnknown(outcome, mutation)) { focusFeedbackRef.current = true; unknownSubmissionRef.current = { values: submittedValues }; setFieldErrors({} as FieldErrors); @@ -524,7 +564,7 @@ export function useAppForm< } return outcome; } finally { - setPending(false); + finishSave(outcome); } })().finally(() => { pendingRef.current = null; @@ -532,38 +572,39 @@ export function useAppForm< pendingRef.current = resend; return resend; }, - [applyOutcome, mutation], + [applyOutcome, finishSave, mutation], ); /** * 1112/01-01. The unknown result's "it was applied": the mutation settles - * its request, then the form shows the save (`settleApplied`). Without a - * mutation there is nothing to settle and it rejects. + * its request, then the form shows the save (`settleApplied`), then `then` + * runs while the form is mounted (1105/08-02: a page opens the list, which + * shows whether the item is there). Without a mutation it rejects. */ - const confirmUnknownEffect = useCallback(async (): Promise => { - if (!mutation) throw new TypeError("useAppForm: confirmUnknownEffect needs the mutation option"); - await mutation.reconcileUnknownEffect("APPLIED"); - settleApplied(); - }, [mutation, settleApplied]); + const confirmUnknownEffect = useCallback( + async (then?: () => void): Promise => { + if (!mutation) throw new TypeError("useAppForm: confirmUnknownEffect needs the mutation option"); + await mutation.reconcileUnknownEffect("APPLIED"); + if (!mountedRef.current) return; + settleApplied(); + then?.(); + }, + [mutation, settleApplied], + ); /** * 1112/01-01. The unknown result's "send the same request again": - * `resendUnknown` with the mutation's own resend. `then` sees the outcome - * before the form does (a page opens what was saved there). + * `resendUnknown` with the mutation's own resend. What it saved goes to + * `onSaved` like a submit's. */ - const resendUnknownEffect = useCallback( - ( - then: (outcome: FormResult | null) => FormResult | null = (outcome) => outcome, - ): Promise | null> => { - if (!mutation) { - return Promise.reject( - new TypeError("useAppForm: resendUnknownEffect needs the mutation option"), - ); - } - return resendUnknown(async () => then(await mutation.resendUnknownEffect())); - }, - [mutation, resendUnknown], - ); + const resendUnknownEffect = useCallback((): Promise | null> => { + if (!mutation) { + return Promise.reject( + new TypeError("useAppForm: resendUnknownEffect needs the mutation option"), + ); + } + return resendUnknown(() => mutation.resendUnknownEffect()); + }, [mutation, resendUnknown]); return Object.freeze({ formId, @@ -643,21 +684,27 @@ function refusalFor( } /** - * 1106/03-01. The resend did not reach the write: the request it repeats is - * still unknown, and the mutation coordinator keeps its key. Signing in again - * still comes first (D-2). A refusal every attempt gets - * (`isRefusedOnEveryAttempt`, the coordinator's own test) settles the request - * instead, and the form shows it as for a first save (field errors, a save - * it takes again). + * 1106/03-01. The resend did not reach the write (`NOT_APPLIED`, + * `NOT_STARTED`) and the request it repeats is still unknown, its key kept. + * Signing in again still comes first (D-2). Otherwise the form shows the + * outcome as for a first save (field errors, a save it takes again). + * 1112/01-01. Whether the request is still unknown is the mutation's own + * answer, read now. A form given no mutation (a page generated before it) + * cannot ask: it reads the refusals every attempt gets + * (`isRefusedOnEveryAttempt`), the same rule the mutation applies. */ -function resendLeftUnknown(outcome: FormResult): boolean { - return ( - !outcome.ok && - (outcome.error.effect === "NOT_APPLIED" || - outcome.error.effect === "NOT_STARTED") && - outcome.error.action !== "reauth" && - !isRefusedOnEveryAttempt(outcome.error) - ); +function resendLeftUnknown( + outcome: FormResult, + mutation: FormSaveMutation | undefined, +): boolean { + if (outcome.ok) return false; + const { effect, action } = outcome.error; + if ((effect !== "NOT_APPLIED" && effect !== "NOT_STARTED") || action === "reauth") { + return false; + } + return mutation + ? mutation.holdsUnknownEffect() + : !isRefusedOnEveryAttempt(outcome.error); } /** 1105/08-01. Nothing has focus: the focused element left the document. */ diff --git a/src/presentation/styles/theme/templates.css b/src/presentation/styles/theme/templates.css index a8cc1da2..ec46b5f2 100644 --- a/src/presentation/styles/theme/templates.css +++ b/src/presentation/styles/theme/templates.css @@ -30,6 +30,12 @@ min-width: 0; } + /* A form page always holds its save feedback (FormSaveFeedback); with + nothing to say it takes no row, so it adds no gap. */ + .page-template__feedback:empty { + display: none; + } + .page-template__breadcrumb { padding-block-start: 1rem; color: var(--color-content-muted); diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index db683485..b2d132ee 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -1363,8 +1363,15 @@ describe("a form bound to its mutation", () => { }; const meta = { requestId: "request-1", traceId: "trace-1" }; - function BoundForm(props: Readonly<{ fetcher: typeof fetch }>) { - const [http] = useState(() => formBinding(props.fetcher)); + function BoundForm( + props: Readonly<{ + fetcher: typeof fetch; + operations?: typeof FORM_DECLARING_OPERATIONS; + onSaved?: (value: unknown) => void; + onConfirmed?: () => void; + }>, + ) { + const [http] = useState(() => formBinding(props.fetcher, props.operations)); const mutation = useApplicationMutation, unknown>({ definitionId: "form-bound-create-v1", definitionVersion: 1, @@ -1384,6 +1391,7 @@ describe("a form bound to its mutation", () => { mapToCommand: (values) => ({ name: values.name }), submit: mutation.submit, mutation, + ...(props.onSaved === undefined ? {} : { onSaved: props.onSaved }), }); return (
void form.submitForm(event)}> @@ -1399,10 +1407,15 @@ describe("a form bound to its mutation", () => { Submit
- +
{form.result} {mutation.state.indicator ?? "none"} + {String(form.pending)} + {String(form.dirty)}
); } @@ -1415,15 +1428,196 @@ describe("a form bound to its mutation", () => { ); } - async function loseFirstSave(fetcher: typeof fetch) { + async function loseFirstSave( + fetcher: typeof fetch, + props: Omit[0], "fetcher"> = {}, + ) { const user = userEvent.setup(); - const view = render(, { wrapper: wrapper(queryClient()) }); + const client = queryClient(); + const view = render(, { wrapper: wrapper(client) }); await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved"); await user.click(screen.getByRole("button", { name: "Submit" })); await screen.findByText(formatMessage("ko-KR", "async.mutationEffectUnknown")); - return { user, view }; + return { user, view, client }; } + /** The user leaves the page and comes back: a new form, the same mutation. */ + function mountAgain( + view: ReturnType, + client: ReturnType, + props: Parameters[0], + ) { + view.unmount(); + return render(, { wrapper: wrapper(client) }); + } + + /** A save the server answers only when the test says so. */ + function heldSave() { + let answer: ((response: Response) => void) | undefined; + const fetcher = vi.fn( + () => + new Promise((resolve) => { + answer = resolve; + }), + ); + return { + fetcher, + answer: async () => { + await waitFor(() => expect(answer).toBeDefined()); + answer?.(Response.json({ success: true, data: { id: "entity-1", name: "Saved" }, meta })); + }, + }; + } + + // fe-testing (round9 confirm review). A form mounted again holds no + // submission of its own: only the coordinator's unknown result stops it. + it("refuses a new save in a form mounted again while the coordinator holds one unknown", async () => { + const fetcher = lostThen(); + const { view, client } = await loseFirstSave(fetcher); + const again = mountAgain(view, client, { fetcher }); + await screen.findByText(formatMessage("ko-KR", "async.mutationEffectUnknown")); + const form = again.container.querySelector("form"); + if (!form) throw new Error("expected the form"); + + fireEvent.submit(form); + + expect(fetcher).toHaveBeenCalledTimes(1); + expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled(); + }); + + // 1105/08-04, moved here from the generated create page test (1112/01-01). + // The user comes back while the save they started still runs: the form + // shows it and sends nothing new. + it("shows a save it did not start and refuses a new one", async () => { + const user = userEvent.setup(); + const held = heldSave(); + const client = queryClient(); + const view = render(, { wrapper: wrapper(client) }); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved"); + await user.click(screen.getByRole("button", { name: "Submit" })); + await waitFor(() => expect(held.fetcher).toHaveBeenCalledTimes(1)); + + const again = mountAgain(view, client, { fetcher: held.fetcher }); + const form = again.container.querySelector("form"); + if (!form) throw new Error("expected the form"); + fireEvent.submit(form); + + expect(await screen.findByText(formatMessage("ko-KR", "async.mutationPending"))).toBeVisible(); + expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled(); + expect(held.fetcher).toHaveBeenCalledTimes(1); + await held.answer(); + }); + + // 1106/08-02, moved here from the generated create page test. A save that + // ends after the user left does not take them to what it saved. + it.each([ + ["while the form is there", false, 1], + ["once the user left the form", true, 0], + ] as const)("opens what was saved only %s", async (_label, leave, opened) => { + const user = userEvent.setup(); + const held = heldSave(); + const onSaved = vi.fn(); + const view = render(, { + wrapper: wrapper(queryClient()), + }); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved"); + await user.click(screen.getByRole("button", { name: "Submit" })); + if (leave) view.unmount(); + + await held.answer(); + + await waitFor(() => expect(held.fetcher).toHaveBeenCalledTimes(1)); + if (opened) await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(onSaved).toHaveBeenCalledTimes(opened); + }); + + // 1105/08-02, moved here from the generated create page test. Confirming + // the unknown result hands over to the page (which opens the list). + it("hands over to the page once the user confirms the save applied", async () => { + const onConfirmed = vi.fn(); + const { user } = await loseFirstSave(lostThen(), { onConfirmed }); + + await user.click( + screen.getByRole("button", { name: formatMessage("ko-KR", "action.confirmMutationApplied") }), + ); + + await waitFor(() => expect(onConfirmed).toHaveBeenCalledTimes(1)); + expect(screen.getByTestId("indicator")).toHaveTextContent("none"); + }); + + // 1112/01-02 영향 (round9 confirm review). Back on the page, the user typed + // a value the first save never had; the resend saves the first one. The + // page opens what was saved with the leave guard on: the typed value is + // still there and unsaved. + it("opens what a resend saved with the values it never sent still guarded", async () => { + const fetcher = lostThen(); + const seen: string[] = []; + const onSaved = vi.fn(() => { + seen.push( + `pending=${screen.getByTestId("pending").textContent} dirty=${screen.getByTestId("dirty").textContent}`, + ); + }); + const { user, view, client } = await loseFirstSave(fetcher); + mountAgain(view, client, { fetcher, onSaved }); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Never sent"); + + await user.click( + await screen.findByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }), + ); + + await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + expect(seen).toEqual(["pending=false dirty=true"]); + expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Never sent"); + }); + + // D-2 (round9 confirm review). The resend meets a sign-in: signing in + // again comes first, before the unknown result that is still held. + it("asks to sign in again before it shows the unknown result", async () => { + const fetcher = lostThen( + Response.json( + { success: false, error: { code: "UNAUTHENTICATED", category: "AUTH", retryable: false }, meta }, + { status: 401 }, + ), + ); + const { user } = await loseFirstSave(fetcher); + + await user.click( + screen.getByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }), + ); + + expect(await screen.findByText("계속하려면 로그인이 필요합니다.")).toBeVisible(); + expect( + screen.queryByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }), + ).not.toBeInTheDocument(); + }); + + // 1112/04-02, the declared 409. Not an input error: the feedback says it, + // and the "check what you entered" summary does not appear. + it("says a declared conflict in the feedback, not as an input error", async () => { + const user = userEvent.setup(); + const fetcher = vi + .fn() + .mockResolvedValueOnce( + Response.json( + { success: false, error: { code: "POSTER_ALREADY_EXISTS", category: "CONFLICT", retryable: false }, meta }, + { status: 409 }, + ), + ); + render(, { + wrapper: wrapper(queryClient()), + }); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Taken"); + + await user.click(screen.getByRole("button", { name: "Submit" })); + + await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("conflict")); + expect(screen.getByText(formatMessage("ko-KR", "form.conflict"))).toBeVisible(); + expect( + screen.queryByRole("heading", { name: formatMessage("ko-KR", "form.errorSummary") }), + ).not.toBeInTheDocument(); + }); + it("refuses a new save while the coordinator holds one unknown", async () => { const fetcher = lostThen(); const { view } = await loseFirstSave(fetcher); diff --git a/tests/e2e/generated-feature.spec.ts b/tests/e2e/generated-feature.spec.ts index f80d424f..3e890a94 100644 --- a/tests/e2e/generated-feature.spec.ts +++ b/tests/e2e/generated-feature.spec.ts @@ -216,6 +216,24 @@ test.describe("the form", () => { })); expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth); }); + + // round9 confirm review. The page always hands FormSaveFeedback to the + // template's feedback area; with nothing to say it takes no row, so the + // heading and the fields stay one gap apart. + test("leaves no room for a save feedback area with nothing to say", async ({ page }) => { + await openForm(page); + const spacing = await page.evaluate(() => { + const box = (selector: string) => document.querySelector(selector)?.getBoundingClientRect(); + const heading = box(".page-template__heading"); + const layout = box(".page-template__layout"); + const template = document.querySelector(".page-template"); + return heading && layout && template + ? { between: layout.top - heading.bottom, rowGap: parseFloat(getComputedStyle(template).rowGap) } + : null; + }); + expect(spacing).not.toBeNull(); + expect(spacing?.between).toBeCloseTo(spacing?.rowGap ?? 0, 0); + }); }); test.describe("the save", () => { diff --git a/tests/unit/create-feature.test.ts b/tests/unit/create-feature.test.ts index d669d9ab..6fec60ad 100644 --- a/tests/unit/create-feature.test.ts +++ b/tests/unit/create-feature.test.ts @@ -568,4 +568,16 @@ describe("generated create page", () => { expect(page).not.toContain("mutation.state.indicator"); expect(page).not.toContain("reconcileUnknownEffect"); }); + + // R-01 완료 기준 (round9 confirm review). Opening what was saved only while + // the page is open is the form's rule too (onSaved), not a mount flag the + // page keeps, and the page calls no resend or settle of its own. + it("keeps no save rule of its own", () => { + const { files } = plan({ id: "invoice-feature", write: "KEYED" }); + const page = files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? ""; + + expect(page).toContain("onSaved:"); + expect(page).not.toMatch(/useRef|useEffect|mounted/u); + expect(page).not.toMatch(/resendUnknown|settleApplied|onResent/u); + }); });