diff --git a/docs/manual/reference/create-feature.md b/docs/manual/reference/create-feature.md index e052d8c7..eec50049 100644 --- a/docs/manual/reference/create-feature.md +++ b/docs/manual/reference/create-feature.md @@ -66,7 +66,7 @@ corepack pnpm create:feature [--context ] [--with-create [--key - `presentation/use--create.ts`: 작성 뮤테이션 정책(`commandMutationIdentity`) - `presentation/-form.ts`: 폼 스키마. 이름 길이는 요청 스키마의 상수(`_NAME_MAX_LENGTH` = 백엔드 `NAME_MAX_LENGTH` 100)를 쓴다 - `presentation/-detail-page.tsx`: `DetailPage` -- `presentation/-create-page.tsx`: `FormPage`. 저장하면 상세를 연다. 결과 불명이면 `AsyncSurface`를 보인다 +- `presentation/-create-page.tsx`: `FormPage`. 저장하면 상세를 연다. 저장 중에 화면을 떠났으면 옮기지 않는다. 결과 불명이면 `AsyncSurface`를 보인다 `domain/`은 만들지 않는다. 업무 규칙이 생기면 사람이 만든다. @@ -76,7 +76,7 @@ corepack pnpm create:feature [--context ] [--with-create [--key - `-feature-input.test.ts`: input 단위 테스트 - `-list-page.test.tsx`: 라우터를 거치는 페이지 테스트(목록, `meta.page.total`, 빈 목록, 실패 후 다시 시도) - `-http-gateway.test.ts`: 짝 백엔드 본문을 손으로 적은 gateway 테스트. 하네스의 재시도 상한은 앱 기본값 2다 -- `-create-page.test.tsx`(`--with-create`): 201 저장 뒤 상세, 400 `_INVALID` 필드 오류와 다시 저장, 응답을 잃은 저장(`NEVER`는 다시 보내기 없음, `KEYED`는 같은 키로 다시 보내기) +- `-create-page.test.tsx`(`--with-create`): 201 저장 뒤 상세, 400 `_INVALID` 필드 오류와 다시 저장, 응답을 잃은 저장(`NEVER`는 다시 보내기 없음, `KEYED`는 같은 키로 다시 보내기), 저장 중 목록으로 간 뒤 끝난 저장(목록에 머문다) 기능 폴더 밖: diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index 9675ec77..bf1367b5 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -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; 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((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(); + }); }); `; } diff --git a/tests/unit/create-feature.test.ts b/tests/unit/create-feature.test.ts index 2e291100..b85d6221 100644 --- a/tests/unit/create-feature.test.ts +++ b/tests/unit/create-feature.test.ts @@ -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" });