fix(form): 저장 뒤 이동과 마운트 판정을 폼이 맡고 다시 로그인 안내를 먼저 그린다

앞 커밋(1112/01-01) 뒤 확인 리뷰가 완료 기준의 남은 셋과 결함 둘을 찾았다.

- 생성 작성 페이지에 마운트 표시(useRef)와 저장 뒤 이동이 남았다. 저장이
  끝나면 페이지가 폼보다 먼저, 폼이 pending인 동안 상세로 옮겼다. 다시
  마운트한 폼에서 재전송이 성공하면 사용자가 돌아와 입력한, 보낸 적 없는
  값을 이탈 확인 없이 버렸다(1112/01-02 영향).
- 폼이 재전송 결과로 결과 불명을 다시 판정했다(resendLeftUnknown).
  코디네이터와 401에서 갈린다. 코디네이터는 결과 불명을 쥐고 폼은 다시
  로그인으로 가는데, FormSaveFeedback이 결과 불명을 먼저 그려 다시 로그인
  안내를 가렸다(D-2 위반).
- 지난 세 결함(1105/08-02·08-04, 1106/08-02)의 시험이 생성 페이지 시험에만
  있었다.

고른 방법: useAppForm에 onSaved를 더한다(추가만). 폼이 결과를 보이고
pending을 끈 뒤, 마운트된 동안만 부른다. confirmUnknownEffect(then)도
마운트된 동안만 then을 부른다. resendUnknownEffect의 then 인자와
FormSaveFeedback의 onResent는 지운다(앞 커밋에서 생겨 아직 내보낸 적이
없다). 재전송 뒤 결과 불명인지는 코디네이터의 새 holdsUnknownEffect로
묻는다. mutation 없이 쓰는 폼(이미 생성한 페이지)은 물을 곳이 없어 같은
거절 표(isRefusedOnEveryAttempt)로 본다. FormSaveFeedback은 다시 로그인
실패를 결과 불명보다 먼저 그린다. 생성 페이지는 mutation.submit을 그대로
넘기고 onSaved와 onConfirmed에서 옮기기만 한다. VD-04 머리 칸에 넣었던
문장은 보완 절로 옮긴다(머리 칸의 백틱 낱말을 문서 검사가 경로로 본다).
페이지가 FormSaveFeedback을 늘 넘기므로, 할 말이 없는 피드백 칸은 자리를
차지하지 않는다(templates.css, 빈 칸이 그리드 간격을 한 줄 더했다).

위험·한계: 저장 뒤 이동이 폼이 결과를 그린 뒤로 한 번 늦어진다. 다시
마운트한 폼에 보내지 않은 값이 있으면 이동이 이탈 확인을 띄운다(의도).

검증: form-foundation 새 시험 일곱과 create-feature 생성 페이지 시험
(RED·GREEN, 막기·다른 저장·충돌 안내 변이 셋), 생성 기능 e2e의 피드백 칸 간격 시험은 desktop에서 돌려 PR
본문에 적는다.

