runtime + host: the theme engine (theme documents, choice catalog, page runtime, fonts; native theme state)

The site-independent theme engine moves from wayBetter for X into the framework:
- runtime/themeSpec.ts: theme document types, the schema's defaults (BASE_*), sanitizing,
  import, overrides, ensureContrast, font roles/stacks, font choices, backgrounds.
- runtime/themeChoice.ts: ThemeChoice and createThemeCatalog(builtins) (normalize, base,
  resolve, palette, all), choiceForId, serializeChoice.
- runtime/themeRuntime.ts: installThemeRuntime(win, site) (live CSS over the site's rules,
  --wb-* vars, site color mode, first-frame snapshot), collectRules, resolvedFonts.
- runtime/fonts.ts: bundled fonts and owner-downloaded Google Fonts from bytes.
- themeApi exports hexToRgb, mix and MONO_FAMILIES (one copy: themeTokens and themeSpec use them).
- host theme.rs: ThemeChoice/ThemeScopes over a site's ThemeSite (envelope checks against
  theme.schema.json, which theme a tab shows, page color, delivery script).
This commit is contained in:
CRTkafa 2026-09-29 06:07:59 +00:00
parent 1a49cf58d4
commit 7568126f2b
9 changed files with 1542 additions and 14 deletions

View file

