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