fix(design-system): 스타일·토큰·story·검사를 토큰 계약에 맞춘다 #56

Merged
donghyeon.kang merged 9 commits from donghyeon.kang/fix/r9-design-tokens-stories AGit into main 2026-11-13 19:13:51 +00:00
34 changed files with 1486 additions and 281 deletions
+4 -4
View File
@@ -30,16 +30,16 @@ paths:
## 함정
1. `check:design-system`이 통과했으니 토큰만 썼다고 본다. 날 색 검사는 `src`의 TS·TSX에서 `#hex`·`oklch(`·`rgb(`만 찾는다. `hsl()`, 색 이름(`red`), 날 px 간격은 안 본다. 토큰 파일 밖 CSS(`src/presentation/styles/**`)는 없는 토큰 참조와 혼합 색 공간만 보고 날 색은 안 본다. 기능 폴더 CSS는 아예 안 본다. 리뷰가 잡는다. — `scripts/check-design-system.ts`, `docs/design/2026-07-26-design-system-platform-design.md` 4.1절 「토큰 CSS 검사 규칙」
1. `check:design-system`이 통과했으니 토큰만 썼다고 본다. TS·TSX에서는 `#hex`·`oklch(`·`rgb(`와 `style={{ … }}`의 손 색·간격만 찾는다. 문자열로 조립한 class, Tailwind 임의 값(`text-[…]`), `hsl()`·색 이름을 담은 다른 문자열은 안 본다. CSS는 `src` 아래 전부를 보고 UI-06이 간격·글자·반경·층·그림자의 날 값을 거절하지만, 너비·높이·위치·opacity는 보지 않는다. 리뷰가 잡는다. — `scripts/check-design-system.ts`, `docs/design/2026-07-26-design-system-platform-design.md` 4.1절 「토큰 CSS 검사 규칙」
2. tooltip에만 필요한 정보를 둔다. 검사기의 tooltip 규칙은 음성 fixture에서만 돌고 실제 소스는 보지 않는다. — `scripts/check-design-system.ts`, `docs/design/2026-07-26-design-system-platform-design.md` 6.1절 10번
3. 포커스 대비 토큰을 `color-mix()`·알파·키워드로 만든다. 3:1 계산은 불투명한 `oklch()`로 끝나는 토큰만 하고 나머지는 실패한다. `color-mix()`는 `in oklab`만 쓴다. — `docs/styling/design-tokens.md` UI-01·UI-02
3. 포커스 대비 토큰을 `color-mix()`·알파·키워드로 만든다. 3:1 계산은 불투명한 `oklch()`로 끝나는 토큰만 하고 나머지는 실패한다. `color-mix()`는 색상각 공간(oklch·lch·hsl·hwb)에서 섞지 않는다. 기본은 `in oklab`이고, 반투명 색을 브라우저가 겹쳐 그린 결과를 재현할 때만 `in srgb`를 쓴다(`component.css`의 가림막). — `docs/styling/design-tokens.md` UI-01·UI-02
4. 다크 테마 재정의를 빠뜨리거나 light 전용 패널·글자색을 박는다. 핵심 역할 토큰은 `:root[data-theme="dark"]`에 모두 있어야 하고, `component.css`에 forced-colors 대체가 있어야 한다. — `docs/styling/design-tokens.md`, `scripts/check-design-system.ts`
5. 디자인 시스템 하위 파일, `lucide-react`, headless 라이브러리를 직접 import한다. `src/presentation/design-system/index.ts`와 vendor facade로만 들어간다. — `docs/architecture/layers.md` 규칙 `design-system-is-reached-through-its-index`·`icon-vendor-is-facade-only`, `docs/design/2026-07-26-design-system-platform-design.md` 6.1절
6. 사용자 값이나 실행 중에 조립한 class 문자열을 쓰고, 같은 bracket 값을 여러 곳에 쓴다. variant는 닫힌 정적 표에서 고르고, 반복되는 bracket 값은 `@theme`로 올린다. — `docs/styling/design-tokens.md` 「임의 값(arbitrary value) 정책」
7. 컴포넌트 API를 열어 둔다: 날 색 prop, vendor 타입 노출, 무제한 `as`, 범위 없는 `className`. — `docs/design/2026-07-26-design-system-platform-design.md` 11절 4단계, 13절
8. primitive가 API·query·인증·저장소를 직접 부른다. pattern·template도 use case를 고르지 않고 상태와 callback을 props로 받는다. — 같은 문서 2절
9. 세 번째 사용 사례가 나오기 전에 제품 전용 조합을 primitive로 올린다. — 같은 문서 2절
10. 시각 골든을 그냥 다시 찍는다. 골든은 코드 리뷰 대상이다. Chromium 하나, Linux, 글꼴 고정(`tests/visual/fonts.conf`)이고 허용 차이는 절대 픽셀 수다. 비율 허용이 1천 px 넘는 회귀를 통과시킨 일이 있어 절대 수로 바꿨다. 실패 screenshot은 시각 회귀가 아니다. — `playwright.visual.config.ts`, `docs/design/2026-07-26-design-system-platform-design.md` 10.3절
10. 시각 골든을 그냥 다시 찍는다. 골든은 코드 리뷰 대상이다. Chromium 하나, Linux, 글꼴 고정(`tests/visual/fonts.conf`)이고 허용 차이는 절대 픽셀 수(`maxDiffPixels`)이고, 한 픽셀의 색 허용치는 0.05다(시각 spec의 `GOLDEN`). 비율 허용이 1천 px 넘는 회귀를, 기본 색 허용치 0.2가 위험 표면의 색상 변경을 통과시킨 일이 있다. 실패 screenshot은 시각 회귀가 아니다. — `playwright.visual.config.ts`, `docs/design/2026-07-26-design-system-platform-design.md` 10.3절
11. 골든이 그리는 범위를 넘겨 짐작한다. 골든은 셸·홈·플랫폼 구성·갤러리 story만 찍고 기능 영역은 가린다. 새 primitive·상태는 갤러리 story에 넣어야 골든에 든다. — `tests/visual/platform.visual.spec.ts`, `PRODUCT.md` 「Capabilities and Constraints」
12. 디자인 시스템이 side effect를 갖거나 무거운 것을 끌어와 초기 청크에 실린다. — `docs/work/reference/defect-patterns.md` B3, `tests/unit/design-system-initial-chunk.test.ts`
@@ -50,7 +50,7 @@ paths:
- [ ] 새 값은 primitive → semantic → component 순서로 파생하고, 컴포넌트는 semantic 토큰을 읽는다. 브랜드는 토큰으로만 바꾼다. — `docs/styling/design-tokens.md`, `PRODUCT.md` 원칙 2
- [ ] 새 component 토큰은 `src/presentation/design-system/tokens/token-contract.ts`에 이름이 있고 어떤 스타일이 읽는다. — UI-03
- [ ] 첫 글꼴은 일반 키워드나 `@font-face`로 싣는 글꼴이다. 패키지로 싣는 글꼴은 `PRODUCT_LOADED_FONT_FAMILIES`에 적는다. — UI-05, `docs/design/2026-07-26-design-system-platform-design.md` 4.1절
- [ ] 아이콘 크기·stroke는 `--icon-size-*`·`--icon-stroke-*`, 색은 `currentColor`다. — 같은 문서 6.1절
- [ ] 아이콘 크기·stroke는 `--size-icon-*`·`--icon-stroke-default`, 색은 `currentColor`다. — 같은 문서 6.1절
컴포넌트
+6 -6
View File
@@ -45,14 +45,14 @@
}
],
"initialJavascript": {
"gzipBytes": 194354,
"files": 17,
"firstFeatureGzipBytes": 6355,
"perFeatureGzipBytes": 528,
"perContextGzipBytes": 21
"gzipBytes": 194143,
"files": 15,
"firstFeatureGzipBytes": 6192,
"perFeatureGzipBytes": 521,
"perContextGzipBytes": 28
},
"serviceWorkerPrecache": {
"assets": 24,
"assets": 22,
"firstFeatureAssets": 14,
"perFeatureAssets": 12,
"perContextAssets": 0
+41 -11
View File
@@ -20,16 +20,39 @@ component별 값에 연결한다.
- UI-01: `--color-focus`는 두 테마 모두에서, focus ring이 놓일 수 있는 모든
surface와 3:1 이상 대비를 가진다. 대비를 계산할 수 있도록 그 토큰들은 불투명한
`oklch()` 값으로 풀려야 한다.
- UI-02: `color-mix()`는 `oklab`에서 섞는다. 색상(hue) 기반 색 공간에서는 섞지
않는다.
- UI-02: `color-mix()`와 gradient는 색상(hue) 기반 색 공간(oklch·lch·hsl·hwb)에서
섞지 않는다. 기본은 `oklab`이다. 반투명 색을 브라우저가 겹쳐 그린 결과를 재현할
때만 `srgb`를 쓴다(`component.css`의 `--dialog-backdrop-on-surface`).
- UI-03: 모든 component 토큰은 어떤 스타일이든 하나에서 읽힌다.
`component.css`의 `@theme`에 정의한 토큰은 모두 `token-contract.ts`의
`REQUIRED_COMPONENT_TOKENS`에 있어야 한다. 필수 semantic 토큰도 스타일
하나가 읽어야 한다. 예외는 `SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER`에
이유와 함께 적는다(지금 `--layer-modal` 하나: native `<dialog>`는 top
layer에 열려 z-index가 닿지 않는다).
- UI-05: `--font-sans`는 generic family로 시작하거나, repository가
`@font-face`로 함께 배포하는 글꼴로 시작한다.
- UI-06: `src/` 아래 토큰 파일 밖의 스타일은 간격(padding·margin·gap),
글자 크기·굵기·줄 높이, 모서리 반경, z-index, 그림자를 손으로 쓰지 않고
토큰(`var(--space-*)`, `--font-size-*`, `--font-weight-*`,
`--line-height-*`, `--radius-*`, `--layer-*`, `--elevation-*`)을 읽는다.
`0`, `auto`, 키워드, `%`, viewport 단위, margin·padding의 1px 선, 부모
글자에 대한 `em`, `line-height: 1`, `z-index` 0·-1은 된다. 맞는 단계가 없으면
`primitive.css`에 단계를 더한다.
- UI-07: `semantic.css`는 색 값을 직접 쓰지 않는다. 색은 `primitive.css`
팔레트에 이름을 두고 `var()`로 읽는다. 토큰끼리 섞는 `color-mix()`는 된다.
그래서 팔레트만 고쳐도 status 색, focus, 어두운 테마가 따라온다.
같은 검사는 다음도 요구한다: `token-contract.ts`의 토큰 이름, 핵심 semantic
역할의 어두운 테마 덮어쓰기, `component.css`의 forced-colors fallback, 토큰 파일
밖에서 가공하지 않은 팔레트 값을 쓰지 않을 것, headless 라이브러리를 직접
import하지 않을 것.
import하지 않을 것. 토큰 파일 밖의 CSS는 `src/` 아래 전부(기능 폴더 포함)를 보고,
날 색을 쓰거나 토큰을 다시 정의하거나 focus ring을 `outline-offset: 0`으로
그리면 실패한다. gradient의 색 공간도 UI-02를 따른다.
primitive의 `className`·`style`은 배치용이다: 그리드 위치, 바깥 여백, 너비 같은
것. 색과 간격·글자·반경·층·그림자는 variant와 토큰으로 정한다. TSX의
`style={{ … }}`에 이런 값을 손으로 쓰면 검사가 실패한다(`var(--…)`를 읽는 것은
된다).
## 테마 계약
@@ -47,14 +70,21 @@ component는 `--color-panel`, `--color-content`, `--color-border`,
## 들어 있는 primitive
- `Button`: primary, secondary, danger, ghost 의도
- `TextField`: label, 도움말, 필수 상태, 연결된 검증 오류
- `Card`: 이름이 붙은 surface와 선택적 footer
- `Alert`와 `Badge`: 색에만 기대지 않는 status 피드백
- `Dialog`: native modal 의미, Escape·backdrop으로 닫기, 닫은 뒤 trigger로 focus
되돌리기
- 비동기·접근 상태 surface: 로딩, 새로고침, 빈 상태, 끝난(terminal) 오류, 인증
필요, 권한 없음, 찾을 수 없음
primitive·pattern·페이지 템플릿·폼 구성요소의 목록은 공개 배럴
`src/presentation/design-system/index.ts`가 정본이다. 이 문서는 목록을 손으로
들지 않는다. 컴포넌트의 상태는 story에서 연다: 갤러리
`src/presentation/design-system/galleries.stories.tsx`(primitive를 함께, 화면
상태), 카탈로그 `src/presentation/design-system/catalog.stories.tsx`(나머지를
묶음마다). 배럴의 화면 컴포넌트마다 story가 있는지는
`tests/unit/design-system-story-coverage.test.ts`가 대조한다.
모든 primitive가 지키는 약속:
- status 피드백(`Alert`, `Badge`, 상태 surface)은 색에만 기대지 않는다. 글자와
아이콘이 같은 뜻을 전한다.
- 필요한 정보를 tooltip에만 두지 않는다.
- overlay(`Dialog`, `Drawer`, `ConfirmationDialog`)는 native modal 의미를 쓰고,
Escape로 닫고, 닫은 뒤 연 곳으로 focus를 돌린다.
임의 값(arbitrary value) 정책:
+45 -5
View File
@@ -9,11 +9,19 @@ import {
REQUIRED_COMPONENT_TOKENS,
REQUIRED_PRIMITIVE_TOKENS,
REQUIRED_SEMANTIC_TOKENS,
SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER,
} from "../src/presentation/design-system/tokens/token-contract.ts";
import {
firstFontFamilyFailures,
focusContrastFailures,
hueMixFailures,
rawSemanticColourFailures,
focusOffsetFailures,
inlineStyleFailures,
rawStyleValueFailures,
styleSheetColourFailures,
tokenRedefinitionFailures,
undeclaredComponentTokenFailures,
unreadTokenFailures,
} from "./lib/design-system-rules.ts";
import { readCustomProperties } from "./lib/oklch-contrast.ts";
@@ -40,12 +48,14 @@ for (const [layer, file, tokens] of tokenLayers) {
}
}
// theme.css only imports the files under styles/theme/, so check them all.
const styleFiles = (
await readdir("src/presentation/styles", { recursive: true })
)
// Every style sheet under src/, not only the ones theme.css imports: a
// feature's own CSS is a style sheet too (1101/12-03).
const tokenFileSet = new Set<string>(Object.values(tokenFiles));
const styleFiles = (await readdir("src", { recursive: true }))
.filter((file) => file.endsWith(".css"))
.map((file) => path.join("src/presentation/styles", file));
.map((file) => path.join("src", file))
.filter((file) => !tokenFileSet.has(file))
.sort();
const cssSources = await Promise.all(
[...Object.values(tokenFiles), ...styleFiles].map(
async (file) => ({ file, source: await readFile(file, "utf8") }),
@@ -63,9 +73,27 @@ for (const { file, source } of cssSources) {
}
}
failures.push(...hueMixFailures({ file, source }));
if (!tokenFileSet.has(file)) {
failures.push(
...rawStyleValueFailures({ file, source }),
...styleSheetColourFailures({ file, source }),
...focusOffsetFailures({ file, source }),
);
}
}
const tokenNames = new Set(
cssSources
.filter(({ file }) => tokenFileSet.has(file))
.flatMap(({ source }) => [...source.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((match) => match[1])),
);
for (const { file, source } of cssSources) {
if (!tokenFileSet.has(file)) failures.push(...tokenRedefinitionFailures({ file, source }, tokenNames));
}
const semanticSource = await readFile(tokenFiles.semantic, "utf8");
failures.push(
...rawSemanticColourFailures({ file: tokenFiles.semantic, source: semanticSource }),
);
const darkSource =
semanticSource.match(/:root\[data-theme="dark"\]\s*\{([\s\S]*?)\n\}/)?.[1] ??
"";
@@ -106,6 +134,17 @@ failures.push(
REQUIRED_COMPONENT_TOKENS,
cssSources.filter(({ file }) => file !== tokenFiles.component),
),
...unreadTokenFailures(
REQUIRED_SEMANTIC_TOKENS.filter(
(token) => !SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER.includes(token),
),
cssSources.filter(({ file }) => file !== tokenFiles.semantic),
"semantic",
),
...undeclaredComponentTokenFailures(
{ file: tokenFiles.component, source: await readFile(tokenFiles.component, "utf8") },
REQUIRED_COMPONENT_TOKENS,
),
...firstFontFamilyFailures(
lightProperties.get("--font-sans") ?? "",
cssSources,
@@ -147,6 +186,7 @@ for (const file of sources) {
) {
failures.push(`raw palette value in ${file}`);
}
failures.push(...hueMixFailures({ file, source }), ...inlineStyleFailures({ file, source }));
if (
file.includes("tests/fixtures/design-system/forbidden") &&
source.includes("TOOLTIP_ONLY_REQUIRED_INFORMATION")
+150 -8
View File
@@ -1,5 +1,5 @@
// The four CSS rules scripts/check-design-system.ts runs over the token
// files and src/presentation/styles/**. Each rule takes file contents and
// The CSS rules scripts/check-design-system.ts runs over the token files and
// the style sheets. Each rule takes file contents and
// returns failure messages, so a test can hand it a violation directly.
import { contrastRatio, resolveColor, resolveValue } from "./oklch-contrast.ts";
@@ -9,11 +9,12 @@ export interface CssSource {
readonly source: string;
}
// Comments keep old code around, and the browser never draws it.
// Comments keep old code around, and the browser never draws it. They turn
// into spaces, newlines kept, so a reported line number stays the file's.
// Limit: a "/*" inside a quoted string would start a false comment. No
// CSS here has one; switch to a CSS tokenizer if that changes.
function withoutComments(css: string): string {
return css.replace(/\/\*[\s\S]*?\*\//g, "");
return css.replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, " "));
}
// UI-01. The focus ring is drawn 3px away from its control, so the colour
@@ -63,10 +64,13 @@ export function focusContrastFailures(
// stop such as oklch(1 0 0) carries hue 0: 14% blue into white came out
// pink. oklab mixes on straight lines and has no hue to drag. CSS
// function names and keywords ignore ASCII case, so OKLCH counts too.
// A gradient interpolates the same way (`linear-gradient(90deg in oklch,
// …)`), and an inline style in TSX is CSS too (1101/12-03).
const HUE_MIX =
/(?:color-mix\(\s*|(?:repeating-)?(?:linear|radial|conic)-gradient\([^,()]*?)\bin\s+(oklch|lch|hsl|hwb)\b/gi;
export function hueMixFailures({ file, source }: CssSource): string[] {
const mixes = withoutComments(source).matchAll(
/color-mix\(\s*in\s+(oklch|lch|hsl|hwb)\b/gi,
);
const mixes = withoutComments(source).matchAll(HUE_MIX);
return [...mixes].map((match) => `${file} mixes colours in ${match[1]}; use oklab`);
}
@@ -79,6 +83,7 @@ export function hueMixFailures({ file, source }: CssSource): string[] {
export function unreadTokenFailures(
tokens: readonly string[],
styles: readonly CssSource[],
layer: "component" | "semantic" = "component",
): string[] {
const read = new Set(
styles.flatMap(({ source }) =>
@@ -88,7 +93,26 @@ export function unreadTokenFailures(
);
return tokens
.filter((token) => !read.has(token))
.map((token) => `component token ${token} is defined but no style reads it`);
.map((token) => `${layer} token ${token} is defined but no style reads it`);
}
// UI-03 (contract). A component token outside REQUIRED_COMPONENT_TOKENS is
// outside UI-03 too: the reader check only walks the contract list, so a
// token defined in component.css and read by nothing passed (1112/04-12).
// Only the @theme block counts: the forced-colors block redefines semantic
// roles, not component tokens.
export function undeclaredComponentTokenFailures(
{ file, source }: CssSource,
contract: readonly string[],
): string[] {
const theme = /@theme\s*\{([\s\S]*?)\n\}/.exec(withoutComments(source))?.[1] ?? "";
return [...theme.matchAll(/(--[a-z0-9-]+)\s*:/g)]
.map((match) => match[1])
.filter((token) => !contract.includes(token))
.map(
(token) =>
`${file} defines ${token}, which REQUIRED_COMPONENT_TOKENS in token-contract.ts does not list`,
);
}
// UI-05. --font-sans named Inter first, but nothing loads Inter, so most
@@ -126,3 +150,121 @@ export function firstFontFamilyFailures(
`--font-sans starts with "${first}", which is neither a generic family, loaded by @font-face, nor listed in PRODUCT_LOADED_FONT_FAMILIES`,
];
}
// UI-07. The semantic layer names roles and reads its colours from the
// palette in primitive.css. A colour written straight into semantic.css is
// out of reach of a rebrand that edits the palette: 36 such values kept the
// status colours, the focus ring and most of the dark theme as they were
// (1112/04-13).
const RAW_COLOUR = /#[0-9a-f]{3,8}\b|\b(?:oklch|oklab|lch|lab|rgba?|hsla?|hwb|color)\(/i;
export function rawSemanticColourFailures({ file, source }: CssSource): string[] {
return [...withoutComments(source).matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/gi)]
.filter((match) => RAW_COLOUR.test(match[2]))
.map(
(match) =>
`${file} ${match[1]} is the raw colour ${match[2].trim()}; name it in primitive.css and read it with var()`,
);
}
// UI-06. A style that writes a spacing, type, radius, layer or shadow value
// by hand does not move when the token does: changing --space-*, --layer-*,
// --elevation-panel or --radius-modal left the shell, the page templates and
// the cards as they were (1112/04-08). Allowed: a token read (var()), 0,
// auto, keywords, %, viewport units, a 1px hairline in margin or padding,
// line-height 1, z-index 0 or -1, and em sizes relative to the parent font.
const LENGTH = /(?<![\w.-])-?(?:\d+\.?\d*|\.\d+)(?:px|rem|em)\b/g;
const NUMBER = /(?<![\w.(-])-?(?:\d+\.?\d*|\.\d+)(?![\w.%])/g;
const SPACING_PROPERTY =
/^(?:padding|margin)(?:-(?:top|right|bottom|left|block|inline)(?:-(?:start|end))?)?$|^(?:row-|column-)?gap$/;
function handWrittenValues(property: string, value: string): string[] {
const tokensRemoved = value.replace(/var\([^)]*\)/g, "");
const lengths = tokensRemoved.match(LENGTH) ?? [];
const numbers = tokensRemoved.replace(LENGTH, "").match(NUMBER) ?? [];
if (SPACING_PROPERTY.test(property)) return lengths.filter((length) => !["1px", "-1px"].includes(length));
if (property === "font-size") return lengths.filter((length) => !/(?<!r)em$/.test(length));
if (property === "font-weight") return numbers;
if (property === "line-height") return [...lengths, ...numbers].filter((item) => item !== "1");
if (/^border(?:-[a-z]+)*-radius$/.test(property)) return lengths;
if (property === "z-index") return numbers.filter((item) => !["0", "-1"].includes(item));
if (property === "box-shadow") return [...lengths, ...numbers];
return [];
}
export function rawStyleValueFailures({ file, source }: CssSource): string[] {
const css = withoutComments(source);
const failures: string[] = [];
for (const match of css.matchAll(/(?<![\w-])([a-z-]+)\s*:\s*([^;{}]+);/g)) {
const [, property, value] = match;
const raw = handWrittenValues(property, value);
if (raw.length === 0) continue;
const line = css.slice(0, match.index).split("\n").length;
failures.push(
`${file}:${line} ${property}: ${value.trim()} writes ${raw.join(", ")} by hand; read a token (docs/styling/design-tokens.md UI-06)`,
);
}
return failures;
}
// Outside the token files a style reads colours, it does not define them.
// 1101/12-03: a raw colour in a feature's own CSS, a token redefined under
// :root in a style sheet (the token file then no longer decides it), and a
// focus ring drawn with no offset (UI-01 measures the ring against the
// surface around the control, not against the control) all passed.
export function styleSheetColourFailures({ file, source }: CssSource): string[] {
return [...withoutComments(source).matchAll(/(?<![\w-])([a-z-]+)\s*:\s*([^;{}]+);/g)]
.filter((match) => !match[1].startsWith("--") && RAW_COLOUR.test(match[2]))
.map((match) => `${file} ${match[1]}: ${match[2].trim()} is a raw colour; read a colour token`);
}
export function tokenRedefinitionFailures(
{ file, source }: CssSource,
tokens: ReadonlySet<string>,
): string[] {
return [...withoutComments(source).matchAll(/(?<![\w-])(--[a-z0-9-]+)\s*:/g)]
.filter((match) => tokens.has(match[1]))
.map((match) => `${file} redefines the token ${match[1]}; change it in the token files`);
}
export function focusOffsetFailures({ file, source }: CssSource): string[] {
return [...withoutComments(source).matchAll(/outline-offset\s*:\s*([^;{}]+);/g)]
.filter((match) => /^(?:-|0(?:\.0*)?(?:px|rem|em)?\s*$)/.test(match[1].trim()))
.map(
(match) =>
`${file} outline-offset: ${match[1].trim()} draws the focus ring on the control; UI-01 measures it against the surface around the control`,
);
}
// 1112/04-14 (decision 2026-11-12). Primitives keep `className` and `style`
// open, so a screen can lay a raw colour or spacing over a primitive. An
// inline style may place things and read tokens; a colour or a spacing,
// type, radius, layer or shadow value written by hand is refused.
// The scale values are judged as UI-06 judges a style sheet: an inline
// style is the same declaration written in camelCase, and React writes a bare
// number as px except for the unitless properties.
const INLINE_COLOUR_KEYWORDS = new Set(["transparent", "currentcolor", "inherit", "initial", "unset", "none"]);
const INLINE_COLOUR_PROPERTY = /^(?:color|background|fill|stroke)$|Color$/;
const INLINE_UNITLESS = new Set(["zIndex", "fontWeight", "lineHeight", "opacity", "flex", "flexGrow", "flexShrink", "order"]);
export function inlineStyleFailures({ file, source }: CssSource): string[] {
const failures: string[] = [];
for (const style of source.matchAll(/style=\{\{([\s\S]*?)\}\}/g)) {
for (const entry of style[1].matchAll(/([A-Za-z]+)\s*:\s*(`[^`]*`|"[^"]*"|'[^']*'|-?[\d.]+)/g)) {
const [, property, written] = entry;
const value = written.replace(/^[`"']|[`"']$/g, "").trim();
const colour =
INLINE_COLOUR_PROPERTY.test(property) &&
!/^var\(/.test(value) &&
!INLINE_COLOUR_KEYWORDS.has(value.toLowerCase());
const css =
/^-?[\d.]+$/.test(written) && !INLINE_UNITLESS.has(property) && Number(value) !== 0 ? `${value}px` : value;
const scale =
handWrittenValues(property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`), css).length > 0;
if (colour || scale) {
failures.push(`${file} style ${property}: ${written} is written by hand; read a token or use a primitive variant`);
}
}
}
return failures;
}
+19
View File
@@ -297,6 +297,25 @@ class SkillTest(unittest.TestCase):
self.assertNotIn("코드 안 제목", names)
self.assertFalse(any(name.startswith("목록 줄") for name in names))
# A token name in a skill that the token files do not define sends a reviewer to make a second copy:
# fe-design-system once asked for `--icon-size-*`, and the tokens are `--size-icon-*`.
TOKEN_NAMESPACES = ("color", "space", "spacing", "font", "line", "radius", "shadow", "duration", "easing", "size",
"icon", "breakpoint", "container", "elevation", "layer", "opacity", "palette", "button",
"field", "dialog", "navigation", "drawer", "toast")
def test_every_token_a_skill_names_is_a_defined_token(self) -> None:
tokens = REPO / "src/presentation/design-system/tokens"
defined = {match for css in tokens.glob("*.css")
for match in re.findall(r"(--[a-z0-9-]+)\s*:", css.read_text(encoding="utf-8"))}
self.assertIn("--size-icon-md", defined)
for path in sorted((CLAUDE / "skills").glob("*/SKILL.md")):
for name in re.findall(r"`(--[a-z0-9*-]+)`", path.read_text(encoding="utf-8")):
if name[2:].split("-")[0] not in self.TOKEN_NAMESPACES:
continue
pattern = re.compile("^" + re.escape(name).replace(r"\*", "[a-z0-9-]+") + "$")
self.assertTrue(any(pattern.match(token) for token in defined),
f"{path.parent.name}: `{name}` names no token in {tokens.relative_to(REPO)}")
def test_each_skill_points_at_its_canonical_playbook_instead_of_copying_it(self) -> None:
for name, canon in self.CANON.items():
body = (CLAUDE / "skills" / name / "SKILL.md").read_text(encoding="utf-8")
@@ -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>
@@ -2,24 +2,25 @@
--button-primary-background: var(--color-action);
--button-primary-content: var(--color-on-action);
--button-primary-hover: var(--color-action-hover);
--button-primary-pressed: var(--color-action-pressed);
--field-border: var(--color-border-strong);
--field-border-invalid: var(--color-danger);
--dialog-elevation: var(--elevation-dialog);
/* 1106/08-03. The modal scrim: the content colour at this weight.
`--dialog-backdrop` is the translucent scrim `::backdrop` paints.
/* 1106/08-03. The modal scrim: the content colour at the scrim opacity
(`--opacity-scrim`). `--dialog-backdrop` is the translucent scrim
`::backdrop` paints.
`--dialog-backdrop-on-surface` is that scrim already laid over the page
surface, an opaque colour, for the root background under the scrollbar
gutter while a modal is open (primitives.css). The two agree because a
browser blends a translucent colour over another in sRGB. */
--dialog-backdrop-weight: 55%;
--dialog-backdrop: color-mix(
in oklab,
var(--color-content) var(--dialog-backdrop-weight),
var(--color-content) calc(var(--opacity-scrim) * 100%),
transparent
);
--dialog-backdrop-on-surface: color-mix(
in srgb,
var(--color-content) var(--dialog-backdrop-weight),
var(--color-content) calc(var(--opacity-scrim) * 100%),
var(--color-surface)
);
--navigation-active-background: color-mix(
@@ -6,12 +6,52 @@
--palette-slate-500: oklch(0.48 0.025 247);
--palette-slate-800: oklch(0.25 0.025 247);
--palette-slate-950: oklch(0.16 0.02 255);
/* Cool greys of the dark theme (hue 255). */
--palette-night-100: oklch(0.94 0.012 255);
--palette-night-300: oklch(0.74 0.025 255);
--palette-night-450: oklch(0.58 0.025 255);
--palette-night-650: oklch(0.36 0.025 255);
--palette-night-800: oklch(0.25 0.025 255);
--palette-night-850: oklch(0.235 0.025 255);
--palette-night-900: oklch(0.205 0.022 255);
--palette-blue-50: oklch(0.95 0.03 255);
--palette-blue-150: oklch(0.83 0.1 245);
--palette-blue-200: oklch(0.83 0.09 250);
--palette-blue-250: oklch(0.79 0.12 245);
--palette-blue-300: oklch(0.75 0.08 250);
--palette-blue-500: oklch(0.7 0.14 250);
--palette-blue-550: oklch(0.55 0.09 250);
--palette-blue-600: oklch(0.55 0.18 255);
--palette-blue-700: oklch(0.48 0.2 255);
--palette-blue-800: oklch(0.38 0.16 255);
--palette-blue-900: oklch(0.27 0.045 255);
/* The focus ring hue. */
--palette-sky-200: oklch(0.82 0.15 220);
--palette-sky-600: oklch(0.52 0.15 230);
/* Success. */
--palette-green-50: oklch(0.95 0.04 155);
--palette-green-200: oklch(0.83 0.1 155);
--palette-green-400: oklch(0.72 0.1 155);
--palette-green-600: oklch(0.53 0.1 155);
--palette-green-800: oklch(0.35 0.12 155);
--palette-green-900: oklch(0.27 0.045 155);
/* Warning. */
--palette-amber-50: oklch(0.96 0.05 80);
--palette-amber-200: oklch(0.88 0.1 80);
--palette-amber-400: oklch(0.75 0.12 80);
--palette-amber-600: oklch(0.58 0.11 80);
--palette-amber-800: oklch(0.38 0.12 70);
--palette-amber-900: oklch(0.29 0.045 80);
--palette-red-50: oklch(0.96 0.035 25);
--palette-red-200: oklch(0.84 0.11 25);
--palette-red-300: oklch(0.76 0.16 25);
--palette-red-400: oklch(0.72 0.12 25);
--palette-red-500: oklch(0.68 0.19 25);
--palette-red-550: oklch(0.56 0.13 25);
--palette-red-600: oklch(0.55 0.2 25);
--palette-red-700: oklch(0.47 0.2 25);
--palette-red-800: oklch(0.42 0.18 25);
--palette-red-900: oklch(0.28 0.055 25);
--space-1: 0.25rem;
--space-2: 0.5rem;
@@ -21,6 +61,8 @@
--space-6: 1.5rem;
--space-8: 2rem;
--space-12: 3rem;
--space-14: 3.5rem;
--space-16: 4rem;
--font-size-xs: 0.75rem;
--font-size-sm: 0.875rem;
@@ -28,6 +70,9 @@
--font-size-lg: 1.125rem;
--font-size-xl: 1.25rem;
--font-size-2xl: 1.5rem;
--font-size-3xl: 2rem;
--font-size-4xl: 3.5rem;
--line-height-compact: 1.05;
--line-height-tight: 1.25;
--line-height-normal: 1.5;
--line-height-relaxed: 1.7;
@@ -40,6 +85,7 @@
--radius-md: 0.75rem;
--radius-full: 999px;
--shadow-sticky: 0 1px 8px rgb(15 23 42 / 8%);
--shadow-panel: 0 8px 28px rgb(15 23 42 / 8%);
--shadow-popover: 0 14px 40px rgb(15 23 42 / 16%);
--shadow-dialog: 0 24px 70px rgb(15 23 42 / 25%);
@@ -14,24 +14,27 @@
--color-danger: var(--palette-red-600);
--color-danger-hover: var(--palette-red-700);
--color-on-action: var(--palette-white);
--color-focus: oklch(0.52 0.15 230);
--color-focus: var(--palette-sky-600);
--color-disabled-content: color-mix(in oklab, var(--color-content) 55%, transparent);
--color-disabled-surface: var(--color-surface-muted);
--color-info-content: oklch(0.38 0.16 255);
--color-info-surface: oklch(0.95 0.03 255);
--color-info-border: oklch(0.75 0.08 250);
--color-success-content: oklch(0.35 0.12 155);
--color-success-surface: oklch(0.95 0.04 155);
--color-success-border: oklch(0.72 0.1 155);
--color-warning-content: oklch(0.38 0.12 70);
--color-warning-surface: oklch(0.96 0.05 80);
--color-warning-border: oklch(0.75 0.12 80);
--color-danger-content: oklch(0.42 0.18 25);
--color-danger-surface: oklch(0.96 0.035 25);
--color-danger-border: oklch(0.72 0.12 25);
--color-info-content: var(--palette-blue-800);
--color-info-surface: var(--palette-blue-50);
--color-info-border: var(--palette-blue-300);
--color-success-content: var(--palette-green-800);
--color-success-surface: var(--palette-green-50);
--color-success-border: var(--palette-green-400);
--color-warning-content: var(--palette-amber-800);
--color-warning-surface: var(--palette-amber-50);
--color-warning-border: var(--palette-amber-400);
--color-danger-content: var(--palette-red-800);
--color-danger-surface: var(--palette-red-50);
--color-danger-border: var(--palette-red-400);
--font-sans: system-ui, "Apple SD Gothic Neo", "Malgun Gothic", "Noto Sans KR", "Noto Sans CJK KR", sans-serif;
/* 08-04. One step per heading level; a product retunes the scale here. */
/* 08-04. One step per heading level; a product retunes the scale here.
The page title grows with the viewport between two steps. */
--font-size-heading-1: clamp(var(--font-size-3xl), 5vw, var(--font-size-4xl));
--line-height-heading-1: var(--line-height-compact);
--font-size-heading-2: var(--font-size-2xl);
--font-size-heading-3: var(--font-size-xl);
--font-size-heading-4: var(--font-size-md);
@@ -40,6 +43,7 @@
--radius-control: var(--radius-sm);
--radius-surface: var(--radius-md);
--radius-modal: var(--radius-md);
--elevation-sticky: var(--shadow-sticky);
--elevation-panel: var(--shadow-panel);
--elevation-popover: var(--shadow-popover);
--elevation-dialog: var(--shadow-dialog);
@@ -56,33 +60,33 @@
:root[data-theme="dark"] {
--color-surface: var(--palette-slate-950);
--color-surface-muted: oklch(0.25 0.025 255);
--color-panel: oklch(0.205 0.022 255);
--color-surface-elevated: oklch(0.235 0.025 255);
--color-border: oklch(0.36 0.025 255);
--color-border-strong: oklch(0.58 0.025 255);
--color-content: oklch(0.94 0.012 255);
--color-content-muted: oklch(0.74 0.025 255);
--color-surface-muted: var(--palette-night-800);
--color-panel: var(--palette-night-900);
--color-surface-elevated: var(--palette-night-850);
--color-border: var(--palette-night-650);
--color-border-strong: var(--palette-night-450);
--color-content: var(--palette-night-100);
--color-content-muted: var(--palette-night-300);
--color-content-inverse: var(--palette-slate-950);
--color-action: var(--palette-blue-500);
--color-action-hover: oklch(0.79 0.12 245);
--color-action-pressed: oklch(0.83 0.1 245);
--color-action-hover: var(--palette-blue-250);
--color-action-pressed: var(--palette-blue-150);
--color-danger: var(--palette-red-500);
--color-danger-hover: oklch(0.76 0.16 25);
--color-danger-hover: var(--palette-red-300);
--color-on-action: var(--palette-slate-950);
--color-focus: oklch(0.82 0.15 220);
--color-focus: var(--palette-sky-200);
--color-disabled-content: color-mix(in oklab, var(--color-content) 55%, transparent);
--color-disabled-surface: var(--color-surface-muted);
--color-info-content: oklch(0.83 0.09 250);
--color-info-surface: oklch(0.27 0.045 255);
--color-info-border: oklch(0.55 0.09 250);
--color-success-content: oklch(0.83 0.1 155);
--color-success-surface: oklch(0.27 0.045 155);
--color-success-border: oklch(0.53 0.1 155);
--color-warning-content: oklch(0.88 0.1 80);
--color-warning-surface: oklch(0.29 0.045 80);
--color-warning-border: oklch(0.58 0.11 80);
--color-danger-content: oklch(0.84 0.11 25);
--color-danger-surface: oklch(0.28 0.055 25);
--color-danger-border: oklch(0.56 0.13 25);
--color-info-content: var(--palette-blue-200);
--color-info-surface: var(--palette-blue-900);
--color-info-border: var(--palette-blue-550);
--color-success-content: var(--palette-green-200);
--color-success-surface: var(--palette-green-900);
--color-success-border: var(--palette-green-600);
--color-warning-content: var(--palette-amber-200);
--color-warning-surface: var(--palette-amber-900);
--color-warning-border: var(--palette-amber-600);
--color-danger-content: var(--palette-red-200);
--color-danger-surface: var(--palette-red-900);
--color-danger-border: var(--palette-red-550);
}
@@ -43,13 +43,28 @@ export const REQUIRED_SEMANTIC_TOKENS = Object.freeze([
"--opacity-skeleton",
] as const);
/**
* 1112/04-08. Required semantic tokens no template style reads, and why.
* check:design-system requires every other required semantic token to be
* read by a style (UI-03). A native `<dialog>` opened with `showModal()` sits
* in the browser's top layer, above every z-index, so the template's dialogs
* and drawer have no `z-index`; `--layer-modal` orders a product's own modal
* surface that is not a `<dialog>`.
*/
export const SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER: readonly string[] = Object.freeze([
"--layer-modal",
]);
export const REQUIRED_COMPONENT_TOKENS = Object.freeze([
"--button-primary-background",
"--button-primary-content",
"--button-primary-hover",
"--button-primary-pressed",
"--field-border",
"--field-border-invalid",
"--dialog-elevation",
"--dialog-backdrop",
"--dialog-backdrop-on-surface",
"--navigation-active-background",
"--drawer-width",
"--toast-width",
+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}
/>
);
}
+49 -49
View File
@@ -1,7 +1,6 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { PageHeader } from "../design-system/index.ts";
import { LinkButton, StandardPage } from "../design-system/index.ts";
import { useLocale } from "../i18n/index.ts";
import { useApplicationRuntime } from "../providers/application-provider.tsx";
import { activeNavigationRoutes } from "../routes/navigation-policy.ts";
@@ -47,53 +46,54 @@ export default function HomePage() {
}, [runtime]);
return (
<section className="ui-page">
<PageHeader
eyebrow={message("home.eyebrow")}
title={message("route.APP_HOME.title")}
description={message("home.description")}
/>
<div className="readiness-grid" role="group" aria-label={message("home.readiness")}>
{READINESS_ITEMS.map((item) => (
<article className="ui-panel" key={item}>
<h2>{message(`home.readiness.${item}.title`)}</h2>
<p>{message(`home.readiness.${item}.description`)}</p>
</article>
))}
<StandardPage
heading={{
eyebrow: message("home.eyebrow"),
title: message("route.APP_HOME.title"),
description: message("home.description"),
}}
>
<div className="home-page__sections">
<div className="readiness-grid" role="group" aria-label={message("home.readiness")}>
{READINESS_ITEMS.map((item) => (
<article className="ui-panel" key={item}>
<h2>{message(`home.readiness.${item}.title`)}</h2>
<p>{message(`home.readiness.${item}.description`)}</p>
</article>
))}
</div>
<p className="ui-runtime-summary" aria-live="polite">
{release === "failed"
? message("home.runtime.failed")
: release
? message("home.runtime.summary", {
buildId: release.buildId,
releaseId: release.releaseId,
})
: message("home.runtime.checking")}
</p>
{starterRoutes.length > 0 ? (
<section className="ui-panel starter-actions" aria-labelledby="starter-title">
<div>
<h2 id="starter-title">{message("home.starter.title")}</h2>
<p>{message("home.starter.description")}</p>
</div>
<div className="button-row">
{starterRoutes.map((route, index) => (
<LinkButton
key={route.routeId}
to={route.path}
variant={index === 0 ? "primary" : "secondary"}
>
{message("home.starter.open", {
title: resolve(`route.${route.routeId}.navigation`),
})}
</LinkButton>
))}
</div>
</section>
) : null}
</div>
<p className="ui-runtime-summary" aria-live="polite">
{release === "failed"
? message("home.runtime.failed")
: release
? message("home.runtime.summary", {
buildId: release.buildId,
releaseId: release.releaseId,
})
: message("home.runtime.checking")}
</p>
{starterRoutes.length > 0 ? (
<section className="ui-panel starter-actions" aria-labelledby="starter-title">
<div>
<h2 id="starter-title">{message("home.starter.title")}</h2>
<p>{message("home.starter.description")}</p>
</div>
<div className="button-row">
{starterRoutes.map((route, index) => (
<Link
key={route.routeId}
className={
index === 0 ? "ui-button" : "ui-button ui-button--secondary"
}
to={route.path}
>
{message("home.starter.open", {
title: resolve(`route.${route.routeId}.navigation`),
})}
</Link>
))}
</div>
</section>
) : null}
</section>
</StandardPage>
);
}
+2 -2
View File
@@ -48,8 +48,8 @@
}
h1 {
font-size: clamp(2rem, 5vw, 3.5rem);
line-height: 1.05;
font-size: var(--font-size-heading-1);
line-height: var(--line-height-heading-1);
letter-spacing: -0.04em;
}
+56 -39
View File
@@ -1,15 +1,22 @@
@layer components {
/* The home page's blocks below the template heading, a page gap apart. */
.home-page__sections {
display: grid;
min-width: 0;
gap: var(--space-6);
}
.readiness-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
gap: var(--space-4);
}
.readiness-grid p,
.starter-actions p {
margin-block-end: 0;
color: var(--color-content-muted);
line-height: 1.65;
line-height: var(--line-height-relaxed);
}
.starter-actions {
@@ -17,23 +24,23 @@
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 1.5rem;
gap: var(--space-6);
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
gap: var(--space-3);
}
.route-loading {
padding-block-start: 4rem;
padding-block-start: var(--space-16);
}
.gallery-section {
display: grid;
gap: 1rem;
padding-block: 0.5rem;
gap: var(--space-4);
padding-block: var(--space-2);
}
.gallery-section__header {
@@ -46,14 +53,14 @@
}
.gallery-section__header p {
margin-block-start: 0.4rem;
margin-block-start: var(--space-2);
color: var(--color-content-muted);
line-height: 1.6;
line-height: var(--line-height-normal);
}
.component-grid {
display: grid;
gap: 1rem;
gap: var(--space-4);
}
.component-grid--two {
@@ -67,45 +74,45 @@
.component-stack,
.example-form {
display: grid;
gap: 1rem;
gap: var(--space-4);
}
.platform-metric-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr));
gap: 1rem;
gap: var(--space-4);
margin-block: 0;
}
.platform-metric {
display: grid;
gap: 0.25rem;
padding: 0.85rem 1rem;
gap: var(--space-1);
padding: var(--space-3) var(--space-4);
border: 1px solid var(--color-border);
border-radius: var(--radius-surface);
background: var(--color-panel);
}
.platform-metric dt {
font-size: 0.8125rem;
font-size: var(--font-size-sm);
color: var(--color-content-muted);
}
.platform-metric dd {
display: grid;
gap: 0.15rem;
gap: var(--space-1);
margin-inline-start: 0;
}
.platform-metric__value {
font-weight: 600;
font-weight: var(--font-weight-semibold);
overflow-wrap: anywhere;
}
.platform-metric__hint,
.platform-operation__path {
display: block;
font-size: 0.8125rem;
font-size: var(--font-size-sm);
color: var(--color-content-muted);
overflow-wrap: anywhere;
}
@@ -113,22 +120,22 @@
.badge-row {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
gap: var(--space-2);
}
.token-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
gap: 0.75rem;
gap: var(--space-3);
}
.token-swatch {
display: grid;
gap: 0.45rem;
gap: var(--space-2);
min-width: 0;
border: 1px solid var(--color-border);
border-radius: var(--radius-control);
padding: 0.75rem;
padding: var(--space-3);
background: var(--color-panel);
}
@@ -141,7 +148,7 @@
.token-swatch code {
overflow: hidden;
color: var(--color-content-muted);
font-size: 0.75rem;
font-size: var(--font-size-xs);
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -152,13 +159,13 @@
max-width: 100%;
box-sizing: border-box;
border: 1px solid var(--color-surface-muted);
border-radius: 999px;
padding: 0.65rem 1rem;
border-radius: var(--radius-full);
padding: var(--space-3) var(--space-4);
color: var(--color-content);
background: var(--color-panel);
box-shadow: 0 8px 28px color-mix(in oklab, var(--color-content) 10%, transparent);
font-size: 0.875rem;
font-weight: 650;
box-shadow: var(--elevation-panel);
font-size: var(--font-size-sm);
font-weight: var(--font-weight-semibold);
}
.state-surface {
@@ -170,24 +177,24 @@
justify-content: center;
border: 1px solid var(--color-surface-muted);
border-radius: var(--radius-surface);
padding: 1.25rem;
padding: var(--space-5);
background: var(--color-surface);
}
.state-surface :is(h2, h3, h4),
.state-surface p {
margin-block-end: 0.75rem;
margin-block-end: var(--space-3);
}
.state-surface > p:not(.state-surface__eyebrow) {
color: var(--color-content-muted);
line-height: 1.55;
line-height: var(--line-height-normal);
}
.state-surface__eyebrow {
color: var(--color-action-hover);
font-size: 0.75rem;
font-weight: 800;
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
letter-spacing: 0.04em;
}
@@ -202,8 +209,22 @@
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: 0.75rem;
gap: var(--space-3);
}
.state-surface--loading .ui-skeleton {
@@ -212,11 +233,7 @@
.state-preview-content {
border-radius: var(--radius-control);
padding: 1rem;
padding: var(--space-4);
background: var(--color-surface);
}
.app-shell__scrim {
display: none;
}
}
+53 -35
View File
@@ -6,7 +6,8 @@
}
.ui-panel {
@apply rounded-surface p-6 shadow-sm;
@apply rounded-surface p-6;
box-shadow: var(--elevation-panel);
border: 1px solid var(--color-border);
background: var(--color-panel);
}
@@ -14,7 +15,7 @@
.ui-button {
@apply rounded-control px-4 py-2 font-semibold;
display: inline-flex;
min-height: 2.75rem;
min-height: var(--size-control-md);
align-items: center;
justify-content: center;
border: 0;
@@ -38,6 +39,10 @@
cursor: progress;
}
.ui-button--primary:active:not(:disabled, [aria-disabled="true"]) {
background: var(--button-primary-pressed);
}
.ui-button--secondary {
border: 1px solid var(--color-surface-muted);
color: var(--color-content);
@@ -70,8 +75,8 @@
.ui-button--compact {
min-height: var(--size-control-sm);
padding: 0.4rem 0.75rem;
font-size: 0.85rem;
padding: var(--space-2) var(--space-3);
font-size: var(--font-size-sm);
}
.ui-icon-button {
@@ -123,7 +128,14 @@
}
.ui-skeleton {
@apply h-24 animate-pulse rounded-surface bg-surface-muted;
@apply h-24 rounded-surface bg-surface-muted;
animation: ui-skeleton-pulse 2s var(--easing-standard) infinite;
}
@keyframes ui-skeleton-pulse {
50% {
opacity: var(--opacity-skeleton);
}
}
.ui-empty,
@@ -133,18 +145,18 @@
.ui-field {
display: grid;
gap: 0.45rem;
gap: var(--space-2);
}
.ui-field__label {
font-weight: 750;
font-weight: var(--font-weight-bold);
}
.ui-field__description,
.ui-field__error {
margin: 0;
font-size: 0.875rem;
line-height: 1.5;
font-size: var(--font-size-sm);
line-height: var(--line-height-normal);
}
.ui-field__description {
@@ -153,20 +165,26 @@
.ui-field__error {
color: var(--color-danger);
font-weight: 650;
font-weight: var(--font-weight-semibold);
}
.ui-field__input {
width: 100%;
min-height: 2.75rem;
min-height: var(--size-control-md);
box-sizing: border-box;
border: 1px solid var(--field-border);
border-radius: var(--radius-control);
padding: 0.65rem 0.8rem;
padding: var(--space-3) var(--space-3);
color: var(--color-content);
background: var(--color-panel);
}
.ui-field__input:disabled {
color: var(--color-disabled-content);
background: var(--color-disabled-surface);
cursor: not-allowed;
}
.ui-field__input[aria-invalid="true"] {
border-color: var(--field-border-invalid);
}
@@ -245,7 +263,7 @@
display: block;
width: 1rem;
height: 1rem;
margin: 0.2rem;
margin: var(--space-1);
border-radius: var(--radius-full);
background: var(--color-content-muted);
content: "";
@@ -278,12 +296,12 @@
display: flex;
min-width: 0;
flex-direction: column;
gap: 1.25rem;
gap: var(--space-5);
border: 1px solid var(--color-border);
border-radius: var(--radius-surface);
padding: 1.25rem;
padding: var(--space-5);
background: var(--color-panel);
box-shadow: 0 8px 28px color-mix(in oklab, var(--color-content) 6%, transparent);
box-shadow: var(--elevation-panel);
}
.ui-card__header :is(h2, h3, h4),
@@ -292,9 +310,9 @@
}
.ui-card__header p {
margin-block-start: 0.4rem;
margin-block-start: var(--space-2);
color: var(--color-content-muted);
line-height: 1.55;
line-height: var(--line-height-normal);
}
.ui-card__content {
@@ -302,7 +320,7 @@
}
.ui-card__footer {
padding-block-start: 1rem;
padding-block-start: var(--space-4);
border-top: 1px solid var(--color-surface-muted);
}
@@ -310,10 +328,10 @@
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
gap: var(--space-4);
border: 1px solid var(--color-surface-muted);
border-radius: var(--radius-control);
padding: 1rem;
padding: var(--space-4);
background: var(--color-surface);
}
@@ -339,7 +357,7 @@
.ui-alert__content,
.ui-alert__content p {
margin-block: 0.35rem 0;
margin-block: var(--space-1) 0;
color: var(--color-content-muted);
}
@@ -354,7 +372,7 @@
border-radius: var(--radius-control);
color: var(--color-content);
background: transparent;
font-size: 1.35rem;
font-size: var(--font-size-xl);
cursor: pointer;
}
@@ -372,12 +390,12 @@
.ui-badge {
display: inline-flex;
border-radius: 999px;
padding: 0.3rem 0.65rem;
border-radius: var(--radius-full);
padding: var(--space-1) var(--space-3);
color: var(--color-content);
background: var(--color-surface-muted);
font-size: 0.8rem;
font-weight: 750;
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
}
.ui-badge--info {
@@ -406,7 +424,7 @@
box-sizing: border-box;
overflow: auto;
border: 0;
border-radius: var(--radius-surface);
border-radius: var(--radius-modal);
padding: 0;
color: var(--color-content);
background: var(--color-panel);
@@ -713,36 +731,36 @@
}
.ui-dialog__surface {
padding: 1.5rem;
padding: var(--space-6);
}
.ui-dialog__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
gap: var(--space-4);
}
.ui-dialog__header h2 {
margin-block-end: 0.35rem;
margin-block-end: var(--space-1);
}
.ui-dialog__header p,
.ui-dialog__content p {
color: var(--color-content-muted);
line-height: 1.6;
line-height: var(--line-height-normal);
}
.ui-dialog__content {
padding-block: 1rem;
padding-block: var(--space-4);
}
.ui-dialog__actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 0.75rem;
padding-block-start: 1rem;
gap: var(--space-3);
padding-block-start: var(--space-4);
border-top: 1px solid var(--color-surface-muted);
}
}
+2 -24
View File
@@ -7,38 +7,16 @@
}
.app-shell__header {
padding-inline: 0.75rem;
padding-inline: var(--space-3);
}
.app-shell__menu-button.ui-icon-button {
display: inline-flex;
}
/* The compact navigation is the menu drawer (`app-shell.tsx`). */
.app-shell__sidebar {
position: fixed;
z-index: 50;
top: 4.5rem;
bottom: 0;
left: 0;
display: none;
width: min(18rem, 85vw);
height: auto;
box-sizing: border-box;
box-shadow: 10px 0 30px color-mix(in oklab, var(--color-content) 15%, transparent);
}
.app-shell__sidebar[data-open="true"] {
display: block;
}
.app-shell__scrim {
position: fixed;
z-index: 40;
inset: 4.5rem 0 0;
display: block;
border: 0;
background: color-mix(in oklab, var(--color-content) 35%, transparent);
cursor: pointer;
}
/* 08-01. Hidden only in the header: the menu drawer (`app-shell.tsx`)
+29 -29
View File
@@ -13,10 +13,10 @@
.skip-link {
position: fixed;
z-index: 100;
top: 0.75rem;
left: 0.75rem;
padding: 0.75rem 1rem;
z-index: var(--layer-navigation);
top: var(--space-3);
left: var(--space-3);
padding: var(--space-3) var(--space-4);
border-radius: var(--radius-control);
color: var(--color-panel);
background: var(--color-content);
@@ -44,23 +44,23 @@
.app-shell__header {
position: sticky;
z-index: 30;
z-index: var(--layer-sticky);
top: 0;
grid-area: header;
display: flex;
align-items: center;
gap: 1rem;
gap: var(--space-4);
min-width: 0;
padding: 0.75rem 1.25rem;
padding: var(--space-3) var(--space-5);
border-bottom: 1px solid var(--color-surface-muted);
background: color-mix(in oklab, var(--color-panel) 92%, var(--color-surface));
box-shadow: 0 1px 8px color-mix(in oklab, var(--color-content) 8%, transparent);
box-shadow: var(--elevation-sticky);
}
.app-shell__brand {
overflow: hidden;
font-size: 1.05rem;
font-weight: 800;
font-size: var(--font-size-md);
font-weight: var(--font-weight-bold);
text-decoration: none;
text-overflow: ellipsis;
white-space: nowrap;
@@ -68,25 +68,25 @@
/* 08-01. The narrow header drops these; the menu drawer carries them. */
.app-shell__drawer-brand {
margin: 0 0 0.75rem;
font-weight: 800;
margin: 0 0 var(--space-3);
font-weight: var(--font-weight-bold);
}
.app-shell__drawer-preferences {
display: grid;
gap: 0.75rem;
margin-top: 1rem;
padding-top: 1rem;
gap: var(--space-3);
margin-top: var(--space-4);
padding-top: var(--space-4);
border-top: 1px solid var(--color-border);
}
.app-shell__menu-button {
display: none;
align-items: center;
gap: 0.4rem;
gap: var(--space-2);
border: 1px solid var(--color-surface-muted);
border-radius: var(--radius-control);
padding: 0.55rem 0.75rem;
padding: var(--space-2) var(--space-3);
color: var(--color-content);
background: var(--color-panel);
cursor: pointer;
@@ -95,7 +95,7 @@
.app-shell__session {
display: flex;
align-items: center;
gap: 0.75rem;
gap: var(--space-3);
margin-inline-start: auto;
}
@@ -120,7 +120,7 @@
.theme-selector .ui-field__input,
.locale-selector .ui-field__input {
min-height: var(--size-control-sm);
padding: 0.35rem 2rem 0.35rem 0.65rem;
padding: var(--space-1) var(--space-8) var(--space-1) var(--space-3);
cursor: pointer;
}
@@ -128,7 +128,7 @@
position: absolute;
top: calc(100% + 0.25rem);
right: 1rem;
padding: 0.5rem;
padding: var(--space-2);
color: var(--color-danger);
background: var(--color-panel);
}
@@ -137,12 +137,12 @@
display: inline-flex;
width: fit-content;
align-items: center;
border-radius: 999px;
padding: 0.3rem 0.65rem;
border-radius: var(--radius-full);
padding: var(--space-1) var(--space-3);
color: var(--color-content-muted);
background: var(--color-surface-muted);
font-size: 0.8rem;
font-weight: 700;
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
}
.session-status[data-state="authenticated"] {
@@ -159,7 +159,7 @@
top: 4.5rem;
grid-area: sidebar;
height: calc(100vh - 4.5rem);
padding: 1.25rem 0.75rem;
padding: var(--space-5) var(--space-3);
border-right: 1px solid var(--color-border);
background: var(--color-panel);
}
@@ -167,7 +167,7 @@
.app-navigation {
display: flex;
flex-direction: column;
gap: 0.25rem;
gap: var(--space-1);
margin: 0;
padding: 0;
list-style: none;
@@ -176,9 +176,9 @@
.app-navigation__link {
display: block;
border-radius: var(--radius-control);
padding: 0.75rem 0.9rem;
padding: var(--space-3) var(--space-4);
color: var(--color-content-muted);
font-weight: 650;
font-weight: var(--font-weight-semibold);
text-decoration: none;
}
@@ -190,7 +190,7 @@
.app-navigation__link.is-active {
color: var(--color-action-hover);
background: var(--navigation-active-background);
font-weight: 800;
font-weight: var(--font-weight-bold);
}
.app-shell__content {
+23 -23
View File
@@ -1,7 +1,7 @@
@layer components {
.page-header {
max-width: 50rem;
padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem;
padding-block: clamp(var(--space-4), 5vw, var(--space-14)) var(--space-2);
}
/* 1112/05-02. Pointer navigation only: a keyboard user keeps the
@@ -11,10 +11,10 @@
}
.page-header__eyebrow {
margin-block-end: 0.75rem;
margin-block-end: var(--space-3);
color: var(--color-action);
font-size: 0.8rem;
font-weight: 800;
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
letter-spacing: 0.08em;
text-transform: uppercase;
}
@@ -22,13 +22,13 @@
.page-header__description {
max-width: 45rem;
color: var(--color-content-muted);
font-size: 1.05rem;
line-height: 1.7;
font-size: var(--font-size-md);
line-height: var(--line-height-relaxed);
}
.page-template {
display: grid;
gap: 1.25rem;
gap: var(--space-5);
min-width: 0;
}
@@ -39,9 +39,9 @@
}
.page-template__breadcrumb {
padding-block-start: 1rem;
padding-block-start: var(--space-4);
color: var(--color-content-muted);
font-size: 0.9rem;
font-size: var(--font-size-sm);
}
.page-template__heading {
@@ -49,7 +49,7 @@
min-width: 0;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
gap: 1rem;
gap: var(--space-4);
}
.page-template__heading .page-header {
@@ -65,13 +65,13 @@
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 0.75rem;
gap: var(--space-3);
}
.page-template__layout {
display: grid;
min-width: 0;
gap: 1.5rem;
gap: var(--space-6);
}
.page-template__layout[data-has-aside="true"] {
@@ -92,7 +92,7 @@
.form-error-summary {
border: 1px solid var(--color-border);
border-radius: var(--radius-surface);
padding: 1rem;
padding: var(--space-4);
background: var(--color-panel);
}
@@ -102,7 +102,7 @@
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 0.75rem;
gap: var(--space-3);
}
.collection-page__result-count {
@@ -114,17 +114,17 @@
.form-page__fields,
.form-page__error-summary {
display: grid;
gap: 1rem;
gap: var(--space-4);
}
.collection-page__pagination {
margin-block-start: 1.25rem;
margin-block-start: var(--space-5);
}
.detail-page__danger {
margin-block-start: 2rem;
margin-block-start: var(--space-8);
border-top: 1px solid var(--color-danger-border);
padding-block-start: 1rem;
padding-block-start: var(--space-4);
}
.form-error-summary {
@@ -133,7 +133,7 @@
}
.form-error-summary :is(h2, h3, h4) {
font-size: 1.1rem;
font-size: var(--font-size-lg);
}
.form-error-summary p,
@@ -142,21 +142,21 @@
}
.form-actions {
padding-block-start: 1rem;
padding-block-start: var(--space-4);
border-top: 1px solid var(--color-border);
}
.form-actions--sticky {
position: sticky;
z-index: 10;
z-index: var(--layer-sticky);
bottom: 0;
padding: 0.75rem;
padding: var(--space-3);
background: color-mix(in oklab, var(--color-panel) 94%, transparent);
}
.status-page {
max-width: 48rem;
padding-block: 2rem;
padding-block: var(--space-8);
}
.status-page__actions {
+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();
});
});
+11
View File
@@ -45,6 +45,17 @@ describe("starter home page", () => {
).toBeVisible();
});
// 1112/04-06. The home page a product keeps is an example of the page
// templates and primitives, not of hand-made copies of them.
it("lays the home page out with the standard template and link buttons", async () => {
const { container } = renderApp("/");
const action = await screen.findByRole("link", { name: "플랫폼 구성 보기" });
expect(action.closest("article.page-template--standard")).not.toBeNull();
expect(action).toHaveClass("ui-button", "ui-button--primary");
expect(container.querySelectorAll("section.ui-page")).toHaveLength(0);
});
it("reaches the platform overview from the starter actions", async () => {
const user = userEvent.setup();
renderApp("/");
@@ -0,0 +1,4 @@
// 1112/04-14. A screen lays a raw colour and spacing over an element.
export function RawInlineStyle() {
return <div style={{ color: "red", padding: 13 }}>raw inline style</div>;
}
+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 }) => {
+236 -2
View File
@@ -1,5 +1,5 @@
import { spawnSync } from "node:child_process";
import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -9,9 +9,21 @@ import {
FOCUS_RING_BACKGROUNDS,
firstFontFamilyFailures,
focusContrastFailures,
focusOffsetFailures,
hueMixFailures,
inlineStyleFailures,
rawSemanticColourFailures,
rawStyleValueFailures,
styleSheetColourFailures,
tokenRedefinitionFailures,
undeclaredComponentTokenFailures,
unreadTokenFailures,
} from "../../scripts/lib/design-system-rules.ts";
import {
REQUIRED_COMPONENT_TOKENS,
REQUIRED_SEMANTIC_TOKENS,
SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER,
} from "../../src/presentation/design-system/tokens/token-contract.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
const css = (source: string) => ({ file: "probe.css", source });
@@ -69,6 +81,22 @@ describe("design system rules", { timeout: childProcessTimeout(3_540) }, () => {
]);
});
// 1101/12-03. A gradient interpolates in its colour space too.
it.each([
"linear-gradient(in oklch, red, blue)",
"linear-gradient(90deg in hsl, red, blue)",
"radial-gradient(circle in lch, red, blue)",
"repeating-conic-gradient(from 0deg in hwb, red, blue)",
])("fails %s", (gradient) => {
expect(hueMixFailures(css(`a { background: ${gradient}; }`))).toHaveLength(1);
});
it("passes a gradient in oklab or without a colour space", () => {
expect(
hueMixFailures(css("a { background: linear-gradient(90deg in oklab, red, blue), linear-gradient(red, blue); }")),
).toEqual([]);
});
it("passes oklab, and old code left in a comment", () => {
expect(
hueMixFailures(
@@ -78,6 +106,39 @@ describe("design system rules", { timeout: childProcessTimeout(3_540) }, () => {
});
});
// 1112/04-13. A rebrand edits the palette; the roles follow it.
describe("UI-07 semantic colours come from the palette", () => {
it.each([
"oklch(0.52 0.15 230)",
"#2563eb",
"rgb(37 99 235)",
"hsl(220 80% 50%)",
"OKLCH(0.5 0.1 200)",
])("fails a role written as %s", (value) => {
expect(rawSemanticColourFailures(css(`:root { --color-focus: ${value}; }`))).toEqual([
`probe.css --color-focus is the raw colour ${value}; name it in primitive.css and read it with var()`,
]);
});
it("passes a palette read, a mix of tokens, and a comment", () => {
expect(
rawSemanticColourFailures(
css(`/* was oklch(0.5 0.1 200) */
:root {
--color-focus: var(--palette-sky-600);
--color-disabled-content: color-mix(in oklab, var(--color-content) 55%, transparent);
--layer-modal: 70;
}`),
),
).toEqual([]);
});
it("passes the repository's semantic tokens", async () => {
const file = "src/presentation/design-system/tokens/semantic.css";
expect(rawSemanticColourFailures({ file, source: await readFile(file, "utf8") })).toEqual([]);
});
});
describe("UI-03 component token readers", () => {
const tokens = ["--field-border", "--field-border-invalid"];
@@ -110,6 +171,151 @@ describe("design system rules", { timeout: childProcessTimeout(3_540) }, () => {
});
});
// 1112/04-08. A style that writes the value by hand ignores the token.
describe("UI-06 styles read spacing, type, radius, layer and shadow tokens", () => {
it.each([
["padding: 0.75rem 1rem", "0.75rem, 1rem"],
["margin-block-start: 0.4rem", "0.4rem"],
["gap: 12px", "12px"],
["font-size: 0.8rem", "0.8rem"],
["font-weight: 800", "800"],
["line-height: 1.6", "1.6"],
["border-radius: 999px", "999px"],
["z-index: 30", "30"],
["box-shadow: 0 1px 8px var(--color-border)", "1px, 8px, 0"],
])("fails %s", (declaration, raw) => {
const [property] = declaration.split(":");
expect(rawStyleValueFailures(css(`.a {\n ${declaration};\n}`))).toEqual([
`probe.css:2 ${property}: ${declaration.slice(property.length + 1).trim()} writes ${raw} by hand; read a token (docs/styling/design-tokens.md UI-06)`,
]);
});
it("passes token reads, zero, keywords, hairlines, relative and viewport values", () => {
expect(
rawStyleValueFailures(
css(`.a {
padding: var(--space-3) var(--space-4);
margin: -1px;
margin-inline: calc(var(--spacing-page) * -1);
padding-block: clamp(var(--space-4), 5vw, var(--space-14)) 0;
gap: 0;
font-size: 0.9em;
font-weight: var(--font-weight-bold);
line-height: 1;
border-radius: 50%;
z-index: var(--layer-sticky);
box-shadow: none;
width: 2rem;
}`),
),
).toEqual([]);
});
it("reports the file's own line after a comment of several lines", () => {
expect(rawStyleValueFailures(css("/* one\n two\n padding: 1rem; */\n.a { padding: 1rem; }"))).toEqual([
"probe.css:4 padding: 1rem writes 1rem by hand; read a token (docs/styling/design-tokens.md UI-06)",
]);
});
});
describe("UI-03 for the required semantic tokens", () => {
it("names the semantic layer in the message", () => {
expect(unreadTokenFailures(["--layer-navigation"], [css(".a { z-index: 1; }")], "semantic")).toEqual([
"semantic token --layer-navigation is defined but no style reads it",
]);
});
it("leaves out only --layer-modal, which the top layer makes unreadable", () => {
expect(SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER).toEqual(["--layer-modal"]);
expect(REQUIRED_SEMANTIC_TOKENS).toContain("--layer-modal");
});
});
// 1112/04-12. Every component token is in the contract UI-03 walks.
describe("component tokens and the contract", () => {
it("fails a component token the contract does not list", () => {
const component = css(`@theme {\n --button-primary-background: x;\n --dialog-backdrop-weight: 55%;\n}\n\n@media (forced-colors: active) {\n :root {\n --color-border: CanvasText;\n }\n}`);
expect(undeclaredComponentTokenFailures(component, ["--button-primary-background"])).toEqual([
"probe.css defines --dialog-backdrop-weight, which REQUIRED_COMPONENT_TOKENS in token-contract.ts does not list",
]);
});
it("passes the repository's component tokens", async () => {
const file = "src/presentation/design-system/tokens/component.css";
expect(
undeclaredComponentTokenFailures({ file, source: await readFile(file, "utf8") }, REQUIRED_COMPONENT_TOKENS),
).toEqual([]);
});
});
// 1101/12-03. Style sheets read colours; the token files define them.
describe("style sheets outside the token files", () => {
it("fails a raw colour, and passes a token read or a mix of tokens", () => {
expect(
styleSheetColourFailures(css(".a { color: #ff0000; border-color: rgb(1 2 3); }\n.b { color: var(--color-content); background: color-mix(in oklab, var(--color-panel) 92%, transparent); }")),
).toEqual([
"probe.css color: #ff0000 is a raw colour; read a colour token",
"probe.css border-color: rgb(1 2 3) is a raw colour; read a colour token",
]);
});
it("fails a token redefined in a style sheet, and passes a local property", () => {
expect(
tokenRedefinitionFailures(css(":root { --font-sans: serif; }\n.a { --local-gap: 1px; }"), new Set(["--font-sans"])),
).toEqual(["probe.css redefines the token --font-sans; change it in the token files"]);
});
it.each(["0", "0px", "-1px"])("fails a focus ring drawn with outline-offset %s", (offset) => {
expect(focusOffsetFailures(css(`.a:focus-visible { outline-offset: ${offset}; }`))).toEqual([
`probe.css outline-offset: ${offset} draws the focus ring on the control; UI-01 measures it against the surface around the control`,
]);
});
it("passes a focus ring drawn away from the control", () => {
expect(focusOffsetFailures(css(".a:focus-visible { outline-offset: 0.1875rem; }"))).toEqual([]);
});
});
// 1112/04-14. Primitives keep className and style open (decision
// 2026-11-12); the check refuses raw values laid over them.
describe("inline styles in TSX", () => {
it("fails a colour or a scale value written by hand", () => {
expect(
inlineStyleFailures({
file: "probe.tsx",
source: `<Button style={{ color: "red", padding: 13, borderRadius: "4px", zIndex: 5 }} />`,
}),
).toEqual([
'probe.tsx style color: "red" is written by hand; read a token or use a primitive variant',
"probe.tsx style padding: 13 is written by hand; read a token or use a primitive variant",
'probe.tsx style borderRadius: "4px" is written by hand; read a token or use a primitive variant',
"probe.tsx style zIndex: 5 is written by hand; read a token or use a primitive variant",
]);
});
it("judges the scale values as UI-06 does, and every colour property", () => {
expect(
inlineStyleFailures({
file: "probe.tsx",
source: `<div style={{ margin: "0 auto", zIndex: -1, lineHeight: 1, borderTopColor: "red", fontWeight: 700 }} />`,
}),
).toEqual([
'probe.tsx style borderTopColor: "red" is written by hand; read a token or use a primitive variant',
"probe.tsx style fontWeight: 700 is written by hand; read a token or use a primitive variant",
]);
});
it("passes token reads, keywords, zero and layout", () => {
expect(
inlineStyleFailures({
file: "probe.tsx",
source:
"<div style={{ backgroundColor: `var(${token})`, color: \"currentColor\", margin: 0, padding: \"var(--space-2)\", gridColumn: \"1 / 3\", width: 120 }} />",
}),
).toEqual([]);
});
});
describe("UI-05 first font family", () => {
it("fails a named font that nothing loads", () => {
expect(firstFontFamilyFailures("Inter, system-ui, sans-serif", [])).toEqual([
@@ -161,13 +367,33 @@ describe("design system rules", { timeout: childProcessTimeout(3_540) }, () => {
await writeFile(target, edited);
};
const semantic = "src/presentation/design-system/tokens/semantic.css";
await edit(semantic, /--color-focus: [^;]+;/, "--color-focus: oklch(0.72 0.16 225);");
// A palette colour too light for 3:1 on the light surfaces (UI-01), read
// as a token so that UI-07 stays quiet.
await edit(semantic, /--color-focus: [^;]+;/, "--color-focus: var(--palette-sky-200);");
await edit(semantic, "--font-sans: ", "--font-sans: Inter, ");
await edit(semantic, "--color-danger-surface: var(--palette-red-50);", "--color-danger-surface: oklch(0.96 0.035 25);");
await edit("src/presentation/styles/theme/primitives.css", "var(--drawer-width)", "20rem");
await edit("src/presentation/styles/theme/shell.css", "z-index: var(--layer-navigation);", "z-index: 50;");
await edit(
"src/presentation/design-system/tokens/component.css",
" --drawer-width:",
" --probe-unlisted: 1px;\n --drawer-width:",
);
await writeFile(
path.join(root, "src/presentation/styles/theme/probe.css"),
".probe { color: color-mix(in oklch, red, blue); }\n",
);
await mkdir(path.join(root, "src/features/probe"), { recursive: true });
await writeFile(
path.join(root, "src/features/probe/probe.css"),
[
".probe-a { color: #ff0000; }",
".probe-b { background: linear-gradient(in oklch, var(--color-action), var(--color-panel)); }",
".probe-c:focus-visible { outline-offset: 0; }",
":root { --font-sans: serif; }",
"",
].join("\n"),
);
const result = spawnSync(process.execPath, [path.resolve("scripts/check-design-system.ts")], {
cwd: root,
@@ -182,6 +408,14 @@ describe("design system rules", { timeout: childProcessTimeout(3_540) }, () => {
/^src\/presentation\/styles\/theme\/probe\.css mixes colours in oklch; use oklab$/,
/^component token --drawer-width is defined but no style reads it$/,
/^--font-sans starts with "Inter", which is neither a generic family, loaded by @font-face, nor listed in PRODUCT_LOADED_FONT_FAMILIES$/,
/^src\/presentation\/styles\/theme\/shell\.css:\d+ z-index: 50 writes 50 by hand; read a token \(docs\/styling\/design-tokens\.md UI-06\)$/,
/^semantic token --layer-navigation is defined but no style reads it$/,
/^src\/features\/probe\/probe\.css color: #ff0000 is a raw colour; read a colour token$/,
/^src\/features\/probe\/probe\.css mixes colours in oklch; use oklab$/,
/^src\/features\/probe\/probe\.css outline-offset: 0 draws the focus ring on the control; UI-01 measures it against the surface around the control$/,
/^src\/features\/probe\/probe\.css redefines the token --font-sans; change it in the token files$/,
/^src\/presentation\/design-system\/tokens\/component\.css defines --probe-unlisted, which REQUIRED_COMPONENT_TOKENS in token-contract\.ts does not list$/,
/^src\/presentation\/design-system\/tokens\/semantic\.css --color-danger-surface is the raw colour oklch\(0\.96 0\.035 25\); name it in primitive\.css and read it with var\(\)$/,
];
expect(failures.filter((failure) => !rules.some((rule) => rule.test(failure)))).toEqual([]);
for (const rule of rules) {
@@ -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([]);
});
});
@@ -0,0 +1,28 @@
import { readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { describe, expect, it } from "vitest";
/**
* 1112/04-11. Playwright's colour threshold 0.2 let a danger surface turn
* green and still match its golden. tests/visual/platform.visual.spec.ts
* passes `GOLDEN` (threshold 0.05) to each screenshot; a new screenshot that
* leaves it out falls back to 0.2.
*/
describe("visual golden colour threshold", () => {
it("passes GOLDEN to every screenshot of the visual specs", async () => {
const folder = "tests/visual";
const specs = (await readdir(folder)).filter((file) => file.endsWith(".spec.ts"));
const calls = (
await Promise.all(specs.map(async (file) => ({ file, source: await readFile(path.join(folder, file), "utf8") })))
).flatMap(({ file, source }) =>
source
.split("toHaveScreenshot(")
.slice(1)
.map((rest) => ({ file, args: rest.slice(0, rest.indexOf(");")) })),
);
expect(calls.length).toBeGreaterThan(0);
expect(calls.filter(({ args }) => !/\bGOLDEN\b/u.test(args)).map(({ file, args }) => `${file}: ${args.trim()}`)).toEqual([]);
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 204 KiB

+15
View File
@@ -30,6 +30,16 @@ async function openGalleryStory(page: Page, storyId: string, title: string) {
await expect(page.getByRole("heading", { level: 1 })).toHaveText(title);
}
/**
* 1112/04-11. How far one pixel's colour may move before it counts as
* changed (pixelmatch's YIQ distance; Playwright's default is 0.2). At 0.2 a
* danger surface turned green (hue 25 to 145) and the dark danger colour one
* palette step darker both passed the goldens. 0.05 fails the first; a clean
* build still differs by 0 px. Every screenshot below takes it; the pixel
* count `maxDiffPixels` stays in playwright.visual.config.ts.
*/
const GOLDEN = Object.freeze({ threshold: 0.05 });
/** `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 });
@@ -75,6 +85,7 @@ test("wide application shell visual contract", async ({ page }) => {
await expectRouteHeading(page, "Clean Architecture Frontend");
await hide(page, WITHOUT_FEATURE_LINKS);
await expect(page).toHaveScreenshot("app-shell-wide-light.png", {
...GOLDEN,
fullPage: true,
});
});
@@ -88,6 +99,7 @@ test("compact drawer and pseudo-locale visual contract", async ({ page }) => {
await expect(page.locator(".ui-drawer")).toHaveJSProperty("open", true);
await hide(page, WITHOUT_FEATURE_LINKS);
await expect(page).toHaveScreenshot("app-shell-compact-pseudo-drawer.png", {
...GOLDEN,
fullPage: true,
});
});
@@ -103,6 +115,7 @@ test.describe("in the dark color scheme", () => {
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
await expect(page.getByRole("main")).toHaveScreenshot(
"design-system-gallery-dark.png",
GOLDEN,
);
});
});
@@ -114,6 +127,7 @@ test("loading empty error and access surfaces visual contract", async ({
await openGalleryStory(page, "platform-galleries--screen-states", "화면 상태");
await expect(page.getByRole("main")).toHaveScreenshot(
"state-surfaces-light.png",
GOLDEN,
);
});
@@ -135,5 +149,6 @@ test("platform composition overview visual contract", async ({ page }) => {
await hide(page, WITHOUT_INSTALLED_FEATURE_SECTIONS);
await expect(page.getByRole("main")).toHaveScreenshot(
"platform-overview-light.png",
GOLDEN,
);
});