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

233 lines
10 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,
rawSemanticColourFailures,
unreadTokenFailures,
} from "../../scripts/lib/design-system-rules.ts";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
const css = (source: string) => ({ file: "probe.css", source });
describe("design system rules", { timeout: childProcessTimeout(3_540) }, () => {
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([]);
});
});
// 1112/04-13. A rebrand edits the palette; the roles follow it.
describe("UI-07 semantic colours come from the palette", () => {
it.each([
"oklch(0.52 0.15 230)",
"#2563eb",
"rgb(37 99 235)",
"hsl(220 80% 50%)",
"OKLCH(0.5 0.1 200)",
])("fails a role written as %s", (value) => {
expect(rawSemanticColourFailures(css(`:root { --color-focus: ${value}; }`))).toEqual([
`probe.css --color-focus is the raw colour ${value}; name it in primitive.css and read it with var()`,
]);
});
it("passes a palette read, a mix of tokens, and a comment", () => {
expect(
rawSemanticColourFailures(
css(`/* was oklch(0.5 0.1 200) */
:root {
--color-focus: var(--palette-sky-600);
--color-disabled-content: color-mix(in oklab, var(--color-content) 55%, transparent);
--layer-modal: 70;
}`),
),
).toEqual([]);
});
it("passes the repository's semantic tokens", async () => {
const file = "src/presentation/design-system/tokens/semantic.css";
expect(rawSemanticColourFailures({ file, source: await readFile(file, "utf8") })).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";
// A palette colour too light for 3:1 on the light surfaces (UI-01), read
// as a token so that UI-07 stays quiet.
await edit(semantic, /--color-focus: [^;]+;/, "--color-focus: var(--palette-sky-200);");
await edit(semantic, "--font-sans: ", "--font-sans: Inter, ");
await edit(semantic, "--color-danger-surface: var(--palette-red-50);", "--color-danger-surface: oklch(0.96 0.035 25);");
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$/,
/^src\/presentation\/design-system\/tokens\/semantic\.css --color-danger-surface is the raw colour oklch\(0\.96 0\.035 25\); name it in primitive\.css and read it with var\(\)$/,
];
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 });
}
});
});