Files
clean-architecture-frontend…/scripts/lib/design-system-rules.ts
T
DongHyeonka b384d29ca5 refactor(tokens): semantic 색을 모두 팔레트에서 읽고 검사가 날 색을 거절한다
`semantic.css`가 팔레트를 거치지 않은 날 `oklch()` 36개를 정의한다(밝은
테마의 focus와 info·success·warning·danger 세 쌍 13개, 어두운 테마 23개).
`PRODUCT.md`와 `docs/styling/design-tokens.md`는 토큰이 primitive →
semantic → component로 파생되고 팔레트는 `primitive.css`에 있다고 적는다.
그래서 팔레트만 바꿔 리브랜드하면 status 색, focus, 어두운 테마 대부분이
그대로다.

고른 방법: 36개 값을 그대로 `primitive.css` 팔레트로 옮기고 semantic은
`var()`로 읽는다. 색상 이름 무리(slate·night·blue·sky·green·amber·red)마다
밝기 순서로 단계 이름을 붙였다. 값은 바꾸지 않아 화면은 같다. 그리고
`check:design-system`에 UI-07을 더한다: semantic 선언값이 날 색(#hex,
oklch·oklab·lch·lab·rgb·hsl·hwb·color 함수)이면 실패하고, 토큰과 위치를
말한다. 버린 대안: 문서에 "semantic은 역할 전용 값을 가질 수 있다"와 예외
목록을 적는 것(리브랜드 약속이 그대로 깨진다).

위험·한계: 다운스트림이 `semantic.css`에 날 색을 더해 두었으면 다음
동기화에서 UI-07이 그 줄을 이름과 함께 알린다. 팔레트로 옮기면 된다.
UI-01 대비 계산은 var 사슬을 따라가므로 그대로 돈다.

검증: 규칙 단위 시험(거절 다섯·통과 셋·저장소 파일)과 check-design-system
연결 시험의 RED·GREEN, 시각 골든 불변은 desktop에서 돌려 PR 본문에 적는다.

Refs: 1112/04-13
2026-11-13 23:27:47 +09:00

145 lines
5.5 KiB
TypeScript

// 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";
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, one this repo ships, or one the product declares it loads
// (PRODUCT_LOADED_FONT_FAMILIES in token-contract.ts, 12-04).
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[],
productLoaded: readonly string[] = [],
): string[] {
const shipped = new Set([
...productLoaded,
...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, 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()`,
);
}