fix(scaffold): 저장 중에 떠난 사용자를 생성 작성 폼이 상세로 옮기지 않는다

문제: 생성기 템플릿의 작성 폼은 저장을 기다린 뒤 openSaved에서 상세로
navigate한다. 그 사이 화면이 남아 있는지 보지 않는다. 저장 중에는 이탈 확인이
꺼져 있어 사용자는 목록이나 다른 기능으로 갈 수 있다. 저장이 끝나면 언마운트된
화면의 navigate가 앱을 그 항목의 상세로 옮긴다(데이터 라우터의 navigate는
언마운트 뒤에도 동작한다, 리뷰 probe 08-R7). 다시 돌아온 작성 폼에 입력이
있으면 이유 없는 이탈 확인 창이 뜬다. 참조 폼은 저장 뒤 이동하지 않아 생성기에만
있다.

고른 방법: 생성 페이지가 마운트 여부를 ref로 들고(useEffect에서 true, 정리에서
false), 저장 뒤 상세 이동과 "변경됨으로 확인" 뒤 목록 이동을 마운트된 동안만
한다. 생성 페이지 테스트에 한 행을 더했다: 저장을 붙잡아 둔 채 breadcrumb으로
목록에 가고, 저장을 끝내면 목록이 새 항목을 보이고(목록 무효화) 1초 안에 상세
heading이 오지 않으며 목록 heading이 남는다. 생성기 단위 테스트가 두 조건과 그
행을 NEVER·KEYED 모두에서 본다. 매뉴얼 reference/create-feature.md에 적었다.
버린 대안: 현재 위치가 작성 라우트인지 보기(다시 돌아온 새 인스턴스가 있으면
옛 인스턴스의 이동도 통과한다), 이동 대신 결과를 남겨 보이기(1106/08-01 (2)처럼;
완료 기준은 이동만 요구해 이번에는 넣지 않았다).

위험·한계: 떠난 뒤 끝난 저장은 다시 돌아온 작성 폼에 결과를 보이지 않는다(참조
폼의 목록 안내는 생성기에 없다). 생성 페이지 테스트의 새 행은 녹색일 때 1초를
기다린다(상세가 오지 않음을 보는 음성 확인). repo 안에 생성 결과 파일은 없다
(src/features/.generated 없음). 이미 생성한 기능에는 반영되지 않는다.

검증: desktop batch에서 확인. node scripts/run-vitest.ts run
tests/unit/create-feature.test.ts, corepack pnpm test:feature-scaffold
(FE-GATE-020, 생성 기능 드릴 NEVER·KEYED)

Refs: 1106/08-02
This commit is contained in:
DongHyeonka
2026-11-06 05:36:06 +09:00
parent fbaaaee43d
commit 116cbf3d06
3 changed files with 90 additions and 7 deletions
+68 -5
View File
@@ -589,7 +589,7 @@ export default function ${pascal}DetailPage() {
export function renderCreatePage({ names, routeId, write }: SliceShape): string {
const { base, camel, pascal, upper } = names;
return `import { useCallback } from "react";
return `import { useCallback, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
import type { Result } from "../../../contracts/result.ts";
@@ -619,7 +619,8 @@ import { ${camel}RouteUrl } from "./${base}-routes.ts";
import { use${pascal}Create } from "./use-${base}-create.ts";
/**
* The create form. A saved item opens its detail page. The backend's refusal
* The create form. A saved item opens its detail page, unless the user left
* this page while it saved. The backend's refusal
* of the name (400 ${write.invalidCode}, refused before the write) shows on
* the field and the form saves again. A save whose result is unknown (the
* response was lost) keeps the form: the user checks, or, for a KEYED
@@ -633,9 +634,18 @@ export default function ${pascal}CreatePage() {
name: message("${camel}.form.name"),
} satisfies Record<keyof ${pascal}FormValues, string>;
const mutation = use${pascal}Create();
// A save outlives this page when the user leaves while it runs. Ending
// then, it does not take them to its item or the list (1106/08-02).
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const openSaved = useCallback(
(outcome: Result<${pascal}ItemView> | null) => {
if (outcome?.ok) {
if (outcome?.ok && mounted.current) {
void navigate(
${camel}RouteUrl("${write.detail.routeId}", {
params: { ${write.idParam}: outcome.value.itemId },
@@ -726,7 +736,7 @@ export default function ${pascal}CreatePage() {
onReconcileUnknownEffect={(resolution) => {
void mutation.reconcileUnknownEffect(resolution).then(() => {
form.settleApplied();
void navigate(${camel}RouteUrl("${routeId}"));
if (mounted.current) void navigate(${camel}RouteUrl("${routeId}"));
});
}}
// Drawn only for a request with a key (a KEYED command).
@@ -788,7 +798,7 @@ export function renderCreatePageTest({ names, apiPath, write }: SliceShape): str
});`;
return `// @vitest-environment jsdom
import { screen } from "@testing-library/react";
import { screen, waitFor, within } from "@testing-library/react";
import { http, HttpResponse, type JsonBodyType } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
@@ -931,6 +941,59 @@ ${unknownTest}
expect(await screen.findByText("First item")).toBeVisible();
expect(posts).toHaveLength(1);
});
// 1106/08-02. The user leaves for the list while the save runs. The save
// that ends then does not take them to the item: they stay on the list.
it("stays on the list the user went to while the create was saving", async () => {
let answerPost: ((response: Response) => void) | undefined;
api.use(
http.post(
\`\${API}${apiPath}\`,
() =>
new Promise<Response>((resolve) => {
answerPost = resolve;
}),
),
);
let lists = 0;
api.use(
http.get(\`\${API}${apiPath}\`, () => {
lists += 1;
return HttpResponse.json({
success: true,
data: lists === 1 ? [] : [{ id: ITEM_ID, name: "First item" }],
meta: META,
});
}),
);
answerItem();
const user = await openForm();
await user.type(await nameField(), "First item");
await user.click(saveButton());
await waitFor(() => expect(answerPost).toBeDefined());
await user.click(
within(screen.getByRole("navigation", { name: KO_MESSAGES["template.breadcrumb"] })).getByRole(
"link",
{ name: MESSAGES["${camel}.list.title"] },
),
);
expect(
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
).toBeVisible();
answerPost?.(created());
// The create invalidates the list: the item there means the save ended.
// Opening the item would show its name as the heading within a second
// (earlier tests here loaded the detail page); it never comes.
expect(await screen.findByRole("link", { name: "First item" })).toBeVisible();
await expect(
screen.findByRole("heading", { level: 1, name: "First item" }, { timeout: 1_000 }),
).rejects.toThrow();
expect(
screen.getByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
).toBeVisible();
});
});
`;
}