결과 불명 상태를 코디네이터(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
200 lines
6.2 KiB
TypeScript
200 lines
6.2 KiB
TypeScript
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 { 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, type ParameterlessMessageKey } from "../i18n/index.ts";
|
|
import type {
|
|
FieldErrors,
|
|
FieldName,
|
|
FormResult,
|
|
FormResultState,
|
|
FormValues,
|
|
} from "./form-contracts.ts";
|
|
|
|
export function Form(
|
|
props: FormHTMLAttributes<HTMLFormElement> & Readonly<{ pending?: boolean }>,
|
|
) {
|
|
const { pending = false, children, ...formProps } = props;
|
|
return (
|
|
<form {...formProps} noValidate aria-busy={pending || undefined}>
|
|
{children}
|
|
</form>
|
|
);
|
|
}
|
|
|
|
export function FormField(
|
|
props: React.ComponentProps<typeof TextField>,
|
|
) {
|
|
return <TextField {...props} />;
|
|
}
|
|
|
|
export function ErrorSummary<Values extends FormValues>(props: Readonly<{
|
|
fieldErrors: FieldErrors<Values>;
|
|
formErrors?: readonly string[];
|
|
fieldLabels: Readonly<Record<FieldName<Values>, string>>;
|
|
fieldId(name: FieldName<Values>): string;
|
|
onFocusField?(name: FieldName<Values>): void;
|
|
/** 08-05. Below the heading of the card or section that holds it. */
|
|
headingLevel?: HeadingLevel | undefined;
|
|
}>) {
|
|
const { message } = useLocale();
|
|
const {
|
|
fieldErrors,
|
|
formErrors = [],
|
|
fieldLabels,
|
|
fieldId,
|
|
onFocusField,
|
|
headingLevel = 2,
|
|
} = props;
|
|
const headingId = useId();
|
|
const Heading = `h${headingLevel}` as const;
|
|
const entries = Object.entries(fieldErrors) as [
|
|
FieldName<Values>,
|
|
string,
|
|
][];
|
|
if (entries.length === 0 && formErrors.length === 0) return null;
|
|
return (
|
|
<section
|
|
className="form-error-summary"
|
|
role="alert"
|
|
aria-labelledby={headingId}
|
|
>
|
|
<Heading id={headingId}>{message("form.errorSummary")}</Heading>
|
|
{entries.length > 0 ? (
|
|
<ul>
|
|
{entries.map(([name, message]) => (
|
|
<li key={name}>
|
|
<a
|
|
href={`#${fieldId(name)}`}
|
|
onClick={(event) => {
|
|
if (!onFocusField) return;
|
|
event.preventDefault();
|
|
onFocusField(name);
|
|
}}
|
|
>
|
|
{fieldLabels[name]}: {message}
|
|
</a>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
) : null}
|
|
{formErrors.map((message) => (
|
|
<p key={message}>{message}</p>
|
|
))}
|
|
</section>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 08-01. A save that failed for a reason other than the input (sign-in,
|
|
* permission, retry later, unavailable) is announced here with its own action, not in
|
|
* ErrorSummary. Pass `useAppForm().failure`.
|
|
*/
|
|
export function FormFailureStatus(props: Readonly<{
|
|
failure: AppFailure | null;
|
|
onAction?: () => void;
|
|
}>) {
|
|
const { message } = useLocale();
|
|
const { failure, onAction } = props;
|
|
if (!failure) return null;
|
|
return (
|
|
<TerminalErrorSurface
|
|
userMessageKey={failure.userMessageKey}
|
|
action={failure.action}
|
|
onAction={onAction}
|
|
// Signing in remounts the scope, so the entered values do not survive.
|
|
description={
|
|
failure.action === "reauth"
|
|
? message("form.reauthLosesInput")
|
|
: undefined
|
|
}
|
|
// 0929/08-04. The same support reference a failed query shows.
|
|
supportReference={failure.requestId}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function FormActions(props: Readonly<{
|
|
children: ReactNode;
|
|
sticky?: boolean;
|
|
}>) {
|
|
return (
|
|
<div
|
|
className={`form-actions${props.sticky ? " form-actions--sticky" : ""}`}
|
|
>
|
|
{props.children}
|
|
</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;
|
|
}
|