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:
@@ -66,7 +66,7 @@ corepack pnpm create:feature <id> [--context <context id>] [--with-create [--key
|
||||
- `presentation/use-<base>-create.ts`: 작성 뮤테이션 정책(`commandMutationIdentity`)
|
||||
- `presentation/<base>-form.ts`: 폼 스키마. 이름 길이는 요청 스키마의 상수(`<BASE>_NAME_MAX_LENGTH` = 백엔드 `NAME_MAX_LENGTH` 100)를 쓴다
|
||||
- `presentation/<base>-detail-page.tsx`: `DetailPage`
|
||||
- `presentation/<base>-create-page.tsx`: `FormPage`. 저장하면 상세를 연다. 결과 불명이면 `AsyncSurface`를 보인다
|
||||
- `presentation/<base>-create-page.tsx`: `FormPage`. 저장하면 상세를 연다. 저장 중에 화면을 떠났으면 옮기지 않는다. 결과 불명이면 `AsyncSurface`를 보인다
|
||||
|
||||
`domain/`은 만들지 않는다. 업무 규칙이 생기면 사람이 만든다.
|
||||
|
||||
@@ -76,7 +76,7 @@ corepack pnpm create:feature <id> [--context <context id>] [--with-create [--key
|
||||
- `<base>-feature-input.test.ts`: input 단위 테스트
|
||||
- `<base>-list-page.test.tsx`: 라우터를 거치는 페이지 테스트(목록, `meta.page.total`, 빈 목록, 실패 후 다시 시도)
|
||||
- `<base>-http-gateway.test.ts`: 짝 백엔드 본문을 손으로 적은 gateway 테스트. 하네스의 재시도 상한은 앱 기본값 2다
|
||||
- `<base>-create-page.test.tsx`(`--with-create`): 201 저장 뒤 상세, 400 `<FEATURE>_INVALID` 필드 오류와 다시 저장, 응답을 잃은 저장(`NEVER`는 다시 보내기 없음, `KEYED`는 같은 키로 다시 보내기)
|
||||
- `<base>-create-page.test.tsx`(`--with-create`): 201 저장 뒤 상세, 400 `<FEATURE>_INVALID` 필드 오류와 다시 저장, 응답을 잃은 저장(`NEVER`는 다시 보내기 없음, `KEYED`는 같은 키로 다시 보내기), 저장 중 목록으로 간 뒤 끝난 저장(목록에 머문다)
|
||||
|
||||
기능 폴더 밖:
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -299,6 +299,26 @@ describe("create:feature --with-create", () => {
|
||||
},
|
||||
);
|
||||
|
||||
// 1106/08-02. A save that ended after the user left the form took them to
|
||||
// the item anyway. The page opens the item or the list only while it is
|
||||
// still mounted, and the generated page test walks that path.
|
||||
it.each(["NEVER", "KEYED"] as const)(
|
||||
"does not open the item when the user left during a %s create",
|
||||
(write) => {
|
||||
const { files } = plan({ id: "invoice-feature", write });
|
||||
const page =
|
||||
files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
|
||||
|
||||
expect(page).toContain("if (outcome?.ok && mounted.current) {");
|
||||
expect(page).toContain(
|
||||
'if (mounted.current) void navigate(invoiceRouteUrl("INVOICE_LIST"));',
|
||||
);
|
||||
expect(
|
||||
files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"),
|
||||
).toContain('it("stays on the list the user went to while the create was saving"');
|
||||
},
|
||||
);
|
||||
|
||||
// 1103/16-07. A backend create made KEYED (IdempotencyExecutor) takes these.
|
||||
it("writes the KEYED values for a backend create made KEYED", () => {
|
||||
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
|
||||
|
||||
Reference in New Issue
Block a user