Files
clean-architecture-frontend…/scripts/lib/design-system-rules.ts
T
DongHyeonka 49d8675f97 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
2026-11-01 19:07:05 +09:00

116 lines
4.1 KiB
TypeScript

// 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`,
];
}