Files
clean-architecture-frontend…/scripts/lib/design-system-rules.ts
DongHyeonka aab85a7467 fix(styles): ghost 버튼 hover 글자를 본문 대비 4.5:1 이상으로 올린다
ghost 버튼에 마우스를 올리면 라이트 테마에서 글자와 배경이 4.14:1이라
본문 기준 4.5:1에 못 미친다.

글자가 이미 있는 --color-action-hover를 읽게 한다. surface-muted를 밝게
바꾸는 안은 danger 글자 쌍(4.52:1)이 같이 흔들려 버렸다. 규칙 하나의
글자·배경 대비를 재는 textContrastFailures와 두 테마 시험을 더한다.

한계: check:design-system은 이 규칙을 부르지 않는다. 단위 시험
(FE-GATE-005)만 돈다. 시각 골든에 hover 상태가 없어 색은 계산으로만 봤다.

검증: 고치기 전 라이트 4.14:1로 1개 실패, 고친 뒤 59개 통과. 문턱을
3·4.2·5.5로 바꾼 변이는 모두 실패한다(경계 4.49와 4.51을 시험이 본다).

Refs: DES-FE-0001
2026-11-22 23:37:48 +09:00

307 lines
14 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. 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, (comment) => comment.replace(/[^\n]/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;
}
// DES-FE-0001. UI-01 measures the focus ring alone, and the ghost button's
// hover drew blue-600 text on slate-100, 4.14:1 in the light theme. WCAG 1.4.3
// asks 4.5:1 of text at the body size, under the pointer too. The pair is read
// from the rule that draws it, so the colours measured are the ones it names.
// check:design-system does not run this rule: design-system-rules.test.ts
// hands it the repository's style sheet in FE-GATE-005.
export function textContrastFailures(
theme: string,
selector: string,
{ file, source }: CssSource,
properties: ReadonlyMap<string, string>,
): string[] {
const drawn = new Map(properties);
for (const [, selectors, body] of withoutComments(source).matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
if (!selectors.split(",").some((item) => item.trim() === selector)) continue;
for (const [, property, value] of body.matchAll(/([a-z-]+)\s*:\s*([^;]+)/g)) {
drawn.set(property, value.trim());
}
}
const text = resolveColor("color", drawn);
const background = resolveColor("background", drawn);
if (!text || !background) {
const property = text ? "background" : "color";
return [
`${file} ${theme} ${selector} ${property} is ${resolveValue(property, drawn) ?? "not defined"}; ` +
"contrast needs an opaque oklch(L C H), hue in degrees with or without deg",
];
}
const ratio = contrastRatio(text, background);
if (ratio >= 4.5) return [];
return [
`${file} ${theme} ${selector} text contrast ${ratio.toFixed(2)}:1 ` +
`(${drawn.get("color")} on ${drawn.get("background")}) is below 4.5: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. 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(HUE_MIX);
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[],
layer: "component" | "semantic" = "component",
): 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) => `${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
// 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()`,
);
}
// 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;
}