Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

8.0 KB
Raw Blame
/**
 * Resolve the preview-iframe theme-token subset from
 * `packages/app/src/globals.css` into a flat `{ name, light, dark }` list.
 *
 * The preview iframe is null-origin and style-isolated — it inherits nothing
 * from the host page. To let embedded `html preview` content (charts, stat
 * cards, custom SVG, …) track OK's theme, a fixed subset of design tokens is
 * injected into every preview `srcDoc` as CSS custom properties. This resolver
 * is the single source of truth for that subset: it parses both theme blocks,
 * resolves `var()` indirections (e.g. dark `--primary` → `var(--color-sky-blue)`
 * → the `@theme` literal), and feeds:
 *
 *   - `packages/core/src/constants/preview-theme-tokens.ts` (regenerated by
 *     `scripts/generate-preview-theme-tokens.ts`)
 *
 * Drift between the parsed CSS and the committed constant is caught by
 * `packages/core/src/constants/preview-theme-tokens.uncached.test.ts`.
 *
 * Node-only — uses `node:fs` and the `culori` colorspace library. Mirrors the
 * sibling `chrome-resolver.ts` and reuses its exact-match block scanner.
 */
import { readFileSync } from 'node:fs';
import { wcagContrast as culoriWcagContrast } from 'culori';
import { findBlockBodies } from './chrome-resolver.ts';

/**
 * The injected token subset. Order is the wire + injection
 * order — chart palette first, then surface / text / structural tokens. This
 * *selection* (which tokens cross into the sandbox) is the deliberate part;
 * the *values* are always generated from `globals.css`, never hand-written.
 */
export const PREVIEW_TOKEN_NAMES = [
  '--chart-1',
  '--chart-2',
  '--chart-3',
  '--chart-4',
  '--chart-5',
  '--primary',
  '--primary-foreground',
  '--foreground',
  '--background',
  '--card',
  '--card-foreground',
  '--muted-foreground',
  '--border',
  '--destructive',
  '--radius',
] as const;

export type PreviewTokenName = (typeof PREVIEW_TOKEN_NAMES)[number];

export interface ResolvedPreviewToken {
  name: PreviewTokenName;
  /** Light-theme value with every `var()` indirection resolved to a literal. */
  light: string;
  /** Dark-theme value with every `var()` indirection resolved to a literal. */
  dark: string;
}

/** A CSS comment, used to strip comments before declaration scanning. */
const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;

/** Collect every `--name: value;` declaration from a block body. */
function parseDecls(body: string): Map<string, string> {
  const withoutComments = body.replace(CSS_COMMENT_RE, '');
  const map = new Map<string, string>();
  const re = /(--[\w-]+)\s*:\s*([^;]+);/g;
  let m: RegExpExecArray | null = re.exec(withoutComments);
  while (m !== null) {
    // Collapse internal whitespace so multi-line values (e.g. a wrapped
    // `oklch(...)`) emit a stable single-line literal.
    map.set(m[1], m[2].trim().replace(/\s+/g, ' '));
    m = re.exec(withoutComments);
  }
  return map;
}

/** Merge declarations from every block body — last write wins (CSS cascade). */
function mergeDecls(bodies: string[]): Map<string, string> {
  const merged = new Map<string, string>();
  for (const body of bodies) {
    for (const [k, v] of parseDecls(body)) merged.set(k, v);
  }
  return merged;
}

// A `var(--name)` / `var(--name, fallback)` reference. The fallback group
// stops at the first paren so a fallback that itself nests `()` is not
// silently mis-captured — `resolveVars` throws loudly if a `var(` survives.
const VAR_RE = /var\(\s*(--[\w-]+)\s*(?:,\s*([^()]*))?\)/g;

/**
 * Replace every `var()` reference in `value` with its resolved literal.
 * `lookup` returns the declared value for a custom property in the relevant
 * theme scope; recursion resolves chained indirections. Throws on an
 * unresolved reference or on a `var(` shape this resolver cannot flatten.
 */
