Files
clean-architecture-frontend…/tests/unit/design-system-rules.test.ts
T
DongHyeonka 838ed410f7 fix(styles): 스타일이 간격·글자·층·그림자 토큰을 읽고 검사가 날 값을 거절한다
셸·페이지 템플릿·카드 CSS가 간격·글자·반경·층·그림자 토큰을 건너뛰고 날
값을 쓴다(`src/presentation/styles/theme/*.css`에서 규칙에 걸리는 선언
118개). `shell.css`·`pages.css`·`templates.css`는 `var(--space-*)`를 한
번도 쓰지 않았고, z-index 100·30·10, 카드·헤더의 손 그림자, `999px`,
`min-height: 2.75rem`이 토큰과 같은 값을 다시 적었다. 필수 semantic 토큰
가운데 `--layer-navigation`·`--layer-modal`·`--opacity-scrim`·
`--opacity-skeleton`·`--elevation-panel`·`--color-disabled-content`·
`--color-action-pressed`를 읽는 스타일이 없었다. 그래서 파생 서비스가
밀도·층·그림자를 토큰으로 바꿔도 화면이 그대로다. 그리고 component.css의
가림막 토큰 셋이 `REQUIRED_COMPONENT_TOKENS`에 없어 UI-03 밖이었다(04-12).

고른 방법:
- 날 값을 토큰으로 바꾼다. 맞는 단계가 없는 간격은 가까운 `--space-*`로
  반올림했다(0.15~0.35rem → 1, 0.4~0.55 → 2, 0.65~0.85 → 3, 0.9 → 4).
  큰 값 3.5rem·4rem은 `--space-14`·`--space-16`을 더했다. 글자 크기도
  가까운 단계(0.8 → xs, 0.8125~0.9 → sm, 1.05 → md, 1.1 → lg, 1.35 → xl),
  굵기 600·650 → semibold, 700·750·800 → bold, 줄 높이 1.5~1.6 → normal,
  1.65·1.7 → relaxed. 페이지 h1은 semantic `--font-size-heading-1`·
  `--line-height-heading-1`(새 primitive 단계 3xl·4xl·compact)을 읽는다.
- 층: skip link는 `--layer-navigation`, sticky 헤더와 sticky 폼 버튼은
  `--layer-sticky`. 그림자: 카드·패널·갤러리 안내는 `--elevation-panel`,
  헤더는 새 `--elevation-sticky`(`--shadow-sticky`). `.ui-panel`의 Tailwind
  `shadow-sm`도 `--elevation-panel`로 바꿔 카드와 같은 높이가 됐다. dialog는
  `--radius-modal`, 가림막 비율은 `--opacity-scrim`을 읽고
  `--dialog-backdrop-weight`는 지웠다.
- 읽는 곳이 없던 semantic 토큰: skeleton 깜박임이 `--opacity-skeleton`,
  꺼진 입력이 `--color-disabled-content`·`--color-disabled-surface`, 누른
  primary 버튼이 새 component 토큰 `--button-primary-pressed`
  (`--color-action-pressed`)를 읽는다. `--layer-modal`은 native `<dialog>`가
  top layer에 열려 z-index가 닿지 않으므로 이유와 함께
  `SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER`에 둔다.
- `check:design-system`에 셋을 더한다. UI-06: styles 아래 간격·글자·반경·
  z-index·그림자의 날 값을 줄 번호와 함께 거절한다. UI-03을 필수 semantic
  토큰으로 넓힌다. component.css `@theme`의 토큰이 모두 계약에 있어야 한다.
  계약에 `--button-primary-pressed`, `--dialog-backdrop`,
  `--dialog-backdrop-on-surface`를 더했다.
- 버린 대안: 맞는 단계가 없는 값마다 primitive 단계를 더하기(단계가 두 배로
  늘어 scale이 무의미해진다). `--layer-modal`을 dialog에 z-index로 읽히기
  (top layer에서는 효과가 없는 가짜 읽기다).

위험·한계: 반올림과 패널 그림자 때문에 화면이 조금 바뀐다(간격 최대
0.15rem, 굵기 800 → 750, 패널 그림자 크기). 시각 골든은 이 커밋에서 다시
찍고 차이를 PR 본문에 적는다. 다운스트림이 styles에 날 값을 더해 두었으면
UI-06이 그 줄을 알린다. 너비·높이·위치(top 등)와 opacity는 UI-06 밖이다.

검증: 규칙 단위 시험과 check-design-system 연결 시험, 새 검사기로 고치기
전 CSS를 돌린 결과(RED), 시각 골든은 desktop에서 돌려 PR 본문에 적는다.

Refs: 1112/04-08, 1112/04-12
2026-11-13 23:27:47 +09:00

326 lines
14 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,
rawStyleValueFailures,
undeclaredComponentTokenFailures,
unreadTokenFailures,
} from "../../scripts/lib/design-system-rules.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}`,
]);
});
});
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",
]);
});
});
// 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([]);
});
});
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",
);
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\/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 });
}
});
});