import postcss from "postcss"; import tailwind from "tailwindcss"; import preset from "../../../tailwind.tokens.preset"; /** * Test helper: what do these Tailwind classes compute to under a given set of CSS variables? * * Compiles the classes with the library's own preset, then resolves `var(--x, fallback)` against * `vars` (an unset variable takes its fallback), and applies the cascade by source order. It is * not a browser: it covers the properties the theme seams touch, not specificity between * different selectors, which is all these class strings need. * * A declaration that reads an unset `--ui-*` variable with no fallback is invalid at computed-value * time, which CSS treats as `unset` (inherit, or the initial value): the same as no declaration on * this element, so it is left out of the result. * * Pass the class list a component actually renders (through `cn()`), not a raw concatenation: the * library merges with tailwind-merge, which drops a class when a later one sets the same property. */ export async function computedFor( classNames: string, vars: Record = {}, states: readonly string[] = [], ): Promise> { return computedIn(await compileClasses(classNames), classNames, vars, states); } /** Tailwind's output for a set of classes, kept so many class lists can be resolved from one compile. */ export interface CompiledClasses { rules: { selectors: string[]; decls: [prop: string, value: string][] }[]; } /** * Compile once (the slow step, about a second with the full preset), then call `computedIn` per class list. * Tailwind orders its output by plugin, variant and class name, never by which other classes are present, so the * cascade read from a shared compile is the one each class list gets on its own. */ export async function compileClasses(classNames: string): Promise { const result = await postcss([ tailwind({ presets: [preset], content: [{ raw: classNames, extension: "html" }], corePlugins: { preflight: false }, } as never), ]).process("@tailwind components;\n@tailwind utilities;", { from: undefined }); const rules: CompiledClasses["rules"] = []; result.root.walkRules((rule) => { if (rule.parent?.type !== "root") return; const decls: [string, string][] = []; rule.walkDecls((d) => { decls.push([d.prop, d.value]); }); rules.push({ selectors: rule.selectors.map(unescape), decls }); }); return { rules }; } /** * `computedFor` against an existing compile. `states` adds the rules of those state variants on top of the base * rules, in source order, e.g. `[":hover"]`, `[":focus-visible"]`, `[":disabled"]` or `['[aria-invalid="true"]']`. */ export function computedIn( compiled: CompiledClasses, classNames: string, vars: Record = {}, states: readonly string[] = [], ): Record { const wanted = new Set(classNames.split(/\s+/).filter(Boolean)); // a selector applies when it is a wanted class followed only by the requested state suffixes const applies = (sel: string) => { for (const cls of wanted) { if (!sel.startsWith(cls)) continue; let rest = sel.slice(cls.length); for (let changed = true; rest && changed; ) { changed = false; for (const st of states) { if (rest.startsWith(st)) { rest = rest.slice(st.length); changed = true; } } } if (rest === "") return true; } return false; }; const out: Record = {}; for (const rule of compiled.rules) { if (!rule.selectors.some(applies)) continue; for (const [prop, raw] of rule.decls) { const value = resolveVars(raw, vars); if (/var\(--ui-[\w-]*\)/.test(value)) delete out[prop]; else out[prop] = value; } } return out; } // CSS identifier unescape: \2c (hex escape, one optional trailing space) and \x (literal); drops the leading dot function unescape(sel: string): string { return sel .trim() .replace(/^\./, "") .replace(/\\([0-9a-fA-F]{1,6}) ?/g, (_m, hex) => String.fromCodePoint(parseInt(hex, 16))) .replace(/\\(.)/g, "$1"); } function resolveVars(value: string, vars: Record): string { let out = ""; for (let i = 0; i < value.length; ) { if (!value.startsWith("var(", i)) { out += value[i++]; continue; } // find the matching close paren, then split name from fallback at the first top-level comma let depth = 0; let j = i + 3; for (; j < value.length; j++) { if (value[j] === "(") depth++; else if (value[j] === ")" && --depth === 0) break; } const inner = value.slice(i + 4, j); const comma = inner.indexOf(","); const name = (comma === -1 ? inner : inner.slice(0, comma)).trim(); const fallback = comma === -1 ? undefined : inner.slice(comma + 1).trim(); const hit = vars[name]; out += hit !== undefined ? resolveVars(hit, vars) : fallback !== undefined ? resolveVars(fallback, vars) : `var(${name})`; i = j + 1; } return out.replace(/\s+/g, " ").trim(); } /** Variables declared in a theme CSS file's light block, as a name -> value map. */ export function themeVars(css: string, selectorFragment: string): Record { const root = postcss.parse(css); const vars: Record = {}; root.walkRules((rule) => { // light block: the rule whose only selector is the bare [data-ui-theme] one if (rule.selectors.length === 1 && rule.selector.trim() === selectorFragment) { rule.walkDecls(/^--/, (d) => { vars[d.prop] = d.value; }); } }); return vars; }