test(storybook): 배럴의 모든 화면 컴포넌트에 story를 두고 저장 상태를 골든에 넣는다

디자인 시스템 배럴(`src/presentation/design-system/index.ts`)의 값 export
가운데 화면 컴포넌트 37개에 story가 없다: SearchField·ConfirmationDialog·
Drawer·Popover·Breadcrumbs·Pagination·LinkButton·Separator·IconButton 같은
primitive, DataTable 등 pattern 다섯, 페이지 템플릿 다섯, 폼 구성요소, 아이콘
아홉. 결과를 모르는 저장(확인·같은 요청 다시 보내기), 충돌, 오래된 데이터,
저장 중은 갤러리와 골든에 없다. 그래서 파생 서비스가 쓸 컴포넌트의 상태를 볼
곳이 없고, 그 배치 회귀를 골든이 잡지 못한다.

고른 방법:
- `catalog.stories.tsx`에 묶음 story 열을 더한다(겹치는 화면, 탐색과 입력,
  아이콘, 화면 패턴, 페이지 템플릿 다섯을 하나씩, 저장 결과). 템플릿 story는
  각자 자기 h1을 그린다.
- ScreenStates 갤러리에 저장 상태 절을 더한다: 결과를 모르는 저장(다시 보내기
  가능), 충돌, 오래된 데이터, 저장 중, 입력과 무관한 저장 실패
  (FormFailureStatus), 입력 오류 요약. `state-surfaces-light` 골든이 이 절을
  담는다.
- `tests/unit/design-system-story-coverage.test.ts`가 배럴의 값 export마다
  story에서 `<Name`으로 그려지는지 대조한다. 그리지 않는 것(Portal·FocusRing·
  VisuallyHidden, 토큰 상수, hook)은 이유와 함께 목록에 둔다.
- 새 story 열은 `tests/storybook/galleries.spec.ts`의 axe 검사(light·dark)에
  더했고, 겹치는 화면 셋(확인 대화 상자, 서랍, 팝오버)은 연 상태로도 본다.
  대조 시험이 catalog story마다 그 목록에 있는지 본다.
- 갤러리에 넣으면서 드러난 둘을 고쳤다. 저장 상태 안내의 문장과 버튼이 붙어
  있었다(`.async-surface__status`: 한 줄로 감싸고 간격, 지원 참조는 아랫줄).
  `FormFailureStatus`가 제목 단계를 받지 못해 카드 안에서 h2로 그려졌다
  (`headingLevel`, 추가만, 다른 상태 표면과 같은 08-05 계약).
