// Formatter: DTCG tokens -> CSS custom properties, for the browser extension // and the web client. // // The emitted property names match what extension/public/theme.css declared by // hand before this package existed, so swapping the generated file in is not // supposed to move any pixels. import { colorToCss, cssNameExtension, dimensionToCss, type ColorValue, type DimensionValue, type Token, } from "../dtcg.js"; /** * How a token's path becomes a custom property name: * * - `theme.*` -> `--` the semantic layer, emitted wholesale * - `radius.*` -> `--radius-` * - `font.*` -> `--font-` * - `palette.*` -> only when the token opts in via the `app.linkport.css` * extension, which also supplies the name. Primitives are * internal by default; the few theme-independent ones * (cream, error, success) surface because the UI genuinely * needs them outside the light/dark split. */ function cssName(token: Token): string | undefined { const [group, ...rest] = token.path.split("."); const leaf = rest.join("-"); switch (group) { case "theme": return `--${leaf}`; case "radius": case "font": return `--${group}-${leaf}`; case "palette": { const name = cssNameExtension(token); return name ? `--${name}` : undefined; } default: return undefined; } } function cssValue(token: Token): string { switch (token.type) { case "color": return colorToCss(token.value as ColorValue); case "dimension": return dimensionToCss(token.value as DimensionValue); case "fontFamily": // Quote any family whose name isn't a bare identifier, per CSS rules. return (token.value as string[]) .map((family) => (/^[a-zA-Z][\w-]*$/.test(family) ? family : JSON.stringify(family))) .join(", "); default: throw new Error(`${token.path}: no CSS serialization for $type "${token.type}"`); } } function declarations(tokens: Map, indent: string): string[] { const lines: string[] = []; for (const token of tokens.values()) { const name = cssName(token); if (name) lines.push(`${indent}${name}: ${cssValue(token)};`); } return lines; } /** * Emit the stylesheet. * * `light` carries the full token set (semantic + the opted-in primitives + * shape); `dark` carries only the semantic layer, and only the properties whose * value actually differs are re-declared under the dark media query — so the * generated file reads the way a person would have written it. */ export function formatCss(light: Map, dark: Map): string { const lightDecls = declarations(light, " "); const changed = new Map(); for (const [path, token] of dark) { const other = light.get(path); if (!other) continue; if (cssValue(token) !== cssValue(other)) changed.set(path, token); } const darkDecls = declarations(changed, " "); return `/* * linkport design tokens — GENERATED, do not edit. * * Source: @linkport/design/tokens/*.tokens.json (DTCG 2025.10). * Regenerate with \`pnpm --filter @linkport/design build\`. */ :root { color-scheme: light dark; ${lightDecls.join("\n")} } @media (prefers-color-scheme: dark) { :root { ${darkDecls.join("\n")} } } `; }