ShtukbaseStandard
package file→ .shtukbase/packages/kit-style/scripts/skin-keer.ts

scripts/skin-keer.ts

165 lines, 7.6 KB.

  1. // Builds the skin "Draft" (skins/keer.css) of the lens kit style from the tokens of keer-style
  2. // (design/keer-style/tokens.css): the light theme is the first block of tokens (theme draft), the dark one is
  3. // that block with [data-theme="draft-dark"] on top. Every kit variable gets the value of a --ds-* role,
  4. // with var() resolved, so the skin needs no tokens.css next to it. Run it again after the tokens change.
  5. //
  6. // bun scripts/skin-keer.ts [--tokens <tokens.css>] [--out <keer.css>] [--check]
  7. //
  8. // Without paths: in this repository the sibling package keer-style and this package's pages; in an
  9. // installed project (run from the project root) design/keer-style/tokens.css and design/kit-style/skins/keer.css.
  10. // --check: exit 1 when the file on disk differs from what would be written.
  11. import { existsSync, readFileSync, writeFileSync } from 'node:fs';
  12. import { dirname, join, relative, resolve } from 'node:path';
  13. import { fileURLToPath } from 'node:url';
  14. const HERE = dirname(fileURLToPath(import.meta.url));
  15. const PKG = resolve(HERE, '..');
  16. type Vars = Record<string, string>;
  17. /** Top-level blocks of a CSS file: selector and the declarations `--name: value` in it (comments removed). */
  18. export function blocks(css: string): { selector: string; vars: Vars }[] {
  19. const text = css.replace(/\/\*[\s\S]*?\*\//g, '');
  20. const out: { selector: string; vars: Vars }[] = [];
  21. let i = 0;
  22. while (i < text.length) {
  23. const open = text.indexOf('{', i);
  24. if (open < 0) break;
  25. const selector = text.slice(i, open).trim();
  26. let depth = 1, j = open + 1;
  27. while (j < text.length && depth) { if (text[j] === '{') depth++; else if (text[j] === '}') depth--; j++; }
  28. const body = text.slice(open + 1, j - 1);
  29. const vars: Vars = {};
  30. if (!body.includes('{')) {
  31. let d = 0, start = 0;
  32. for (let k = 0; k <= body.length; k++) {
  33. const c = body[k];
  34. if (c === '(') d++; else if (c === ')') d--;
  35. else if ((c === ';' && d === 0) || k === body.length) {
  36. const decl = body.slice(start, k).trim();
  37. start = k + 1;
  38. const m = /^(--[\w-]+|color-scheme)\s*:\s*([\s\S]+)$/.exec(decl);
  39. if (m) vars[m[1]] = m[2].replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')').trim();
  40. }
  41. }
  42. }
  43. out.push({ selector, vars });
  44. i = j;
  45. }
  46. return out;
  47. }
  48. /** The value of a variable with every var(--x) inside replaced by the value of --x (in the same theme). */
  49. export function resolveVar(name: string, vars: Vars, seen: string[] = []): string {
  50. const v = vars[name];
  51. if (v === undefined) throw new Error(`the tokens have no ${name}`);
  52. if (seen.includes(name)) throw new Error(`tokens refer to each other in a circle: ${[...seen, name].join(' → ')}`);
  53. return v.replace(/var\((--[\w-]+)\)/g, (_, n) => resolveVar(n, vars, [...seen, name]));
  54. }
  55. const OPTIONS = ['gray', 'brown', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'red'];
  56. /**
  57. * What every kit variable is in keer-style terms. A string is a --ds-* role; a function builds a value from
  58. * resolved roles. Kit variables not named here (teal, which keer-style has no option for) keep the "Kit" values.
  59. */
  60. const MAP: Record<string, string | ((r: (n: string) => string) => string)> = {
  61. '--bg': '--ds-bg',
  62. '--bg2': '--ds-bg-secondary',
  63. '--bg3': '--ds-bg-tertiary',
  64. '--panel': '--ds-bg-raised',
  65. '--lx-card': '--ds-bg-raised',
  66. '--ink': '--ds-text-primary',
  67. '--lx-muted': '--ds-text-secondary',
  68. '--faint': '--ds-mark-tertiary',
  69. '--line': '--ds-border-primary',
  70. '--line2': '--ds-border-strong',
  71. '--wash': '--ds-wash-hover',
  72. '--wash2': '--ds-wash-pressed',
  73. '--tray': '--ds-bg-sidebar',
  74. '--lx-accent': '--ds-accent',
  75. '--accent-soft': '--ds-accent-soft',
  76. '--canvas': '--ds-bg',
  77. '--canvas-dot': '--ds-canvas-dot',
  78. '--canvas-grid': '--ds-border-secondary',
  79. '--shadow': '--ds-shadow-card',
  80. '--shadow-lift': (r) => `0 0 0 1px ${r('--ds-border-primary')}, ${r('--ds-shadow-popover')}`,
  81. '--shadow-peek': '--ds-shadow-overlay',
  82. '--lx-radius': '--ds-radius-md',
  83. '--radius-lg': '--ds-radius-xl',
  84. '--font': '--ds-font-sans',
  85. '--mono': '--ds-font-mono',
  86. '--selection': (r) => `color-mix(in srgb, ${r('--ds-champagne')} 40%, transparent)`,
  87. '--card-hover': '--ds-bg-tertiary',
  88. '--c-default': '--ds-mark-tertiary',
  89. '--cb-default': '--ds-wash-pressed',
  90. '--cf-default': '--ds-text-secondary',
  91. '--ct-default': '--ds-bg-secondary',
  92. ...Object.fromEntries(OPTIONS.flatMap((o) => [
  93. [`--c-${o}`, `--ds-option-${o}-dot`],
  94. [`--cb-${o}`, `--ds-option-${o}-bg`],
  95. [`--cf-${o}`, `--ds-option-${o}-fg`],
  96. // area fill: a light tint of the option over the page background
  97. [`--ct-${o}`, (r: (n: string) => string) => `color-mix(in srgb, ${r(`--ds-option-${o}-dot`)} 7%, ${r('--ds-bg')})`],
  98. ])),
  99. 'color-scheme': 'color-scheme',
  100. };
  101. function theme(vars: Vars): string[] {
  102. const r = (n: string) => resolveVar(n, vars);
  103. return Object.entries(MAP).map(([k, v]) => ` ${k}: ${typeof v === 'string' ? r(v) : v(r)};`);
  104. }
  105. export function renderSkin(tokensCss: string): string {
  106. const bs = blocks(tokensCss);
  107. const root = bs.find((b) => /(^|,)\s*:root\s*$/.test(b.selector) && Object.keys(b.vars).length > 20);
  108. const dark = bs.find((b) => b.selector === '[data-theme="draft-dark"]');
  109. if (!root) throw new Error('the tokens have no :root block with theme 1 (draft)');
  110. if (!dark) throw new Error('the tokens have no [data-theme="draft-dark"] block: there is nothing to build the dark theme of the skin from');
  111. return [
  112. '/* @tokens — the skin "Draft" (id keer): variables of the lens kit from the tokens of the keer-style style.',
  113. ' * @skin keer | Draft',
  114. ' * Built by scripts/skin-keer.ts of the kit-style package from tokens.css of the keer-style package — do not edit by hand:',
  115. ' * fix the tokens and run the script again. The light theme is theme 1 (draft), the dark one is draft-dark.',
  116. ' * Turned on by the attribute data-skin="keer" on <html>; included after skins/kit.css.',
  117. ' */',
  118. ':root[data-skin="keer"] {',
  119. ...theme(root.vars),
  120. '}',
  121. ':root[data-skin="keer"][data-theme="dark"] {',
  122. ...theme({ ...root.vars, ...dark.vars }),
  123. '}',
  124. '',
  125. ].join('\n');
  126. }
  127. function arg(name: string): string | undefined {
  128. const i = process.argv.indexOf(name);
  129. return i > 0 ? process.argv[i + 1] : undefined;
  130. }
  131. if (import.meta.main) {
  132. const repoTokens = resolve(PKG, '..', 'keer-style', 'pages', 'design', 'keer-style', 'tokens.css');
  133. const repoOut = join(PKG, 'pages', 'design', 'kit-style', 'skins', 'keer.css');
  134. const inRepo = existsSync(repoTokens) && existsSync(dirname(repoOut));
  135. const tokens = resolve(arg('--tokens') ?? (inRepo ? repoTokens : join(process.cwd(), 'design', 'keer-style', 'tokens.css')));
  136. const out = resolve(arg('--out') ?? (inRepo ? repoOut : join(process.cwd(), 'design', 'kit-style', 'skins', 'keer.css')));
  137. if (!existsSync(tokens)) {
  138. console.log(`no keer-style tokens: ${tokens} — install the keer-style package or give --tokens`);
  139. process.exit(2);
  140. }
  141. let css: string;
  142. try {
  143. css = renderSkin(readFileSync(tokens, 'utf8'));
  144. } catch (e) {
  145. console.log(`the skin "Draft" is not built: ${(e as Error).message}`);
  146. process.exit(1);
  147. }
  148. const old = existsSync(out) ? readFileSync(out, 'utf8') : null;
  149. const rel = relative(process.cwd(), out) || out;
  150. if (process.argv.includes('--check')) {
  151. if (old !== css) { console.log(`the skin is stale: ${rel} — run bun scripts/skin-keer.ts`); process.exit(1); }
  152. console.log(`the skin is up to date: ${rel}`);
  153. } else if (old === css) console.log(`the skin is unchanged: ${rel}`);
  154. else { writeFileSync(out, css); console.log(`the skin "Draft" is built: ${rel}`); }
  155. }