Files
clean-architecture-frontend…/scripts/lib/design-system-rules.ts
DongHyeonka b4ccadab77 feat(design-system): 제품이 싣는 글꼴을 토큰 계약에 선언하게 한다 (1101/12-04)
문제
첫 글꼴 규칙(check:design-system)은 --font-sans의 첫 글꼴이 일반
키워드이거나 검사하는 CSS 안의 @font-face로 실릴 때만 통과시킨다. 글꼴
패키지 import, @import url(…), index.html의 <link>로 싣는 글꼴은 볼 수
없어 실패한다. memento 토큰이 이미 이 규칙에 걸린다. 선언할 곳이 없으니
제품은 템플릿 소유 스크립트를 고치게 된다.

고른 방법
- token-contract.ts에 PRODUCT_LOADED_FONT_FAMILIES(템플릿은 빈 목록)를
  둔다. 제품은 토큰 계약 파일에서 자기가 싣는 글꼴 이름을 적는다.
- firstFontFamilyFailures가 세 번째 인자로 이 목록을 받아 @font-face로
  실은 글꼴과 같이 허용한다. check-design-system.ts가 목록을 넘긴다.
- 실패 메시지에 목록 이름을 넣어 어디에 선언하는지 알린다.
- docs/styling/design-system-platform.md 4.1절 표의 첫 글꼴 행을 고친다.
- 12-04의 (1)~(3)과 (5)는 e714c0d가 했다(deg·음수 색상각, 지원 형식을
  적는 포커스 메시지, -apple-system·BlinkMacSystemFont, 규칙 문서). 이
  커밋은 (4)만 한다.
버린 대안
- 패키지 import·<link>를 찾아 실제로 싣는지 판정: 진입점·CDN·번들러
  설정까지 봐야 해서 규칙이 커진다.
- 목록을 design-system/index.ts로도 내보내기: 앱 코드가 쓰지 않는다.

위험·한계
- 검사는 목록을 믿는다. 글꼴이 실제로 실리는지 보지 않는다. 주석과
  문서에 "모든 화면이 싣는 글꼴만 적는다"고 적었다.
- 실패 메시지 문구가 바뀐다. 문구를 단언하는 곳은
  tests/unit/design-system-rules.test.ts뿐이다.
- 새 공개 이름 PRODUCT_LOADED_FONT_FAMILIES가 생긴다.

검증
- RED: 새 테스트 "passes a family the product declares it loads, and only
  that one"이 실패(expected [ Array(1) ] to deeply equal []).
- GREEN: design-system-rules·oklch-contrast·design-system-contract
  22/22 통과.
- 실제 스크립트 probe: CSS 사본의 --font-sans를 "Pretendard Variable"로
  시작하게 하고 node scripts/check-design-system.ts → 빈 목록이면 새
  메시지로 실패(exit 1), 목록에 넣으면 PASS(exit 0). 저장소 CSS는 PASS.
- tsc(app·node·test), 바꾼 파일 eslint, verify-documentation-readiness
  PASS_SCOPED.

Refs: docs/reviews/2026-11-01-maturity-review/12-guardrails-ci.md 12-04
2026-11-03 01:24:31 +09:00

129 lines
4.8 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, 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`,
];
}