test(visual): 갤러리를 Storybook story로 옮기고 골든 대상을 바꾼다

예제 화면 /examples/ui·/examples/states가 visual 골든 2장과 갤러리
브라우저 시험의 대상이다. 2026-11-07 소유자 결정으로 예제 화면을
지우므로 그 역할을 먼저 옮긴다(design-docs repo-structure/
04-frontend-layout.md 9.2절 2단계 (1)).

두 갤러리 화면을 그대로 src/presentation/design-system/
galleries.stories.tsx로 옮겼다. 화면 단위 story(parameters.page)는
preview가 여백을 더하지 않아 앱 안과 같은 폭으로 그려진다. visual
설정은 Storybook 정적 빌드를 두 번째 web server로 띄우고
(TEST_VISUAL_WORKSHOP_PORT, 빌드 명령은 workshop 설정과 같은
scripts/lib/storybook-static.ts), 골든 2장은 그 story를 찍는다. 어두운
골든은 테마 선택기가 없어 시스템 dark(colorScheme)로 그린다. e2e의
갤러리 상호작용(텍스트 필드, 모달 포커스, 메뉴·탭·토스트, 열린 대화
상자 axe, 320px 리플로)은 tests/storybook/galleries.spec.ts로 옮겼다.

위험: 골든의 픽셀 색 허용치(threshold 0.2)는 그대로다. 미세한 토큰
변화는 옛 골든처럼 새 골든도 잡지 못한다.

