Files
clean-architecture-frontend…/scripts/check-design-system.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

203 lines
6.7 KiB
TypeScript

import { mkdir, readFile, readdir } from "node:fs/promises";
import { designSystemReportArtifactSchema } from "./contracts/release-artifacts.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
import path from "node:path";
import {
PRODUCT_LOADED_FONT_FAMILIES,
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,
rawStyleValueFailures,
undeclaredComponentTokenFailures,
unreadTokenFailures,
} from "./lib/design-system-rules.ts";
import { readCustomProperties } from "./lib/oklch-contrast.ts";
const fixtureMode = process.argv.includes("--fixture");
const failures: string[] = [];
const tokenFiles = {
primitive: "src/presentation/design-system/tokens/primitive.css",
semantic: "src/presentation/design-system/tokens/semantic.css",
component: "src/presentation/design-system/tokens/component.css",
};
const tokenLayers: Array<readonly [string, string, readonly string[]]> = [
["primitive", tokenFiles.primitive, REQUIRED_PRIMITIVE_TOKENS],
["semantic", tokenFiles.semantic, REQUIRED_SEMANTIC_TOKENS],
["component", tokenFiles.component, REQUIRED_COMPONENT_TOKENS],
];
for (const [layer, file, tokens] of tokenLayers) {
const source = await readFile(file, "utf8");
for (const token of tokens) {
if (!source.includes(`${token}:`)) {
failures.push(`${layer} token is missing: ${token}`);
}
}
}
// theme.css only imports the files under styles/theme/, so check them all.
const styleFiles = (
await readdir("src/presentation/styles", { recursive: true })
)
.filter((file) => file.endsWith(".css"))
.map((file) => path.join("src/presentation/styles", file));
const cssSources = await Promise.all(
[...Object.values(tokenFiles), ...styleFiles].map(
async (file) => ({ file, source: await readFile(file, "utf8") }),
),
);
const definitions = new Set(
cssSources.flatMap(({ source }) =>
[...source.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((match) => match[1]),
),
);
for (const { file, source } of cssSources) {
for (const match of source.matchAll(/var\((--[a-z0-9-]+)/g)) {
if (!definitions.has(match[1])) {
failures.push(`${file} uses undefined token ${match[1]}`);
}
}
failures.push(...hueMixFailures({ file, source }));
if (styleFiles.includes(file)) failures.push(...rawStyleValueFailures({ file, source }));
}
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] ??
"";
for (const token of [
"--color-surface",
"--color-surface-muted",
"--color-surface-elevated",
"--color-content",
"--color-content-muted",
"--color-content-inverse",
"--color-border",
"--color-border-strong",
"--color-action",
"--color-action-hover",
"--color-action-pressed",
"--color-danger",
"--color-focus",
"--color-disabled-content",
"--color-disabled-surface",
]) {
if (!darkSource.includes(`${token}:`)) {
failures.push(`dark theme token is missing: ${token}`);
}
}
const lightProperties = new Map([
...readCustomProperties(await readFile(tokenFiles.primitive, "utf8")),
...readCustomProperties(semanticSource.split(':root[data-theme="dark"]')[0]),
]);
const darkProperties = new Map([
...lightProperties,
...readCustomProperties(darkSource),
]);
// Rule texts and reasons: scripts/lib/design-system-rules.ts.
failures.push(
...focusContrastFailures("light", lightProperties),
...focusContrastFailures("dark", darkProperties),
...unreadTokenFailures(
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,
PRODUCT_LOADED_FONT_FAMILIES,
),
);
const componentSource = await readFile(tokenFiles.component, "utf8");
if (!componentSource.includes("@media (forced-colors: active)")) {
failures.push("forced-colors token fallback is missing");
}
async function listSourceFiles(directory: string): Promise<string[]> {
const result: string[] = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) result.push(...(await listSourceFiles(target)));
else if (/\.(?:ts|tsx|mts|cts)$/.test(entry.name)) result.push(target);
}
return result;
}
const sources = fixtureMode
? await listSourceFiles("tests/fixtures/design-system/forbidden")
: await listSourceFiles("src");
for (const file of sources) {
const source = await readFile(file, "utf8");
// Icon vendor and design-system deep imports are graph rules in
// .dependency-cruiser.json (check:architecture), which also sees relative,
// dynamic and type imports (12-08, 12-10).
if (
/from\s+["'](?:react-aria-components|@radix-ui\/[^"']+)["']/.test(source)
) {
failures.push(`direct headless vendor import in ${file}`);
}
if (
!file.includes("src/presentation/design-system/tokens/") &&
/(?:#[0-9a-f]{3,8}\b|oklch\(|rgba?\()/i.test(source)
) {
failures.push(`raw palette value in ${file}`);
}
if (
file.includes("tests/fixtures/design-system/forbidden") &&
source.includes("TOOLTIP_ONLY_REQUIRED_INFORMATION")
) {
failures.push(`tooltip-only required information in ${file}`);
}
}
const report = designSystemReportArtifactSchema.parse({
schemaVersion: 1,
mode: fixtureMode ? "negative-fixture" : "source",
checkedTokenCount:
REQUIRED_PRIMITIVE_TOKENS.length +
REQUIRED_SEMANTIC_TOKENS.length +
REQUIRED_COMPONENT_TOKENS.length,
failures,
passed: failures.length === 0,
});
await mkdir("artifacts/quality", { recursive: true });
await writeValidatedJsonArtifact({
path: fixtureMode
? "artifacts/quality/design-system-fixture.json"
: "artifacts/quality/design-system.json",
schema: designSystemReportArtifactSchema,
value: report,
});
if (failures.length > 0) {
process.stderr.write(`Design system contract failed:\n${failures.join("\n")}\n`);
process.exit(1);
}
process.stdout.write(
`Design system contract: ${report.checkedTokenCount} tokens and headless vendor boundary PASS\n`,
);