fix(form): 폼이 mutation을 받아 저장 규칙을 맡고 FormSaveFeedback이 피드백을 그린다

결과 불명 상태를 코디네이터(useApplicationMutation)와 폼(useAppForm)이
따로 갖고, 둘을 맞추는 규칙은 생성 작성 페이지의 사본에 있다: 결과 불명·
다른 저장 중 새 저장 막기, 「변경됨으로 확인」 뒤 settleApplied, 같은 키
재전송, 다른 저장이 도는 동안의 표시. 그래서 플랫폼에서 고친 것(1105/08-02,
1105/08-04, 1106/08-02)이 이미 생성한 기능에 들어가지 않는다(1112/01-01).
같은 구조에서 셋이 더 나온다.

- 재전송이 쓰기 전에 거절되거나(429·503) 선언한 409가 나면 "입력 내용을
  확인해 주세요." 요약 아래 나온다(1112/04-02).
- 폼 밖에서 부른 같은 입력이 NOT_APPLIED로 끝나면 훅은 결과 불명인데 폼은
  다시 시도를 보인다(1106/03-01 ②).
- 필드 이름이 붙은 결과 불명(VALIDATION_REJECTED + MAYBE_APPLIED)이 필드
  오류와 결과 불명 화면을 함께 띄운다(1101/03-04).

고른 방법(R9-D1, 권하는 안으로 정함(2026-11-12, 총괄)): useAppForm에 선택
옵션 mutation을 더한다(추가만). 주면 폼이 saveBlocked로 새 저장을 막고
confirmUnknownEffect·resendUnknownEffect를 내주며, 입력 오류가 아닌 저장
안내를 notice로 둔다. 새 FormSaveFeedback이 결과 불명 → 저장 실패 → 충돌 →
다른 저장 순으로 피드백을 그리고, AsyncSurface의 새 notice 칸에 재전송 거절
안내를 보인다. 결과 불명을 코디네이터 상태로 먼저 보므로 ②도 같은 화면이
된다. 폼은 MAYBE_APPLIED를 입력 오류보다 먼저 본다. 생성 작성 페이지는 이
둘을 쓰고 자기 사본을 지운다. mutation을 주지 않은 폼은 전과 같다. 버린
대안: 판정 hook을 따로 두고 폼은 그대로(사본이 하나 더 생긴다).

위험·한계: 이미 생성한 기능은 바뀌지 않는다. CHANGELOG에 생성 페이지를
옮기는 방법을 적는다. 다시 마운트한 폼이 mutation 없이 쓰이면 ②는 그대로다.
VD-04 결정 5의 범위(선언하지 않은 409만)는 머리 블록에 적었다(1103/03-01 (3)).

검증: tests/component/form-foundation.test.tsx의 새 시험 넷(막기, 확인,
재전송 거절 표면, 결과 불명 우선)과 create-feature.test.ts의 생성 페이지
시험이 고치기 전 코드에서 실패하고 고친 뒤 통과한다. 생성 페이지는
FE-GATE-020 scaffold 드릴과 FE-GATE-008 e2e가 돈다(PR 본문).

