fix(design-system): 컴포넌트 토큰 사용 검사가 이름 전체를 맞춰 본다 (12-01, 12-02)
문제: UI-03 규칙은 source.includes(`var(${token}`)로 독자를 찾는다.
"var(--field-border"가 var(--field-border-invalid) 안에도 있어서, 독자가
0곳이던 --field-border를 통과시켰다. 주석 안의 var(--x)도 독자로 셌다.
그리고 이번 브랜치의 디자인 규칙 4개(포커스 대비, oklab 혼합, 토큰
사용, 첫 글꼴)는 스크립트 본문에 바로 있어서, 규칙을 꺼도 잡는 테스트가
없었다(12-02).
고른 방법:
- 규칙 4개를 scripts/lib/design-system-rules.ts의 순수 함수로 옮긴다.
입력은 CSS 글자와 토큰 맵이고 출력은 실패 메시지다. 메시지 문구와
순서는 그대로다.
- 토큰 독자는 var(--name) 또는 var(--name, ...)처럼 이름 전체가 맞아야
한다. "var"는 대소문자를 무시하고, 사용자 정의 속성 이름은 CSS 규칙
대로 대소문자를 구분한다.
- 토큰 사용 규칙과 oklab 혼합 규칙은 CSS 주석을 지우고 본다(리뷰 probe
B5 우회, B12 오탐).
- oklab 혼합 규칙은 대소문자를 무시한다(B1 `in OKLCH` 우회). CSS
키워드는 대소문자를 구분하지 않는다.
- ui-design-audit.md의 UI-03 행에 다섯 번째 토큰을 적는다.
버린 대안: 12-02가 제안한 --root 인자와 CSS 음성 fixture 폴더. 규칙별
검출을 증명하려면 어차피 실패 메시지를 단언하는 테스트가 필요하고,
순수 함수 단위 테스트가 fixture 파일 없이 같은 것을 증명한다. 게이트의
--fixture 모드와 산출물 스키마는 바꾸지 않았다.
위험·한계:
- 주석 제거는 정규식이라 따옴표 문자열 안의 "/*"를 주석 시작으로
본다. 지금 CSS에는 없다.
- 12-03의 나머지 우회(그라디언트, TSX 인라인, base.css 재정의,
outline-offset 0, feature CSS)와 12-04의 오탐(-apple-system, deg,
알파, color-mix 표면)은 그대로다. 포커스·글꼴 규칙은 주석을 지우지
않는다.
- 게이트의 check:design-system:fixture는 여전히 TSX fixture 두 개만으로
"기대 실패"를 채운다. CSS 규칙 회귀는 test:unit이 잡는다.
검증:
- RED(규칙을 동작 그대로 옮긴 상태): tests/unit/design-system-rules.test.ts
11개 중 5개 실패. "does not count a longer token that starts with the
same name"이 "expected [] to deeply equal [ Array(1) ]"로 실패했다.
나머지 4개는 대문자 OKLCH, 주석 안 혼합, VAR( --x , ...) 형태, 주석
안 독자.
- 고친 검사를 앞 커밋 전 CSS(402e1db)에 돌리면 "component token
--field-border is defined but no style reads it"으로 실패했다.
- GREEN: 같은 파일 11/11 통과. tests/unit 166파일 2364개 통과.
- 변이: 대비 기준 < 0, 혼합 정규식 무력화, 토큰·글꼴 판정 무조건
통과로 바꾸면 규칙마다 실패 테스트가 하나 이상 깨졌다(7/11 실패).
- check:design-system PASS, --fixture는 기대대로 실패. tsc(app, node,
test) 통과, 바꾼 파일 eslint 통과, verify-documentation PASS_SCOPED.
Refs: docs/reviews/2026-11-01-maturity-review/12-guardrails-ci.md 12-01, 12-02
This commit is contained in:
@@ -190,7 +190,7 @@
|
||||
| --- | --- | --- | --- | --- |
|
||||
| UI-01 | 충족 | `735e280` | `check:design-system`: 두 테마의 포커스 색과 표면 8종 대비 3:1 미만이면 실패. `tests/unit/oklch-contrast.test.ts` | 라이트 포커스 `oklch(0.52 0.15 230)`, 최저 4.24:1. 계산식은 브라우저 실측(2.33:1)과 일치 |
|
||||
| UI-02 | 충족 | `84dbb3a` | `check:design-system`: `color-mix`를 oklch·lch·hsl·hwb로 섞으면 실패 | 15곳을 `in oklab`으로 |
|
||||
| UI-03 | 충족 | `4bb15e6` | `check:design-system`: 계약의 컴포넌트 토큰을 읽는 스타일이 없으면 실패 | 범위 확대: `--navigation-active-background`와 기본 버튼 토큰 3개까지 모두 4개가 읽히지 않고 있었다 |
|
||||
| UI-03 | 충족 | `4bb15e6` | `check:design-system`: 계약의 컴포넌트 토큰을 읽는 스타일이 없으면 실패 | 범위 확대: `--navigation-active-background`와 기본 버튼 토큰 3개까지 모두 4개가 읽히지 않고 있었다. 다섯 번째 `--field-border`는 검사가 이름 앞부분만 맞춰 놓쳤다(성숙도 리뷰 12-01). 검사를 이름 전체 일치로 고치고, 입력란 테두리가 이 토큰을 읽게 했다 |
|
||||
| UI-04 | 충족 | `5d2ed17` | `tests/e2e/i18n.spec.ts`: 선택 상자 폭이 브라우저가 옵션에 필요한 폭보다 좁으면 실패(ko·en·en-XA) | chromium·firefox·webkit 통과 |
|
||||
| UI-05 | 부분 충족 | `c6730ea` | `check:design-system`: `--font-sans`의 첫 글꼴이 기본 키워드도 아니고 `@font-face`로 싣지도 않으면 실패 | 결정: 대안 (b) 시스템 글꼴 스택. 남은 것: 시각 테스트 실행 환경의 글꼴 고정 |
|
||||
| UI-06 | 충족 | `2560580` | 없음 — 지울 수 있는 예제 화면의 문구라 검사 비용이 더 크다 | 예제 화면 4곳의 eyebrow 제거. 예제는 의도적으로 i18n 검사 밖(`scripts/check-i18n.ts` 대상 폴더) |
|
||||
|
||||
@@ -5,7 +5,13 @@ import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
||||
import path from "node:path";
|
||||
|
||||
import { REQUIRED_COMPONENT_TOKENS, REQUIRED_PRIMITIVE_TOKENS, REQUIRED_SEMANTIC_TOKENS } from "../src/presentation/design-system/tokens/token-contract.ts";
|
||||
import { contrastRatio, readCustomProperties, resolveColor } from "./lib/oklch-contrast.ts";
|
||||
import {
|
||||
firstFontFamilyFailures,
|
||||
focusContrastFailures,
|
||||
hueMixFailures,
|
||||
unreadTokenFailures,
|
||||
} from "./lib/design-system-rules.ts";
|
||||
import { readCustomProperties } from "./lib/oklch-contrast.ts";
|
||||
|
||||
const fixtureMode = process.argv.includes("--fixture");
|
||||
const failures: string[] = [];
|
||||
@@ -51,12 +57,7 @@ for (const { file, source } of cssSources) {
|
||||
failures.push(`${file} uses undefined token ${match[1]}`);
|
||||
}
|
||||
}
|
||||
// UI-02. Hue-based spaces interpolate the hue angle, and an achromatic
|
||||
// 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.
|
||||
for (const match of source.matchAll(/color-mix\(\s*in\s+(oklch|lch|hsl|hwb)\b/g)) {
|
||||
failures.push(`${file} mixes colours in ${match[1]}; use oklab`);
|
||||
}
|
||||
failures.push(...hueMixFailures({ file, source }));
|
||||
}
|
||||
|
||||
const semanticSource = await readFile(tokenFiles.semantic, "utf8");
|
||||
@@ -84,19 +85,6 @@ for (const token of [
|
||||
failures.push(`dark theme token is missing: ${token}`);
|
||||
}
|
||||
}
|
||||
// UI-01. The focus ring is drawn 3px away from its control, so the colour
|
||||
// next to it is the surface behind the control, not the control itself.
|
||||
// WCAG 1.4.11 asks 3:1 against that neighbour, in both themes.
|
||||
const FOCUS_RING_BACKGROUNDS = [
|
||||
"--color-surface",
|
||||
"--color-surface-muted",
|
||||
"--color-panel",
|
||||
"--color-surface-elevated",
|
||||
"--color-info-surface",
|
||||
"--color-success-surface",
|
||||
"--color-warning-surface",
|
||||
"--color-danger-surface",
|
||||
] as const;
|
||||
const lightProperties = new Map([
|
||||
...readCustomProperties(await readFile(tokenFiles.primitive, "utf8")),
|
||||
...readCustomProperties(semanticSource.split(':root[data-theme="dark"]')[0]),
|
||||
@@ -105,61 +93,16 @@ const darkProperties = new Map([
|
||||
...lightProperties,
|
||||
...readCustomProperties(darkSource),
|
||||
]);
|
||||
for (const [theme, properties] of [
|
||||
["light", lightProperties],
|
||||
["dark", darkProperties],
|
||||
] as const) {
|
||||
const focus = resolveColor("--color-focus", properties);
|
||||
for (const background of FOCUS_RING_BACKGROUNDS) {
|
||||
const surface = resolveColor(background, properties);
|
||||
if (!focus || !surface) {
|
||||
failures.push(`${theme} --color-focus or ${background} is not a plain oklch() value`);
|
||||
continue;
|
||||
}
|
||||
const ratio = contrastRatio(focus, surface);
|
||||
if (ratio < 3) {
|
||||
failures.push(
|
||||
`${theme} --color-focus contrast ${ratio.toFixed(2)}:1 against ${background} is below 3:1`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UI-03. A component token nobody reads is a second copy of a decision:
|
||||
// the style that should use it repeats the formula instead, and a product
|
||||
// that rebrands through the token sees nothing change.
|
||||
const styleSources = cssSources.filter(({ file }) => file !== tokenFiles.component);
|
||||
for (const token of REQUIRED_COMPONENT_TOKENS) {
|
||||
if (!styleSources.some(({ source }) => source.includes(`var(${token}`))) {
|
||||
failures.push(`component token ${token} is defined but no style reads it`);
|
||||
}
|
||||
}
|
||||
|
||||
// UI-05. --font-sans named Inter first, but nothing loads Inter, so most
|
||||
// machines drew another font and Hangul never came from Inter at all.
|
||||
// The first family must be a generic keyword or one this repo ships.
|
||||
const GENERIC_FONT_FAMILIES = new Set([
|
||||
"system-ui",
|
||||
"ui-sans-serif",
|
||||
"ui-serif",
|
||||
"ui-monospace",
|
||||
"sans-serif",
|
||||
"serif",
|
||||
"monospace",
|
||||
]);
|
||||
const shippedFontFamilies = new Set(
|
||||
cssSources.flatMap(({ source }) =>
|
||||
[...source.matchAll(/@font-face\s*\{[^}]*font-family:\s*["']?([^;"']+)/g)]
|
||||
.map((match) => match[1].trim()),
|
||||
// Rule texts and reasons: scripts/lib/design-system-rules.ts.
|
||||
failures.push(
|
||||
...focusContrastFailures("light", lightProperties),
|
||||
...focusContrastFailures("dark", darkProperties),
|
||||
...unreadTokenFailures(
|
||||
REQUIRED_COMPONENT_TOKENS,
|
||||
cssSources.filter(({ file }) => file !== tokenFiles.component),
|
||||
),
|
||||
...firstFontFamilyFailures(lightProperties.get("--font-sans") ?? "", cssSources),
|
||||
);
|
||||
const fontSans = lightProperties.get("--font-sans") ?? "";
|
||||
const firstFontFamily = fontSans.split(",")[0]?.trim().replace(/^["']|["']$/g, "") ?? "";
|
||||
if (!GENERIC_FONT_FAMILIES.has(firstFontFamily) && !shippedFontFamilies.has(firstFontFamily)) {
|
||||
failures.push(
|
||||
`--font-sans starts with "${firstFontFamily}", which is neither a generic family nor loaded by @font-face`,
|
||||
);
|
||||
}
|
||||
|
||||
const componentSource = await readFile(tokenFiles.component, "utf8");
|
||||
if (!componentSource.includes("@media (forced-colors: active)")) {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// The four CSS rules scripts/check-design-system.ts runs over the token
|
||||
// files and src/presentation/styles/**. Each rule takes file contents and
|
||||
// returns failure messages, so a test can hand it a violation directly.
|
||||
|
||||
import { contrastRatio, resolveColor } from "./oklch-contrast.ts";
|
||||
|
||||
export interface CssSource {
|
||||
readonly file: string;
|
||||
readonly source: string;
|
||||
}
|
||||
|
||||
// Comments keep old code around, and the browser never draws it.
|
||||
// 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, "");
|
||||
}
|
||||
|
||||
// UI-01. The focus ring is drawn 3px away from its control, so the colour
|
||||
// next to it is the surface behind the control, not the control itself.
|
||||
// WCAG 1.4.11 asks 3:1 against that neighbour, in both themes.
|
||||
export const FOCUS_RING_BACKGROUNDS = [
|
||||
"--color-surface",
|
||||
"--color-surface-muted",
|
||||
"--color-panel",
|
||||
"--color-surface-elevated",
|
||||
"--color-info-surface",
|
||||
"--color-success-surface",
|
||||
"--color-warning-surface",
|
||||
"--color-danger-surface",
|
||||
] as const;
|
||||
|
||||
export function focusContrastFailures(
|
||||
theme: string,
|
||||
properties: ReadonlyMap<string, string>,
|
||||
): string[] {
|
||||
const failures: string[] = [];
|
||||
const focus = resolveColor("--color-focus", properties);
|
||||
for (const background of FOCUS_RING_BACKGROUNDS) {
|
||||
const surface = resolveColor(background, properties);
|
||||
if (!focus || !surface) {
|
||||
failures.push(`${theme} --color-focus or ${background} is not a plain oklch() value`);
|
||||
continue;
|
||||
}
|
||||
const ratio = contrastRatio(focus, surface);
|
||||
if (ratio < 3) {
|
||||
failures.push(
|
||||
`${theme} --color-focus contrast ${ratio.toFixed(2)}:1 against ${background} is below 3:1`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
// UI-02. Hue-based spaces interpolate the hue angle, and an achromatic
|
||||
// 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.
|
||||
export function hueMixFailures({ file, source }: CssSource): string[] {
|
||||
const mixes = withoutComments(source).matchAll(
|
||||
/color-mix\(\s*in\s+(oklch|lch|hsl|hwb)\b/gi,
|
||||
);
|
||||
return [...mixes].map((match) => `${file} mixes colours in ${match[1]}; use oklab`);
|
||||
}
|
||||
|
||||
// UI-03. A component token nobody reads is a second copy of a decision:
|
||||
// the style that should use it repeats the formula instead, and a product
|
||||
// that rebrands through the token sees nothing change.
|
||||
// A read is var(--name) or var(--name, fallback) with the whole name: a
|
||||
// prefix match took var(--field-border-invalid) for a read of
|
||||
// --field-border (12-01). "var" ignores case; custom property names don't.
|
||||
export function unreadTokenFailures(
|
||||
tokens: readonly string[],
|
||||
styles: readonly CssSource[],
|
||||
): string[] {
|
||||
const read = new Set(
|
||||
styles.flatMap(({ source }) =>
|
||||
[...withoutComments(source).matchAll(/var\(\s*(--[^\s,)]+)\s*[,)]/gi)]
|
||||
.map((match) => match[1]),
|
||||
),
|
||||
);
|
||||
return tokens
|
||||
.filter((token) => !read.has(token))
|
||||
.map((token) => `component token ${token} is defined but no style reads it`);
|
||||
}
|
||||
|
||||
// UI-05. --font-sans named Inter first, but nothing loads Inter, so most
|
||||
// machines drew another font and Hangul never came from Inter at all.
|
||||
// The first family must be a generic keyword or one this repo ships.
|
||||
const GENERIC_FONT_FAMILIES = new Set([
|
||||
"system-ui",
|
||||
"ui-sans-serif",
|
||||
"ui-serif",
|
||||
"ui-monospace",
|
||||
"sans-serif",
|
||||
"serif",
|
||||
"monospace",
|
||||
]);
|
||||
|
||||
export function firstFontFamilyFailures(
|
||||
fontSans: string,
|
||||
styles: readonly CssSource[],
|
||||
): string[] {
|
||||
const shipped = new Set(
|
||||
styles.flatMap(({ source }) =>
|
||||
[...source.matchAll(/@font-face\s*\{[^}]*font-family:\s*["']?([^;"']+)/g)]
|
||||
.map((match) => match[1].trim()),
|
||||
),
|
||||
);
|
||||
const first = fontSans.split(",")[0]?.trim().replace(/^["']|["']$/g, "") ?? "";
|
||||
if (GENERIC_FONT_FAMILIES.has(first) || shipped.has(first)) return [];
|
||||
return [
|
||||
`--font-sans starts with "${first}", which is neither a generic family nor loaded by @font-face`,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
FOCUS_RING_BACKGROUNDS,
|
||||
firstFontFamilyFailures,
|
||||
focusContrastFailures,
|
||||
hueMixFailures,
|
||||
unreadTokenFailures,
|
||||
} from "../../scripts/lib/design-system-rules.ts";
|
||||
|
||||
const css = (source: string) => ({ file: "probe.css", source });
|
||||
|
||||
describe("design system rules", () => {
|
||||
describe("UI-01 focus ring contrast", () => {
|
||||
const tokens = (focus: string) =>
|
||||
new Map([
|
||||
...FOCUS_RING_BACKGROUNDS.map((surface) => [surface, "oklch(1 0 0)"] as const),
|
||||
["--color-focus", focus],
|
||||
]);
|
||||
|
||||
it("fails a focus colour below 3:1 against a surface", () => {
|
||||
// The light focus ring before UI-01.
|
||||
expect(focusContrastFailures("light", tokens("oklch(0.72 0.16 225)"))).toContainEqual(
|
||||
expect.stringMatching(/^light --color-focus contrast 2\.\d\d:1 against --color-panel is below 3:1$/),
|
||||
);
|
||||
});
|
||||
|
||||
it("passes a focus colour at 3:1 or more on every surface", () => {
|
||||
expect(focusContrastFailures("light", tokens("oklch(0.52 0.15 230)"))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("UI-02 colour mixing space", () => {
|
||||
it("fails a hue-based mixing space", () => {
|
||||
expect(hueMixFailures(css("a { color: color-mix(in oklch, red, blue); }"))).toEqual([
|
||||
"probe.css mixes colours in oklch; use oklab",
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails it in upper case, since CSS keywords ignore case", () => {
|
||||
expect(hueMixFailures(css("a { color: COLOR-MIX(in OKLCH, red, blue); }"))).toEqual([
|
||||
"probe.css mixes colours in OKLCH; use oklab",
|
||||
]);
|
||||
});
|
||||
|
||||
it("passes oklab, and old code left in a comment", () => {
|
||||
expect(
|
||||
hueMixFailures(
|
||||
css("/* was color-mix(in oklch, red, blue) */ a { color: color-mix(in oklab, red, blue); }"),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("UI-03 component token readers", () => {
|
||||
const tokens = ["--field-border", "--field-border-invalid"];
|
||||
|
||||
// 12-01: "var(--field-border" is also the start of
|
||||
// "var(--field-border-invalid)".
|
||||
it("does not count a longer token that starts with the same name", () => {
|
||||
expect(
|
||||
unreadTokenFailures(tokens, [css("a { border-color: var(--field-border-invalid); }")]),
|
||||
).toEqual(["component token --field-border is defined but no style reads it"]);
|
||||
});
|
||||
|
||||
it("counts var(--x) and var(--x, fallback), with any case for var", () => {
|
||||
for (const source of [
|
||||
"a { border-color: var(--field-border); }",
|
||||
"a { border: 1px solid VAR( --field-border , red); }",
|
||||
]) {
|
||||
expect(unreadTokenFailures(["--field-border"], [css(source)])).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not count a name in another case, since custom properties are case-sensitive", () => {
|
||||
expect(unreadTokenFailures(["--field-border"], [css("a { color: var(--Field-Border); }")]))
|
||||
.toEqual(["component token --field-border is defined but no style reads it"]);
|
||||
});
|
||||
|
||||
it("does not count a read inside a comment", () => {
|
||||
expect(unreadTokenFailures(["--field-border"], [css("/* var(--field-border) */")])).toEqual([
|
||||
"component token --field-border is defined but no style reads it",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("UI-05 first font family", () => {
|
||||
it("fails a named font that nothing loads", () => {
|
||||
expect(firstFontFamilyFailures("Inter, system-ui, sans-serif", [])).toEqual([
|
||||
'--font-sans starts with "Inter", which is neither a generic family nor loaded by @font-face',
|
||||
]);
|
||||
});
|
||||
|
||||
it("passes a generic family, or a family loaded by @font-face", () => {
|
||||
expect(firstFontFamilyFailures("system-ui, sans-serif", [])).toEqual([]);
|
||||
expect(
|
||||
firstFontFamilyFailures('"Brand Sans", sans-serif', [
|
||||
css('@font-face { font-family: "Brand Sans"; src: url(brand.woff2); }'),
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user