The site adapter's staticCss(choice, mode) is written to its own <style> (wb-theme-static), rebuilt only when the theme or the site's mode changes or on refresh(); the palette pass never reads it back as the site's rules, and the first-frame snapshot carries it.
323 lines
17 KiB
TypeScript
323 lines
17 KiB
TypeScript
// 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;
|
|
}
|
|
|
|
type RuleNode = { selectorText?: string; style?: RuleLike['style']; cssRules?: ArrayLike<RuleNode>; conditionText?: string; type?: number; constructor?: { name?: string } };
|
|
const isSupports = (rule: RuleNode) => rule.type === 12 || rule.constructor?.name === 'CSSSupportsRule';
|
|
|
|
/**
|
|
* A style rule as it takes effect. Tailwind 4 writes an opacity utility as a fallback plus the real
|
|
* value in a nested `@supports`:
|
|
* `.bg-white\/15 { background-color: var(--white); @supports (color: color-mix(in lab, red, red)) { background-color: color-mix(in oklab, var(--white) 15%, transparent) } }`.
|
|
* Read alone, the outer declaration is a solid white fill; where the browser passes the condition the
|
|
* nested one is what paints, so it answers for the rule.
|
|
*/
|
|
function effectiveRule(rule: RuleNode, supported: (condition: string) => boolean): RuleLike {
|
|
const overrides: Array<RuleLike['style']> = [];
|
|
for (const child of Array.from(rule.cssRules ?? [])) {
|
|
if (!isSupports(child) || !supported(child.conditionText ?? '')) continue;
|
|
for (const inner of Array.from(child.cssRules ?? [])) {
|
|
// Bare declarations inside the group: a CSSNestedDeclarations, or `& { }` in older engines.
|
|
if (inner.style && (inner.selectorText === undefined || inner.selectorText === '&')) overrides.push(inner.style);
|
|
}
|
|
}
|
|
if (!overrides.length) return rule as RuleLike;
|
|
const outer = rule.style!;
|
|
return {
|
|
selectorText: rule.selectorText!,
|
|
style: {
|
|
getPropertyValue(name) {
|
|
for (let i = overrides.length - 1; i >= 0; i--) { const value = overrides[i]!.getPropertyValue(name); if (value) return value; }
|
|
return outer.getPropertyValue(name);
|
|
},
|
|
length: outer.length,
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s (the
|
|
* engine's own sheets: read as the site's, their radii and colors would be re-declared), each as it
|
|
* takes effect (`effectiveRule`). A `@supports` group the browser does not pass is left out.
|
|
*/
|
|
export function collectRules(doc: Document, own: HTMLStyleElement | null | ReadonlyArray<HTMLStyleElement | null>): RuleLike[] {
|
|
const ours = (Array.isArray(own) ? own : [own]).filter(Boolean) as HTMLStyleElement[];
|
|
const rules: RuleLike[] = [];
|
|
const css = (doc.defaultView as (Window & typeof globalThis) | null)?.CSS;
|
|
const verdicts = new Map<string, boolean>();
|
|
const supported = (condition: string) => {
|
|
if (!condition || !css?.supports) return true;
|
|
let verdict = verdicts.get(condition);
|
|
if (verdict === undefined) { try { verdict = css.supports(condition); } catch { verdict = true; } verdicts.set(condition, verdict); }
|
|
return verdict;
|
|
};
|
|
const walk = (list: ArrayLike<RuleNode>) => {
|
|
for (const rule of Array.from(list)) {
|
|
if (rule.selectorText !== undefined && rule.style) rules.push(effectiveRule(rule, supported));
|
|
else if (rule.cssRules && rule.selectorText === undefined && (!isSupports(rule) || supported(rule.conditionText ?? ''))) walk(rule.cssRules);
|
|
}
|
|
};
|
|
for (const sheet of Array.from(doc.styleSheets)) {
|
|
if (ours.includes(sheet.ownerNode as HTMLStyleElement)) continue;
|
|
try { walk(sheet.cssRules as unknown as ArrayLike<RuleNode>); } 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[];
|
|
/**
|
|
* The theme's CSS that does not depend on the site's stylesheet: components, variants, decoration,
|
|
* icons. It lives in its own sheet (`staticId`), so the site inserting rules never rebuilds it; it is
|
|
* rebuilt when the theme or the site's mode changes and on `refresh()` (the owner's switches, the
|
|
* icon choice, the language).
|
|
*/
|
|
staticCss?(choice: ThemeChoice, mode: Mode): string;
|
|
/** Id of that sheet's `<style>` (default `wb-theme-static`). */
|
|
staticId?: 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;
|
|
/** Rebuilds the theme's CSS now: something it depends on besides the theme changed (the owner's switches, the icon choice). */
|
|
refresh(): 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 staticId = site.staticId ?? 'wb-theme-static';
|
|
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'] });
|
|
};
|
|
|
|
let staticKey = '';
|
|
let staticText = '';
|
|
/** The static sheet sits right after the palette sheet (its part rules are more specific anyway; order only breaks ties). */
|
|
const placeStatic = (fixed: HTMLStyleElement | null, style: HTMLStyleElement | null) => {
|
|
if (!fixed || !style?.isConnected) return;
|
|
if (style.nextElementSibling !== fixed) style.after(fixed);
|
|
};
|
|
const render = (force = false) => {
|
|
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
|
|
let fixed = doc.getElementById(staticId) as HTMLStyleElement | null;
|
|
if (doc.body) { watchMode(); syncResolved(); }
|
|
if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
|
|
if (!doc.body) return;
|
|
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
|
|
if (early && snapshot?.key !== snapshotKey) dropEarly();
|
|
// The static sheet follows the theme and the mode only (and `refresh()`), never the site's rules.
|
|
if (site.staticCss && (force || staticKey !== snapshotKey)) {
|
|
staticKey = snapshotKey;
|
|
let text = '';
|
|
try { text = site.staticCss(choice, mode); } catch (error) { console.error(`[${name}] theme structure failed`, error); }
|
|
staticText = text;
|
|
if (text) {
|
|
if (!fixed) { fixed = doc.createElement('style'); fixed.id = staticId; }
|
|
if (fixed.textContent !== text) fixed.textContent = text;
|
|
} else { fixed?.remove(); fixed = null; }
|
|
}
|
|
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`;
|
|
if (!force && key === lastKey) { placeStatic(fixed, style); 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, fixed]), choice, mode, vars);
|
|
if (style.textContent !== css) style.textContent = css;
|
|
// Last in <head> so equal-specificity `!important` rules win over the site's; the static sheet after it.
|
|
const last = fixed?.isConnected && doc.head?.lastElementChild === fixed ? fixed.previousElementSibling : doc.head?.lastElementChild;
|
|
if (style.parentNode !== doc.head || last !== style) (doc.head || doc.documentElement).appendChild(style);
|
|
placeStatic(fixed, style);
|
|
const full = `${themeVarsCss(resolved)}\n${css}${staticText ? `\n${staticText}` : ''}`;
|
|
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); };
|
|
},
|
|
refresh() { try { render(true); } catch (error) { console.error(`[${name}] theme failed`, error); } },
|
|
};
|
|
// 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;
|
|
}
|