Refs: 1112/01-01, 1112/04-02, 1106/03-01, 1101/03-04, 1103/03-01
This commit is contained in:
DongHyeonka
2026-11-12 23:21:21 +09:00
parent 7420bafe49
commit 6b79e7b39f
10 changed files with 393 additions and 61 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
- 상태: 채택(보완)
- 작성일: 2026-07-26
- 요약: 폼은 외부 폼 라이브러리 대신 native form 이벤트를 쓰는 local `useAppForm` facade로 처리하고 검증 오류·충돌·저장 실패를 구분해 보여 준다는 결정이다.
- 현재 정본: `src/presentation/forms/`, `src/presentation/templates/`
- 현재 정본: `src/presentation/forms/`, `src/presentation/templates/`. 결정 5(409를 입력 오류로 바꾸지 않음)는 기능이 선언하지 않은 409에 적용된다. 기능이 `refusalMessages`로 선언한 쓰기 전 거절(409 포함)은 필드 오류로 보인다(1103/03-01, `docs/manual/02-decision-tables.md` 4절의 `refusalMessages` 문단)
<!-- 머리 블록 끝 -->
# VD-04: Native form controller와 local facade
+1 -1
View File
@@ -185,7 +185,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
- 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`).
- 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_UNIQUE_VIOLATION` 등 `DB_*`, `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다. 폼을 막는 400 `BAD_PARAMETER`나 409 `DB_UNIQUE_VIOLATION`은 어느 층에서든, 트랜잭션 안에서도 나온다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...; contract 6.1 reads this platform code as possibly raised after the write`로 거부한다.
- 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다.
- 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다.
- 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다. 필드 이름이 붙은 실패라도 결과 불명(`MAYBE_APPLIED`)이면 필드 오류가 아니라 결과 불명으로 보인다. 같은 키 재전송이 쓰기 전에 거절되면, `mutation`을 준 폼은 그 안내를 입력 오류 요약이 아니라 결과 불명 표면(`FormSaveFeedback`)에 보인다.
**503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.**
+1 -1
View File
@@ -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` | 쓰기 slice `presentation/<base>-form.ts`와 `<base>-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인) |
| 폼 | `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/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` | 가드 테스트. 역할·권한 힌트 예제는 없음 |
+17 -45
View File
@@ -594,15 +594,14 @@ import { Link, useNavigate } from "react-router-dom";
import type { Result } from "../../../contracts/result.ts";
import {
AsyncSurface,
Button,
DirtyNavigationDialog,
ErrorSummary,
Form,
FormActions,
FormFailureStatus,
FormField,
FormPage,
FormSaveFeedback,
useAppForm,
useDirtyNavigationGuard,
} from "../../../presentation/design-system/index.ts";
@@ -664,33 +663,21 @@ export default function ${pascal}CreatePage() {
},
[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).
const form = useAppForm({
schema: ${camel}FormSchema,
defaultValues: ${upper}_FORM_DEFAULTS,
allowedServerFields: ["name"],
mapToCommand: to${pascal}CreateCommand,
submit,
mutation,
});
const effectUnknown = mutation.state.indicator === "mutation-effect-unknown";
const blocked = effectUnknown || mutation.state.indicator === "mutation-pending";
// A save this form did not start holds the coordinator (one left running
// when the user came back, or the check behind "confirm applied"): the save
// is off and the feedback says a save is running (1105/08-04).
const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending;
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
return (
<Form
id={form.formId}
pending={form.pending}
onSubmit={(event) => {
if (blocked) {
event.preventDefault();
return;
}
void form.submitForm(event);
}}
>
<Form id={form.formId} pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<FormPage
feedbackId={form.feedbackId}
breadcrumb={<Link to={${camel}RouteUrl("${routeId}")}>{message("${camel}.list.title")}</Link>}
@@ -715,38 +702,23 @@ export default function ${pascal}CreatePage() {
type="submit"
pending={form.pending}
pendingLabel={message("${camel}.form.saving")}
disabled={effectUnknown || otherSaveRunning}
disabled={form.effectUnknown || form.otherSaveRunning}
>
{message("${camel}.form.save")}
</Button>
</FormActions>
}
feedback={
form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : undefined}
/>
) : effectUnknown ? (
<AsyncSurface
state={mutation.state}
supportReference={form.supportReference}
// The list shows whether the item is there; the form alone
// would show nothing but an emptied input (1105/08-02).
onReconcileUnknownEffect={(resolution) => {
void mutation.reconcileUnknownEffect(resolution).then(() => {
form.settleApplied();
if (mounted.current) void navigate(${camel}RouteUrl("${routeId}"));
});
}}
// Drawn only for a request with a key (a KEYED command).
onResendUnknownEffect={() => {
void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect()));
}}
/>
) : otherSaveRunning && form.result !== "effect-unknown" ? (
<AsyncSurface state={mutation.state} />
) : null
<FormSaveFeedback
form={form}
// 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}"));
}}
// The resend is drawn only for a request with a key (a KEYED command).
onResent={openSaved}
/>
}
guard={<DirtyNavigationDialog guard={guard} />}
/>
@@ -142,6 +142,12 @@ export type AsyncSurfaceProps = Readonly<{
* terminal error shows its own `failure.requestId`.
*/
supportReference?: string | undefined;
/**
* 1112/04-02. Words about the unknown save shown with it (a resend the
* server refused before the write: `form.resendLater`), not under the input
* error summary.
*/
notice?: ReactNode;
}>;
export function AsyncSurface({
@@ -155,6 +161,7 @@ export function AsyncSurface({
onResendUnknownEffect,
headingLevel,
supportReference,
notice,
}: AsyncSurfaceProps) {
const { message } = useLocale();
if (state.base === "idle") return idle ?? null;
@@ -231,6 +238,7 @@ export function AsyncSurface({
{message("action.resendMutation")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" && notice ? <p>{notice}</p> : null}
{state.indicator === "mutation-effect-unknown" && supportReference ? (
<p>
{message("template.supportReference", {
+1
View File
@@ -123,6 +123,7 @@ export {
FormActions,
FormFailureStatus,
FormField,
FormSaveFeedback,
useAppForm,
useDirtyNavigationGuard,
} from "../forms/index.ts";
+73 -2
View File
@@ -1,13 +1,16 @@
import { useId, type FormHTMLAttributes, type ReactNode } from "react";
import type { AsyncState } from "../../application/view-models/async-state.ts";
import type { AppFailure } from "../../contracts/errors.ts";
import { TerminalErrorSurface } from "../components/async-surface.tsx";
import { AsyncSurface, TerminalErrorSurface } from "../components/async-surface.tsx";
import type { HeadingLevel } from "../components/state-surfaces.tsx";
import { TextField } from "../components/ui/text-field.ts";
import { useLocale } from "../i18n/index.ts";
import { useLocale, type ParameterlessMessageKey } from "../i18n/index.ts";
import type {
FieldErrors,
FieldName,
FormResult,
FormResultState,
FormValues,
} from "./form-contracts.ts";
@@ -126,3 +129,71 @@ export function FormActions(props: Readonly<{
</div>
);
}
/** What FormSaveFeedback reads of a `useAppForm` result given the `mutation` option. */
export type FormSaveFeedbackForm<Output> = Readonly<{
effectUnknown: boolean;
otherSaveRunning: boolean;
mutationState: AsyncState | undefined;
failure: AppFailure | null;
result: FormResultState;
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>;
}>;
/**
* 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`).
*/
export function FormSaveFeedback<Output>(props: Readonly<{
form: FormSaveFeedbackForm<Output>;
/** After "it was applied" has settled the request (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 notice = form.notice ? message(form.notice) : undefined;
if (form.effectUnknown && form.mutationState) {
return (
<AsyncSurface
notice={notice}
onReconcileUnknownEffect={() => {
void form.confirmUnknownEffect().then(() => onConfirmed?.());
}}
onResendUnknownEffect={() => {
void form.resendUnknownEffect(onResent);
}}
state={form.mutationState}
supportReference={form.supportReference}
/>
);
}
if (form.failure) {
return (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : onFailureAction}
/>
);
}
if (form.result === "conflict" && notice) {
return <p role="alert">{notice}</p>;
}
if (form.otherSaveRunning && form.mutationState && form.result !== "effect-unknown") {
return <AsyncSurface state={form.mutationState} />;
}
return null;
}
+120 -11
View File
@@ -9,6 +9,7 @@ import {
type FormEvent,
} from "react";
import { flushSync } from "react-dom";
import type { AsyncState } from "../../application/view-models/async-state.ts";
import type { ZodIssue, ZodType } from "../../contracts/zod.ts";
import {
isRefusedOnEveryAttempt,
@@ -39,6 +40,16 @@ export type FormRefusalMessage<Values extends FormValues> = Readonly<{
field?: FieldName<Values>;
}>;
/**
* 1112/01-01. What `useAppForm` needs of the mutation it saves through
* (`useApplicationMutation`). A `BoundMutation` is one.
*/
export type FormSaveMutation<Output> = Readonly<{
state: AsyncState;
reconcileUnknownEffect(resolution: "APPLIED"): Promise<void>;
resendUnknownEffect(): Promise<FormResult<Output> | null>;
}>;
type AppFormOptions<
Values extends FormValues,
Command,
@@ -60,6 +71,16 @@ type AppFormOptions<
* unknown whatever its code.
*/
refusalMessages?: Readonly<Record<string, FormRefusalMessage<Values>>>;
/**
* 1112/01-01. The mutation `submit` goes through. Given, the form owns the
* rules a page used to copy: it refuses a save while the mutation holds an
* unknown result or runs one this form did not start (`saveBlocked`), the
* unknown result's confirm and resend go through it
* (`confirmUnknownEffect`, `resendUnknownEffect`), and what it says about
* a save that is not an input error goes to `notice` for
* `FormSaveFeedback`, not to the input error summary.
*/
mutation?: FormSaveMutation<Output>;
}>;
export function useAppForm<
@@ -76,6 +97,7 @@ export function useAppForm<
submit,
resetOnSuccess = true,
refusalMessages,
mutation,
} = options;
const generatedId = useId().replaceAll(":", "");
const formId = `app-form-${generatedId}`;
@@ -108,6 +130,16 @@ export function useAppForm<
[formErrorKeys, resolve],
);
const [pending, setPending] = useState(false);
// 1112/04-02. With a mutation: the status line FormSaveFeedback shows.
const [notice, setNotice] = useState<ParameterlessMessageKey | null>(null);
const indicator = mutation?.state.indicator;
const effectUnknown = indicator === "mutation-effect-unknown";
// A save of this mutation the form did not start: one left running when
// the user came back, or the check behind "confirm applied" (1105/08-04).
const otherSaveRunning = indicator === "mutation-pending" && !pending;
const saveBlocked = effectUnknown || indicator === "mutation-pending";
const saveBlockedRef = useRef(saveBlocked);
saveBlockedRef.current = saveBlocked;
const [result, setResult] = useState<FormResultState>("idle");
const [statusFailure, setStatusFailure] = useState<AppFailure | null>(null);
const pendingRef = useRef<Promise<FormResult<Output> | null> | null>(null);
@@ -176,6 +208,8 @@ export function useAppForm<
return next;
});
setFormErrors([]);
// The notice of a save still unknown stays; a conflict's goes with it.
setNotice((current) => (unknownSubmissionRef.current ? current : null));
setResult((current) =>
unknownSubmissionRef.current ? current : "idle",
);
@@ -208,6 +242,7 @@ export function useAppForm<
setTouched(new Set());
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("idle");
},
[defaultValues],
@@ -221,6 +256,7 @@ export function useAppForm<
flushSync(() => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("success");
if (resetOnSuccess) {
setValues(defaultValues);
@@ -246,6 +282,7 @@ export function useAppForm<
focusFeedbackRef.current = focusIsLost();
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("success");
}, []);
@@ -264,6 +301,7 @@ export function useAppForm<
unknownSubmissionRef.current = null;
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("idle");
}, []);
@@ -303,7 +341,20 @@ export function useAppForm<
if (onField !== undefined) focusField(onField);
return;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
if (
outcome.error.effect === "MAYBE_APPLIED" &&
outcome.error.action !== "reauth"
) {
// 1101/03-04. Before an input error: a save that may have applied is
// not corrected and sent again, whatever field its failure names.
focusFeedbackRef.current = true;
unknownSubmissionRef.current = { values: submittedValues };
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
// 0929/08-04. Kept for its request id, not shown as a status.
setStatusFailure(outcome.error);
setResult("effect-unknown");
} else if (outcome.error.kind === "VALIDATION_REJECTED") {
unknownSubmissionRef.current = null;
const mapped = mapValidationFailureToFields<Values>(
outcome.error,
@@ -321,19 +372,19 @@ export function useAppForm<
setFormErrors([]);
setStatusFailure(outcome.error);
setResult("reauth-required");
} else if (outcome.error.effect === "MAYBE_APPLIED") {
focusFeedbackRef.current = true;
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") {
settleSaved();
} else if (outcome.error.kind === "CONFLICT") {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = null;
setFormErrors(["form.conflict"]);
// 1112/04-02. Not an input error: with a mutation, FormSaveFeedback
// says it; without one the page reads it from formErrors as before.
if (mutation) {
setFormErrors([]);
setNotice("form.conflict");
} else {
setFormErrors(["form.conflict"]);
}
setResult("conflict");
} else if (
outcome.error.kind === "FORBIDDEN" ||
@@ -359,6 +410,7 @@ export function useAppForm<
allowedServerFields,
focusField,
focusFirstError,
mutation,
refusalMessages,
settleSuccessfulValues,
settleUnsentValues,
@@ -369,6 +421,7 @@ export function useAppForm<
async (): Promise<FormResult<Output> | null> => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
const parsed = await schema.safeParseAsync(values);
if (!parsed.success) {
@@ -419,6 +472,9 @@ export function useAppForm<
// let a second submit through before the command starts.
if (pendingRef.current) return pendingRef.current;
if (unknownSubmissionRef.current) return Promise.resolve(null);
// 1112/01-01. The mutation holds an unknown result or runs a save this
// form did not start: a new save would go out as a second request.
if (saveBlockedRef.current) return Promise.resolve(null);
const submission = validateAndSubmit().finally(() => {
pendingRef.current = null;
});
@@ -453,7 +509,15 @@ export function useAppForm<
focusFeedbackRef.current = true;
unknownSubmissionRef.current = { values: submittedValues };
setFieldErrors({} as FieldErrors<Values>);
setFormErrors(["form.resendLater"]);
// 1112/04-02. With a mutation the words go to the unknown
// result's own surface (FormSaveFeedback), not under the input
// error summary.
if (mutation) {
setFormErrors([]);
setNotice("form.resendLater");
} else {
setFormErrors(["form.resendLater"]);
}
setResult("effect-unknown");
} else if (outcome) {
applyOutcome(outcome, submittedValues);
@@ -468,7 +532,37 @@ export function useAppForm<
pendingRef.current = resend;
return resend;
},
[applyOutcome],
[applyOutcome, 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.
*/
const confirmUnknownEffect = useCallback(async (): Promise<void> => {
if (!mutation) throw new TypeError("useAppForm: confirmUnknownEffect needs the mutation option");
await mutation.reconcileUnknownEffect("APPLIED");
settleApplied();
}, [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).
*/
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],
);
return Object.freeze({
@@ -510,6 +604,21 @@ export function useAppForm<
reset,
settleApplied,
settleNotApplied,
/**
* 1112/01-01. With the `mutation` option: the mutation holds an unknown
* result or runs a save; `submitForm` sends nothing. Without it, false.
*/
saveBlocked,
/** The mutation's request is unknown: FormSaveFeedback shows its surface. */
effectUnknown,
/** A save of the mutation this form did not start is running. */
otherSaveRunning,
/** The mutation's state, for FormSaveFeedback's surfaces. */
mutationState: mutation?.state,
/** 1112/04-02. What the save feedback says besides a failure (a key). */
notice,
confirmUnknownEffect,
resendUnknownEffect,
});
}
+156
View File
@@ -26,6 +26,7 @@ import {
Form,
FormFailureStatus,
FormField,
FormSaveFeedback,
useAppForm,
useDirtyNavigationGuard,
validationMessage,
@@ -1346,3 +1347,158 @@ describe("correcting a field after a server validation refusal", () => {
expect(sentKeys(fetcher)).toEqual(["key-1", "key-1", "key-2"]);
});
});
// 1112/01-01. The page used to hold the rules of a save through a mutation:
// it refused a new save while the coordinator held one unknown or running,
// and it wired the unknown-result surface's confirm and resend to the form.
// A generated page kept its own copy, so a platform fix never reached it.
// Now the form takes the mutation and FormSaveFeedback draws the feedback.
describe("a form bound to its mutation", () => {
let token = 0;
const scope = {
...scopeSnapshot(),
identities: createRuntimeIdentityRegistry({
tokenFactory: () => `bound-identity-token-${String(++token).padStart(4, "0")}`,
}),
};
const meta = { requestId: "request-1", traceId: "trace-1" };
function BoundForm(props: Readonly<{ fetcher: typeof fetch }>) {
const [http] = useState(() => formBinding(props.fetcher));
const mutation = useApplicationMutation<Readonly<{ name: string; note?: string }>, unknown>({
definitionId: "form-bound-create-v1",
definitionVersion: 1,
operationId: commandMutationIdentity(FORM_CREATE_CONTRACT).operationId,
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
invalidate: [],
execute: (command, { intent }) =>
http.execute("FORM_CREATE_ENTITY", { name: command.name }, { intent }),
});
const form = useAppForm({
schema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit: mutation.submit,
mutation,
});
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={{ name: "Name", note: "Note" }}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit" pending={form.pending} disabled={form.saveBlocked}>
Submit
</Button>
<div id={form.feedbackId} tabIndex={-1}>
<FormSaveFeedback form={form} />
</div>
<output data-testid="result">{form.result}</output>
<output data-testid="indicator">{mutation.state.indicator ?? "none"}</output>
</Form>
);
}
function lostThen(...answers: Response[]) {
const fetcher = vi.fn<typeof fetch>().mockRejectedValueOnce(new TypeError("Failed to fetch"));
for (const answer of answers) fetcher.mockResolvedValueOnce(answer);
return fetcher.mockImplementation(async () =>
Response.json({ success: true, data: { id: "entity-1", name: "Saved" }, meta }),
);
}
async function loseFirstSave(fetcher: typeof fetch) {
const user = userEvent.setup();
const view = render(<BoundForm fetcher={fetcher} />, { wrapper: wrapper(queryClient()) });
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 };
}
it("refuses a new save while the coordinator holds one unknown", async () => {
const fetcher = lostThen();
const { view } = await loseFirstSave(fetcher);
const form = view.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();
});
it("confirms the save applied through the form, which settles both", async () => {
const { user } = await loseFirstSave(lostThen());
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.confirmMutationApplied") }),
);
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("success"));
expect(screen.getByTestId("indicator")).toHaveTextContent("none");
});
// UX-02 (1112/04-02). The same-key resend was refused before the write: the
// save is still unknown, and the words say so where the unknown result is,
// not under the "check what you entered" summary.
it("says a resend refused before the write in the feedback, not as an input error", async () => {
const fetcher = lostThen(
Response.json(
{
success: false,
error: { code: "RATE_LIMIT_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true },
meta,
},
{ status: 503 },
),
);
const { user } = await loseFirstSave(fetcher);
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
);
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
const status = await screen.findByRole("status");
await waitFor(() =>
expect(status).toHaveTextContent(formatMessage("ko-KR", "form.resendLater")),
);
expect(
screen.queryByRole("heading", { name: formatMessage("ko-KR", "form.errorSummary") }),
).not.toBeInTheDocument();
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown");
});
});
// 1101/03-04. A failure that is both a field refusal and possibly applied
// (a feature's mapProblem says VALIDATION_REJECTED, the classifier
// MAYBE_APPLIED) shows the unknown result only: correcting the field would
// send a second save of something that may already be saved.
describe("a possibly applied failure that names a field", () => {
it("shows the unknown result, not a field error", async () => {
const user = userEvent.setup();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure("VALIDATION_REJECTED", "CREATE_ENTITY", 0, {
effect: "MAYBE_APPLIED",
validationIssues: [{ path: "name", code: "SIZE" }],
}),
}));
render(<FormHarness submit={submit} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Alpha");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"));
expect(screen.getByRole("textbox", { name: /Name/ })).not.toHaveAccessibleDescription(/./u);
});
});
+15
View File
@@ -554,3 +554,18 @@ describe("create:feature writing", () => {
await expect(access(path.join(root, "src"))).rejects.toThrow();
});
});
// 1112/01-01. The generated create page leaves the rules of a save through
// its mutation to the platform form: it gives useAppForm the mutation and
// draws FormSaveFeedback, so a platform fix to those rules reaches it.
describe("generated create page", () => {
it("hands the save rules to the platform form", () => {
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
const page = files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
expect(page).toContain(" mutation,\n");
expect(page).toContain("<FormSaveFeedback");
expect(page).not.toContain("mutation.state.indicator");
expect(page).not.toContain("reconcileUnknownEffect");
});
});