- 버린 대안: 컴포넌트마다 variant 행렬 story를 한 번에 쓰기(이번 범위는 "모든
  화면 컴포넌트에 story 하나 이상"이고, 행렬은 컴포넌트를 고칠 때 더한다).
  StatusPage를 갤러리에 넣기(자기 h1을 그려 갤러리의 h1과 겹친다. 자기
  story로 뒀다).

위험·한계: 갤러리 골든이 바뀐다(이 커밋에서 다시 찍는다). theme·locale
toolbar는 아직 없다. story axe가 20번 늘어 FE-GATE-008이 조금 길어진다.

검증: 대조 시험(고치기 전 story 파일에서 37개 누락으로 실패), story 빌드
(FE-GATE-011), story axe와 시각 골든(FE-GATE-008)은 desktop에서 돌려 PR
본문에 적는다.

Refs: 1112/04-10
This commit is contained in:
DongHyeonka
2026-11-13 23:27:47 +09:00
parent d5083f862d
commit 2f3ebba46b
9 changed files with 619 additions and 2 deletions
@@ -203,7 +203,7 @@ export function AsyncSurface({
return (
<section aria-busy={state.overlay.refreshing || state.overlay.mutationPending}>
{state.indicator ? (
<div role="status" aria-live="polite">
<div className="async-surface__status" role="status" aria-live="polite">
<span>
{message(
state.indicator === "stale-degraded"
@@ -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<typeof meta>;
function Page(props: Readonly<{ title: string; description: string; children: React.ReactNode }>) {
return (
<section className="ui-page" lang="ko-KR">
<PageHeader title={props.title} description={props.description} />
{props.children}
</section>
);
}
export const Overlays: Story = {
render: () => <OverlayCatalog />,
};
function OverlayCatalog() {
const [confirming, setConfirming] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
const drawerTrigger = useRef<HTMLButtonElement | null>(null);
return (
<Page title="겹치는 화면" description="확인 대화 상자, 서랍, 팝오버는 Escape로 닫고 연 곳으로 포커스를 돌립니다.">
<div className="ui-cluster">
<Button variant="danger" onClick={() => setConfirming(true)}>
항목 삭제
</Button>
<Button ref={drawerTrigger} variant="secondary" onClick={() => setDrawerOpen(true)}>
서랍 열기
</Button>
<Popover triggerLabel="도움말">
<p>팝오버는 짧은 보조 설명을 담습니다.</p>
</Popover>
</div>
<ConfirmationDialog
open={confirming}
title="이 항목을 삭제할까요?"
description="삭제한 항목은 되돌릴 수 없습니다."
confirmLabel="삭제"
cancelLabel="취소"
danger
onConfirm={() => setConfirming(false)}
onCancel={() => setConfirming(false)}
/>
<Drawer
open={drawerOpen}
onClose={() => setDrawerOpen(false)}
returnFocusRef={drawerTrigger}
title="필터"
closeLabel="서랍 닫기"
>
<p>서랍 안의 내용입니다.</p>
</Drawer>
</Page>
);
}
export const NavigationAndControls: Story = {
render: () => <NavigationCatalog />,
};
function NavigationCatalog() {
const [page, setPage] = useState(2);
const [query, setQuery] = useState("보고서");
return (
<Page title="탐색과 입력" description="링크 버튼, 아이콘 버튼, 검색 입력, 이동 경로, 페이지 탐색입니다.">
<Breadcrumbs
label="이동 경로"
items={[{ label: "홈", href: "#home" }, { label: "보고서", href: "#reports" }, { label: "이번 달" }]}
/>
<div className="ui-cluster">
<LinkButton href="#reports">보고서 보기</LinkButton>
<LinkButton href="#archive" variant="secondary">
보관함
</LinkButton>
<IconButton accessibleName="메뉴 열기" variant="secondary">
<MenuIcon />
</IconButton>
<Spinner label="불러오는 중" />
</div>
<Separator />
<SearchField
label="검색어"
value={query}
onChange={(event) => setQuery(event.currentTarget.value)}
clearLabel="검색어 지우기"
onClear={() => setQuery("")}
/>
<Field label="직접 그린 입력" description="Field는 레이블·설명·오류를 입력과 잇습니다.">
{({ controlId, describedBy, invalid }) => (
<input
aria-describedby={describedBy}
aria-invalid={invalid || undefined}
className="ui-field__input"
id={controlId}
/>
)}
</Field>
<Pagination
label="페이지"
page={page}
pageCount={5}
previousLabel="이전 페이지"
nextLabel="다음 페이지"
pageLabel={(candidate) => `${candidate}쪽`}
onChange={setPage}
/>
</Page>
);
}
export const Icons: Story = {
render: () => (
<Page title="의미 아이콘" description="아이콘은 장식이고, 뜻은 옆 글자나 버튼 이름이 전합니다.">
<ul className="ui-cluster">
{[
["닫기", <CloseIcon key="close" />],
["오류", <ErrorIcon key="error" />],
["정보", <InfoIcon key="info" />],
["메뉴", <MenuIcon key="menu" />],
["다음", <NextIcon key="next" />],
["이전", <PreviousIcon key="previous" />],
["검색", <SearchIcon key="search" />],
["성공", <SuccessIcon key="success" />],
["경고", <WarningIcon key="warning" />],
].map(([label, icon]) => (
<li className="ui-cluster" key={label as string}>
{icon}
<span>{label}</span>
</li>
))}
</ul>
</Page>
),
};
const ROWS = Object.freeze([
{ id: "r-1", name: "1월 보고서", owner: "운영팀" },
{ id: "r-2", name: "2월 보고서", owner: "재무팀" },
]);
export const Patterns: Story = {
render: () => <PatternCatalog />,
};
function PatternCatalog() {
const [page, setPage] = useState(1);
return (
<Page title="화면 패턴" description="표, 검색 도구 막대, 접기 묶음, 페이지 막대, 접근 상태입니다.">
<SearchFilterToolbar
label="보고서 찾기"
search={<SearchField label="검색어" clearLabel="검색어 지우기" onClear={() => {}} />}
resetLabel="필터 초기화"
onReset={() => setPage(1)}
resultCount="2개 항목"
/>
<DataTable
caption="보고서 목록"
columns={[
{ id: "name", header: "이름", cell: (row) => row.name },
{ id: "owner", header: "담당", cell: (row) => row.owner },
]}
rows={ROWS}
rowKey={(row) => row.id}
empty={<EmptySurface title="보고서가 없습니다." />}
/>
<PaginationBar
label="보고서 페이지"
page={page}
pageCount={3}
previousLabel="이전 페이지"
nextLabel="다음 페이지"
pageLabel={(candidate) => `${candidate}쪽`}
onChange={setPage}
range="1–2 / 2"
/>
<DisclosureGroup
label="자주 묻는 질문"
items={[
{ id: "q-1", title: "보고서는 언제 만들어지나요?", content: <p>매월 첫날 만들어집니다.</p> },
{ id: "q-2", title: "누가 볼 수 있나요?", content: <p>담당 팀이 볼 수 있습니다.</p> },
]}
/>
<div className="component-grid component-grid--three">
<AccessSurface kind="auth-required" headingLevel={2} onAction={() => {}} />
<AccessSurface kind="forbidden" headingLevel={2} onAction={() => {}} />
<AccessSurface kind="not-found" headingLevel={2} onAction={() => {}} />
</div>
</Page>
);
}
// One story per page template: each draws the page's own h1.
export const StandardTemplate: Story = {
render: () => (
<div lang="ko-KR">
<StandardPage
heading={{ eyebrow: "템플릿", title: "기본 페이지", description: "제목, 행동, 본문, 보조 정보 자리입니다." }}
actions={[{ kind: "button", label: "행동", onAction: () => {} }]}
aside={<p>보조 정보</p>}
>
<p>본문</p>
</StandardPage>
</div>
),
};
export const CollectionTemplate: Story = {
render: () => (
<div lang="ko-KR">
<CollectionPage
heading={{ title: "목록 페이지", description: "도구 막대, 결과 수, 목록, 페이지 탐색 자리입니다." }}
actions={[{ kind: "link", label: "새 보고서", href: "#new", variant: "primary" }]}
resultCount="2개 항목"
>
<ul aria-label="보고서">
{ROWS.map((row) => (
<li key={row.id}>{row.name}</li>
))}
</ul>
</CollectionPage>
</div>
),
};
export const DetailTemplate: Story = {
render: () => (
<div lang="ko-KR">
<DetailPage
heading={{ title: "상세 페이지", description: "속성, 본문, 위험한 작업 자리입니다." }}
metadata={<p>담당: 운영팀</p>}
destructiveAction={<Button variant="danger">삭제</Button>}
>
<p>상세 내용</p>
</DetailPage>
</div>
),
};
export const FormTemplate: Story = {
render: () => <FormCatalog />,
};
const SAVE_ERROR = createFailure("RATE_LIMITED", "EXAMPLE", 0);
function FormCatalog() {
const [submitted, setSubmitted] = useState(false);
return (
<div lang="ko-KR">
<FormPage
heading={{ title: "폼 페이지", description: "오류 요약, 입력, 저장 결과, 저장 버튼 자리입니다." }}
feedback={<FormFailureStatus failure={submitted ? SAVE_ERROR : null} onAction={() => setSubmitted(false)} />}
errorSummary={
<ErrorSummary
fieldErrors={submitted ? { name: "이름을 입력해 주세요." } : {}}
fieldLabels={{ name: "이름" }}
fieldId={(name) => `catalog-${name}`}
/>
}
fields={
<Form id="catalog-form" pending={false} onSubmit={(event) => {
event.preventDefault();
setSubmitted(true);
}}>
<FormField id="catalog-name" label="이름" required />
</Form>
}
formActions={
<FormActions>
<Button form="catalog-form" type="submit">
저장
</Button>
</FormActions>
}
/>
</div>
);
}
export const StatusTemplate: Story = {
render: () => (
<div lang="ko-KR">
<StatusPage
variant="unauthenticated"
heading={{ title: "로그인이 필요합니다.", description: "이 화면을 보려면 로그인해 주세요." }}
primaryAction={{ kind: "button", label: "로그인", onAction: () => {} }}
secondaryAction={{ kind: "link", label: "홈으로", href: "#home", variant: "secondary" }}
supportReference="build-1:incident-1"
/>
</div>
),
};
/** What FormSaveFeedback and DirtyNavigationDialog read, drawn without a form. */
export const FormFeedback: Story = {
render: () => <FormFeedbackCatalog />,
};
function FormFeedbackCatalog() {
const [leaving, setLeaving] = useState(false);
return (
<Page title="저장 결과" description="결과를 모르는 저장, 다시 로그인, 저장하지 않고 떠나기 안내입니다.">
<Card title="결과를 모르는 저장">
<FormSaveFeedback
form={{
effectUnknown: true,
otherSaveRunning: false,
mutationState: deriveAsyncState({
data: { id: "saved" },
hasMutationEffectUnknown: true,
isUnknownEffectResendable: true,
}),
failure: null,
result: "effect-unknown",
notice: null,
supportReference: "request-1",
submitForm: async () => undefined,
confirmUnknownEffect: async () => {},
resendUnknownEffect: async () => null,
}}
/>
</Card>
<Card title="다시 로그인">
<FormSaveFeedback
form={{
effectUnknown: false,
otherSaveRunning: false,
mutationState: undefined,
failure: createFailure("AUTH_REQUIRED", "EXAMPLE", 0),
result: "reauth-required",
notice: null,
supportReference: undefined,
submitForm: async () => undefined,
confirmUnknownEffect: async () => {},
resendUnknownEffect: async () => null,
}}
/>
</Card>
<Button variant="secondary" onClick={() => setLeaving(true)}>
저장하지 않고 떠나기
</Button>
<DirtyNavigationDialog
guard={{ blocked: leaving, stay: () => setLeaving(false), leave: () => setLeaving(false) }}
/>
</Page>
);
}
@@ -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() {
</div>
</section>
<section className="gallery-section" aria-labelledby="write-states-title">
<header className="gallery-section__header">
<h2 id="write-states-title">저장 상태</h2>
<p>결과를 모르는 저장, 충돌, 오래된 데이터, 저장 중을 입력을 지운 채가 아니라 그 위에 알립니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="결과를 모르는 저장">
<AsyncSurface
headingLevel={4}
state={unknownState}
supportReference="request-1"
onReconcileUnknownEffect={() => setLastAction("저장된 것으로 확인했습니다.")}
onResendUnknownEffect={() => setLastAction("같은 요청을 다시 보냈습니다.")}
/>
</Card>
<Card title="충돌">
<AsyncSurface
headingLevel={4}
state={conflictState}
onResolveConflict={() => setLastAction("최신 상태를 다시 불러옵니다.")}
>
<div className="state-preview-content">입력은 유지됩니다.</div>
</AsyncSurface>
</Card>
<Card title="오래된 데이터">
<AsyncSurface headingLevel={4} state={staleState} onRetry={() => setLastAction("다시 불러옵니다.")}>
<div className="state-preview-content">지난 데이터를 계속 보여 줍니다.</div>
</AsyncSurface>
</Card>
<Card title="저장 중">
<AsyncSurface headingLevel={4} state={savingState}>
<div className="state-preview-content">입력한 변경</div>
</AsyncSurface>
</Card>
<Card title="입력과 무관한 저장 실패">
<FormFailureStatus
headingLevel={4}
failure={createFailure("RATE_LIMITED", "EXAMPLE", 0)}
onAction={() => setLastAction("잠시 뒤 다시 저장합니다.")}
/>
</Card>
<Card title="입력 오류 요약">
<ErrorSummary
headingLevel={4}
fieldErrors={{ name: "이름을 입력해 주세요." }}
fieldLabels={{ name: "이름" }}
fieldId={(name) => `gallery-${name}`}
/>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="access-states-title">
<header className="gallery-section__header">
<h2 id="access-states-title">접근과 탐색 상태</h2>
+4 -1
View File
@@ -96,9 +96,11 @@ export function ErrorSummary<Values extends FormValues>(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 (
<TerminalErrorSurface
@@ -113,6 +115,7 @@ export function FormFailureStatus(props: Readonly<{
}
// 0929/08-04. The same support reference a failed query shows.
supportReference={failure.requestId}
headingLevel={headingLevel}
/>
);
}
+14
View File
@@ -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);
}
+13
View File
@@ -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(<FormFailureStatus failure={failure} headingLevel={4} />);
expect(screen.getByRole("heading", { level: 4 })).toBeVisible();
rerender(<FormFailureStatus failure={failure} />);
expect(screen.getByRole("heading", { level: 2 })).toBeVisible();
});
});
+34
View File
@@ -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 }) => {
@@ -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<string[]> {
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<string> {
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([]);
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

After

Width:  |  Height:  |  Size: 204 KiB