Merge pull request 'fix(design-system): 스타일·토큰·story·검사를 토큰 계약에 맞춘다' (#56) from donghyeon.kang/fix/r9-design-tokens-stories into main
frontend-quality-gates / merge / static checks (push) Successful in 1m12s
frontend-quality-gates / merge / tests (push) Failing after 10m10s
frontend-quality-gates / merge / browser tests (push) Successful in 6m1s
frontend-quality-gates / FE-GATE-017 / diagram-review (push) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (push) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (push) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (push) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (push) Skipped
frontend-quality-gates / external-vulnerability-provider (push) Skipped
frontend-quality-gates / external-provenance-provider (push) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (push) Skipped
frontend-quality-gates / deploy-promoted-release (push) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (push) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (push) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (push) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (push) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (push) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (push) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (push) Skipped
frontend-quality-gates / main / self-tests and removal drills (push) Failing after 2m3s

This commit was merged in pull request #56.
This commit is contained in:
2026-11-13 19:13:49 +00:00
34 changed files with 1486 additions and 281 deletions
+45 -5
View File
@@ -9,11 +9,19 @@ import {
REQUIRED_COMPONENT_TOKENS,
REQUIRED_PRIMITIVE_TOKENS,
REQUIRED_SEMANTIC_TOKENS,
SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER,
} from "../src/presentation/design-system/tokens/token-contract.ts";
import {
firstFontFamilyFailures,
focusContrastFailures,
hueMixFailures,
rawSemanticColourFailures,
focusOffsetFailures,
inlineStyleFailures,
rawStyleValueFailures,
styleSheetColourFailures,
tokenRedefinitionFailures,
undeclaredComponentTokenFailures,
unreadTokenFailures,
} from "./lib/design-system-rules.ts";
import { readCustomProperties } from "./lib/oklch-contrast.ts";
@@ -40,12 +48,14 @@ for (const [layer, file, tokens] of tokenLayers) {
}
}
// theme.css only imports the files under styles/theme/, so check them all.
const styleFiles = (
await readdir("src/presentation/styles", { recursive: true })
)
// Every style sheet under src/, not only the ones theme.css imports: a
// feature's own CSS is a style sheet too (1101/12-03).
const tokenFileSet = new Set<string>(Object.values(tokenFiles));
const styleFiles = (await readdir("src", { recursive: true }))
.filter((file) => file.endsWith(".css"))
.map((file) => path.join("src/presentation/styles", file));
.map((file) => path.join("src", file))
.filter((file) => !tokenFileSet.has(file))
.sort();
const cssSources = await Promise.all(
[...Object.values(tokenFiles), ...styleFiles].map(
async (file) => ({ file, source: await readFile(file, "utf8") }),
@@ -63,9 +73,27 @@ for (const { file, source } of cssSources) {
}
}
failures.push(...hueMixFailures({ file, source }));
if (!tokenFileSet.has(file)) {
failures.push(
...rawStyleValueFailures({ file, source }),
...styleSheetColourFailures({ file, source }),
...focusOffsetFailures({ file, source }),
);
}
}
const tokenNames = new Set(
cssSources
.filter(({ file }) => tokenFileSet.has(file))
.flatMap(({ source }) => [...source.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((match) => match[1])),
);
for (const { file, source } of cssSources) {
if (!tokenFileSet.has(file)) failures.push(...tokenRedefinitionFailures({ file, source }, tokenNames));
}
const semanticSource = await readFile(tokenFiles.semantic, "utf8");
failures.push(
...rawSemanticColourFailures({ file: tokenFiles.semantic, source: semanticSource }),
);
const darkSource =
semanticSource.match(/:root\[data-theme="dark"\]\s*\{([\s\S]*?)\n\}/)?.[1] ??
"";
@@ -106,6 +134,17 @@ failures.push(
REQUIRED_COMPONENT_TOKENS,
cssSources.filter(({ file }) => file !== tokenFiles.component),
),
...unreadTokenFailures(
REQUIRED_SEMANTIC_TOKENS.filter(
(token) => !SEMANTIC_TOKENS_WITHOUT_TEMPLATE_READER.includes(token),
),
cssSources.filter(({ file }) => file !== tokenFiles.semantic),
"semantic",
),
...undeclaredComponentTokenFailures(
{ file: tokenFiles.component, source: await readFile(tokenFiles.component, "utf8") },
REQUIRED_COMPONENT_TOKENS,
),
...firstFontFamilyFailures(
lightProperties.get("--font-sans") ?? "",
cssSources,
@@ -147,6 +186,7 @@ for (const file of sources) {
) {
failures.push(`raw palette value in ${file}`);
}
failures.push(...hueMixFailures({ file, source }), ...inlineStyleFailures({ file, source }));
if (
file.includes("tests/fixtures/design-system/forbidden") &&
source.includes("TOOLTIP_ONLY_REQUIRED_INFORMATION")
+150 -8
View File
@@ -1,5 +1,5 @@
// The four CSS rules scripts/check-design-system.ts runs over the token
// files and src/presentation/styles/**. Each rule takes file contents and
// The CSS rules scripts/check-design-system.ts runs over the token files and
// the style sheets. Each rule takes file contents and
// returns failure messages, so a test can hand it a violation directly.
import { contrastRatio, resolveColor, resolveValue } from "./oklch-contrast.ts";
@@ -9,11 +9,12 @@ export interface CssSource {
readonly source: string;
}
// Comments keep old code around, and the browser never draws it.
// Comments keep old code around, and the browser never draws it. They turn
// into spaces, newlines kept, so a reported line number stays the file's.
// Limit: a "/*" inside a quoted string would start a false comment. No
// CSS here has one; switch to a CSS tokenizer if that changes.
function withoutComments(css: string): string {
return css.replace(/\/\*[\s\S]*?\*\//g, "");
return css.replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, " "));
}
// UI-01. The focus ring is drawn 3px away from its control, so the colour
@@ -63,10 +64,13 @@ export function focusContrastFailures(
// stop such as oklch(1 0 0) carries hue 0: 14% blue into white came out
// pink. oklab mixes on straight lines and has no hue to drag. CSS
// function names and keywords ignore ASCII case, so OKLCH counts too.
// A gradient interpolates the same way (`linear-gradient(90deg in oklch,
// …)`), and an inline style in TSX is CSS too (1101/12-03).
const HUE_MIX =
/(?:color-mix\(\s*|(?:repeating-)?(?:linear|radial|conic)-gradient\([^,()]*?)\bin\s+(oklch|lch|hsl|hwb)\b/gi;
export function hueMixFailures({ file, source }: CssSource): string[] {
const mixes = withoutComments(source).matchAll(
/color-mix\(\s*in\s+(oklch|lch|hsl|hwb)\b/gi,
);
const mixes = withoutComments(source).matchAll(HUE_MIX);
return [...mixes].map((match) => `${file} mixes colours in ${match[1]}; use oklab`);
}
@@ -79,6 +83,7 @@ export function hueMixFailures({ file, source }: CssSource): string[] {
export function unreadTokenFailures(
tokens: readonly string[],
styles: readonly CssSource[],
layer: "component" | "semantic" = "component",
): string[] {
const read = new Set(
styles.flatMap(({ source }) =>
@@ -88,7 +93,26 @@ export function unreadTokenFailures(
);
return tokens
.filter((token) => !read.has(token))
.map((token) => `component token ${token} is defined but no style reads it`);
.map((token) => `${layer} token ${token} is defined but no style reads it`);
}
// UI-03 (contract). A component token outside REQUIRED_COMPONENT_TOKENS is
// outside UI-03 too: the reader check only walks the contract list, so a
// token defined in component.css and read by nothing passed (1112/04-12).
// Only the @theme block counts: the forced-colors block redefines semantic
// roles, not component tokens.
export function undeclaredComponentTokenFailures(
{ file, source }: CssSource,
contract: readonly string[],
): string[] {
const theme = /@theme\s*\{([\s\S]*?)\n\}/.exec(withoutComments(source))?.[1] ?? "";
return [...theme.matchAll(/(--[a-z0-9-]+)\s*:/g)]
.map((match) => match[1])
.filter((token) => !contract.includes(token))
.map(
(token) =>
`${file} defines ${token}, which REQUIRED_COMPONENT_TOKENS in token-contract.ts does not list`,
);
}
// UI-05. --font-sans named Inter first, but nothing loads Inter, so most
@@ -126,3 +150,121 @@ export function firstFontFamilyFailures(
`--font-sans starts with "${first}", which is neither a generic family, loaded by @font-face, nor listed in PRODUCT_LOADED_FONT_FAMILIES`,
];
}
// UI-07. The semantic layer names roles and reads its colours from the
// palette in primitive.css. A colour written straight into semantic.css is
// out of reach of a rebrand that edits the palette: 36 such values kept the
// status colours, the focus ring and most of the dark theme as they were
// (1112/04-13).
const RAW_COLOUR = /#[0-9a-f]{3,8}\b|\b(?:oklch|oklab|lch|lab|rgba?|hsla?|hwb|color)\(/i;
export function rawSemanticColourFailures({ file, source }: CssSource): string[] {
return [...withoutComments(source).matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/gi)]
.filter((match) => RAW_COLOUR.test(match[2]))
.map(
(match) =>
`${file} ${match[1]} is the raw colour ${match[2].trim()}; name it in primitive.css and read it with var()`,
);
}
// UI-06. A style that writes a spacing, type, radius, layer or shadow value
// by hand does not move when the token does: changing --space-*, --layer-*,
// --elevation-panel or --radius-modal left the shell, the page templates and
// the cards as they were (1112/04-08). Allowed: a token read (var()), 0,
// auto, keywords, %, viewport units, a 1px hairline in margin or padding,
// line-height 1, z-index 0 or -1, and em sizes relative to the parent font.
const LENGTH = /(?<![\w.-])-?(?:\d+\.?\d*|\.\d+)(?:px|rem|em)\b/g;
const NUMBER = /(?<![\w.(-])-?(?:\d+\.?\d*|\.\d+)(?![\w.%])/g;
const SPACING_PROPERTY =
/^(?:padding|margin)(?:-(?:top|right|bottom|left|block|inline)(?:-(?:start|end))?)?$|^(?:row-|column-)?gap$/;
function handWrittenValues(property: string, value: string): string[] {
const tokensRemoved = value.replace(/var\([^)]*\)/g, "");
const lengths = tokensRemoved.match(LENGTH) ?? [];
const numbers = tokensRemoved.replace(LENGTH, "").match(NUMBER) ?? [];
if (SPACING_PROPERTY.test(property)) return lengths.filter((length) => !["1px", "-1px"].includes(length));
if (property === "font-size") return lengths.filter((length) => !/(?<!r)em$/.test(length));
if (property === "font-weight") return numbers;
if (property === "line-height") return [...lengths, ...numbers].filter((item) => item !== "1");
if (/^border(?:-[a-z]+)*-radius$/.test(property)) return lengths;
if (property === "z-index") return numbers.filter((item) => !["0", "-1"].includes(item));
if (property === "box-shadow") return [...lengths, ...numbers];
return [];
}
export function rawStyleValueFailures({ file, source }: CssSource): string[] {
const css = withoutComments(source);
const failures: string[] = [];
for (const match of css.matchAll(/(?<![\w-])([a-z-]+)\s*:\s*([^;{}]+);/g)) {
const [, property, value] = match;
const raw = handWrittenValues(property, value);
if (raw.length === 0) continue;
const line = css.slice(0, match.index).split("\n").length;
failures.push(
`${file}:${line} ${property}: ${value.trim()} writes ${raw.join(", ")} by hand; read a token (docs/styling/design-tokens.md UI-06)`,
);
}
return failures;
}
// Outside the token files a style reads colours, it does not define them.
// 1101/12-03: a raw colour in a feature's own CSS, a token redefined under
// :root in a style sheet (the token file then no longer decides it), and a
// focus ring drawn with no offset (UI-01 measures the ring against the
// surface around the control, not against the control) all passed.
export function styleSheetColourFailures({ file, source }: CssSource): string[] {
return [...withoutComments(source).matchAll(/(?<![\w-])([a-z-]+)\s*:\s*([^;{}]+);/g)]
.filter((match) => !match[1].startsWith("--") && RAW_COLOUR.test(match[2]))
.map((match) => `${file} ${match[1]}: ${match[2].trim()} is a raw colour; read a colour token`);
}
export function tokenRedefinitionFailures(
{ file, source }: CssSource,
tokens: ReadonlySet<string>,
): string[] {
return [...withoutComments(source).matchAll(/(?<![\w-])(--[a-z0-9-]+)\s*:/g)]
.filter((match) => tokens.has(match[1]))
.map((match) => `${file} redefines the token ${match[1]}; change it in the token files`);
}
export function focusOffsetFailures({ file, source }: CssSource): string[] {
return [...withoutComments(source).matchAll(/outline-offset\s*:\s*([^;{}]+);/g)]
.filter((match) => /^(?:-|0(?:\.0*)?(?:px|rem|em)?\s*$)/.test(match[1].trim()))
.map(
(match) =>
`${file} outline-offset: ${match[1].trim()} draws the focus ring on the control; UI-01 measures it against the surface around the control`,
);
}
// 1112/04-14 (decision 2026-11-12). Primitives keep `className` and `style`
// open, so a screen can lay a raw colour or spacing over a primitive. An
// inline style may place things and read tokens; a colour or a spacing,
// type, radius, layer or shadow value written by hand is refused.
// The scale values are judged as UI-06 judges a style sheet: an inline
// style is the same declaration written in camelCase, and React writes a bare
// number as px except for the unitless properties.
const INLINE_COLOUR_KEYWORDS = new Set(["transparent", "currentcolor", "inherit", "initial", "unset", "none"]);
const INLINE_COLOUR_PROPERTY = /^(?:color|background|fill|stroke)$|Color$/;
const INLINE_UNITLESS = new Set(["zIndex", "fontWeight", "lineHeight", "opacity", "flex", "flexGrow", "flexShrink", "order"]);
export function inlineStyleFailures({ file, source }: CssSource): string[] {
const failures: string[] = [];
for (const style of source.matchAll(/style=\{\{([\s\S]*?)\}\}/g)) {
for (const entry of style[1].matchAll(/([A-Za-z]+)\s*:\s*(`[^`]*`|"[^"]*"|'[^']*'|-?[\d.]+)/g)) {
const [, property, written] = entry;
const value = written.replace(/^[`"']|[`"']$/g, "").trim();
const colour =
INLINE_COLOUR_PROPERTY.test(property) &&
!/^var\(/.test(value) &&
!INLINE_COLOUR_KEYWORDS.has(value.toLowerCase());
const css =
/^-?[\d.]+$/.test(written) && !INLINE_UNITLESS.has(property) && Number(value) !== 0 ? `${value}px` : value;
const scale =
handWrittenValues(property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`), css).length > 0;
if (colour || scale) {
failures.push(`${file} style ${property}: ${written} is written by hand; read a token or use a primitive variant`);
}
}
}
return failures;
}
+19
View File
@@ -297,6 +297,25 @@ class SkillTest(unittest.TestCase):
self.assertNotIn("코드 안 제목", names)
self.assertFalse(any(name.startswith("목록 줄") for name in names))
# A token name in a skill that the token files do not define sends a reviewer to make a second copy:
# fe-design-system once asked for `--icon-size-*`, and the tokens are `--size-icon-*`.
TOKEN_NAMESPACES = ("color", "space", "spacing", "font", "line", "radius", "shadow", "duration", "easing", "size",
"icon", "breakpoint", "container", "elevation", "layer", "opacity", "palette", "button",
"field", "dialog", "navigation", "drawer", "toast")
def test_every_token_a_skill_names_is_a_defined_token(self) -> None:
tokens = REPO / "src/presentation/design-system/tokens"
defined = {match for css in tokens.glob("*.css")
for match in re.findall(r"(--[a-z0-9-]+)\s*:", css.read_text(encoding="utf-8"))}
self.assertIn("--size-icon-md", defined)
for path in sorted((CLAUDE / "skills").glob("*/SKILL.md")):
for name in re.findall(r"`(--[a-z0-9*-]+)`", path.read_text(encoding="utf-8")):
if name[2:].split("-")[0] not in self.TOKEN_NAMESPACES:
continue
pattern = re.compile("^" + re.escape(name).replace(r"\*", "[a-z0-9-]+") + "$")
self.assertTrue(any(pattern.match(token) for token in defined),
f"{path.parent.name}: `{name}` names no token in {tokens.relative_to(REPO)}")
def test_each_skill_points_at_its_canonical_playbook_instead_of_copying_it(self) -> None:
for name, canon in self.CANON.items():
body = (CLAUDE / "skills" / name / "SKILL.md").read_text(encoding="utf-8")