返回 CodeWhale
whale-tokens.ts
根目录 / web / lib / whale-tokens.ts
1 import { readFileSync } from "node:fs";
2 import { siteCss } from "./site-css";
3
4 /**
5 * The design palette as the site actually resolves it.
6 *
7 * `app/tokens.css` is generated by `scripts/export-design-tokens.py` from
8 * the terminal palette and the vendored GPUI semantic design artifact
9 * (the latter supplies `--gpui-dark-*` / `--gpui-light-*`), and `app/styles/tokens-roles.css`
10 * carries the hand-kept `--gpui-*` aliases over them. Site variables state
11 * which token each uses (`--paper: var(--gpui-paper)`) instead of repeating
12 * the hex. The contract tests still need the literal color to check parity
13 * and contrast, so this reads both files and flattens the alias chains
14 * (`--whale-success` -> `--whale-working-green` -> `#9bd66f`,
15 * `--paper` -> `--gpui-paper` -> `--gpui-light-bg` -> `#faf8f5`). The Blue Stage light preset's
16 * `LIGHT_*` consts export as `--light-*` beside them, and the Shoreline
17 * redesign's dark/light pair exports as `--shoreline-*` /
18 * `--shoreline-light-*`.
19 *
20 * Node-only (`node:fs`): imported by the contract tests, never by a component.
21 */
22 const RAW: Record<string, string> = (() => {
23 const generated = readFileSync(new URL("../app/tokens.css", import.meta.url), "utf8");
24 const globals = siteCss();
25 const raw: Record<string, string> = {};
26 for (const match of generated.matchAll(/--((?:whale|light|shoreline-light|shoreline|gpui)-[\w-]+):\s*([^;]+);/g)) {
27 raw[match[1]] = match[2].trim();
28 }
29 for (const match of globals.matchAll(/--((?:gpui|ocean|brand|sea|tide)-[\w-]+):\s*([^;]+);/g)) {
30 raw[match[1]] = match[2].trim();
31 }
32 if (Object.keys(raw).length === 0) {
33 throw new Error("no palette properties found in tokens.css/styles");
34 }
35 return raw;
36 })();
37
38 function flatten(name: string, seen = new Set<string>()): string {
39 const value = RAW[name];
40 if (value === undefined) throw new Error(`Unknown design token: --${name}`);
41 const alias = value.match(/^var\(--([\w-]+)\)$/);
42 if (!alias) return value;
43 if (seen.has(name)) throw new Error(`Cyclic design token alias: --${name}`);
44 return flatten(alias[1], seen.add(name));
45 }
46
47 /** Resolve a `var(--whale-*)`, `var(--light-*)`, `var(--shoreline-*)`, `var(--gpui-*)`, `var(--ocean-*)` or `var(--brand-*)` reference to its literal value; pass anything else through. */
48 export function resolveWhale(value: string): string {
49 const match = value.match(/^var\(--((?:whale|light|shoreline-light|shoreline|gpui|ocean|brand|sea|tide)-[\w-]+)\)$/);
50 return match ? flatten(match[1]) : value;
51 }
52
52 lines TYPESCRIPT