/** * Read a sitekit consumer's `globals.css` (+ its generated `fonts.ts`) into a * SiteTheme. Pure; `scripts/import-repo.ts` is the command around it. * * Only the light `@theme` block is read (the first one); a site with a dark * scheme gets its `.dark`/media block read as `darkPalette` when present. * Colours may be literal hex or `var(--primitive-…)` references to hex. * * Text tokens below WCAG AA are moved to the nearest shade that passes, * because sitekit's theme schema refuses them: darker on a light page, * lighter on a dark one. Every move is returned so it can be reported. */ import { AA_TEXT, contrastRatio, siteThemeSchema, SITE_FACES, type SiteFace, type SitePalette, type SiteTheme, } from '@bitbaum/sitekit'; export type ThemeChange = { token: keyof SitePalette; from: string; to: string; before: number; after: number; against: string; }; const TOKENS: Record = { surfacePage: 'color-surface-page', surfaceRaised: 'color-surface-raised', fgPrimary: 'color-fg-primary', fgSecondary: 'color-fg-secondary', fgTertiary: 'color-fg-tertiary', fgMuted: 'color-fg-muted', borderSubtle: 'color-border-subtle', borderStrong: 'color-border-strong', accent: 'color-accent', statusPositive: 'color-status-positive', statusWarning: 'color-status-warning', statusNegative: 'color-status-negative', }; /** Every `--name: value;` in a block of CSS, last one wins. */ export function declarations(css: string): Map { const out = new Map(); for (const m of css.matchAll(/--([a-z0-9-]+)\s*:\s*([^;]+);/gi)) out.set(m[1]!, m[2]!.trim()); return out; } /** The body of the first `@theme { … }` block. */ export function themeBlock(css: string): string | null { const start = css.search(/@theme\s*\{/); if (start < 0) return null; let depth = 0; for (let i = css.indexOf('{', start); i < css.length; i++) { if (css[i] === '{') depth++; else if (css[i] === '}' && --depth === 0) return css.slice(css.indexOf('{', start) + 1, i); } return null; } function resolveColor( value: string | undefined, vars: Map, depth = 0, ): string | null { if (!value || depth > 5) return null; const v = value.trim(); if (/^#[0-9a-f]{6}$/i.test(v)) return v.toLowerCase(); if (/^#[0-9a-f]{3}$/i.test(v)) return ('#' + [...v.slice(1)].map((c) => c + c).join('')).toLowerCase(); const ref = /^var\(--([a-z0-9-]+)\)$/i.exec(v); return ref ? resolveColor(vars.get(ref[1]!), vars, depth + 1) : null; } function hexToRgb(h: string): [number, number, number] { return [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)) as [number, number, number]; } function rgbToHex(rgb: number[]): string { return ( '#' + rgb .map((c) => Math.round(Math.max(0, Math.min(255, c))) .toString(16) .padStart(2, '0'), ) .join('') ); } /** * The closest colour to `color`, mixed toward black (or white), whose * contrast against every background is at least `min`. Mixing in small steps * keeps the hue; the first step that passes is the smallest change. */ export function nearestPassing(color: string, backgrounds: string[], min = AA_TEXT): string { const ok = (c: string) => backgrounds.every((b) => contrastRatio(c, b) >= min); if (ok(color)) return color; const rgb = hexToRgb(color); const lightBg = backgrounds.every( (b) => contrastRatio(b, '#000000') > contrastRatio(b, '#ffffff'), ); const target = lightBg ? 0 : 255; for (let t = 0.01; t <= 1; t += 0.01) { const c = rgbToHex(rgb.map((x) => x + (target - x) * t)); if (ok(c)) return c; } return lightBg ? '#000000' : '#ffffff'; } /** Move every text token (and the accent behind a button label) to AA. */ export function fixPalette(p: SitePalette): { palette: SitePalette; changes: ThemeChange[] } { const palette = { ...p }; const changes: ThemeChange[] = []; const surfaces = [palette.surfacePage, palette.surfaceRaised]; for (const token of ['fgPrimary', 'fgSecondary', 'fgTertiary', 'fgMuted'] as const) { const from = palette[token]; const to = nearestPassing(from, surfaces); if (to !== from) { const worst = (c: string) => Math.min(...surfaces.map((s) => contrastRatio(c, s))); changes.push({ token, from, to, before: worst(from), after: worst(to), against: 'page and raised surfaces', }); palette[token] = to; } } // The filled button's label is the page colour, so the accent moves, away from the page. const from = palette.accent; const to = nearestPassing(from, [palette.surfacePage]); if (to !== from) { changes.push({ token: 'accent', from, to, before: contrastRatio(from, palette.surfacePage), after: contrastRatio(to, palette.surfacePage), against: 'the button label (page colour)', }); palette.accent = to; } return { palette, changes }; } /** `display=cormorant-garamond;…` and `body=dm-sans;…` from design-tokens' generated fonts.ts. */ export function facesFromFontsTs(fontsTs: string): { display?: string; body?: string } { return { display: /'display=([a-z0-9-]+)/.exec(fontsTs)?.[1], body: /'body=([a-z0-9-]+)/.exec(fontsTs)?.[1], }; } function faceFor(stack: string | undefined, generated: string | undefined): SiteFace { if (stack && /var\(--font-(display|body)\)/.test(stack) && generated && generated in SITE_FACES) { return generated as SiteFace; } const s = (stack ?? '').toLowerCase(); for (const [id, css] of Object.entries(SITE_FACES)) { const family = /'([^']+)'/.exec(css)?.[1]?.toLowerCase(); if (family && s.includes(family)) return id as SiteFace; } if (s.includes('georgia') || (s.includes('serif') && !s.includes('sans'))) return 'system-serif'; return 'system-sans'; } export type ImportedTheme = { ok: true; theme: SiteTheme; changes: ThemeChange[] } | { ok: false; reason: string }; export function importTheme(css: string, fontsTs = ''): ImportedTheme { const block = themeBlock(css); if (!block) return { ok: false, reason: 'no @theme block in globals.css' }; const vars = declarations(block); const raw = {} as SitePalette; for (const [key, name] of Object.entries(TOKENS) as [keyof SitePalette, string][]) { const color = resolveColor(vars.get(name), vars); if (!color) return { ok: false, reason: `--${name} is missing or not a hex colour` }; raw[key] = color; } const { palette, changes } = fixPalette(raw); const faces = facesFromFontsTs(fontsTs); const shell = /^(\d+)rem$/.exec(vars.get('spacing-shell') ?? '')?.[1]; const candidate = { palette, type: { heading: faceFor(vars.get('font-heading'), faces.display), body: faceFor(vars.get('font-sans'), faces.body), ...(vars.get('tracking-display') ? { trackingDisplay: vars.get('tracking-display') } : {}), ...(vars.get('tracking-caps') ? { trackingCaps: vars.get('tracking-caps') } : {}), }, ...(shell ? { shellRem: Math.min(96, Math.max(48, Number(shell))) } : {}), }; const parsed = siteThemeSchema.safeParse(candidate); if (!parsed.success) { return { ok: false, reason: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '), }; } return { ok: true, theme: parsed.data, changes }; }