файл пакета→ .shtukbase/packages/design-base/lib/css.ts
lib/css.ts
166 строк, 7.0 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // A small CSS reader for the design checks: blocks with their selectors, enclosing at-rules and declarations
- // (with lines), theme schemes from custom properties, and var() substitution. Not a full parser: enough for
- // stylesheets people write by hand (plain CSS, Tailwind 4 `@theme`, nesting).
- export type Decl = { prop: string; value: string; line: number };
- export type Block = { prelude: string; selectors: string[]; at: string[]; parents: string[]; decls: Decl[]; line: number };
- /** Comments → spaces (newlines kept, so lines stay right). */
- export function stripComments(text: string): string {
- return text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '));
- }
- export function parseCss(src: string): Block[] {
- const text = stripComments(src);
- type Frame = { prelude: string; decls: Decl[]; line: number };
- const stack: Frame[] = [{ prelude: '', decls: [], line: 1 }];
- const blocks: Block[] = [];
- let buf = '';
- let bufLine = 1;
- let line = 1;
- let paren = 0;
- let quote = '';
- const flush = () => {
- const s = buf.trim();
- buf = '';
- if (!s) return;
- const i = s.indexOf(':');
- if (i <= 0 || s.startsWith('@')) return;
- const prop = s.slice(0, i).trim();
- if (!/^(--)?[a-zA-Z-][\w-]*$/.test(prop)) return;
- stack[stack.length - 1].decls.push({ prop: prop.startsWith('--') ? prop : prop.toLowerCase(), value: s.slice(i + 1).trim().replace(/\s*!important$/i, ''), line: bufLine });
- };
- for (let k = 0; k < text.length; k++) {
- const c = text[k];
- if (c === '\n') line++;
- if (!buf.trim() && c.trim()) bufLine = line;
- if (quote) { buf += c; if (c === quote && text[k - 1] !== '\\') quote = ''; continue; }
- if (c === '"' || c === "'") { quote = c; buf += c; continue; }
- if (c === '(') paren++;
- if (c === ')') paren = Math.max(0, paren - 1);
- if (paren > 0) { buf += c; continue; }
- if (c === '{') {
- stack.push({ prelude: buf.trim().replace(/\s+/g, ' '), decls: [], line: bufLine });
- buf = '';
- continue;
- }
- if (c === ';') { flush(); continue; }
- if (c === '}') {
- flush();
- if (stack.length < 2) continue;
- const f = stack.pop() as Frame;
- const outer = stack.slice(1).map((x) => x.prelude);
- blocks.push({
- prelude: f.prelude,
- selectors: f.prelude.startsWith('@') ? [] : splitTop(f.prelude),
- at: outer.filter((p) => p.startsWith('@')),
- parents: outer.filter((p) => !p.startsWith('@')),
- decls: f.decls,
- line: f.line,
- });
- continue;
- }
- buf += c;
- }
- return blocks;
- }
- /** Splits on top-level commas (not inside parentheses or brackets). */
- export function splitTop(s: string, sep = ','): string[] {
- const out: string[] = [];
- let depth = 0;
- let cur = '';
- for (const c of s) {
- if (c === '(' || c === '[') depth++;
- if (c === ')' || c === ']') depth--;
- if (c === sep && depth === 0) { out.push(cur.trim()); cur = ''; } else cur += c;
- }
- if (cur.trim()) out.push(cur.trim());
- return out;
- }
- /** The theme a selector is the root of: 'base' (:root, html, @theme), a scheme name, or null (not a theme root). */
- export function themeOf(selector: string, darkMedia: boolean): string | null {
- const s = selector.replace(/\s+/g, '');
- if (/^(:root|html|:host|\[data-theme\]|body)$/.test(s)) return darkMedia ? 'dark' : 'base';
- if (/^(:root|html|body)?\.light$/.test(s)) return 'base';
- if (/^(:root|html|body)?\.dark$/.test(s)) return 'dark';
- const m = /^(?::root|html|body)?\[data-(?:theme|mode|color-scheme|scheme)=["']?([\w-]+)["']?\]$/.exec(s);
- if (m) return m[1] === 'light' ? 'base' : m[1];
- return null;
- }
- export type Themes = Map<string, Map<string, string>>;
- /** Custom properties per theme. 'base' holds :root/html/@theme; every other scheme is base plus its own overrides.
- * `scopes`: blocks that set custom properties for a part of the page (`[data-theme=x] .sidebar`, `.card`), keyed
- * by the scheme they live in; each is that scheme plus the block's own values. */
- export function themes(files: { rel: string; text: string }[]): { themes: Themes; scopes: Map<string, Map<string, string>[]>; where: Map<string, string> } {
- const base = new Map<string, string>();
- const over = new Map<string, Map<string, string>>();
- const scoped: { scheme: string; vars: Map<string, string> }[] = [];
- const where = new Map<string, string>();
- for (const f of files) {
- for (const b of parseCss(f.text)) {
- if (b.parents.length) continue;
- const darkMedia = b.at.some((a) => /prefers-color-scheme\s*:\s*dark/.test(a));
- const own = b.decls.filter((d) => d.prop.startsWith('--'));
- if (!own.length) continue;
- const names = new Set<string>();
- if (b.prelude.startsWith('@theme')) names.add('base');
- for (const sel of b.selectors) {
- const root = themeOf(sel, darkMedia);
- if (root) { names.add(root); continue; }
- const head = sel.split(/\s*[\s>+~]\s*/)[0];
- scoped.push({ scheme: themeOf(head, darkMedia) ?? (darkMedia ? 'dark' : 'base'), vars: new Map(own.map((d) => [d.prop, d.value])) });
- }
- for (const name of names) {
- const target = name === 'base' ? base : over.get(name) ?? over.set(name, new Map()).get(name)!;
- for (const d of own) {
- target.set(d.prop, d.value);
- where.set(`${name} ${d.prop}`, `${f.rel}:${d.line}`);
- }
- }
- }
- }
- const out: Themes = new Map();
- out.set('base', base);
- for (const [name, vars] of over) out.set(name, new Map([...base, ...vars]));
- const scopes = new Map<string, Map<string, string>[]>();
- for (const s of scoped) {
- const parent = out.get(s.scheme) ?? base;
- const list = scopes.get(s.scheme) ?? scopes.set(s.scheme, []).get(s.scheme)!;
- list.push(new Map([...parent, ...s.vars]));
- }
- return { themes: out, scopes, where };
- }
- /** Replaces var(--x[, fallback]) with values from `vars`, recursively. Returns null when something stays unknown. */
- export function resolveVars(value: string, vars: Map<string, string>, depth = 0): string | null {
- if (depth > 12) return null;
- const i = value.indexOf('var(');
- if (i < 0) return value;
- let d = 0;
- let j = i + 3;
- for (; j < value.length; j++) {
- if (value[j] === '(') d++;
- else if (value[j] === ')') { d--; if (d === 0) break; }
- }
- if (j >= value.length) return null;
- const inner = value.slice(i + 4, j);
- const [name, ...rest] = splitTop(inner);
- const fallback = rest.length ? rest.join(',') : null;
- let rep: string | null = vars.has(name.trim()) ? resolveVars(vars.get(name.trim()) as string, vars, depth + 1) : null;
- if (rep === null && fallback !== null) rep = resolveVars(fallback, vars, depth + 1);
- if (rep === null) return null;
- return resolveVars(value.slice(0, i) + rep + value.slice(j + 1), vars, depth + 1);
- }
- /** A length literal → px (rem and em at 16px), or null when it is not a plain length. */
- export function px(token: string): number | null {
- const m = /^(-?\d*\.?\d+)(px|rem|em)?$/.exec(token.trim());
- if (!m) return null;
- const n = Number(m[1]);
- if (!m[2]) return n === 0 ? 0 : null;
- return m[2] === 'px' ? n : n * 16;
- }