файл пакета→ .shtukbase/packages/kit-style/scripts/skin-keer.ts
scripts/skin-keer.ts
165 строк, 7.6 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Builds the skin "Draft" (skins/keer.css) of the lens kit style from the tokens of keer-style
- // (design/keer-style/tokens.css): the light theme is the first block of tokens (theme draft), the dark one is
- // that block with [data-theme="draft-dark"] on top. Every kit variable gets the value of a --ds-* role,
- // with var() resolved, so the skin needs no tokens.css next to it. Run it again after the tokens change.
- //
- // bun scripts/skin-keer.ts [--tokens <tokens.css>] [--out <keer.css>] [--check]
- //
- // Without paths: in this repository the sibling package keer-style and this package's pages; in an
- // installed project (run from the project root) design/keer-style/tokens.css and design/kit-style/skins/keer.css.
- // --check: exit 1 when the file on disk differs from what would be written.
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
- import { dirname, join, relative, resolve } from 'node:path';
- import { fileURLToPath } from 'node:url';
- const HERE = dirname(fileURLToPath(import.meta.url));
- const PKG = resolve(HERE, '..');
- type Vars = Record<string, string>;
- /** Top-level blocks of a CSS file: selector and the declarations `--name: value` in it (comments removed). */
- export function blocks(css: string): { selector: string; vars: Vars }[] {
- const text = css.replace(/\/\*[\s\S]*?\*\//g, '');
- const out: { selector: string; vars: Vars }[] = [];
- let i = 0;
- while (i < text.length) {
- const open = text.indexOf('{', i);
- if (open < 0) break;
- const selector = text.slice(i, open).trim();
- let depth = 1, j = open + 1;
- while (j < text.length && depth) { if (text[j] === '{') depth++; else if (text[j] === '}') depth--; j++; }
- const body = text.slice(open + 1, j - 1);
- const vars: Vars = {};
- if (!body.includes('{')) {
- let d = 0, start = 0;
- for (let k = 0; k <= body.length; k++) {
- const c = body[k];
- if (c === '(') d++; else if (c === ')') d--;
- else if ((c === ';' && d === 0) || k === body.length) {
- const decl = body.slice(start, k).trim();
- start = k + 1;
- const m = /^(--[\w-]+|color-scheme)\s*:\s*([\s\S]+)$/.exec(decl);
- if (m) vars[m[1]] = m[2].replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')').trim();
- }
- }
- }
- out.push({ selector, vars });
- i = j;
- }
- return out;
- }
- /** The value of a variable with every var(--x) inside replaced by the value of --x (in the same theme). */
- export function resolveVar(name: string, vars: Vars, seen: string[] = []): string {
- const v = vars[name];
- if (v === undefined) throw new Error(`the tokens have no ${name}`);
- if (seen.includes(name)) throw new Error(`tokens refer to each other in a circle: ${[...seen, name].join(' → ')}`);
- return v.replace(/var\((--[\w-]+)\)/g, (_, n) => resolveVar(n, vars, [...seen, name]));
- }
- const OPTIONS = ['gray', 'brown', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'red'];
- /**
- * What every kit variable is in keer-style terms. A string is a --ds-* role; a function builds a value from
- * resolved roles. Kit variables not named here (teal, which keer-style has no option for) keep the "Kit" values.
- */
- const MAP: Record<string, string | ((r: (n: string) => string) => string)> = {
- '--bg': '--ds-bg',
- '--bg2': '--ds-bg-secondary',
- '--bg3': '--ds-bg-tertiary',
- '--panel': '--ds-bg-raised',
- '--lx-card': '--ds-bg-raised',
- '--ink': '--ds-text-primary',
- '--lx-muted': '--ds-text-secondary',
- '--faint': '--ds-mark-tertiary',
- '--line': '--ds-border-primary',
- '--line2': '--ds-border-strong',
- '--wash': '--ds-wash-hover',
- '--wash2': '--ds-wash-pressed',
- '--tray': '--ds-bg-sidebar',
- '--lx-accent': '--ds-accent',
- '--accent-soft': '--ds-accent-soft',
- '--canvas': '--ds-bg',
- '--canvas-dot': '--ds-canvas-dot',
- '--canvas-grid': '--ds-border-secondary',
- '--shadow': '--ds-shadow-card',
- '--shadow-lift': (r) => `0 0 0 1px ${r('--ds-border-primary')}, ${r('--ds-shadow-popover')}`,
- '--shadow-peek': '--ds-shadow-overlay',
- '--lx-radius': '--ds-radius-md',
- '--radius-lg': '--ds-radius-xl',
- '--font': '--ds-font-sans',
- '--mono': '--ds-font-mono',
- '--selection': (r) => `color-mix(in srgb, ${r('--ds-champagne')} 40%, transparent)`,
- '--card-hover': '--ds-bg-tertiary',
- '--c-default': '--ds-mark-tertiary',
- '--cb-default': '--ds-wash-pressed',
- '--cf-default': '--ds-text-secondary',
- '--ct-default': '--ds-bg-secondary',
- ...Object.fromEntries(OPTIONS.flatMap((o) => [
- [`--c-${o}`, `--ds-option-${o}-dot`],
- [`--cb-${o}`, `--ds-option-${o}-bg`],
- [`--cf-${o}`, `--ds-option-${o}-fg`],
- // area fill: a light tint of the option over the page background
- [`--ct-${o}`, (r: (n: string) => string) => `color-mix(in srgb, ${r(`--ds-option-${o}-dot`)} 7%, ${r('--ds-bg')})`],
- ])),
- 'color-scheme': 'color-scheme',
- };
- function theme(vars: Vars): string[] {
- const r = (n: string) => resolveVar(n, vars);
- return Object.entries(MAP).map(([k, v]) => ` ${k}: ${typeof v === 'string' ? r(v) : v(r)};`);
- }
- export function renderSkin(tokensCss: string): string {
- const bs = blocks(tokensCss);
- const root = bs.find((b) => /(^|,)\s*:root\s*$/.test(b.selector) && Object.keys(b.vars).length > 20);
- const dark = bs.find((b) => b.selector === '[data-theme="draft-dark"]');
- if (!root) throw new Error('the tokens have no :root block with theme 1 (draft)');
- 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');
- return [
- '/* @tokens — the skin "Draft" (id keer): variables of the lens kit from the tokens of the keer-style style.',
- ' * @skin keer | Draft',
- ' * Built by scripts/skin-keer.ts of the kit-style package from tokens.css of the keer-style package — do not edit by hand:',
- ' * fix the tokens and run the script again. The light theme is theme 1 (draft), the dark one is draft-dark.',
- ' * Turned on by the attribute data-skin="keer" on <html>; included after skins/kit.css.',
- ' */',
- ':root[data-skin="keer"] {',
- ...theme(root.vars),
- '}',
- ':root[data-skin="keer"][data-theme="dark"] {',
- ...theme({ ...root.vars, ...dark.vars }),
- '}',
- '',
- ].join('\n');
- }
- function arg(name: string): string | undefined {
- const i = process.argv.indexOf(name);
- return i > 0 ? process.argv[i + 1] : undefined;
- }
- if (import.meta.main) {
- const repoTokens = resolve(PKG, '..', 'keer-style', 'pages', 'design', 'keer-style', 'tokens.css');
- const repoOut = join(PKG, 'pages', 'design', 'kit-style', 'skins', 'keer.css');
- const inRepo = existsSync(repoTokens) && existsSync(dirname(repoOut));
- const tokens = resolve(arg('--tokens') ?? (inRepo ? repoTokens : join(process.cwd(), 'design', 'keer-style', 'tokens.css')));
- const out = resolve(arg('--out') ?? (inRepo ? repoOut : join(process.cwd(), 'design', 'kit-style', 'skins', 'keer.css')));
- if (!existsSync(tokens)) {
- console.log(`no keer-style tokens: ${tokens} — install the keer-style package or give --tokens`);
- process.exit(2);
- }
- let css: string;
- try {
- css = renderSkin(readFileSync(tokens, 'utf8'));
- } catch (e) {
- console.log(`the skin "Draft" is not built: ${(e as Error).message}`);
- process.exit(1);
- }
- const old = existsSync(out) ? readFileSync(out, 'utf8') : null;
- const rel = relative(process.cwd(), out) || out;
- if (process.argv.includes('--check')) {
- if (old !== css) { console.log(`the skin is stale: ${rel} — run bun scripts/skin-keer.ts`); process.exit(1); }
- console.log(`the skin is up to date: ${rel}`);
- } else if (old === css) console.log(`the skin is unchanged: ${rel}`);
- else { writeFileSync(out, css); console.log(`the skin "Draft" is built: ${rel}`); }
- }