ShtukbaseStandard
包文件→ .shtukbase/packages/design-tokens/lib/contract.ts

lib/contract.ts

161 行, 8.6 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // The token contract v1: which CSS custom properties a style must define, which of them need a dark value, and the
  2. // defaults of the optional extension. Other design packages call this file: `readContract`, `styleChoice`,
  3. // `styleCssPath`, `checkCss`, `fallbacks`, `defaultsCss`. The working directory is the project root.
  4. // The contract data is `lib/contract.json`; its copy `pages/design/contract.json` is what a project gets and may
  5. // extend (a project's own `/design/contract.json` wins when it is valid). Bun only, no dependencies.
  6. import { existsSync, readFileSync } from 'node:fs';
  7. import { join } from 'node:path';
  8. import { parseCss, resolveVars, themeOf } from '../../design-base/lib/css.ts';
  9. import { readPage } from '../../collections/checks/lib/pages.ts';
  10. import packaged from './contract.json';
  11. export const CONTRACT_PAGE = 'design/contract.json';
  12. export const DESIGN_PAGE = 'design/design.md';
  13. export type Contract = {
  14. version: number;
  15. /** Every name a style must define in `:root` (light), with the leading `--`. */
  16. required: string[];
  17. /** The required names that are colours: each needs a value in the dark scheme too. */
  18. colors: string[];
  19. /** Optional names with the default that applies when a style does not set them. */
  20. extension: Record<string, string>;
  21. };
  22. const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
  23. const names = (v: unknown): string[] | null =>
  24. Array.isArray(v) && v.every((x) => typeof x === 'string' && /^--[\w-]+$/.test(x)) ? (v as string[]) : null;
  25. /** A contract object, or the problem with it. */
  26. export function parseContract(data: unknown): { contract: Contract | null; problem: string | null } {
  27. if (!isObj(data)) return { contract: null, problem: 'the contract is not a JSON object' };
  28. const required = names(data.required);
  29. const colors = names(data.colors);
  30. if (typeof data.version !== 'number') return { contract: null, problem: 'the contract has no numeric "version"' };
  31. if (!required) return { contract: null, problem: '"required" is a list of names like --card' };
  32. if (!colors) return { contract: null, problem: '"colors" is a list of names like --card' };
  33. const stray = colors.filter((c) => !required.includes(c));
  34. if (stray.length) return { contract: null, problem: `"colors" names that are not required: ${stray.join(', ')}` };
  35. const ext = data.extension;
  36. if (!isObj(ext) || Object.entries(ext).some(([k, v]) => !/^--[\w-]+$/.test(k) || typeof v !== 'string' || !v.trim()))
  37. return { contract: null, problem: '"extension" is an object {--name: default CSS value}' };
  38. return { contract: { version: data.version, required, colors, extension: ext as Record<string, string> }, problem: null };
  39. }
  40. /** The contract of the project (`/design/contract.json`), else the one this package carries. */
  41. export function readContract(root = process.cwd()): Contract {
  42. const p = join(root, CONTRACT_PAGE);
  43. if (existsSync(p)) {
  44. try {
  45. const { contract } = parseContract(JSON.parse(readFileSync(p, 'utf8')));
  46. if (contract) return contract;
  47. } catch { /* a broken file: the packaged contract applies */ }
  48. }
  49. return parseContract(packaged).contract as Contract;
  50. }
  51. /** The project's choice on `/design/design.md`: the style id and the library ids ('' and [] when not chosen). */
  52. export function styleChoice(root = process.cwd()): { style: string; libraries: string[] } {
  53. const p = join(root, DESIGN_PAGE);
  54. const fm = existsSync(p) ? readPage(p).fm : {};
  55. const style = typeof fm.style === 'string' ? fm.style.trim() : '';
  56. const libraries = Array.isArray(fm.libraries) ? fm.libraries.map((x: unknown) => String(x).trim()).filter(Boolean) : [];
  57. return { style: /^[\w.-]+$/.test(style) ? style : '', libraries };
  58. }
  59. /** Project path of the built tokens of the chosen style (`design/<style>/tokens.css`), or null when none is chosen. */
  60. export function styleCssPath(root = process.cwd()): string | null {
  61. const { style } = styleChoice(root);
  62. return style ? `design/${style}/tokens.css` : null;
  63. }
  64. export type Scheme = Map<string, string>;
  65. /** The light scheme (`:root`, `@theme`) and the dark one (`.dark`, `[data-theme="dark"]`, prefers-color-scheme: dark), own declarations only. */
  66. export function schemes(css: string): { light: Scheme; dark: Scheme | null } {
  67. const light: Scheme = new Map();
  68. let dark: Scheme | null = null;
  69. for (const b of parseCss(css)) {
  70. if (b.parents.length) continue;
  71. const media = b.at.some((a) => /prefers-color-scheme\s*:\s*dark/.test(a));
  72. const own = b.decls.filter((d) => d.prop.startsWith('--'));
  73. const roots = new Set<string>();
  74. if (b.prelude.startsWith('@theme')) roots.add('base');
  75. for (const s of b.selectors) {
  76. const t = themeOf(s, media);
  77. if (t === 'base' || t === 'dark') roots.add(t);
  78. }
  79. if (roots.has('base')) for (const d of own) light.set(d.prop, d.value);
  80. if (roots.has('dark')) {
  81. dark ??= new Map();
  82. for (const d of own) dark.set(d.prop, d.value);
  83. }
  84. }
  85. return { light, dark };
  86. }
  87. /** Problems of a stylesheet against the contract (one line each; `where` names the file in the lines). */
  88. export function checkCss(css: string, where: string, contract: Contract): string[] {
  89. const out: string[] = [];
  90. const { light, dark } = schemes(css);
  91. for (const n of contract.required) if (!light.has(n)) out.push(`${where}: :root has no ${n}`);
  92. const colors = contract.colors.filter((n) => light.has(n));
  93. if (!dark) out.push(`${where}: no dark scheme (.dark, [data-theme="dark"]) — every colour needs a dark value`);
  94. else
  95. for (const n of contract.colors) {
  96. // light-dark() in the light value carries both values.
  97. if (!dark.has(n) && !/light-dark\(/.test(light.get(n) ?? '')) out.push(`${where}: the dark scheme has no ${n}`);
  98. }
  99. const scheme = (name: string, own: Scheme) => {
  100. const vars = new Map([...light, ...own]);
  101. for (const n of colors) {
  102. if (!own.has(n) && name === 'dark') continue;
  103. const v = vars.get(n) as string;
  104. if (resolveVars(v, vars) === null) out.push(`${where}: ${name} scheme: ${n} refers to a variable that does not exist`);
  105. }
  106. };
  107. scheme('light', new Map());
  108. if (dark) scheme('dark', dark);
  109. return out;
  110. }
  111. /** Extension names the stylesheet does not set: the contract's defaults apply to them. */
  112. export function fallbacks(css: string, contract: Contract): string[] {
  113. const { light } = schemes(css);
  114. return Object.keys(contract.extension).filter((n) => !light.has(n));
  115. }
  116. /** A short line naming the fallbacks: the hue family is one item. */
  117. export function fallbackLine(missing: string[]): string {
  118. const hue = missing.filter((n) => /^--sb-hue-\d+(-soft|-tint|-ink)?$/.test(n));
  119. const rest = missing.filter((n) => !hue.includes(n));
  120. const items = [...rest];
  121. if (hue.length) items.push(`--sb-hue-1 … --sb-hue-12 with -soft, -tint, -ink (${hue.length} names)`);
  122. return items.join(', ');
  123. }
  124. /** A `:root { … }` block with the defaults of the given extension names, to put before a style's CSS. */
  125. export function defaultsCss(missing: string[], contract: Contract): string {
  126. const lines = missing.filter((n) => n in contract.extension).map((n) => ` ${n}: ${contract.extension[n]};`);
  127. return lines.length ? `:root {\n${lines.join('\n')}\n}\n` : '';
  128. }
  129. export type Health = { missing: string[]; fallbacks: string[]; extra: string[] };
  130. /** The health of a stylesheet against the contract, as names for the bands of a convention: `missing` (required names, a colour's
  131. * dark value as `--x (dark)`, a broken reference as `--x (broken in light)`), `fallbacks` (optional names left out) and `extra`
  132. * (names the style sets that the contract does not know). No band filled means `full`. */
  133. export function health(css: string, contract: Contract): Health {
  134. const { light, dark } = schemes(css);
  135. const missing = contract.required.filter((n) => !light.has(n));
  136. if (!dark) missing.push(...contract.colors.map((n) => `${n} (dark)`));
  137. else for (const n of contract.colors) if (!dark.has(n) && !/light-dark\(/.test(light.get(n) ?? '')) missing.push(`${n} (dark)`);
  138. for (const line of checkCss(css, '', contract)) {
  139. const m = /(light|dark) scheme: (--[\w-]+) refers to a variable that does not exist/.exec(line);
  140. if (m) missing.push(`${m[2]} (broken in ${m[1]})`);
  141. }
  142. // Tailwind v4 mirrors a theme name as --color-<name> (and animations as --animate-*): derived names, not extras
  143. const known = new Set([...contract.required, ...Object.keys(contract.extension), ...contract.colors.map((n) => `--color-${n.slice(2)}`)]);
  144. const extra = [...new Set([...light.keys(), ...(dark?.keys() ?? [])])].filter((n) => !known.has(n) && !n.startsWith('--animate-')).sort();
  145. return { missing, fallbacks: fallbacks(css, contract), extra };
  146. }