Files
clean-architecture-frontend…/scripts/lib/design-system-rules.ts
T
DongHyeonka e714c0d770 fix(design-system): 디자인 검사가 deg 색상각과 시스템 글꼴 이름을 받는다 (12-04)
문제
디자인 규칙이 올바른 CSS를 거부한다. 포커스 대비 규칙의 parseOklch는
색상각 단위 deg와 음수 색상각을 읽지 못해 oklch(52% 0.15 230deg)를 실패로
센다(B13). 첫 글꼴 규칙은 -apple-system, BlinkMacSystemFont로 시작하는
시스템 글꼴 스택을 실패로 센다(B6). color-mix()·알파 표면(B10, B11)은
"--color-focus or X is not a plain oklch() value"로 실패해서 어느 토큰이
무슨 값인지, 무엇이면 되는지 알 수 없다. 네 규칙의 설명은 코드 주석에만
있다.

고른 방법
- parseOklch가 색상각에 deg와 음수를 받는다. 알파는 계속 받지 않는다.
- oklch-contrast.ts에 resolveValue(var() 사슬 끝 값)를 두고 resolveColor가
  그것을 쓴다. 포커스 규칙은 계산할 수 없는 토큰마다 "<테마> <토큰> is
  <값>; contrast needs an opaque oklch(L C H), hue in degrees with or
  without deg"를 낸다. 포커스 색 자체를 못 읽으면 표면 8개 대신 한 줄이다.
- 첫 글꼴 허용 목록에 -apple-system, BlinkMacSystemFont를 더한다.
- docs/styling/design-system-platform.md 4.1절에 규칙 4개, 지원 형식,
  검사 위치를 표 하나로 적는다.
버린 대안
- color-mix()·알파 표면을 배경 위에 섞어 계산: 무엇이 아래에 그려지는지
  규칙이 모른다. 추측하지 않고 실패하는 기존 원칙을 유지하고 메시지로
  해결 형식을 알린다(리뷰 대안 비교와 같다).
- 리뷰 개선 (4) token-contract.ts에 "제품이 싣는 글꼴" 목록: 공개 계약에
  새 이름을 넣는 설계 선택이고 완료 기준에 없다. 문서 표에 "아직 선언할
  곳이 없어 실패한다"로 적었다.
- rad·grad·turn 단위: 쓰는 곳이 없다. 넣지 않은 단위는 메시지가 알려 준다.

위험·한계
- 실패 메시지 문구가 바뀐다. 문구를 단언하는 곳은 이 테스트 파일뿐이다.
- 패키지·<link>로 싣는 글꼴, 12-03의 검사 위치 밖 CSS는 그대로다.
- 화면 변화 없음. CSS를 바꾸지 않았다.

검증
- RED(수정 전): design-system-rules·oklch-contrast 테스트 19개 중 4개
  실패. "reads a hue written with deg" expected [ …(8) ] to deeply equal [],
  "names the value it cannot compute …" 메시지 불일치, "-apple-system"
  expected [ Array(1) ] to deeply equal [], parseOklch("…230deg") expected
  null.
- GREEN: 같은 두 파일과 design-system-contract 21/21 통과. 실제 스크립트
  probe: 포커스를 oklch(52% 0.15 230deg)로 → PASS(B13). surface-muted를
  oklch(0.97 0 0 / 0.9)로 → "light --color-surface-muted is oklch(0.97 0 0
  / 0.9); contrast needs …"로 실패(B11). 저장소 CSS는 PASS.
- tsc(tsconfig.node, tsconfig.test), 바꾼 파일 eslint, verify-
  documentation-readiness PASS_SCOPED.

Refs: docs/reviews/2026-11-01-maturity-review/12-guardrails-ci.md 12-04
2026-11-01 22:16:26 +09:00

126 lines
4.6 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, resolveValue } 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;
// A colour-mix() or translucent value depends on what is drawn beneath it,
// so the rule refuses it rather than guess (12-04). The message says which
// token and which form it can compute.
export function focusContrastFailures(
theme: string,
properties: ReadonlyMap<string, string>,
): string[] {
const unreadable = (token: string) =>
`${theme} ${token} is ${resolveValue(token, properties) ?? "not defined"}; ` +
"contrast needs an opaque oklch(L C H), hue in degrees with or without deg";
const focus = resolveColor("--color-focus", properties);
if (!focus) return [unreadable("--color-focus")];
const failures: string[] = [];
for (const background of FOCUS_RING_BACKGROUNDS) {
const surface = resolveColor(background, properties);
if (!surface) {
failures.push(unreadable(background));
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, a browser name for the
// system font, or one this repo ships.
const GENERIC_FONT_FAMILIES = new Set([
"system-ui",
"-apple-system",
"BlinkMacSystemFont",
"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`,
];
}