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, tokenRedefinitionFailures, 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", ]); }); // 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: ``, }), ).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: `
`, }), ).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: "", }), ).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 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 }); } }); });