diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index f2773888..783f0c08 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -203,7 +203,7 @@ export function AsyncSurface({ return (
{state.indicator ? ( -
+
{message( state.indicator === "stale-degraded" diff --git a/src/presentation/design-system/catalog.stories.tsx b/src/presentation/design-system/catalog.stories.tsx new file mode 100644 index 00000000..1978b593 --- /dev/null +++ b/src/presentation/design-system/catalog.stories.tsx @@ -0,0 +1,411 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { useRef, useState } from "react"; + +import { deriveAsyncState } from "../../application/view-models/async-state.ts"; +import { createFailure } from "../../contracts/errors.ts"; +import { + AccessSurface, + Breadcrumbs, + Button, + Card, + CloseIcon, + CollectionPage, + ConfirmationDialog, + DataTable, + DetailPage, + DirtyNavigationDialog, + DisclosureGroup, + Drawer, + EmptySurface, + ErrorIcon, + ErrorSummary, + Field, + Form, + FormActions, + FormFailureStatus, + FormField, + FormPage, + FormSaveFeedback, + IconButton, + InfoIcon, + LinkButton, + MenuIcon, + NextIcon, + PageHeader, + Pagination, + PaginationBar, + Popover, + PreviousIcon, + SearchField, + SearchFilterToolbar, + SearchIcon, + Separator, + Spinner, + StandardPage, + StatusPage, + SuccessIcon, + WarningIcon, +} from "./index.ts"; + +/** + * 1112/04-10. Every screen component the design-system barrel exports has a + * story (tests/unit/design-system-story-coverage.test.ts), so its states can + * be opened, and tests/storybook/galleries.spec.ts scans each story with axe + * in both colour schemes. The galleries (galleries.stories.tsx) show the + * primitives together; these show the rest one group at a time. + * Example copy is Korean in every locale, like the galleries (08-07). + */ +const meta = { + title: "Platform/Catalog", + parameters: { + layout: "fullscreen", + page: true, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +function Page(props: Readonly<{ title: string; description: string; children: React.ReactNode }>) { + return ( +
+ + {props.children} +
+ ); +} + +export const Overlays: Story = { + render: () => , +}; + +function OverlayCatalog() { + const [confirming, setConfirming] = useState(false); + const [drawerOpen, setDrawerOpen] = useState(false); + const drawerTrigger = useRef(null); + return ( + +
+ + + +

팝오버는 짧은 보조 설명을 담습니다.

+
+
+ setConfirming(false)} + onCancel={() => setConfirming(false)} + /> + setDrawerOpen(false)} + returnFocusRef={drawerTrigger} + title="필터" + closeLabel="서랍 닫기" + > +

서랍 안의 내용입니다.

+
+
+ ); +} + +export const NavigationAndControls: Story = { + render: () => , +}; + +function NavigationCatalog() { + const [page, setPage] = useState(2); + const [query, setQuery] = useState("보고서"); + return ( + + +
+ 보고서 보기 + + 보관함 + + + + + +
+ + setQuery(event.currentTarget.value)} + clearLabel="검색어 지우기" + onClear={() => setQuery("")} + /> + + {({ controlId, describedBy, invalid }) => ( + + )} + + `${candidate}쪽`} + onChange={setPage} + /> +
+ ); +} + +export const Icons: Story = { + render: () => ( + +
    + {[ + ["닫기", ], + ["오류", ], + ["정보", ], + ["메뉴", ], + ["다음", ], + ["이전", ], + ["검색", ], + ["성공", ], + ["경고", ], + ].map(([label, icon]) => ( +
  • + {icon} + {label} +
  • + ))} +
+
+ ), +}; + +const ROWS = Object.freeze([ + { id: "r-1", name: "1월 보고서", owner: "운영팀" }, + { id: "r-2", name: "2월 보고서", owner: "재무팀" }, +]); + +export const Patterns: Story = { + render: () => , +}; + +function PatternCatalog() { + const [page, setPage] = useState(1); + return ( + + {}} />} + resetLabel="필터 초기화" + onReset={() => setPage(1)} + resultCount="2개 항목" + /> + row.name }, + { id: "owner", header: "담당", cell: (row) => row.owner }, + ]} + rows={ROWS} + rowKey={(row) => row.id} + empty={} + /> + `${candidate}쪽`} + onChange={setPage} + range="1–2 / 2" + /> + 매월 첫날 만들어집니다.

}, + { id: "q-2", title: "누가 볼 수 있나요?", content:

담당 팀이 볼 수 있습니다.

}, + ]} + /> +
+ {}} /> + {}} /> + {}} /> +
+
+ ); +} + +// One story per page template: each draws the page's own h1. +export const StandardTemplate: Story = { + render: () => ( +
+ {} }]} + aside={

보조 정보

} + > +

