Files
clean-architecture-frontend…/tests/unit/design-system-rules.test.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

194 lines
8.4 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
FOCUS_RING_BACKGROUNDS,
firstFontFamilyFailures,
focusContrastFailures,
hueMixFailures,
unreadTokenFailures,
} from "../../scripts/lib/design-system-rules.ts";
const css = (source: string) => ({ file: "probe.css", source });
describe("design system rules", () => {
describe("UI-01 focus ring contrast", () => {
const tokens = (focus: string) =>
new Map([
...FOCUS_RING_BACKGROUNDS.map((surface) => [surface, "oklch(1 0 0)"] as const),
["--color-focus", focus],
]);
it("fails a focus colour below 3:1 against a surface", () => {
// The light focus ring before UI-01.
expect(focusContrastFailures("light", tokens("oklch(0.72 0.16 225)"))).toContainEqual(
expect.stringMatching(/^light --color-focus contrast 2\.\d\d:1 against --color-panel is below 3:1$/),
);
});
it("passes a focus colour at 3:1 or more on every surface", () => {
expect(focusContrastFailures("light", tokens("oklch(0.52 0.15 230)"))).toEqual([]);
});
// 12-04 B13: CSS allows a hue angle with its unit.
it("reads a hue written with deg", () => {
expect(focusContrastFailures("light", tokens("oklch(52% 0.15 230deg)"))).toEqual([]);
});
// 12-04 B10, B11: still refused, but the message names the token, its
// value and the one form the rule can compute.
it("names the value it cannot compute and the form it can", () => {
const properties = new Map([
...tokens("oklch(0.52 0.15 230)"),
["--color-panel", "color-mix(in oklab, var(--color-surface) 92%, black)"],
["--color-info-surface", "oklch(0.97 0.02 230 / 0.9)"],
]);
const supported = "contrast needs an opaque oklch(L C H), hue in degrees with or without deg";
expect(focusContrastFailures("light", properties)).toEqual([
`light --color-panel is color-mix(in oklab, var(--color-surface) 92%, black); ${supported}`,
`light --color-info-surface is oklch(0.97 0.02 230 / 0.9); ${supported}`,
]);
});
});
describe("UI-02 colour mixing space", () => {
it("fails a hue-based mixing space", () => {
expect(hueMixFailures(css("a { color: color-mix(in oklch, red, blue); }"))).toEqual([
"probe.css mixes colours in oklch; use oklab",
]);
});
it("fails it in upper case, since CSS keywords ignore case", () => {
expect(hueMixFailures(css("a { color: COLOR-MIX(in OKLCH, red, blue); }"))).toEqual([
"probe.css mixes colours in OKLCH; use oklab",
]);
});
it("passes oklab, and old code left in a comment", () => {
expect(
hueMixFailures(
css("/* was color-mix(in oklch, red, blue) */ a { color: color-mix(in oklab, red, blue); }"),
),
).toEqual([]);
});
});
describe("UI-03 component token readers", () => {
const tokens = ["--field-border", "--field-border-invalid"];
// 12-01: "var(--field-border" is also the start of
// "var(--field-border-invalid)".
it("does not count a longer token that starts with the same name", () => {
expect(
unreadTokenFailures(tokens, [css("a { border-color: var(--field-border-invalid); }")]),
).toEqual(["component token --field-border is defined but no style reads it"]);
});
it("counts var(--x) and var(--x, fallback), with any case for var", () => {
for (const source of [
"a { border-color: var(--field-border); }",
"a { border: 1px solid VAR( --field-border , red); }",
]) {
expect(unreadTokenFailures(["--field-border"], [css(source)])).toEqual([]);
}
});
it("does not count a name in another case, since custom properties are case-sensitive", () => {
expect(unreadTokenFailures(["--field-border"], [css("a { color: var(--Field-Border); }")]))
.toEqual(["component token --field-border is defined but no style reads it"]);
});
it("does not count a read inside a comment", () => {
expect(unreadTokenFailures(["--field-border"], [css("/* var(--field-border) */")])).toEqual([
"component token --field-border is defined but no style reads it",
]);
});
});
describe("UI-05 first font family", () => {
it("fails a named font that nothing loads", () => {
expect(firstFontFamilyFailures("Inter, system-ui, sans-serif", [])).toEqual([
'--font-sans starts with "Inter", which is neither a generic family, loaded by @font-face, nor listed in PRODUCT_LOADED_FONT_FAMILIES',
]);
});
it("passes a generic family, or a family loaded by @font-face", () => {
expect(firstFontFamilyFailures("system-ui, sans-serif", [])).toEqual([]);
// 12-04 B6: the WebKit and Blink names for the system font.
expect(firstFontFamilyFailures("-apple-system, BlinkMacSystemFont, system-ui", []))
.toEqual([]);
expect(firstFontFamilyFailures("BlinkMacSystemFont, system-ui", [])).toEqual([]);
expect(
firstFontFamilyFailures('"Brand Sans", sans-serif', [
css('@font-face { font-family: "Brand Sans"; src: url(brand.woff2); }'),
]),
).toEqual([]);
});
// 1101/12-04 (4): a font package import or a <link> loads the family
// outside the checked CSS, so the product declares it instead.
it("passes a family the product declares it loads, and only that one", () => {
const declared = ["Pretendard Variable"];
expect(
firstFontFamilyFailures('"Pretendard Variable", system-ui', [], declared),
).toEqual([]);
expect(firstFontFamilyFailures("Inter, system-ui", [], declared)).toEqual([
'--font-sans starts with "Inter", which is neither a generic family, loaded by @font-face, nor listed in PRODUCT_LOADED_FONT_FAMILIES',
]);
});
});
// 12-02: the cases above test the rule functions. This one tests that
// check:design-system still calls each of them on the token files and
// styles/**: drop a call from the script and it fails here, while the
// repository CSS keeps passing the gate.
it("check-design-system.ts reports one violation per rule in a copy of the CSS", async () => {
const root = await mkdtemp(path.join(tmpdir(), "design-system-rules-"));
try {
for (const folder of ["src/presentation/design-system/tokens", "src/presentation/styles"]) {
await cp(folder, path.join(root, folder), { recursive: true });
}
const edit = async (file: string, from: string | RegExp, to: string) => {
const target = path.join(root, file);
const source = await readFile(target, "utf8");
const edited = source.replace(from, to);
if (edited === source) throw new Error(`${String(from)} not found in ${file}`);
await writeFile(target, edited);
};
const semantic = "src/presentation/design-system/tokens/semantic.css";
await edit(semantic, /--color-focus: [^;]+;/, "--color-focus: oklch(0.72 0.16 225);");
await edit(semantic, "--font-sans: ", "--font-sans: Inter, ");
await edit("src/presentation/styles/theme/primitives.css", "var(--drawer-width)", "20rem");
await writeFile(
path.join(root, "src/presentation/styles/theme/probe.css"),
".probe { color: color-mix(in oklch, red, blue); }\n",
);
const result = spawnSync(process.execPath, [path.resolve("scripts/check-design-system.ts")], {
cwd: root,
encoding: "utf8",
});
expect(result.status, result.stderr).toBe(1);
const { failures } = JSON.parse(
await readFile(path.join(root, "artifacts/quality/design-system.json"), "utf8"),
) as { failures: string[] };
const rules = [
/^light --color-focus contrast \d\.\d\d:1 against --color-[a-z-]+ is below 3:1$/,
/^src\/presentation\/styles\/theme\/probe\.css mixes colours in oklch; use oklab$/,
/^component token --drawer-width is defined but no style reads it$/,
/^--font-sans starts with "Inter", which is neither a generic family, loaded by @font-face, nor listed in PRODUCT_LOADED_FONT_FAMILIES$/,
];
expect(failures.filter((failure) => !rules.some((rule) => rule.test(failure)))).toEqual([]);
for (const rule of rules) {
expect(failures, String(rule)).toContainEqual(expect.stringMatching(rule));
}
} finally {
await rm(root, { recursive: true, force: true });
}
});
});