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

536 lines
24 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { cp, mkdir, 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,
focusOffsetFailures,
hueMixFailures,
inlineStyleFailures,
rawSemanticColourFailures,
rawStyleValueFailures,
styleSheetColourFailures,
textContrastFailures,
tokenRedefinitionFailures,
undeclaredComponentTokenFailures,
unreadTokenFailures,
} from "../../scripts/lib/design-system-rules.ts";
import { readCustomProperties } from "../../scripts/lib/oklch-contrast.ts";
import {
REQUIRED_COMPONENT_TOKENS,
REQUIRED_SEMANTIC_TOKENS,
SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER,
} from "../../src/presentation/design-system/tokens/token-contract.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}`,
]);
});
});
// DES-FE-0001. The label of a ghost button is body-size text under the
// pointer too.
describe("text contrast of a style rule", () => {
const selector = ".ui-button--ghost:hover";
const palette = new Map([
["--blue-600", "oklch(0.55 0.18 255)"],
["--blue-700", "oklch(0.48 0.2 255)"],
["--slate-100", "oklch(0.94 0.01 247)"],
]);
const rule = (colour: string) =>
css(`@layer components {\n .a, ${selector} { color: ${colour}; background: var(--slate-100); }\n}`);
it("fails text below 4.5:1", () => {
expect(textContrastFailures("light", selector, rule("var(--blue-600)"), palette)).toEqual([
`probe.css light ${selector} text contrast 4.14:1 (var(--blue-600) on var(--slate-100)) is below 4.5:1`,
]);
});
it("passes text at 4.5:1 or more", () => {
expect(textContrastFailures("light", selector, rule("var(--blue-700)"), palette)).toEqual([]);
});
it("draws the line at 4.5:1, failing 4.49:1 and passing 4.51:1", () => {
expect(textContrastFailures("light", selector, rule("oklch(0.53 0.18 255)"), palette)).toEqual([
`probe.css light ${selector} text contrast 4.49:1 (oklch(0.53 0.18 255) on var(--slate-100)) is below 4.5:1`,
]);
expect(textContrastFailures("light", selector, rule("oklch(0.529 0.18 255)"), palette)).toEqual([]);
});
it("fails a colour it cannot compute, and a rule that is not there", () => {
const supported = "contrast needs an opaque oklch(L C H), hue in degrees with or without deg";
expect(textContrastFailures("light", selector, rule("currentColor"), palette)).toEqual([
`probe.css light ${selector} color is currentColor; ${supported}`,
]);
expect(textContrastFailures("light", ".missing:hover", rule("var(--blue-700)"), palette)).toEqual([
`probe.css light .missing:hover color is not defined; ${supported}`,
]);
});
it.each(["light", "dark"])("passes the repository's ghost hover in the %s theme", async (theme) => {
const tokens = "src/presentation/design-system/tokens";
const [light, dark = ""] = (await readFile(`${tokens}/semantic.css`, "utf8")).split(':root[data-theme="dark"]');
const properties = new Map([
...readCustomProperties(await readFile(`${tokens}/primitive.css`, "utf8")),
...readCustomProperties(light),
...(theme === "dark" ? readCustomProperties(dark) : []),
]);
const file = "src/presentation/styles/theme/primitives.css";
expect(
textContrastFailures(theme, selector, { file, source: await readFile(file, "utf8") }, properties),
).toEqual([]);
});
});
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",
]);
});
// 1101/12-03. A gradient interpolates in its colour space too.
it.each([
"linear-gradient(in oklch, red, blue)",
"linear-gradient(90deg in hsl, red, blue)",
"radial-gradient(circle in lch, red, blue)",
"repeating-conic-gradient(from 0deg in hwb, red, blue)",
])("fails %s", (gradient) => {
expect(hueMixFailures(css(`a { background: ${gradient}; }`))).toHaveLength(1);
});
it("passes a gradient in oklab or without a colour space", () => {
expect(
hueMixFailures(css("a { background: linear-gradient(90deg in oklab, red, blue), linear-gradient(red, blue); }")),
).toEqual([]);
});
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",
]);
});
});
// 1112/04-08. A style that writes the value by hand ignores the token.
describe("UI-06 styles read spacing, type, radius, layer and shadow tokens", () => {
it.each([
["padding: 0.75rem 1rem", "0.75rem, 1rem"],
["margin-block-start: 0.4rem", "0.4rem"],
["gap: 12px", "12px"],
["font-size: 0.8rem", "0.8rem"],
["font-weight: 800", "800"],
["line-height: 1.6", "1.6"],
["border-radius: 999px", "999px"],
["z-index: 30", "30"],
["box-shadow: 0 1px 8px var(--color-border)", "1px, 8px, 0"],
])("fails %s", (declaration, raw) => {
const [property] = declaration.split(":");
expect(rawStyleValueFailures(css(`.a {\n ${declaration};\n}`))).toEqual([
`probe.css:2 ${property}: ${declaration.slice(property.length + 1).trim()} writes ${raw} by hand; read a token (docs/styling/design-tokens.md UI-06)`,
]);
});
it("passes token reads, zero, keywords, hairlines, relative and viewport values", () => {
expect(
rawStyleValueFailures(
css(`.a {
padding: var(--space-3) var(--space-4);
margin: -1px;
margin-inline: calc(var(--spacing-page) * -1);
padding-block: clamp(var(--space-4), 5vw, var(--space-14)) 0;
gap: 0;
font-size: 0.9em;
font-weight: var(--font-weight-bold);
line-height: 1;
border-radius: 50%;
z-index: var(--layer-sticky);
box-shadow: none;
width: 2rem;
}`),
),
).toEqual([]);
});
it("reports the file's own line after a comment of several lines", () => {
expect(rawStyleValueFailures(css("/* one\n two\n padding: 1rem; */\n.a { padding: 1rem; }"))).toEqual([
"probe.css:4 padding: 1rem writes 1rem by hand; read a token (docs/styling/design-tokens.md UI-06)",
]);
});
});
describe("UI-03 for the required semantic tokens", () => {
it("names the semantic layer in the message", () => {
expect(unreadTokenFailures(["--layer-navigation"], [css(".a { z-index: 1; }")], "semantic")).toEqual([
"semantic token --layer-navigation is defined but no style reads it",
]);
});
it("leaves out only --layer-modal, which the top layer makes unreadable", () => {
expect(SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER).toEqual(["--layer-modal"]);
expect(REQUIRED_SEMANTIC_TOKENS).toContain("--layer-modal");
});
});
// 1112/04-12. Every component token is in the contract UI-03 walks.
describe("component tokens and the contract", () => {
it("fails a component token the contract does not list", () => {
const component = css(`@theme {\n --button-primary-background: x;\n --dialog-backdrop-weight: 55%;\n}\n\n@media (forced-colors: active) {\n :root {\n --color-border: CanvasText;\n }\n}`);
expect(undeclaredComponentTokenFailures(component, ["--button-primary-background"])).toEqual([
"probe.css defines --dialog-backdrop-weight, which REQUIRED_COMPONENT_TOKENS in token-contract.ts does not list",
]);
});
it("passes the repository's component tokens", async () => {
const file = "src/presentation/design-system/tokens/component.css";
expect(
undeclaredComponentTokenFailures({ file, source: await readFile(file, "utf8") }, REQUIRED_COMPONENT_TOKENS),
).toEqual([]);
});
});
// 1101/12-03. Style sheets read colours; the token files define them.
describe("style sheets outside the token files", () => {
it("fails a raw colour, and passes a token read or a mix of tokens", () => {
expect(
styleSheetColourFailures(css(".a { color: #ff0000; border-color: rgb(1 2 3); }\n.b { color: var(--color-content); background: color-mix(in oklab, var(--color-panel) 92%, transparent); }")),
).toEqual([
"probe.css color: #ff0000 is a raw colour; read a colour token",
"probe.css border-color: rgb(1 2 3) is a raw colour; read a colour token",
]);
});
it("fails a token redefined in a style sheet, and passes a local property", () => {
expect(
tokenRedefinitionFailures(css(":root { --font-sans: serif; }\n.a { --local-gap: 1px; }"), new Set(["--font-sans"])),
).toEqual(["probe.css redefines the token --font-sans; change it in the token files"]);
});
it.each(["0", "0px", "-1px"])("fails a focus ring drawn with outline-offset %s", (offset) => {
expect(focusOffsetFailures(css(`.a:focus-visible { outline-offset: ${offset}; }`))).toEqual([
`probe.css outline-offset: ${offset} draws the focus ring on the control; UI-01 measures it against the surface around the control`,
]);
});
it("passes a focus ring drawn away from the control", () => {
expect(focusOffsetFailures(css(".a:focus-visible { outline-offset: 0.1875rem; }"))).toEqual([]);
});
});
// 1112/04-14. Primitives keep className and style open (decision
// 2026-11-12); the check refuses raw values laid over them.
describe("inline styles in TSX", () => {
it("fails a colour or a scale value written by hand", () => {
expect(
inlineStyleFailures({
file: "probe.tsx",
source: `<Button style={{ color: "red", padding: 13, borderRadius: "4px", zIndex: 5 }} />`,
}),
).toEqual([
'probe.tsx style color: "red" is written by hand; read a token or use a primitive variant',
"probe.tsx style padding: 13 is written by hand; read a token or use a primitive variant",
'probe.tsx style borderRadius: "4px" is written by hand; read a token or use a primitive variant',
"probe.tsx style zIndex: 5 is written by hand; read a token or use a primitive variant",
]);
});
it("judges the scale values as UI-06 does, and every colour property", () => {
expect(
inlineStyleFailures({
file: "probe.tsx",
source: `<div style={{ margin: "0 auto", zIndex: -1, lineHeight: 1, borderTopColor: "red", fontWeight: 700 }} />`,
}),
).toEqual([
'probe.tsx style borderTopColor: "red" is written by hand; read a token or use a primitive variant',
"probe.tsx style fontWeight: 700 is written by hand; read a token or use a primitive variant",
]);
});
it("passes token reads, keywords, zero and layout", () => {
expect(
inlineStyleFailures({
file: "probe.tsx",
source:
"<div style={{ backgroundColor: `var(${token})`, color: \"currentColor\", margin: 0, padding: \"var(--space-2)\", gridColumn: \"1 / 3\", width: 120 }} />",
}),
).toEqual([]);
});
});
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 edit("src/presentation/styles/theme/shell.css", "z-index: var(--layer-navigation);", "z-index: 50;");
await edit(
"src/presentation/design-system/tokens/component.css",
" --drawer-width:",
" --probe-unlisted: 1px;\n --drawer-width:",
);
await writeFile(
path.join(root, "src/presentation/styles/theme/probe.css"),
".probe { color: color-mix(in oklch, red, blue); }\n",
);
await mkdir(path.join(root, "src/features/probe"), { recursive: true });
await writeFile(
path.join(root, "src/features/probe/probe.css"),
[
".probe-a { color: #ff0000; }",
".probe-b { background: linear-gradient(in oklch, var(--color-action), var(--color-panel)); }",
".probe-c:focus-visible { outline-offset: 0; }",
":root { --font-sans: serif; }",
"",
].join("\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\/styles\/theme\/shell\.css:\d+ z-index: 50 writes 50 by hand; read a token \(docs\/styling\/design-tokens\.md UI-06\)$/,
/^semantic token --layer-navigation is defined but no style reads it$/,
/^src\/features\/probe\/probe\.css color: #ff0000 is a raw colour; read a colour token$/,
/^src\/features\/probe\/probe\.css mixes colours in oklch; use oklab$/,
/^src\/features\/probe\/probe\.css outline-offset: 0 draws the focus ring on the control; UI-01 measures it against the surface around the control$/,
/^src\/features\/probe\/probe\.css redefines the token --font-sans; change it in the token files$/,
/^src\/presentation\/design-system\/tokens\/component\.css defines --probe-unlisted, which REQUIRED_COMPONENT_TOKENS in token-contract\.ts does not list$/,
/^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 });
}
});
// REV-FE-0002. check:design-system:fixture passes on exit 1 and the header,
// which one rejected file gives. Each forbidden fixture is rejected by the
// one rule it is for, and a file no rule rejects makes the script exit 2,
// so a rule dropped from the TSX loop fails here and in FE-GATE-029.
describe("check-design-system.ts --fixture", () => {
const fixtures = "tests/fixtures/design-system/forbidden";
const runFixtureMode = async (extra?: { file: string; source: string }) => {
const root = await mkdtemp(path.join(tmpdir(), "design-system-fixture-"));
try {
for (const folder of ["src/presentation/design-system/tokens", "src/presentation/styles", fixtures]) {
await cp(folder, path.join(root, folder), { recursive: true });
}
if (extra) await writeFile(path.join(root, fixtures, extra.file), extra.source);
const result = spawnSync(process.execPath, [path.resolve("scripts/check-design-system.ts"), "--fixture"], {
cwd: root,
encoding: "utf8",
});
const { failures } = JSON.parse(
await readFile(path.join(root, "artifacts/quality/design-system-fixture.json"), "utf8"),
) as { failures: string[] };
return { status: result.status, stderr: result.stderr, failures };
} finally {
await rm(root, { recursive: true, force: true });
}
};
it("rejects every forbidden fixture by its own rule", async () => {
const { status, stderr, failures } = await runFixtureMode();
expect(status, stderr).toBe(1);
expect(stderr).toContain("Design system contract failed:");
expect([...failures].sort()).toEqual(
[
`${fixtures}/hue-mix.tsx mixes colours in hsl; use oklab`,
`${fixtures}/raw-inline-style.tsx style color: "red" is written by hand; read a token or use a primitive variant`,
`${fixtures}/raw-inline-style.tsx style padding: 13 is written by hand; read a token or use a primitive variant`,
`direct headless vendor import in ${fixtures}/headless-vendor-import.tsx`,
`raw palette value in ${fixtures}/raw-palette.tsx`,
].sort(),
);
});
it("exits 2 when a fixture file is not rejected", async () => {
const { status, stderr } = await runFixtureMode({
file: "probe.tsx",
source: 'export function Probe() {\n return <p className="probe">reads tokens</p>;\n}\n',
});
expect(status, stderr).toBe(2);
expect(stderr).toBe(`Design system fixture was not rejected:\n${fixtures}/probe.tsx\n`);
});
});
});