Refs: 1112/01-01, 1112/01-02, 1105/08-02, 1105/08-04, 1106/08-02, 1112/04-02
This commit is contained in:
DongHyeonka
2026-11-13 00:03:42 +09:00
parent 6b79e7b39f
commit 63ba523519
11 changed files with 381 additions and 113 deletions
+5 -1
View File
@@ -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).
+1
View File
@@ -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에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`<base>-create-page.test.tsx`)처럼 400 본문을 손으로 적는다.
② **기준**
+2 -2
View File
@@ -96,7 +96,7 @@ const search = (q: string) =>
| 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use-<base>-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/<base>-contract-contribution.ts`, `presentation/use-<base>-create.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/<base>-create-page.tsx` | 기능 테스트만(쓰기 slice는 `<base>-create-page.test.tsx`) |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect`. 폼으로 저장하면 아래 「폼」 행의 `FormSaveFeedback`이 이 둘을 잇는다 | 쓰기 slice `presentation/<base>-create-page.tsx` | 기능 테스트(쓰기 slice는 `<base>-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/<base>-form.ts`와 `<base>-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/<base>-form.ts`와 `<base>-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인), `tests/component/form-foundation.test.tsx` |
| 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/<base>-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) |
| 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 코드 조각: [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 403 페이지 테스트 `tests/features/<id>/<base>-forbidden.test.tsx` | 가드 테스트. 역할·권한 힌트 예제는 없음 |
+12 -40
View File
@@ -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<keyof ${pascal}FormValues, string>;
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={<DirtyNavigationDialog guard={guard} />}
@@ -280,6 +280,13 @@ type ApplicationMutationController<Input, Value> = 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<Input> =
@@ -869,6 +876,11 @@ export function useApplicationMutation<Input, Value>(
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<Input, Value>(
reconcileUnknownEffect,
resendUnknownEffect,
canResendUnknownEffect,
holdsUnknownEffect,
});
}
+23 -22
View File
@@ -140,55 +140,56 @@ export type FormSaveFeedbackForm<Output> = Readonly<{
notice: ParameterlessMessageKey | null;
supportReference: string | undefined;
submitForm(): Promise<unknown>;
confirmUnknownEffect(): Promise<void>;
resendUnknownEffect(
then?: (outcome: FormResult<Output> | null) => FormResult<Output> | null,
): Promise<FormResult<Output> | null>;
confirmUnknownEffect(then?: () => void): Promise<void>;
resendUnknownEffect(): Promise<FormResult<Output> | 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<Output>(props: Readonly<{
form: FormSaveFeedbackForm<Output>;
/** 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<Output> | null) => FormResult<Output> | 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 ? (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : onFailureAction}
/>
) : null;
if (form.failure?.action === "reauth") return failureStatus;
if (form.effectUnknown && form.mutationState) {
return (
<AsyncSurface
notice={notice}
onReconcileUnknownEffect={() => {
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 (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : onFailureAction}
/>
);
}
if (failureStatus) return failureStatus;
if (form.result === "conflict" && notice) {
return <p role="alert">{notice}</p>;
}
+89 -42
View File
@@ -48,6 +48,11 @@ export type FormSaveMutation<Output> = Readonly<{
state: AsyncState;
reconcileUnknownEffect(resolution: "APPLIED"): Promise<void>;
resendUnknownEffect(): Promise<FormResult<Output> | 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<Output>;
/**
* 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<Output> | null) => {
if (!mountedRef.current) return;
flushSync(() => setPending(false));
if (outcome?.ok) onSaved?.(outcome.value);
},
[onSaved],
);
const validateAndSubmit = useCallback(
async (): Promise<FormResult<Output> | null> => {
setFieldErrors({} as FieldErrors<Values>);
@@ -446,17 +483,19 @@ export function useAppForm<
const command = mapToCommand(parsed.data);
setPending(true);
let outcome: FormResult<Output> | 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<Output> | 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<Values>);
@@ -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<void> => {
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<void> => {
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<Output> | null) => FormResult<Output> | null = (outcome) => outcome,
): Promise<FormResult<Output> | 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<FormResult<Output> | 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<Values extends FormValues>(
}
/**
* 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<unknown>): 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<unknown>,
mutation: FormSaveMutation<unknown> | 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. */
@@ -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);
+200 -6
View File
@@ -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<Readonly<{ name: string; note?: string }>, 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 (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
@@ -1399,10 +1407,15 @@ describe("a form bound to its mutation", () => {
Submit
</Button>
<div id={form.feedbackId} tabIndex={-1}>
<FormSaveFeedback form={form} />
<FormSaveFeedback
form={form}
{...(props.onConfirmed === undefined ? {} : { onConfirmed: props.onConfirmed })}
/>
</div>
<output data-testid="result">{form.result}</output>
<output data-testid="indicator">{mutation.state.indicator ?? "none"}</output>
<output data-testid="pending">{String(form.pending)}</output>
<output data-testid="dirty">{String(form.dirty)}</output>
</Form>
);
}
@@ -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<Parameters<typeof BoundForm>[0], "fetcher"> = {},
) {
const user = userEvent.setup();
const view = render(<BoundForm fetcher={fetcher} />, { wrapper: wrapper(queryClient()) });
const client = queryClient();
const view = render(<BoundForm fetcher={fetcher} {...props} />, { 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<typeof render>,
client: ReturnType<typeof queryClient>,
props: Parameters<typeof BoundForm>[0],
) {
view.unmount();
return render(<BoundForm {...props} />, { 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<typeof fetch>(
() =>
new Promise<Response>((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(<BoundForm fetcher={held.fetcher} />, { 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(<BoundForm fetcher={held.fetcher} onSaved={onSaved} />, {
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<typeof fetch>()
.mockResolvedValueOnce(
Response.json(
{ success: false, error: { code: "POSTER_ALREADY_EXISTS", category: "CONFLICT", retryable: false }, meta },
{ status: 409 },
),
);
render(<BoundForm fetcher={fetcher} operations={FORM_DECLARING_OPERATIONS} />, {
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);
+18
View File
@@ -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", () => {
+12
View File
@@ -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);
});
});