@ -0,0 +1,243 @@
// The theme engine in a site's page: keeps one `<style>` with the theme's CSS in sync while the site
// adds its own rules (React apps insert them lazily), exposes the resolved theme as `--wb-*` custom
// properties for plugins and the UI kit, follows the site's own color mode, and paints the last
// theme from the page's first frame (a snapshot in the page's storage). What the CSS is comes from
// the site adapter (`ThemeRuntimeSite`): X re-declares its own stylesheet rules with the theme's
// colors (`buildThemeCss`) and adds type/shape/layout rules over its selectors.
import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts';
import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts';
import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts';
/** A style rule as the engine reads it (CSSStyleRule, or a plain object in tests). */
export type RuleLike = { selectorText: string; style: { getPropertyValue(name: string): string; length?: number } };
/** The font roles as the plugin API reports them in a site's page; an inheriting interface uses `siteStack` (the site's own font). */
export function resolvedFonts(font: FontSpec, siteStack: string): ResolvedFonts {
const roles = resolveFontRoles(font, siteStack);
return Object.fromEntries(FONT_ROLE_NAMES.map(role => {
const { stack, weight, size, tracking, tabular, inherited } = roles[role];
return [role, { stack, weight, size, tracking, tabular, inherited }];
})) as ResolvedFonts;
}
/** Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s. */
export function collectRules(doc: Document, own: HTMLStyleElement | null): RuleLike[] {
const rules: RuleLike[] = [];
const walk = (list: CSSRuleList) => {
for (const rule of Array.from(list)) {
if ('selectorText' in rule && 'style' in rule) rules.push(rule as unknown as RuleLike);
else if ('cssRules' in rule && !('selectorText' in rule)) walk((rule as CSSGroupingRule).cssRules);
}
};
for (const sheet of Array.from(doc.styleSheets)) {
if (own && sheet.ownerNode === own) continue;
try { walk(sheet.cssRules); } catch { /* Cross-origin sheet. */ }
}
return rules;
}
function ruleCount(doc: Document): number {
let count = 0;
for (const sheet of Array.from(doc.styleSheets)) { try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ } }
return count;
}
/**
* The last theme CSS a tab showed, kept in the page's own storage so the next document paints it
* from its first frame: native code only hands the theme over once the page has finished loading,
* and the live CSS needs the site's rules, which it inserts while it renders. sessionStorage is per
* tab and survives reloads and navigations; localStorage (smaller cap: the site uses it too) is per
* account and covers a tab's first document.
*/
export type ThemeSnapshot = { key: string; choice: unknown; css: string };
const SNAPSHOT_KEY = 'wb:theme-snapshot';
export const SNAPSHOT_SESSION_MAX = 1_000_000;
export const SNAPSHOT_LOCAL_MAX = 200_000;
export type SnapshotStores = { session?: Storage | null; local?: Storage | null };
function stores(win: Window): SnapshotStores {
const get = (name: 'sessionStorage' | 'localStorage') => { try { return win[name]; } catch { return null; } };
return { session: get('sessionStorage'), local: get('localStorage') };
}
export function readSnapshot({ session, local }: SnapshotStores): ThemeSnapshot | null {
for (const store of [session, local]) {
try {
const value = JSON.parse(store?.getItem(SNAPSHOT_KEY) || 'null') as Partial<ThemeSnapshot> | null;
if (value && typeof value.key === 'string' && typeof value.css === 'string' && value.css && value.choice) return value as ThemeSnapshot;
} catch { /* Missing, blocked or foreign data: no snapshot. */ }
}
return null;
}
/** Stores `snapshot` (null clears it: the site's own look needs none), each store within its cap. */
export function writeSnapshot({ session, local }: SnapshotStores, snapshot: ThemeSnapshot | null) {
const json = snapshot ? JSON.stringify(snapshot) : '';
for (const [store, max] of [[session, SNAPSHOT_SESSION_MAX], [local, SNAPSHOT_LOCAL_MAX]] as const) {
try {
if (json && json.length <= max) store?.setItem(SNAPSHOT_KEY, json);
else store?.removeItem(SNAPSHOT_KEY);
} catch { /* Quota or blocked storage: the next document just starts unthemed. */ }
}
}
/** What the engine needs to know about a site. `Mode` is the site's own color mode (X: light, dim, dark). */
export type ThemeRuntimeSite<Mode extends string = string> = {
/** The site's built-in themes (themeChoice.ts). */
catalog: ThemeCatalog;
/** The mode before the page has a body. */
initialMode: Mode;
/** The site's color mode as the page paints it now (read before the theme's own override: e.g. the body's inline style). */
readMode(win: Window): Mode;
/** The theme's CSS for the site's current `rules` (the engine's own sheet excluded) in `mode`; `vars` are `siteVars` as the site sets them. */
css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record<string, string>): string;
/** The active theme resolved for plugins and the UI kit (the site's own palette when the theme keeps its colors). */
resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme;
/** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */
siteVars?: readonly string[];
/** Id of the theme's `<style>` (default `wb-theme-css`). */
styleId?: string;
/** Name in console errors. */
name?: string;
};
export type ThemeHandle<Mode extends string = string> = {
apply(choice: unknown): void;
current(): ThemeChoice;
theme(): ThemeSpec;
/** The site's color mode the theme was last rendered for. */
mode(): Mode;
/** The active theme as values for plugins (`api.theme.current()`). */
resolved(): ResolvedTheme;
/** Calls `listener` after the theme or the site's color mode changes. */
onChange(listener: () => void): () => void;
};
export type ThemeRuntimeOptions = { /** Registers bundled families (e.g. "Geist") in the page before they are used. */ loadFonts?(names: string[]): void };
const VARS_ID = 'wb-theme-vars';
/** Keeps the site's page in the owner's theme (see the top of this file). */
export function installThemeRuntime<Mode extends string>(win: Window, site: ThemeRuntimeSite<Mode>, options: ThemeRuntimeOptions = {}): ThemeHandle<Mode> {
const doc = win.document;
const name = site.name ?? 'wayBetter';
const styleId = site.styleId ?? 'wb-theme-css';
const { catalog } = site;
// Document start (no <html> yet): the snapshot as an adopted sheet paints with the site's first
// frame. It stays while the live CSS is for the same theme and site mode, and goes when they differ.
const storage = stores(win);
const snapshot = readSnapshot(storage);
let early: CSSStyleSheet | null = null;
if (snapshot) {
try {
const Sheet = (win as Window & typeof globalThis).CSSStyleSheet;
early = new Sheet();
early.replaceSync(snapshot.css);
doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, early];
} catch { early = null; }
}
const dropEarly = () => {
if (!early) return;
const sheet = early;
early = null;
try { doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(item => item !== sheet); } catch { /* Never break the site. */ }
};
let savedCss = snapshot?.css ?? '';
let choice = catalog.defaultChoice;
let theme = catalog.resolve(choice);
let lastKey = '';
let timer: ReturnType<typeof setInterval> | null = null;
const active = () => !isNeutral(theme) || !!choice.accent;
let mode: Mode = site.initialMode;
let resolved: ResolvedTheme = site.resolved(choice, mode);
let resolvedKey = themeKey(resolved);
const listeners = new Set<() => void>();
const readMode = () => (doc.body ? site.readMode(win) : mode);
/** `--wb-*` on :root for plugin CSS, and a change notice when anything visible changed. */
const syncResolved = () => {
if (doc.body) mode = readMode();
resolved = site.resolved(choice, mode);
const key = themeKey(resolved);
let vars = doc.getElementById(VARS_ID) as HTMLStyleElement | null;
if (!vars?.isConnected) {
vars = doc.createElement('style');
vars.id = VARS_ID;
(doc.head || doc.documentElement).appendChild(vars);
}
const css = themeVarsCss(resolved);
if (vars.textContent !== css) vars.textContent = css;
if (key === resolvedKey) return;
resolvedKey = key;
for (const listener of [...listeners]) {
try { listener(); } catch (error) { console.error(`[${name}] theme listener failed`, error); }
}
};
let modeObserver: MutationObserver | null = null;
const watchMode = () => {
if (modeObserver || !doc.body) return;
// Sites repaint the body when their own display setting changes (X: Default / Dim / Lights out).
const Observer = (win as Window & typeof globalThis).MutationObserver ?? globalThis.MutationObserver;
if (!Observer) return;
modeObserver = new Observer(() => { try { if (readMode() !== mode) syncResolved(); } catch { /* Never break the site. */ } });
modeObserver.observe(doc.body, { attributes: true, attributeFilter: ['style'] });
};
const render = (force = false) => {
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
if (doc.body) { watchMode(); syncResolved(); }
if (!active()) { style?.remove(); lastKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
if (!doc.body) return;
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
if (early && snapshot?.key !== snapshotKey) dropEarly();
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0)}`;
if (!force && key === lastKey) return;
lastKey = key;
if (!style) { style = doc.createElement('style'); style.id = styleId; }
// The site's own values, not the ones our previous render overrode (switching themes re-reads them).
if (style.sheet) style.sheet.disabled = true;
const vars: Record<string, string> = {};
if (site.siteVars?.length) {
const rootStyle = win.getComputedStyle(doc.documentElement);
for (const name of site.siteVars) vars[name] = rootStyle.getPropertyValue(name).trim();
}
if (style.sheet) style.sheet.disabled = false;
const css = site.css(collectRules(doc, style), choice, mode, vars);
if (style.textContent !== css) style.textContent = css;
// Last in <head> so equal-specificity `!important` rules win over the site's.
if (style.parentNode !== doc.head || doc.head.lastElementChild !== style) (doc.head || doc.documentElement).appendChild(style);
const full = `${themeVarsCss(resolved)}\n${css}`;
if (full !== savedCss) { savedCss = full; writeSnapshot(storage, { key: snapshotKey, choice, css: full }); }
};
const handle: ThemeHandle<Mode> = {
apply(input) {
choice = catalog.normalize(input);
theme = catalog.resolve(choice);
const fonts = bundledFontsUsed(theme);
if (fonts.length) { try { options.loadFonts?.(fonts); } catch (error) { console.error(`[${name}] theme fonts failed`, error); } }
if (active()) {
if (!timer) timer = setInterval(() => { try { render(); } catch { /* Never break the site. */ } }, 1200);
} else if (timer) { clearInterval(timer); timer = null; }
try { render(true); } catch (error) { console.error(`[${name}] theme failed`, error); }
win.dispatchEvent(new CustomEvent('wb-theme'));
},
current: () => choice,
theme: () => theme,
mode: () => mode,
resolved: () => {
if (doc.body && readMode() !== mode) syncResolved();
return resolved;
},
onChange(listener) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
};
// The snapshot's theme until native code hands over the current one (usually the same): the
// live CSS then already renders at DOMContentLoaded instead of after the page finished loading.
if (snapshot) { try { handle.apply(snapshot.choice); } catch { /* Never break the site. */ } }
if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', () => render(true), { once: true });
// `--wb-*` exist from the start (the site's own palette until a theme is applied), for plugins and the UI kit.
else if (doc.body) { try { watchMode(); syncResolved(); } catch { /* Never break the site. */ } }
return handle;
}