검증(desktop): test:storybook 6 passed, test:visual 7 passed,
playwright-run-isolation 단위 시험 통과. 변이 확인: --color-action을
파랑→빨강으로 바꾸면 새 골든이 어두운 쪽 42,313px, 밝은 쪽 22,359px
차이로 실패했다. 옛 골든(main f33e4778)도 40,238px, 22,511px로 실패했다.
미세 변이(어두운 --color-danger red-500→600, 밝은 --color-danger-surface
색상각 25→145)는 옛·새 골든 모두 통과했다. 변이는 되돌렸다.
This commit is contained in:
DongHyeonka
2026-11-08 13:51:54 +09:00
parent f33e4778bb
commit c7e80f2f8a
19 changed files with 749 additions and 138 deletions
+13 -4
View File
@@ -86,7 +86,10 @@ const queryClient = createQueryClient();
const preview: Preview = {
decorators: [
(Story) => (
// A page story (`parameters.page`, the galleries) draws its own
// `.ui-page`, as a route page does inside the shell's `main`; a component
// story gets a padded page around it.
(Story, context) => (
<ApplicationProvider application={application}>
<QueryClientProvider client={queryClient}>
<MemoryRouter>
@@ -94,9 +97,15 @@ const preview: Preview = {
<ThemeProvider>
<SessionProvider>
<div id="portal-root" />
<main className="ui-page" style={{ padding: "1rem" }}>
<Story />
</main>
{context.parameters["page"] === true ? (
<main>
<Story />
</main>
) : (
<main className="ui-page" style={{ padding: "1rem" }}>
<Story />
</main>
)}
</SessionProvider>
</ThemeProvider>
</LocaleProvider>
+7 -7
View File
@@ -38,8 +38,8 @@
- local form facade, field/error summary, dirty navigation dialog
- `src/presentation/templates`
- Standard, Collection, Detail, Form, Status page template
- `/examples/ui`, `/examples/states`
- 실행 가능한 primitive와 상태 예제
- `src/presentation/design-system/galleries.stories.tsx`
- 실행 가능한 primitive와 상태 예제(Storybook 갤러리 story)
- component/E2E/axe 테스트
- 필드 설명과 오류 연결
- native dialog 닫기와 trigger focus 복원
@@ -623,8 +623,8 @@ RP-10의 Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어
## 10. Storybook과 시각 검증
현재 `/examples/ui`는 실행 중인 앱 셸과 primitive 통합을 확인하는 데 유지한다.
그러나 runtime gallery는 isolated component workshop을 대체하지 않는다.
디자인 시스템 갤러리와 화면 상태 갤러리는 Storybook story다. 앱 셸과 primitive의
통합은 `/`와 `/examples/platform`을 여는 e2e가 확인한다.
[Storybook 공식 UI 테스트 문서](https://storybook.js.org/docs/writing-tests)는
story를 기반으로 interaction, accessibility, visual test를 구성하는 방법을
@@ -796,8 +796,8 @@ long-content
### Step 9. 통합 예제를 추가한다
- `/examples/ui`에는 primitive를 추가한다.
- `/examples/states`에는 새로운 공통 상태를 추가한다.
- 갤러리 story(`galleries.stories.tsx`)의 `DesignSystem`에는 primitive를 추가한다.
- 같은 파일의 `ScreenStates`에는 새로운 공통 상태를 추가한다.
- pattern/template은 domain-neutral fixture로 실제 조합을 보여 준다.
- production profile에서 예제 route를 제외할 수 있는 계약을 유지한다.
@@ -919,7 +919,7 @@ component contract에 기록한다. 예를 들어 `Separator`에는 pending/erro
9. locale provider, pseudo-locale, RTL 검증을 추가한다.
10. Storybook, story a11y, interaction test를 추가한다.
11. pinned browser 환경의 visual regression gate를 추가한다.
12. `/examples/ui`와 `/examples/states`를 통합 smoke gallery로 유지한다.
12. 디자인 시스템·화면 상태 갤러리를 Storybook story로 유지하고 visual 골든의 대상으로 쓴다.
이 순서는 라이브러리 수를 늘리는 것이 목표가 아니다. 각 단계가 제품 개발자가
중복 구현할 문제를 하나씩 제거하고, 외부 공급자를 교체할 수 있는 로컬 계약과
+2 -1
View File
@@ -7,7 +7,8 @@ the dark theme, and `component.css` maps roles to per-component values.
`src/presentation/styles/theme.css` only imports the three files and the style
files under `src/presentation/styles/theme/`. Components consume semantic
color, spacing, typography, status, and radius tokens through static classes.
`/examples/ui` is the executable token and primitive gallery.
The executable token and primitive gallery is the workshop story
`src/presentation/design-system/galleries.stories.tsx` (`corepack pnpm storybook`).
## Rules a rebrand must keep
@@ -808,8 +808,10 @@ production runtime config에 `MOCK_MODE`, `SCENARIO`, fake token 같은 key를
## 12. Storybook 테스트
Storybook은 component를 격리해 state를 열거하고 실제 브라우저 interaction과
접근성을 검사하는 개발·CI surface다. `/examples/ui`는 앱 통합 smoke로 유지하되
Storybook을 대신하지 않는다.
접근성을 검사하는 개발·CI surface다. 디자인 시스템 갤러리와 화면 상태 갤러리도
story다(`src/presentation/design-system/galleries.stories.tsx`). 갤러리의 브라우저
상호작용 검사는 `tests/storybook/galleries.spec.ts`가, 앱 셸 안의 통합 확인은
`/`와 `/examples/platform`을 여는 e2e가 맡는다.
### 12.1 Global decorator
@@ -945,9 +947,10 @@ Playwright `toHaveScreenshot()`을 사용한다.
- `app-shell-wide-light`: `/`, 1440×900, light, 전체 페이지 — wide app shell
- `app-shell-compact-pseudo-drawer`: `/`, 390×844, en-XA, 메뉴 서랍 열림 —
compact app shell, pseudo-locale, 열린 drawer
- `design-system-gallery-dark`: `/examples/ui`, dark — design-system 갤러리
- `state-surfaces-light`: `/examples/states` — loading, background refresh,
empty, error, 401, 403, 404
- `design-system-gallery-dark`: Storybook 정적 빌드의 갤러리 story
`platform-galleries--design-system`, 1280×900, 시스템 dark — design-system 갤러리
- `state-surfaces-light`: Storybook 정적 빌드의 `platform-galleries--screen-states`,
1280×1100 — loading, background refresh, empty, error, 401, 403, 404
- `platform-overview-light`: `/examples/platform` — 플랫폼 구성 개요
`check-test-evidence`는 기준선 PNG가 4장 이상인지만 본다. 위 목록의 각
@@ -1034,7 +1037,7 @@ TEST_RUN_ID=a playwright test
|---|---|---|
| `TEST_RUN_ID` | 다섯 Playwright 설정, `tests/e2e/preload-use.spec.ts` | `dist`, `artifacts/tests/<이름>/` |
| `RUN_OUTPUT_ROOT` | 빌드 단계 전부(`scripts/build-frontend.ts`가 부르는 것), `vite.config.ts`. 설정이 web server에만 넘긴다. 빌드 뒤 검사(`scripts/generate-supply-chain.ts`, `scripts/check-bundle.ts`)는 `.`이 아니면 멈춘다 | `.` |
| `TEST_E2E_PORT`, `TEST_VISUAL_PORT`, `TEST_CAPABILITIES_PORT`, `TEST_STORYBOOK_PORT`, `TEST_DEV_PORT` | 각 설정 | 빈 포트 |
| `TEST_E2E_PORT`, `TEST_VISUAL_PORT`, `TEST_VISUAL_WORKSHOP_PORT`, `TEST_CAPABILITIES_PORT`, `TEST_STORYBOOK_PORT`, `TEST_DEV_PORT` | 각 설정(`TEST_VISUAL_WORKSHOP_PORT`는 visual 설정의 두 번째 서버, 갤러리 골든이 여는 Storybook 정적 빌드) | 빈 포트 |
- run ID는 글자·숫자·`.`·`_`·`-` 64자 이하이고 글자나 숫자로 시작한다.
- 포트 변수를 주면 그 포트를 쓴다. 디버깅할 때 고정하는 용도다.
+5 -14
View File
@@ -4,22 +4,14 @@ import {
reservePort,
TEST_PORT_VARIABLES,
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
import { storybookStaticServer } from "./scripts/lib/storybook-static.ts";
// 1105/12-04. Under TEST_RUN_ID the workshop is built into the run's own
// folder (.tmp/runs/<id>/artifacts/storybook/static) with build:storybook's
// two steps and another output folder, and the results and report are the
// run's own. Unset, the gate's build:storybook writes artifacts/storybook/static.
// The static server listens on a free port (TEST_STORYBOOK_PORT pins one).
const staticDirectory = testRunPath("artifacts/storybook/static");
// 1105/12-04. Under TEST_RUN_ID the workshop build (storybookStaticServer),
// the results and the report are the run's own. The static server listens on
// a free port (TEST_STORYBOOK_PORT pins one).
const port = await reservePort(TEST_PORT_VARIABLES.storybook);
const origin = `http://127.0.0.1:${port}`;
const buildWorkshop =
testRunRoot() === "."
? "corepack pnpm build:storybook"
: "node scripts/generate-product-feature-index.ts && " +
`corepack pnpm exec storybook build -o ${staticDirectory}`;
export default defineConfig({
testDir: "./tests/storybook",
@@ -45,8 +37,7 @@ export default defineConfig({
screenshot: "only-on-failure",
},
webServer: {
command:
`${buildWorkshop} && node scripts/serve-static.ts ${staticDirectory} ${port}`,
command: storybookStaticServer(port).command,
url: origin,
reuseExistingServer: false,
},
+26 -13
View File
@@ -10,6 +10,7 @@ import {
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
import { storybookStaticServer } from "./scripts/lib/storybook-static.ts";
// 1105/12-04. Under TEST_RUN_ID the results, report and build are the run's
// own (.tmp/runs/<id>/); the goldens in snapshotDir are shared and only read.
@@ -18,6 +19,11 @@ import {
const dist = testRunPath("dist");
const port = await reservePort(TEST_PORT_VARIABLES.visual);
const origin = `http://127.0.0.1:${port}`;
// The design-system and screen-state galleries are workshop stories
// (src/presentation/design-system/galleries.stories.tsx); their goldens open
// the static workshop, which the second server serves
// (TEST_VISUAL_WORKSHOP_PORT pins its port).
const workshopPort = await reservePort(TEST_PORT_VARIABLES.visualWorkshop);
export default defineConfig({
testDir: "./tests/visual",
@@ -62,19 +68,26 @@ export default defineConfig({
},
},
},
webServer: {
// The home page and the platform overview print the build and release
// identity. CI sets VITE_BUILD_ID, VITE_COMMIT_SHA and RELEASE_ID for the
// whole workflow, so its build drew other text than the goldens and every
// CI run failed here. The goldens are the template's shape, captured with
// the local identity.
// 1103/11-08: CI too, or the build is checked as a release build.
env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command:
`corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`,
url: origin,
reuseExistingServer: false,
},
webServer: [
{
// The home page and the platform overview print the build and release
// identity. CI sets VITE_BUILD_ID, VITE_COMMIT_SHA and RELEASE_ID for
// the whole workflow, so its build drew other text than the goldens and
// every CI run failed here. The goldens are the template's shape,
// captured with the local identity.
// 1103/11-08: CI too, or the build is checked as a release build.
env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command:
`corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`,
url: origin,
reuseExistingServer: false,
},
{
command: storybookStaticServer(workshopPort).command,
url: `http://127.0.0.1:${workshopPort}`,
reuseExistingServer: false,
},
],
projects: [
{ name: "visual-fonts", testMatch: /fonts\.setup\.ts$/ },
{ name: "chromium-visual", dependencies: ["visual-fonts"] },
+18
View File
@@ -113,15 +113,33 @@ export function checkoutBuildReadFailure(
/**
* The port variable of each Playwright config's web server. Unset, the config
* picks a free port; set, it uses that one (to pin a port while debugging).
* `visualWorkshop` is the visual config's second server, the static workshop
* the gallery goldens open.
*/
export const TEST_PORT_VARIABLES = Object.freeze({
e2e: "TEST_E2E_PORT",
visual: "TEST_VISUAL_PORT",
visualWorkshop: "TEST_VISUAL_WORKSHOP_PORT",
capabilities: "TEST_CAPABILITIES_PORT",
storybook: "TEST_STORYBOOK_PORT",
dev: "TEST_DEV_PORT",
} as const);
/**
* The origin of a config's second server, for its specs. The runner reserved
* the port in `variable` (reservePort) and its workers inherit it.
*/
export function reservedOrigin(
variable: string,
environment: Readonly<Record<string, string | undefined>> = process.env,
): string {
const port = environment[variable];
if (port === undefined || port === "") {
throw new Error(`${variable} is not set: run this spec through its Playwright config`);
}
return `http://127.0.0.1:${port}`;
}
/**
* A port nothing listens on now: the one the kernel gives a socket bound to
* port 0, which is closed again. Another process can still take it before the
+27
View File
@@ -0,0 +1,27 @@
import { testRunPath, testRunRoot } from "./run-isolation.ts";
/**
* The static workshop a Playwright config serves: the workshop tests
* (playwright.storybook.config.ts) and the gallery goldens
* (playwright.visual.config.ts) open the same build.
*
* 1105/12-04. Under TEST_RUN_ID the workshop is built into the run's own
* folder (.tmp/runs/<id>/artifacts/storybook/static) with build:storybook's
* two steps and another output folder. Unset, the gate's build:storybook
* writes artifacts/storybook/static.
*/
export function storybookStaticServer(port: number): Readonly<{
directory: string;
command: string;
}> {
const directory = testRunPath("artifacts/storybook/static");
const build =
testRunRoot() === "."
? "corepack pnpm build:storybook"
: "node scripts/generate-product-feature-index.ts && " +
`corepack pnpm exec storybook build -o ${directory}`;
return Object.freeze({
directory,
command: `${build} && node scripts/serve-static.ts ${directory} ${port}`,
});
}
@@ -0,0 +1,442 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { useState, type FormEvent } from "react";
import { deriveAsyncState } from "../../application/view-models/async-state.ts";
import { createFailure } from "../../contracts/errors.ts";
import {
Alert,
AsyncSurface,
AuthRequiredSurface,
Badge,
Button,
Card,
Checkbox,
Dialog,
EmptySurface,
ForbiddenSurface,
LoadingSurface,
Menu,
NotFoundSurface,
PageHeader,
ProgressBar,
RadioGroup,
Select,
Switch,
Tabs,
TerminalErrorSurface,
TextArea,
TextField,
ToastProvider,
Tooltip,
useToast,
} from "./index.ts";
/**
* The design-system gallery and the screen-state gallery. They were the
* template's example screens `/examples/ui` and `/examples/states`; the
* visual goldens `design-system-gallery-dark` and `state-surfaces-light`
* (tests/visual/platform.visual.spec.ts) and the workshop tests
* (tests/storybook/galleries.spec.ts) open these stories in the static
* Storybook build. The primitives keep their own suites; these stories show
* them together, with the tokens they draw with.
*/
const meta = {
title: "Platform/Galleries",
parameters: {
layout: "fullscreen",
// Drawn like a route page: the preview's `main` adds no page of its own.
page: true,
},
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
export const DesignSystem: Story = {
render: () => <DesignSystemGallery />,
};
export const ScreenStates: Story = {
render: () => <ScreenStateGallery />,
};
const COLOR_TOKENS = Object.freeze([
["Surface", "--color-surface"],
["Muted surface", "--color-surface-muted"],
["Content", "--color-content"],
["Muted content", "--color-content-muted"],
["Action", "--color-action"],
["Danger", "--color-danger"],
["Focus", "--color-focus"],
]);
function DesignSystemGallery() {
return (
<ToastProvider>
<UiGalleryContent />
</ToastProvider>
);
}
function UiGalleryContent() {
const toast = useToast();
const [projectName, setProjectName] = useState("");
const [description, setDescription] = useState("");
const [template, setTemplate] = useState("application");
const [reviewed, setReviewed] = useState(false);
const [notifications, setNotifications] = useState(true);
const [density, setDensity] = useState("comfortable");
const [fieldTouched, setFieldTouched] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [notice, setNotice] = useState(
"구성요소를 조작하면 결과가 여기에 표시됩니다.",
);
const [alertVisible, setAlertVisible] = useState(true);
const fieldError =
fieldTouched && projectName.trim().length === 0
? "프로젝트 이름을 입력해 주세요."
: undefined;
function submitExample(event: FormEvent<HTMLFormElement>): void {
event.preventDefault();
setFieldTouched(true);
if (projectName.trim().length === 0) {
setNotice("입력값을 확인해 주세요.");
return;
}
setNotice(`“${projectName.trim()}” 입력을 확인했습니다.`);
}
return (
// 08-07. Example copy is Korean in every locale (outside the catalog).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="UI 구성요소"
description="제품 도메인과 독립적인 공통 컨트롤, 피드백, 표면과 디자인 토큰을 직접 조작할 수 있습니다."
/>
<section className="gallery-section" aria-labelledby="controls-title">
<header className="gallery-section__header">
<h2 id="controls-title">버튼과 입력</h2>
<p>키보드, 비활성 상태, 오류 설명을 포함한 기본 상호작용입니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="버튼" description="의미와 위험도에 따라 변형을 선택합니다.">
<div className="button-row">
<Button onClick={() => setNotice("기본 작업을 실행했습니다.")}>
기본 작업
</Button>
<Button
variant="secondary"
onClick={() => setNotice("보조 작업을 실행했습니다.")}
>
보조 작업
</Button>
<Button
variant="danger"
onClick={() => setNotice("위험 작업 예제를 선택했습니다.")}
>
위험 작업
</Button>
<Button disabled>사용 불가</Button>
</div>
</Card>
<Card title="입력창" description="레이블과 도움말, 오류가 입력에 연결됩니다.">
<form className="example-form" noValidate onSubmit={submitExample}>
<TextField
label="프로젝트 이름"
description="새 도메인을 연결할 때 사용할 중립적인 예제입니다."
error={fieldError}
value={projectName}
required
onChange={(event) => setProjectName(event.currentTarget.value)}
/>
<Button type="submit">입력 확인</Button>
</form>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="form-controls-title">
<header className="gallery-section__header">
<h2 id="form-controls-title">폼과 선택 컨트롤</h2>
<p>native semantics, 설명·오류 연결과 controlled 상태를 제공합니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="긴 입력과 선택">
<div className="component-stack">
<TextArea
label="설명"
maxLength={120}
value={description}
onChange={(event) => setDescription(event.currentTarget.value)}
/>
<Select
label="시작 템플릿"
options={[
{ value: "application", label: "Application" },
{ value: "library", label: "Library" },
]}
value={template}
onChange={(event) => setTemplate(event.currentTarget.value)}
/>
<Checkbox
checked={reviewed}
label="접근성 계약을 확인했습니다."
onChange={(event) => setReviewed(event.currentTarget.checked)}
/>
</div>
</Card>
<Card title="단일 선택과 설정">
<div className="component-stack">
<RadioGroup
label="화면 밀도"
name="density"
onChange={setDensity}
options={[
{ value: "comfortable", label: "여유롭게" },
{ value: "compact", label: "조밀하게" },
]}
value={density}
/>
<Switch
checked={notifications}
description="boolean 설정에만 switch를 사용합니다."
label="알림 사용"
onChange={setNotifications}
/>
<ProgressBar label="설정 준비도" max={4} value={3} />
</div>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="feedback-title">
<header className="gallery-section__header">
<h2 id="feedback-title">피드백과 모달</h2>
<p>상태 전달은 색에만 의존하지 않으며, 모든 제어에는 이름이 있습니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="알림과 배지" description="짧은 상태와 문맥형 피드백입니다.">
<div className="component-stack">
{alertVisible ? (
<Alert
title="설정이 저장되었습니다."
variant="success"
onDismiss={() => setAlertVisible(false)}
>
<p>운영 환경에는 실제 저장 포트를 연결하세요.</p>
</Alert>
) : (
<Button
variant="secondary"
onClick={() => setAlertVisible(true)}
>
알림 다시 표시
</Button>
)}
<div className="badge-row" aria-label="배지 변형">
<Badge>중립</Badge>
<Badge variant="info">정보</Badge>
<Badge variant="success">준비됨</Badge>
<Badge variant="warning">확인 필요</Badge>
<Badge variant="danger">실패</Badge>
</div>
</div>
</Card>
<Card title="모달" description="배경과 키보드 Esc로 닫고 포커스를 복원합니다.">
<div className="button-row">
<Button onClick={() => setDialogOpen(true)}>모달 열기</Button>
<Menu
items={[
{
id: "inspect",
label: "상태 확인",
onSelect: () => setNotice("메뉴 작업을 실행했습니다."),
},
{
id: "notify",
label: "Toast 표시",
onSelect: () =>
toast.push({
id: "gallery-saved",
title: "예제가 저장되었습니다.",
tone: "success",
}),
},
]}
triggerLabel="작업 메뉴"
/>
<Tooltip content="이 설명은 필수 정보가 아닙니다.">
<Button variant="ghost">도움말</Button>
</Tooltip>
</div>
<Dialog
open={dialogOpen}
onClose={() => setDialogOpen(false)}
title="연동 확인"
description="도메인 작업을 실행하기 전 확인 화면의 기본 구조입니다."
actions={
<>
<Button
variant="secondary"
onClick={() => setDialogOpen(false)}
>
취소
</Button>
<Button
onClick={() => {
setNotice("모달의 확인 작업을 실행했습니다.");
setDialogOpen(false);
}}
>
확인
</Button>
</>
}
>
<p>민감한 값이나 구현 세부정보는 확인 문구에 포함하지 않습니다.</p>
</Dialog>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="navigation-title">
<header className="gallery-section__header">
<h2 id="navigation-title">탐색 패턴</h2>
<p>화살표 키와 명시적인 활성화 정책을 갖는 탭 예제입니다.</p>
</header>
<Tabs
activation="manual"
label="디자인 시스템 계층"
tabs={[
{
id: "tokens",
label: "토큰",
panel: <p>원시 값에서 의미와 컴포넌트 토큰을 파생합니다.</p>,
},
{
id: "primitives",
label: "프리미티브",
panel: <p>native semantics와 interaction을 닫습니다.</p>,
},
{
id: "patterns",
label: "패턴",
panel: <p>반복되는 사용자 문제를 조합으로 해결합니다.</p>,
},
]}
/>
</section>
<section className="gallery-section" aria-labelledby="tokens-title">
<header className="gallery-section__header">
<h2 id="tokens-title">디자인 토큰</h2>
<p>구성요소가 사용하는 의미 기반 색상과 형태 토큰입니다.</p>
</header>
<div className="token-grid">
{COLOR_TOKENS.map(([label, token]) => (
<article className="token-swatch" key={token}>
<span
className="token-swatch__color"
style={{ backgroundColor: `var(${token})` }}
aria-hidden="true"
/>
<strong>{label}</strong>
<code>{token}</code>
</article>
))}
</div>
</section>
<output className="gallery-notice" aria-live="polite">
{notice}
</output>
</section>
);
}
function ScreenStateGallery() {
const [lastAction, setLastAction] = useState(
"상태 화면의 작업을 선택하면 결과가 여기에 표시됩니다.",
);
const refreshingState = deriveAsyncState({
data: ["기존 데이터"],
isFetching: true,
});
return (
// 08-07. Example copy is Korean in every locale (outside the catalog).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="화면 상태"
description="로딩, 빈 화면, 오류, 인증 필요와 권한 없음 상태가 다음 행동까지 일관되게 안내합니다."
/>
<section className="gallery-section" aria-labelledby="async-states-title">
<header className="gallery-section__header">
<h2 id="async-states-title">비동기 데이터 상태</h2>
<p>초기 로딩과 백그라운드 갱신을 구분해 기존 콘텐츠를 보존합니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="초기 로딩">
<LoadingSurface label="예제 데이터를 불러오는 중" />
</Card>
<Card title="백그라운드 갱신">
<AsyncSurface headingLevel={4} state={refreshingState}>
<div className="state-preview-content">기존 콘텐츠는 계속 표시됩니다.</div>
</AsyncSurface>
</Card>
<Card title="빈 화면">
<EmptySurface
headingLevel={4}
title="아직 표시할 항목이 없습니다."
description="첫 항목을 추가하거나 필터를 초기화할 수 있습니다."
action={
<Button onClick={() => setLastAction("빈 화면 작업을 실행했습니다.")}>
첫 작업 시작
</Button>
}
/>
</Card>
<Card title="복구 가능한 오류">
<TerminalErrorSurface
headingLevel={4}
userMessageKey={
createFailure("NETWORK_UNREACHABLE", "EXAMPLE", 0)
.userMessageKey
}
action="retry"
onAction={() => setLastAction("오류 요청을 다시 시도했습니다.")}
/>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="access-states-title">
<header className="gallery-section__header">
<h2 id="access-states-title">접근과 탐색 상태</h2>
<p>인증 여부와 서버 권한 결과를 서로 다른 상태로 전달합니다.</p>
</header>
<div className="component-grid component-grid--three">
<AuthRequiredSurface
headingLevel={3}
onSignIn={() => setLastAction("로그인 연동 작업을 시작했습니다.")}
/>
<ForbiddenSurface
headingLevel={3}
onNavigate={() => setLastAction("접근 가능한 화면으로 이동합니다.")}
/>
<NotFoundSurface
headingLevel={3}
onNavigate={() => setLastAction("시작 화면으로 이동합니다.")}
/>
</div>
</section>
<output className="gallery-notice" aria-live="polite">
{lastAction}
</output>
</section>
);
}
-16
View File
@@ -135,19 +135,3 @@ test("@a11y reduced-motion policy disables long animation", async ({ page }) =>
.evaluate((body) => getComputedStyle(body).animationDuration);
expect(["0s", "0.00001s", "1e-05s"]).toContain(duration);
});
test("@a11y opened design-system dialog has no blocking violations", async ({
page,
}) => {
await page.goto("/examples/ui");
await page.getByRole("button", { name: "모달 열기" }).click();
const results = await new AxeBuilder({ page })
.include(".ui-dialog")
.withTags(WCAG_TAGS)
.analyze();
expect(
results.violations.filter((violation) =>
["critical", "serious"].includes(violation.impact ?? ""),
),
).toEqual([]);
});
@@ -1,29 +0,0 @@
import { expect, test } from "../support/browser/strict-browser-test.ts";
test("runs menu typeahead, tabs and duplicate toast interactions", async ({
page,
}) => {
await page.goto("/examples/ui");
const menuTrigger = page.getByRole("button", { name: "작업 메뉴" });
await menuTrigger.focus();
await page.keyboard.press("ArrowDown");
await page.keyboard.type("toast");
const toastItem = page.getByRole("menuitem", { name: "Toast 표시" });
await expect(toastItem).toBeFocused();
await page.keyboard.press("Enter");
await expect(page.getByText("예제가 저장되었습니다.")).toBeVisible();
await expect(menuTrigger).toBeFocused();
const tokenTab = page.getByRole("tab", { name: "토큰" });
await tokenTab.focus();
await page.keyboard.press("ArrowRight");
const primitiveTab = page.getByRole("tab", { name: "프리미티브" });
await expect(primitiveTab).toBeFocused();
await expect(primitiveTab).toHaveAttribute("aria-selected", "false");
await page.keyboard.press("Enter");
await expect(primitiveTab).toHaveAttribute("aria-selected", "true");
await expect(
page.getByRole("tabpanel", { name: "프리미티브" }),
).toContainText("native semantics");
});
-34
View File
@@ -1,34 +0,0 @@
import { expect, test } from "../support/browser/strict-browser-test.ts";
test("validates and reports the common text-field flow", async ({ page }) => {
await page.goto("/examples/ui");
await page.getByRole("button", { name: "입력 확인" }).click();
const field = page.getByRole("textbox", { name: "프로젝트 이름" });
await expect(field).toHaveAttribute("aria-invalid", "true");
await expect(field).toHaveAccessibleDescription(
/프로젝트 이름을 입력해 주세요/,
);
await field.fill("Starter");
await page.getByRole("button", { name: "입력 확인" }).click();
await expect(page.getByText("“Starter” 입력을 확인했습니다.")).toBeVisible();
});
test("traps modal interaction and restores focus to the trigger", async ({
page,
}) => {
await page.goto("/examples/ui");
const trigger = page.getByRole("button", { name: "모달 열기" });
await trigger.click();
const dialog = page.getByRole("dialog", { name: "연동 확인" });
await expect(dialog).toBeVisible();
await expect(
dialog.getByRole("button", { name: "연동 확인 닫기" }),
).toBeFocused();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await expect(trigger).toBeFocused();
});
+16 -3
View File
@@ -25,7 +25,14 @@ const PORT_VARIABLES: Readonly<Record<ConfigName, string>> = {
storybook: "TEST_STORYBOOK_PORT",
dev: "TEST_DEV_PORT",
};
const RUN_VARIABLES = ["TEST_RUN_ID", "RUN_OUTPUT_ROOT", ...Object.values(PORT_VARIABLES)];
/** The port variables of the configs' second servers. */
const SECOND_SERVER_PORT_VARIABLES = ["TEST_VISUAL_WORKSHOP_PORT"];
const RUN_VARIABLES = [
"TEST_RUN_ID",
"RUN_OUTPUT_ROOT",
...Object.values(PORT_VARIABLES),
...SECOND_SERVER_PORT_VARIABLES,
];
const held: Server[] = [];
/** For afterEach: forgets the loaded configs and frees the ports `hold` took. */
@@ -111,12 +118,18 @@ function outputs(config: PlaywrightTestConfig) {
};
}
/** The config's own server: the first one when it starts more than one. */
export function webServer(config: PlaywrightTestConfig) {
const server = config.webServer;
if (!server || Array.isArray(server)) throw new TypeError("expected one web server");
const [server] = webServers(config);
if (!server) throw new TypeError("expected a web server");
return server;
}
export function webServers(config: PlaywrightTestConfig) {
const servers = config.webServer;
return servers === undefined ? [] : Array.isArray(servers) ? servers : [servers];
}
/** Each config's results, report and JUnit file, by its folder under artifacts/tests. */
export function describeResultFolders(
runs: ConfigRuns,
+113
View File
@@ -0,0 +1,113 @@
import AxeBuilder from "@axe-core/playwright";
import {
expect,
test,
type Page,
} from "../support/browser/strict-browser-test.ts";
/**
* The design-system gallery (src/presentation/design-system/galleries.stories.tsx)
* in a real browser. These checks ran on the template's example screen
* `/examples/ui` until the galleries became workshop stories; the primitives
* keep their own component suites. The a11y addon's own axe run is switched
* off, as in workshop.spec.ts: the dialog check below owns it.
*/
async function openDesignSystemGallery(page: Page) {
await page.goto(
"/iframe.html?id=platform-galleries--design-system&viewMode=story&globals=a11y.manual:!true",
);
await expect(
page.getByRole("heading", { level: 1, name: "UI 구성요소" }),
).toBeVisible();
}
test("validates and reports the common text-field flow", async ({ page }) => {
await openDesignSystemGallery(page);
await page.getByRole("button", { name: "입력 확인" }).click();
const field = page.getByRole("textbox", { name: "프로젝트 이름" });
await expect(field).toHaveAttribute("aria-invalid", "true");
await expect(field).toHaveAccessibleDescription(
/프로젝트 이름을 입력해 주세요/,
);
await field.fill("Starter");
await page.getByRole("button", { name: "입력 확인" }).click();
await expect(page.getByText("“Starter” 입력을 확인했습니다.")).toBeVisible();
});
test("traps modal interaction and restores focus to the trigger", async ({
page,
}) => {
await openDesignSystemGallery(page);
const trigger = page.getByRole("button", { name: "모달 열기" });
await trigger.click();
const dialog = page.getByRole("dialog", { name: "연동 확인" });
await expect(dialog).toBeVisible();
await expect(
dialog.getByRole("button", { name: "연동 확인 닫기" }),
).toBeFocused();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await expect(trigger).toBeFocused();
});
test("opened design-system dialog has no blocking violations", async ({
page,
}) => {
await openDesignSystemGallery(page);
await page.getByRole("button", { name: "모달 열기" }).click();
const results = await new AxeBuilder({ page })
.include(".ui-dialog")
.withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"])
.analyze();
expect(
results.violations.filter((violation) =>
["critical", "serious"].includes(violation.impact ?? ""),
),
).toEqual([]);
});
test("runs menu typeahead, tabs and duplicate toast interactions", async ({
page,
}) => {
await openDesignSystemGallery(page);
const menuTrigger = page.getByRole("button", { name: "작업 메뉴" });
await menuTrigger.focus();
await page.keyboard.press("ArrowDown");
await page.keyboard.type("toast");
const toastItem = page.getByRole("menuitem", { name: "Toast 표시" });
await expect(toastItem).toBeFocused();
await page.keyboard.press("Enter");
await expect(page.getByText("예제가 저장되었습니다.")).toBeVisible();
await expect(menuTrigger).toBeFocused();
const tokenTab = page.getByRole("tab", { name: "토큰" });
await tokenTab.focus();
await page.keyboard.press("ArrowRight");
const primitiveTab = page.getByRole("tab", { name: "프리미티브" });
await expect(primitiveTab).toBeFocused();
await expect(primitiveTab).toHaveAttribute("aria-selected", "false");
await page.keyboard.press("Enter");
await expect(primitiveTab).toHaveAttribute("aria-selected", "true");
await expect(
page.getByRole("tabpanel", { name: "프리미티브" }),
).toContainText("native semantics");
});
test("reflows the gallery at the 320px minimum without horizontal overflow", async ({
page,
}) => {
await page.setViewportSize({ width: 320, height: 720 });
await openDesignSystemGallery(page);
const viewport = await page.evaluate(() => ({
clientWidth: document.documentElement.clientWidth,
scrollWidth: document.documentElement.scrollWidth,
}));
expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth);
});
+2 -1
View File
@@ -41,8 +41,9 @@ describe("local build environment (1103/11-08)", () => {
});
it("starts the visual goldens' build as a local build inside a CI job", () => {
// The app preview is the first server; the second serves the workshop.
const webServer = visualConfig.webServer;
const env = Array.isArray(webServer) ? undefined : webServer?.env;
const env = (Array.isArray(webServer) ? webServer[0] : webServer)?.env;
// Playwright merges a web server's env over the runner's process.env.
expect(ciBuildEnvironmentFailures({ ...CI_JOB, ...env })).toEqual([]);
@@ -8,8 +8,10 @@ import {
describeServerPorts,
itExitsWhenItsPortIsTaken,
itKeepsTheViteCacheInTheRun,
hold,
releaseRuns,
webServer,
webServers,
} from "../helpers/playwright-run-isolation.ts";
/**
@@ -87,6 +89,43 @@ describe("the build a run serves", () => {
describeServerPorts(runs, ["e2e", "visual", "storybook", "dev"]);
// The gallery goldens open workshop stories: the visual config starts the
// static workshop next to its preview, on a port of its own.
describe("the visual config's workshop server", () => {
const workshop = async (environment: Readonly<Record<string, string>> = {}) => {
const runner = await runs.loadProcess("visual", environment);
const servers = webServers(runner.config);
expect(servers).toHaveLength(2);
return { runner, server: servers[1]! };
};
it("is a free port of its own the runner hands to its workers", async () => {
const { runner, server } = await workshop();
const port = Number(runner.after["TEST_VISUAL_WORKSHOP_PORT"]);
expect(port).toBeGreaterThan(0);
expect(port).not.toBe(Number(runner.after["TEST_VISUAL_PORT"]));
expect(server.url).toBe(`http://127.0.0.1:${port}`);
expect(server.command).toMatch(new RegExp(` ${port}$`, "u"));
expect(server.reuseExistingServer).toBe(false);
});
it("moves for a second run while the first run's server holds its port", async () => {
const first = (await workshop()).server.url;
await hold(Number(new URL(String(first)).port));
expect((await workshop()).server.url).not.toBe(first);
});
it("serves the build the workshop config serves, in the run's folder", async () => {
const pinned = { TEST_VISUAL_WORKSHOP_PORT: "40124", TEST_STORYBOOK_PORT: "40124" };
for (const environment of [pinned, { ...pinned, TEST_RUN_ID: "a" }]) {
const { server } = await workshop(environment);
expect(server.command).toBe(webServer(await runs.load("storybook", environment)).command);
}
});
});
describe("vite servers", () => {
itExitsWhenItsPortIsTaken(runs, ["e2e", "visual", "dev"]);
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 123 KiB

+30 -10
View File
@@ -3,6 +3,10 @@ import {
test,
type Page,
} from "../support/browser/strict-browser-test.ts";
import {
reservedOrigin,
TEST_PORT_VARIABLES,
} from "../../scripts/lib/run-isolation.ts";
import {
ROUTE_FEATURE_OWNER,
ROUTE_REGISTRY,
@@ -14,6 +18,18 @@ async function expectRouteHeading(page: Page, title: string) {
await expect(page.getByRole("heading", { level: 1 })).toHaveText(title);
}
/**
* A gallery story in the static workshop the config's second server serves
* (src/presentation/design-system/galleries.stories.tsx). The a11y addon's own
* axe run is switched off, as in tests/storybook: it has nothing to draw.
*/
async function openGalleryStory(page: Page, storyId: string, title: string) {
await page.goto(
`${reservedOrigin(TEST_PORT_VARIABLES.visualWorkshop)}/iframe.html?id=${storyId}&viewMode=story&globals=a11y.manual:!true`,
);
await expect(page.getByRole("heading", { level: 1 })).toHaveText(title);
}
/** `toHaveScreenshot` takes a stylesheet only as a file; a tag does the same. */
async function hide(page: Page, css: string) {
if (css !== "") await page.addStyleTag({ content: css });
@@ -76,22 +92,26 @@ test("compact drawer and pseudo-locale visual contract", async ({ page }) => {
});
});
test("design-system gallery dark visual contract", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await page.goto("/examples/ui");
await expectRouteHeading(page, "UI 구성요소");
await page.locator("#theme-preference").selectOption("dark");
await expect(page.getByRole("main")).toHaveScreenshot(
"design-system-gallery-dark.png",
);
test.describe("in the dark color scheme", () => {
// The workshop has no theme selector: the theme provider follows the
// system preference there, as the app does until a user picks one.
test.use({ colorScheme: "dark" });
test("design-system gallery dark visual contract", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 900 });
await openGalleryStory(page, "platform-galleries--design-system", "UI 구성요소");
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
await expect(page.getByRole("main")).toHaveScreenshot(
"design-system-gallery-dark.png",
);
});
});
test("loading empty error and access surfaces visual contract", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 1100 });
await page.goto("/examples/states");
await expectRouteHeading(page, "화면 상태");
await openGalleryStory(page, "platform-galleries--screen-states", "화면 상태");
await expect(page.getByRole("main")).toHaveScreenshot(
"state-surfaces-light.png",
);