본문

+
+
+ ), +}; + +export const CollectionTemplate: Story = { + render: () => ( +
+ +
    + {ROWS.map((row) => ( +
  • {row.name}
  • + ))} +
+
+
+ ), +}; + +export const DetailTemplate: Story = { + render: () => ( +
+ 담당: 운영팀

} + destructiveAction={} + > +

상세 내용

+
+
+ ), +}; + +export const FormTemplate: Story = { + render: () => , +}; + +const SAVE_ERROR = createFailure("RATE_LIMITED", "EXAMPLE", 0); + +function FormCatalog() { + const [submitted, setSubmitted] = useState(false); + return ( +
+ setSubmitted(false)} />} + errorSummary={ + `catalog-${name}`} + /> + } + fields={ +
{ + event.preventDefault(); + setSubmitted(true); + }}> + + + } + formActions={ + + + + } + /> +
+ ); +} + +export const StatusTemplate: Story = { + render: () => ( +
+ {} }} + secondaryAction={{ kind: "link", label: "홈으로", href: "#home", variant: "secondary" }} + supportReference="build-1:incident-1" + /> +
+ ), +}; + +/** What FormSaveFeedback and DirtyNavigationDialog read, drawn without a form. */ +export const FormFeedback: Story = { + render: () => , +}; + +function FormFeedbackCatalog() { + const [leaving, setLeaving] = useState(false); + return ( + + + undefined, + confirmUnknownEffect: async () => {}, + resendUnknownEffect: async () => null, + }} + /> + + + undefined, + confirmUnknownEffect: async () => {}, + resendUnknownEffect: async () => null, + }} + /> + + + setLeaving(false), leave: () => setLeaving(false) }} + /> + + ); +} diff --git a/src/presentation/design-system/galleries.stories.tsx b/src/presentation/design-system/galleries.stories.tsx index 7d9bdde1..0624385b 100644 --- a/src/presentation/design-system/galleries.stories.tsx +++ b/src/presentation/design-system/galleries.stories.tsx @@ -13,7 +13,9 @@ import { Checkbox, Dialog, EmptySurface, + ErrorSummary, ForbiddenSurface, + FormFailureStatus, LoadingSurface, Menu, NotFoundSurface, @@ -364,6 +366,15 @@ function ScreenStateGallery() { data: ["기존 데이터"], isFetching: true, }); + // 1112/04-10. The write states a page draws through AsyncSurface. + const unknownState = deriveAsyncState({ + data: ["보낸 변경"], + hasMutationEffectUnknown: true, + isUnknownEffectResendable: true, + }); + const conflictState = deriveAsyncState({ data: ["입력한 변경"], hasMutationConflict: true }); + const staleState = deriveAsyncState({ data: ["지난 데이터"], isStale: true, isDegraded: true }); + const savingState = deriveAsyncState({ data: ["입력한 변경"], isMutationPending: true }); return ( // 08-07. Example copy is Korean in every locale (outside the catalog). @@ -413,6 +424,58 @@ function ScreenStateGallery() {
+
+
+

저장 상태

+

결과를 모르는 저장, 충돌, 오래된 데이터, 저장 중을 입력을 지운 채가 아니라 그 위에 알립니다.

+
+
+ + setLastAction("저장된 것으로 확인했습니다.")} + onResendUnknownEffect={() => setLastAction("같은 요청을 다시 보냈습니다.")} + /> + + + setLastAction("최신 상태를 다시 불러옵니다.")} + > +
입력은 유지됩니다.
+
+
+ + setLastAction("다시 불러옵니다.")}> +
지난 데이터를 계속 보여 줍니다.
+
+
+ + +
입력한 변경
+
+
+ + setLastAction("잠시 뒤 다시 저장합니다.")} + /> + + + `gallery-${name}`} + /> + +
+
+

접근과 탐색 상태

