ui / scripts / design-tokens.test.tsmain at d68d7e1
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { expect, test } from "vitest";
// The look's values live in the token files (src/styles/AGENTS.md):
// a colour is a named token (`text-success`, `bg-warning/10`), and a text size is a step of the
// type scale (`text-2xs` to `text-2xl`). This test reads the kit's source as text,
// so it covers class strings, inline styles and stylesheets alike. No AST: a regex per line, with
// comment lines skipped.
const repoRoot = resolve(import.meta.dirname, "..");
const SOURCE = /^src\/.+\.(tsx?|css|html)$/;
const ALLOWED = [
// the token files: where the values are written
/^src\/styles\//,
// shadcn's components, vendored byte for byte (scripts/shadcn-drift.ts)
/\/components\/ui\//,
// tests assert on what the browser computed
/\.(test|spec)\.tsx?$/,
];
// Files whose colours are not the page's look.
const EXCEPTIONS = [
{
file: "src/components/log-in-with-iterate.tsx",
why: "a sign-in button for other people's sites: one look, whatever the host page's theme",
},
];
const PALETTE =
/(?<![\w-])(?:[a-z-]+:)*[a-z-]+-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|[1-9]00|950)(?:\/\d+)?(?![\w-])/g;
const HEX = /(?<![\w/&-])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])/gi;
const ARBITRARY_SIZE = /(?<![\w-])text-\[(?:length:)?[\d.]+(?:px|r?em)\]|\[font-size:[^\]]+\]/g;
test("colours are tokens and text sizes are steps of the scale", () => {
const files = execFileSync("git", ["ls-files"], { cwd: repoRoot, encoding: "utf8" })
.split("\n")
.filter(
(file) =>
SOURCE.test(file) &&
!ALLOWED.some((pattern) => pattern.test(file)) &&
!EXCEPTIONS.some((exception) => exception.file === file),
);
const found = files.flatMap((file) =>
readFileSync(resolve(repoRoot, file), "utf8")
.split("\n")
.flatMap((line, index) => {
if (/^\s*(\/\/|\/?\*)/.test(line)) return [];
const hits = [
...[...line.matchAll(PALETTE)].map((m) => `raw palette class ${m[0]}`),
...[...line.matchAll(HEX)].map((m) => `hex colour ${m[0]}`),
...[...line.matchAll(ARBITRARY_SIZE)].map((m) => `arbitrary text size ${m[0]}`),
];
return hits.map((hit) => `${file}:${index + 1}: ${hit}`);
}),
);
expect(
found,
"Use a colour token (success, warning, info, destructive, chart-1…5, muted, …) or a step of the type scale (text-2xs … text-2xl). New values go in src/styles/ and the kernel's core/lib/src/theme/tokens.css.",
).toEqual([]);
});