function resolveVars(
  value: string,
  lookup: (name: string) => string | undefined,
  depth = 0,
): string {
  if (depth > 16) {
    throw new Error(
      `preview-theme-token-resolver: var() resolution exceeded depth 16 on "${value}"`,
    );
  }
  if (!value.includes('var(')) return value.trim();
  const replaced = value.replace(VAR_RE, (_match, name: string, fallback?: string) => {
    const resolved = lookup(name);
    if (resolved !== undefined) return resolveVars(resolved, lookup, depth + 1);
    if (fallback !== undefined && fallback.trim() !== '') {
      return resolveVars(fallback, lookup, depth + 1);
    }
    throw new Error(`preview-theme-token-resolver: unresolved var(${name}) with no fallback`);
  });
  if (replaced.includes('var(')) {
    throw new Error(
      `preview-theme-token-resolver: could not flatten a var() shape in "${value}" (nested fallback?)`,
    );
  }
  return replaced.trim();
}

/**
 * Parse the preview token subset from `globals.css`, resolving `var()`
 * indirections against the `@theme` / `:root` / `.dark` scopes.
 *
 * `--radius` is declared only in `:root`; like every token, dark falls back to
 * the `:root` value when `.dark` carries no override.
 *
 * Throws on a missing token, a missing theme block, or an unresolvable
 * `var()` — callers handle once at generation time; a failure here should
 * fail the regen, not emit a half-resolved constant.
 */
export function resolvePreviewThemeTokensFromCss(cssPath: string): ResolvedPreviewToken[] {
  const css = readFileSync(cssPath, 'utf8');
  const rootDecls = mergeDecls(findBlockBodies(css, ':root'));
  const darkDecls = mergeDecls(findBlockBodies(css, '.dark'));
  const themeDecls = mergeDecls(findBlockBodies(css, '@theme'));
  if (rootDecls.size === 0) {
    throw new Error('preview-theme-token-resolver: no :root block found in globals.css');
  }
  if (darkDecls.size === 0) {
    throw new Error('preview-theme-token-resolver: no .dark block found in globals.css');
  }

  const lightLookup = (n: string): string | undefined => rootDecls.get(n) ?? themeDecls.get(n);
  const darkLookup = (n: string): string | undefined =>
    darkDecls.get(n) ?? rootDecls.get(n) ?? themeDecls.get(n);

  return PREVIEW_TOKEN_NAMES.map((name) => {
    const rawLight = rootDecls.get(name);
    if (rawLight === undefined) {
      throw new Error(`preview-theme-token-resolver: ${name} not declared in any :root block`);
    }
    const rawDark = darkDecls.get(name) ?? rawLight;
    return {
      name,
      light: resolveVars(rawLight, lightLookup),
      dark: resolveVars(rawDark, darkLookup),
    };
  });
}

/**
 * Render the resolved tokens as a TypeScript module body. Output stays
 * byte-stable so the regen script and the drift test both anchor on it.
 */
export function renderPreviewThemeTokensModule(tokens: ResolvedPreviewToken[]): string {
  const entries = tokens
    .map((t) => `  { name: '${t.name}', light: '${t.light}', dark: '${t.dark}' },`)
    .join('\n');
  return `/**
 * Preview-iframe theme tokens — the design-token subset injected into every
 * \`html preview\` iframe's \`srcDoc\` as CSS custom properties, so embedded
 * content can reference \`var(--chart-1)\`, \`var(--foreground)\`, … and track
 * the reader's light/dark theme.
 *
 * GENERATED FILE — do not hand-edit. Regenerate after changing any listed
 * token in \`packages/app/src/globals.css\`:
 *
 *     pnpm exec tsx packages/core/scripts/generate-preview-theme-tokens.ts
 *
 * Drift between this file and the CSS is caught by
 * \`preview-theme-tokens.uncached.test.ts\` (re-resolves from globals.css).
 */

export interface PreviewThemeToken {
  /** CSS custom-property name, e.g. '--chart-1'. */
  readonly name: string;
  /** Resolved light-theme value — every \`var()\` indirection resolved to a literal. */
  readonly light: string;
  /** Resolved dark-theme value. */
  readonly dark: string;
}

export const PREVIEW_THEME_TOKENS: readonly PreviewThemeToken[] = [
${entries}
];
`;
}

/**
 * WCAG 2.x contrast ratio (1–21) between two CSS colors. Thin wrapper over
 * culori so the chart-palette contrast test can live in `src/` without a
 * direct culori import — culori is a script-tier dependency here, mirroring
 * how `chrome-resolver` is the sole culori importer for the chrome tokens.
 */
export function wcagContrast(colorA: string, colorB: string): number {
  return culoriWcagContrast(colorA, colorB);
}