diff --git a/src/presentation/forms/form-components.tsx b/src/presentation/forms/form-components.tsx index 3f3fb912..08035681 100644 --- a/src/presentation/forms/form-components.tsx +++ b/src/presentation/forms/form-components.tsx @@ -96,9 +96,11 @@ export function ErrorSummary(props: Readonly<{ export function FormFailureStatus(props: Readonly<{ failure: AppFailure | null; onAction?: () => void; + /** 08-05. Below the heading of the card or section that holds it. */ + headingLevel?: HeadingLevel | undefined; }>) { const { message } = useLocale(); - const { failure, onAction } = props; + const { failure, onAction, headingLevel } = props; if (!failure) return null; return ( ); } diff --git a/src/presentation/styles/theme/pages.css b/src/presentation/styles/theme/pages.css index 78a74f69..0bdae05c 100644 --- a/src/presentation/styles/theme/pages.css +++ b/src/presentation/styles/theme/pages.css @@ -209,6 +209,20 @@ background: var(--color-danger-surface); } + /* The notice over kept content: its words and actions on one wrapping row, + a request reference or a refusal on its own row below. */ + .async-surface__status { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2) var(--space-3); + } + + .async-surface__status > p { + flex-basis: 100%; + margin: 0; + } + .state-surface--loading { gap: var(--space-3); } diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index b066be89..cd0c927b 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -1715,3 +1715,16 @@ describe("a possibly applied failure that names a field", () => { expect(screen.getByRole("textbox", { name: /Name/ })).not.toHaveAccessibleDescription(/./u); }); }); + +// 08-05, 1112/04-10. A save failure inside a card or section takes the +// heading level below that container's title, as the other surfaces do. +describe("FormFailureStatus heading level", () => { + it("draws its title at the level it is given, and h2 by default", () => { + const failure = createFailure("RATE_LIMITED", "EXAMPLE", 0); + const { rerender } = render(); + expect(screen.getByRole("heading", { level: 4 })).toBeVisible(); + + rerender(); + expect(screen.getByRole("heading", { level: 2 })).toBeVisible(); + }); +}); diff --git a/tests/storybook/galleries.spec.ts b/tests/storybook/galleries.spec.ts index 8b1379e6..2d4c3290 100644 --- a/tests/storybook/galleries.spec.ts +++ b/tests/storybook/galleries.spec.ts @@ -95,6 +95,29 @@ test("opened design-system dialog has no blocking violations", async ({ ).toEqual([]); }); +// 1112/04-10. The catalog's overlays are scanned open, as the gallery dialog is. +for (const overlay of [ + { open: "항목 삭제", layer: ".ui-dialog", name: "이 항목을 삭제할까요?" }, + { open: "서랍 열기", layer: ".ui-drawer", name: "필터" }, + { open: "도움말", layer: ".ui-popover", name: "도움말" }, +] as const) { + test(`opened catalog overlay "${overlay.name}" has no blocking violations`, async ({ page }) => { + await page.goto("/iframe.html?id=platform-catalog--overlays&viewMode=story&globals=a11y.manual:!true"); + await expect(page.getByRole("heading", { level: 1, name: "겹치는 화면" })).toBeVisible(); + await page.getByRole("button", { name: overlay.open }).click(); + await expect(page.getByRole("dialog", { name: overlay.name })).toBeVisible(); + const results = await new AxeBuilder({ page }) + .include(overlay.layer) + .withTags([...WCAG_AXE_TAGS]) + .analyze(); + expect( + results.violations.filter((violation) => + ["critical", "serious"].includes(violation.impact ?? ""), + ), + ).toEqual([]); + }); +} + // 1112/05-04. The galleries replaced the example screens, whose whole page // the route scan checked. With no feature installed they are the only place // the empty, error, sign-in and access surfaces are drawn, so the whole story @@ -102,6 +125,17 @@ test("opened design-system dialog has no blocking violations", async ({ for (const story of [ { id: "platform-galleries--design-system", heading: "UI 구성요소" }, { id: "platform-galleries--screen-states", heading: "화면 상태" }, + // 1112/04-10. The catalog: every barrel component outside the galleries. + { id: "platform-catalog--overlays", heading: "겹치는 화면" }, + { id: "platform-catalog--navigation-and-controls", heading: "탐색과 입력" }, + { id: "platform-catalog--icons", heading: "의미 아이콘" }, + { id: "platform-catalog--patterns", heading: "화면 패턴" }, + { id: "platform-catalog--standard-template", heading: "기본 페이지" }, + { id: "platform-catalog--collection-template", heading: "목록 페이지" }, + { id: "platform-catalog--detail-template", heading: "상세 페이지" }, + { id: "platform-catalog--form-template", heading: "폼 페이지" }, + { id: "platform-catalog--status-template", heading: "로그인이 필요합니다." }, + { id: "platform-catalog--form-feedback", heading: "저장 결과" }, ] as const) { for (const colorScheme of ["light", "dark"] as const) { test(`${story.id} has no blocking violations in ${colorScheme}`, async ({ page }) => { diff --git a/tests/unit/design-system-story-coverage.test.ts b/tests/unit/design-system-story-coverage.test.ts new file mode 100644 index 00000000..4563dabd --- /dev/null +++ b/tests/unit/design-system-story-coverage.test.ts @@ -0,0 +1,79 @@ +import { readFile, readdir } from "node:fs/promises"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +/** + * 1112/04-10. A product builds its screens from the design-system barrel. + * A component without a story has no place where its states can be opened + * and scanned (tests/storybook/galleries.spec.ts runs axe over the stories), + * and 43 of the barrel's components had none. + */ +const BARREL = "src/presentation/design-system/index.ts"; + +// Exports that draw nothing of their own, with the reason. +const WITHOUT_STORY = new Map([ + ["Portal", "moves its children to another node"], + ["FocusRing", "wraps a child to draw the focus ring the stories already show"], + ["VisuallyHidden", "draws nothing visible"], + ["DESIGN_TOKEN_CONTRACT", "a constant"], + ["REQUIRED_COMPONENT_TOKENS", "a constant"], + ["REQUIRED_PRIMITIVE_TOKENS", "a constant"], + ["REQUIRED_SEMANTIC_TOKENS", "a constant"], + ["useAppForm", "a hook"], + ["useDirtyNavigationGuard", "a hook"], + ["useToast", "a hook"], +]); + +async function barrelValueExports(): Promise { + const source = await readFile(BARREL, "utf8"); + return [...source.matchAll(/export\s*\{([^}]*)\}/g)] + .flatMap((match) => match[1].split(",")) + .map((name) => name.trim()) + .filter((name) => name !== "" && !name.startsWith("type ")); +} + +async function storySources(): Promise { + const files = (await readdir("src", { recursive: true })) + .filter((file) => file.endsWith(".stories.tsx")) + .map((file) => path.join("src", file)); + expect(files.length).toBeGreaterThan(0); + const sources = await Promise.all(files.map((file) => readFile(file, "utf8"))); + // A name in a comment or a string is not a drawing of it. + return sources + .map((source) => + source + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/(^|[^:])\/\/.*$/gm, "$1") + .replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, '""'), + ) + .join("\n"); +} + +describe("design-system story coverage", () => { + it("draws every screen component of the barrel in a story", async () => { + const exports = await barrelValueExports(); + const stories = await storySources(); + expect(exports).toContain("Button"); + + const drawn = (name: string) => new RegExp(`<${name}[\\s/>]`, "u").test(stories); + expect(exports.filter((name) => !WITHOUT_STORY.has(name) && !drawn(name))).toEqual([]); + }); + + // tests/storybook/galleries.spec.ts scans each catalog story with axe; a + // story added to the catalog and not to that list is drawn and not scanned. + it("scans every catalog story with axe", async () => { + const catalog = await readFile("src/presentation/design-system/catalog.stories.tsx", "utf8"); + const spec = await readFile("tests/storybook/galleries.spec.ts", "utf8"); + const ids = [...catalog.matchAll(/^export const (\w+): Story/gmu)].map( + ([, name = ""]) => `platform-catalog--${name.replace(/([a-z0-9])([A-Z])/gu, "$1-$2").toLowerCase()}`, + ); + expect(ids.length).toBeGreaterThan(0); + expect(ids.filter((id) => !spec.includes(`"${id}"`))).toEqual([]); + }); + + it("names a reason only for exports the barrel still has", async () => { + const exports = await barrelValueExports(); + expect([...WITHOUT_STORY.keys()].filter((name) => !exports.includes(name))).toEqual([]); + }); +}); diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png index be5422ee..5f039dfe 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png differ