fix(forms): 필드 오류가 아닌 저장 실패 뒤 키보드 포커스를 실패 상태로 옮긴다 (1103/08-02)

문제
참조 폼 페이지는 저장 중과 결과 불명 동안 저장 버튼에 disabled를 준다.
포커스가 있던 버튼이 꺼지면 브라우저가 포커스를 body로 내려놓는다. 폼은 필드
오류일 때만 포커스를 옮겼으므로, 키보드로 저장했다가 결과 불명(500)이나 429를
받으면 세 엔진 모두 포커스가 body로 떨어졌다. 복구 버튼은 폼 위 feedback
자리에 있어 셸 머리말부터 다시 지나야 닿았다.

고른 방법
- useAppForm이 feedbackId를 내고, 필드 오류·성공이 아닌 결과(결과 불명,
  재인증, 권한 없음, 다시 시도, 사용 불가, 충돌)로 끝나면 렌더 뒤 그 요소에
  포커스를 준다. FormPage(StandardPage)는 feedbackId를 받으면 feedback 자리를
  id + tabIndex=-1인 포커스 대상으로 만든다. 페이지마다 포커스 코드를 복사하지
  않게 하려고 hook과 템플릿에 두었다.
- 참조 폼의 저장 버튼은 저장 중에 disabled 대신 Button의 pending(aria-busy)을
  쓴다. 중복 제출은 지금처럼 폼(submitForm)과 onSubmit 가드가 막는다. 결과
  불명 동안에는 여전히 꺼진다(08-01 범위). 그때는 위의 포커스 이동이 받는다.
- 첫 행동 버튼 대신 feedback 자리 전체를 포커스한 이유: 실패 종류마다 버튼
  구성이 다르고, Tab 한 번에 첫 복구 버튼에 닿는다.
매뉴얼 02 6절 FormPage에 feedbackId와 pending을 적었다.

위험·한계
- 스크린 리더가 포커스된 feedback 자리를 어떻게 읽는지는 확인하지 않았다.
- 파생 폼 페이지는 feedbackId를 넘겨야 이 동작을 얻는다.
- "deduplicates create" 테스트의 저장 중 단언을 disabled에서 aria-busy와
  포커스 유지로 바꿨다. 한 번만 호출되는 단언은 그대로다.

검증
- RED: reference-page.test.tsx 새 2행(결과 불명, 429)이 수정 전 실패. e2e
  reference-save.spec.ts 새 2건이 수정 전 소스에서 chromium·firefox·webkit
  6건 모두 실패(feedback 자리 focused 아님).
- 수정 후 reference-save·reference-form e2e 3엔진 45건 통과(heavy lock,
  CHOKIDAR_USEPOLLING=1). tests/component·tests/features 60 files / 368
  tests 통과. check:types, eslint, check:design-system, check:i18n,
  verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/08-presentation.md 08-02
