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
@@ -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,
});
}