ShtukbaseStandard
package file→ .shtukbase/packages/design-base/lib/css.ts

lib/css.ts

166 lines, 7.0 KB.

  1. // A small CSS reader for the design checks: blocks with their selectors, enclosing at-rules and declarations
  2. // (with lines), theme schemes from custom properties, and var() substitution. Not a full parser: enough for
  3. // stylesheets people write by hand (plain CSS, Tailwind 4 `@theme`, nesting).
  4. export type Decl = { prop: string; value: string; line: number };
  5. export type Block = { prelude: string; selectors: string[]; at: string[]; parents: string[]; decls: Decl[]; line: number };
  6. /** Comments → spaces (newlines kept, so lines stay right). */
  7. export function stripComments(text: string): string {
  8. return text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '));
  9. }
  10. export function parseCss(src: string): Block[] {
  11. const text = stripComments(src);
  12. type Frame = { prelude: string; decls: Decl[]; line: number };
  13. const stack: Frame[] = [{ prelude: '', decls: [], line: 1 }];
  14. const blocks: Block[] = [];
  15. let buf = '';
  16. let bufLine = 1;
  17. let line = 1;
  18. let paren = 0;
  19. let quote = '';
  20. const flush = () => {
  21. const s = buf.trim();
  22. buf = '';
  23. if (!s) return;
  24. const i = s.indexOf(':');
  25. if (i <= 0 || s.startsWith('@')) return;
  26. const prop = s.slice(0, i).trim();
  27. if (!/^(--)?[a-zA-Z-][\w-]*$/.test(prop)) return;
  28. stack[stack.length - 1].decls.push({ prop: prop.startsWith('--') ? prop : prop.toLowerCase(), value: s.slice(i + 1).trim().replace(/\s*!important$/i, ''), line: bufLine });
  29. };
  30. for (let k = 0; k < text.length; k++) {
  31. const c = text[k];
  32. if (c === '\n') line++;
  33. if (!buf.trim() && c.trim()) bufLine = line;
  34. if (quote) { buf += c; if (c === quote && text[k - 1] !== '\\') quote = ''; continue; }
  35. if (c === '"' || c === "'") { quote = c; buf += c; continue; }
  36. if (c === '(') paren++;
  37. if (c === ')') paren = Math.max(0, paren - 1);
  38. if (paren > 0) { buf += c; continue; }
  39. if (c === '{') {
  40. stack.push({ prelude: buf.trim().replace(/\s+/g, ' '), decls: [], line: bufLine });
  41. buf = '';
  42. continue;
  43. }
  44. if (c === ';') { flush(); continue; }
  45. if (c === '}') {
  46. flush();
  47. if (stack.length < 2) continue;
  48. const f = stack.pop() as Frame;
  49. const outer = stack.slice(1).map((x) => x.prelude);
  50. blocks.push({
  51. prelude: f.prelude,
  52. selectors: f.prelude.startsWith('@') ? [] : splitTop(f.prelude),
  53. at: outer.filter((p) => p.startsWith('@')),
  54. parents: outer.filter((p) => !p.startsWith('@')),
  55. decls: f.decls,
  56. line: f.line,
  57. });
  58. continue;
  59. }
  60. buf += c;
  61. }
  62. return blocks;
  63. }
  64. /** Splits on top-level commas (not inside parentheses or brackets). */
  65. export function splitTop(s: string, sep = ','): string[] {
  66. const out: string[] = [];
  67. let depth = 0;
  68. let cur = '';
  69. for (const c of s) {
  70. if (c === '(' || c === '[') depth++;
  71. if (c === ')' || c === ']') depth--;
  72. if (c === sep && depth === 0) { out.push(cur.trim()); cur = ''; } else cur += c;
  73. }
  74. if (cur.trim()) out.push(cur.trim());
  75. return out;
  76. }
  77. /** The theme a selector is the root of: 'base' (:root, html, @theme), a scheme name, or null (not a theme root). */
  78. export function themeOf(selector: string, darkMedia: boolean): string | null {
  79. const s = selector.replace(/\s+/g, '');
  80. if (/^(:root|html|:host|\[data-theme\]|body)$/.test(s)) return darkMedia ? 'dark' : 'base';
  81. if (/^(:root|html|body)?\.light$/.test(s)) return 'base';
  82. if (/^(:root|html|body)?\.dark$/.test(s)) return 'dark';
  83. const m = /^(?::root|html|body)?\[data-(?:theme|mode|color-scheme|scheme)=["']?([\w-]+)["']?\]$/.exec(s);
  84. if (m) return m[1] === 'light' ? 'base' : m[1];
  85. return null;
  86. }
  87. export type Themes = Map<string, Map<string, string>>;
  88. /** Custom properties per theme. 'base' holds :root/html/@theme; every other scheme is base plus its own overrides.
  89. * `scopes`: blocks that set custom properties for a part of the page (`[data-theme=x] .sidebar`, `.card`), keyed
  90. * by the scheme they live in; each is that scheme plus the block's own values. */
  91. export function themes(files: { rel: string; text: string }[]): { themes: Themes; scopes: Map<string, Map<string, string>[]>; where: Map<string, string> } {
  92. const base = new Map<string, string>();
  93. const over = new Map<string, Map<string, string>>();
  94. const scoped: { scheme: string; vars: Map<string, string> }[] = [];
  95. const where = new Map<string, string>();
  96. for (const f of files) {
  97. for (const b of parseCss(f.text)) {
  98. if (b.parents.length) continue;
  99. const darkMedia = b.at.some((a) => /prefers-color-scheme\s*:\s*dark/.test(a));
  100. const own = b.decls.filter((d) => d.prop.startsWith('--'));
  101. if (!own.length) continue;
  102. const names = new Set<string>();
  103. if (b.prelude.startsWith('@theme')) names.add('base');
  104. for (const sel of b.selectors) {
  105. const root = themeOf(sel, darkMedia);
  106. if (root) { names.add(root); continue; }
  107. const head = sel.split(/\s*[\s>+~]\s*/)[0];
  108. scoped.push({ scheme: themeOf(head, darkMedia) ?? (darkMedia ? 'dark' : 'base'), vars: new Map(own.map((d) => [d.prop, d.value])) });
  109. }
  110. for (const name of names) {
  111. const target = name === 'base' ? base : over.get(name) ?? over.set(name, new Map()).get(name)!;
  112. for (const d of own) {
  113. target.set(d.prop, d.value);
  114. where.set(`${name} ${d.prop}`, `${f.rel}:${d.line}`);
  115. }
  116. }
  117. }
  118. }
  119. const out: Themes = new Map();
  120. out.set('base', base);
  121. for (const [name, vars] of over) out.set(name, new Map([...base, ...vars]));
  122. const scopes = new Map<string, Map<string, string>[]>();
  123. for (const s of scoped) {
  124. const parent = out.get(s.scheme) ?? base;
  125. const list = scopes.get(s.scheme) ?? scopes.set(s.scheme, []).get(s.scheme)!;
  126. list.push(new Map([...parent, ...s.vars]));
  127. }
  128. return { themes: out, scopes, where };
  129. }
  130. /** Replaces var(--x[, fallback]) with values from `vars`, recursively. Returns null when something stays unknown. */
  131. export function resolveVars(value: string, vars: Map<string, string>, depth = 0): string | null {
  132. if (depth > 12) return null;
  133. const i = value.indexOf('var(');
  134. if (i < 0) return value;
  135. let d = 0;
  136. let j = i + 3;
  137. for (; j < value.length; j++) {
  138. if (value[j] === '(') d++;
  139. else if (value[j] === ')') { d--; if (d === 0) break; }
  140. }
  141. if (j >= value.length) return null;
  142. const inner = value.slice(i + 4, j);
  143. const [name, ...rest] = splitTop(inner);
  144. const fallback = rest.length ? rest.join(',') : null;
  145. let rep: string | null = vars.has(name.trim()) ? resolveVars(vars.get(name.trim()) as string, vars, depth + 1) : null;
  146. if (rep === null && fallback !== null) rep = resolveVars(fallback, vars, depth + 1);
  147. if (rep === null) return null;
  148. return resolveVars(value.slice(0, i) + rep + value.slice(j + 1), vars, depth + 1);
  149. }
  150. /** A length literal → px (rem and em at 16px), or null when it is not a plain length. */
  151. export function px(token: string): number | null {
  152. const m = /^(-?\d*\.?\d+)(px|rem|em)?$/.exec(token.trim());
  153. if (!m) return null;
  154. const n = Number(m[1]);
  155. if (!m[2]) return n === 0 ? 0 : null;
  156. return m[2] === 'px' ? n : n * 16;
  157. }