This commit is contained in:
DongHyeonka
2026-11-04 20:42:32 +09:00
parent 2963c6f42c
commit 2d5d41f85d
6 changed files with 142 additions and 6 deletions
+1
View File
@@ -212,6 +212,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
- `CollectionPage`: 목록. 도구 막대, 필터, 결과 수, 일괄 작업, 페이지 넘김 자리가 있다. 생성된 뼈대가 이것이다.
- `DetailPage`: 한 항목 보기. 요약(`metadata`)과 위험한 작업(`destructiveAction`) 자리가 있다.
- `FormPage`: 만들기·고치기. 오류 요약, 필드, 폼 버튼, 이탈 확인(`guard`) 자리가 있다.
- `feedbackId={form.feedbackId}`를 넘기면 저장이 필드 오류가 아닌 실패(결과 불명, 429 등)로 끝날 때 포커스가 실패 상태로 간다. 저장 버튼은 저장 중에 `disabled` 대신 `pending`을 쓴다. 꺼진 버튼은 키보드 포커스를 잃는다.
- `StatusPage`: 안내 화면. 로그인 필요, 권한 없음, 없음, 쓸 수 없음, 오프라인, 점검, 예상 못 한 오류(`variant`).
- `StandardPage`: 위 넷에 맞지 않는 페이지. 넷 모두 이것을 바탕으로 한다.
@@ -68,6 +68,7 @@ export default function ReferenceResourceFormPage() {
}}
>
<FormPage
feedbackId={form.feedbackId}
breadcrumb={
<button
className="ui-button ui-button--ghost"
@@ -117,13 +118,16 @@ export default function ReferenceResourceFormPage() {
>
{message("reference.form.cancel")}
</Button>
{/* 1103/08-02. Busy, not disabled, while saving: a disabled
button drops keyboard focus. The form refuses a second
submit itself. */}
<Button
type="submit"
disabled={form.pending || mutationBlocked}
pending={form.pending}
pendingLabel={message("reference.form.saving")}
disabled={mutationEffectUnknown}
>
{form.pending
? message("reference.form.saving")
: message("reference.form.save")}
{message("reference.form.save")}
</Button>
<Button
variant="ghost"
+24
View File
@@ -1,5 +1,6 @@
import {
useCallback,
useEffect,
useId,
useMemo,
useRef,
@@ -54,6 +55,7 @@ export function useAppForm<
} = options;
const generatedId = useId().replaceAll(":", "");
const formId = `app-form-${generatedId}`;
const feedbackId = `${formId}-feedback`;
const [values, setValues] = useState<Values>(defaultValues);
const [initialValues, setInitialValues] = useState<Values>(defaultValues);
const [touched, setTouched] = useState<ReadonlySet<FieldName<Values>>>(
@@ -86,6 +88,17 @@ export function useAppForm<
const [statusFailure, setStatusFailure] = useState<AppFailure | null>(null);
const pendingRef = useRef<Promise<FormResult<Output> | null> | null>(null);
const unknownSubmissionRef = useRef<Values | null>(null);
// 1103/08-02. A save that ends in neither a field error nor success shows
// its status above the form while the page disables the button that had
// focus, so the browser drops focus to the body. The status takes focus
// once it has rendered (`feedbackId`).
const focusFeedbackRef = useRef(false);
useEffect(() => {
if (!focusFeedbackRef.current) return;
focusFeedbackRef.current = false;
const feedback = document.getElementById(feedbackId);
if (feedback instanceof HTMLElement) feedback.focus();
});
const dirty = useMemo(
() => JSON.stringify(values) !== JSON.stringify(initialValues),
@@ -214,11 +227,13 @@ export function useAppForm<
focusFirstError(mapped.fieldErrors);
} else if (outcome.error.action === "reauth") {
// D-2. Signing in again comes first, whatever the effect.
focusFeedbackRef.current = true;
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
setResult("reauth-required");
} else if (outcome.error.effect === "MAYBE_APPLIED") {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = submittedValues;
setFormErrors([]);
// 0929/08-04. Kept for its request id, not shown as a status.
@@ -227,6 +242,7 @@ export function useAppForm<
} else if (outcome.error.effect === "APPLIED_CONFIRMED") {
settleSuccessfulValues(submittedValues);
} else if (outcome.error.kind === "CONFLICT") {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = null;
setFormErrors(["form.conflict"]);
setResult("conflict");
@@ -234,6 +250,7 @@ export function useAppForm<
outcome.error.kind === "FORBIDDEN" ||
outcome.error.action === "retry"
) {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
@@ -242,6 +259,7 @@ export function useAppForm<
);
} else {
// F-10. Not an input error either: shown by FormFailureStatus.
focusFeedbackRef.current = true;
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
@@ -347,6 +365,12 @@ export function useAppForm<
return Object.freeze({
formId,
/**
* 1103/08-02. Give it to the page template (`FormPage` `feedbackId`): the
* feedback area takes focus when a save ends in a status instead of a
* field error.
*/
feedbackId,
values,
dirty,
touched,
+13 -1
View File
@@ -39,6 +39,11 @@ export type PageTemplateSlots = Readonly<{
children?: ReactNode;
aside?: ReactNode;
feedback?: ReactNode;
/**
* 1103/08-02. Makes the feedback area a focus target under this id
* (`useAppForm` `feedbackId`), so a form can move focus there.
*/
feedbackId?: string;
}>;
export function StandardPage(props: PageTemplateSlots) {
@@ -66,7 +71,14 @@ export function StandardPage(props: PageTemplateSlots) {
<div className="page-template__notices">{props.notices}</div>
) : null}
{props.feedback ? (
<div className="page-template__feedback">{props.feedback}</div>
<div
className="page-template__feedback"
{...(props.feedbackId === undefined
? {}
: { id: props.feedbackId, tabIndex: -1 })}
>
{props.feedback}
</div>
) : null}
<div
className="page-template__layout"
+42
View File
@@ -34,6 +34,25 @@ async function routeCreate(
return calls;
}
/**
* 1103/08-02. Saves from the keyboard and checks where focus lands: in the
* failure status above the form, one Tab away from its first action, not on
* the body after the page disabled the save button.
*/
async function saveFromKeyboard(page: Page, expectedFirstAction: string) {
await page
.getByRole("textbox", { name: /새 항목 이름/ })
.fill("Saved in the browser");
await page.getByRole("button", { name: "저장" }).focus();
await page.keyboard.press("Enter");
await expect(page.locator(".page-template__feedback")).toBeFocused();
await page.keyboard.press("Tab");
await expect(
page.getByRole("button", { name: expectedFirstAction }),
).toBeFocused();
}
const created = (route: Route) =>
route.fulfill({
status: 201,
@@ -97,6 +116,20 @@ test.describe("after a rate-limited save", () => {
"Saved in the browser",
]);
});
test("keeps keyboard focus in the failure status", async ({ page }) => {
await openForm(page);
await routeCreate(page, [
(route) =>
route.fulfill({
status: 429,
headers: { "retry-after": "1" },
json: { title: "Too many requests" },
}),
]);
await saveFromKeyboard(page, "다시 시도");
});
});
test.describe("after a save whose result is unknown", () => {
@@ -129,4 +162,13 @@ test.describe("after a save whose result is unknown", () => {
await expect(page.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible();
await expect(page.getByText("지원 참조: corr-save-500")).toBeVisible();
});
test("keeps keyboard focus in the unknown-result status", async ({ page }) => {
await openForm(page);
await routeCreate(page, [
(route) => route.fulfill({ status: 500, json: { title: "Internal error" } }),
]);
await saveFromKeyboard(page, "변경됨으로 확인");
});
});
@@ -332,7 +332,11 @@ describe("reference feature page states", () => {
await user.dblClick(submit);
await waitFor(() => expect(createResource).toHaveBeenCalledOnce());
expect(screen.getByRole("button", { name: "저장 중…" })).toBeDisabled();
// 1103/08-02. Busy, not disabled: a disabled button drops keyboard focus
// to the body. The second click is refused by the form, not the button.
const saving = screen.getByRole("button", { name: "저장 중…" });
expect(saving).toHaveAttribute("aria-busy", "true");
expect(saving).toHaveFocus();
finish?.({
ok: false,
@@ -463,6 +467,55 @@ describe("reference feature page states", () => {
},
);
/**
* 1103/08-02. A keyboard save whose failure is not a field error used to
* leave focus on a button the result disables, so the browser dropped it
* to the body. Focus now moves to the failure status above the form, and
* one Tab reaches its first recovery action.
*/
it.each([
{
result: "unknown",
failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
text: "변경 결과를 확인할 수 없습니다.",
firstAction: "변경됨으로 확인",
},
{
result: "rate-limited",
failure: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "NOT_APPLIED",
httpStatus: 429,
}),
text: "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
firstAction: "다시 시도",
},
])("moves focus to the failure status after a keyboard save ($result)", async ({
failure,
text,
firstAction,
}) => {
const user = userEvent.setup();
renderReference(
inputWith({ createResource: async () => ({ ok: false, error: failure }) }),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Keyboard save",
);
screen.getByRole("button", { name: "저장" }).focus();
await user.keyboard("{Enter}");
const status = (await screen.findByText(text)).closest(
".page-template__feedback",
);
await waitFor(() => expect(status).toHaveFocus());
await user.tab();
expect(screen.getByRole("button", { name: firstAction })).toHaveFocus();
});
// 0929/08-04. The ids a user quotes to support reach the screens that
// need them, and the sample status page shows no made-up reference.
it("shows the request id of an unknown create next to its result", async () => {