diff --git a/docs/adr/VD-04-native-form-facade.md b/docs/adr/VD-04-native-form-facade.md index 859500a4..91a263e4 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/` +- 현재 정본: `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 diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 145996e6..f2fbdc95 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -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`로 분류하지 않는다.** diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index 6fa3962b..d8ef76a8 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -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/-form.ts`와 `-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인) | +| 폼 | `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/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 bf1367b5..2ac3cb93 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -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 ( -
{ - if (blocked) { - event.preventDefault(); - return; - } - void form.submitForm(event); - }} - > + void form.submitForm(event)}> {message("${camel}.list.title")}} @@ -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")} } feedback={ - form.failure ? ( - void form.submitForm() : undefined} - /> - ) : effectUnknown ? ( - { - 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" ? ( - - ) : null + { + 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={} /> diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index 041d3072..f2773888 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -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")} ) : null} + {state.indicator === "mutation-effect-unknown" && notice ?

{notice}

: null} {state.indicator === "mutation-effect-unknown" && supportReference ? (

{message("template.supportReference", { diff --git a/src/presentation/design-system/index.ts b/src/presentation/design-system/index.ts index 4ec1456e..535d724f 100644 --- a/src/presentation/design-system/index.ts +++ b/src/presentation/design-system/index.ts @@ -123,6 +123,7 @@ export { FormActions, FormFailureStatus, FormField, + FormSaveFeedback, useAppForm, useDirtyNavigationGuard, } from "../forms/index.ts"; diff --git a/src/presentation/forms/form-components.tsx b/src/presentation/forms/form-components.tsx index a5d400a7..b7a98b0c 100644 --- a/src/presentation/forms/form-components.tsx +++ b/src/presentation/forms/form-components.tsx @@ -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<{ ); } + +/** What FormSaveFeedback reads of a `useAppForm` result given the `mutation` option. */ +export type FormSaveFeedbackForm = Readonly<{ + effectUnknown: boolean; + otherSaveRunning: boolean; + mutationState: AsyncState | undefined; + failure: AppFailure | null; + result: FormResultState; + notice: ParameterlessMessageKey | null; + supportReference: string | undefined; + submitForm(): Promise; + confirmUnknownEffect(): Promise; + resendUnknownEffect( + then?: (outcome: FormResult | null) => FormResult | null, + ): 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`). + */ +export function FormSaveFeedback(props: Readonly<{ + form: FormSaveFeedbackForm; + /** 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 | 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 notice = form.notice ? message(form.notice) : undefined; + if (form.effectUnknown && form.mutationState) { + return ( + { + void form.confirmUnknownEffect().then(() => onConfirmed?.()); + }} + onResendUnknownEffect={() => { + void form.resendUnknownEffect(onResent); + }} + state={form.mutationState} + supportReference={form.supportReference} + /> + ); + } + if (form.failure) { + return ( + void form.submitForm() : onFailureAction} + /> + ); + } + if (form.result === "conflict" && notice) { + return

{notice}

; + } + if (form.otherSaveRunning && form.mutationState && form.result !== "effect-unknown") { + return ; + } + return null; +} diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index 406b7300..eefb38ba 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -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 = Readonly<{ field?: FieldName; }>; +/** + * 1112/01-01. What `useAppForm` needs of the mutation it saves through + * (`useApplicationMutation`). A `BoundMutation` is one. + */ +export type FormSaveMutation = Readonly<{ + state: AsyncState; + reconcileUnknownEffect(resolution: "APPLIED"): Promise; + resendUnknownEffect(): Promise | null>; +}>; + type AppFormOptions< Values extends FormValues, Command, @@ -60,6 +71,16 @@ type AppFormOptions< * unknown whatever its code. */ refusalMessages?: Readonly>>; + /** + * 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; }>; 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(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("idle"); const [statusFailure, setStatusFailure] = useState(null); const pendingRef = useRef | 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); setFormErrors([]); + setNotice(null); setResult("idle"); }, [defaultValues], @@ -221,6 +256,7 @@ export function useAppForm< flushSync(() => { setFieldErrors({} as FieldErrors); setFormErrors([]); + setNotice(null); setResult("success"); if (resetOnSuccess) { setValues(defaultValues); @@ -246,6 +282,7 @@ export function useAppForm< focusFeedbackRef.current = focusIsLost(); setFieldErrors({} as FieldErrors); setFormErrors([]); + setNotice(null); setResult("success"); }, []); @@ -264,6 +301,7 @@ export function useAppForm< unknownSubmissionRef.current = null; setFieldErrors({} as FieldErrors); 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); + 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( 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 | null> => { setFieldErrors({} as FieldErrors); 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); - 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 => { + 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 | 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], ); 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, }); } diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 0324f8fd..db683485 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -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, 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 ( + void form.submitForm(event)}> + + + +
+ +
+ {form.result} + {mutation.state.indicator ?? "none"} + + ); + } + + function lostThen(...answers: Response[]) { + const fetcher = vi.fn().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(, { 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(); + 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); + }); +}); diff --git a/tests/unit/create-feature.test.ts b/tests/unit/create-feature.test.ts index addc1b40..d669d9ab 100644 --- a/tests/unit/create-feature.test.ts +++ b/tests/unit/create-feature.test.ts @@ -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("