Theme runtime: a static sheet for what does not depend on the site's stylesheet (components, variants, decoration, icons); refresh()

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.
This commit is contained in:
CRTkafa 2026-09-30 23:30:34 +07:00
parent 3d9189077a
commit 124ebb3a73

View file

@ -55,10 +55,12 @@ function effectiveRule(rule: RuleNode, supported: (condition: string) => boolean
} }
/** /**
* Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s, each as * Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s (the
* it takes effect (`effectiveRule`). A `@supports` group the browser does not pass is left out. * 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): RuleLike[] { 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 rules: RuleLike[] = [];
const css = (doc.defaultView as (Window & typeof globalThis) | null)?.CSS; const css = (doc.defaultView as (Window & typeof globalThis) | null)?.CSS;
const verdicts = new Map<string, boolean>(); const verdicts = new Map<string, boolean>();
@ -75,7 +77,7 @@ export function collectRules(doc: Document, own: HTMLStyleElement | null): RuleL
} }
}; };
for (const sheet of Array.from(doc.styleSheets)) { for (const sheet of Array.from(doc.styleSheets)) {
if (own && sheet.ownerNode === own) continue; if (ours.includes(sheet.ownerNode as HTMLStyleElement)) continue;
try { walk(sheet.cssRules as unknown as ArrayLike<RuleNode>); } catch { /* Cross-origin sheet. */ } try { walk(sheet.cssRules as unknown as ArrayLike<RuleNode>); } catch { /* Cross-origin sheet. */ }
} }
return rules; return rules;
@ -140,6 +142,15 @@ export type ThemeRuntimeSite<Mode extends string = string> = {
resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme; resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme;
/** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */ /** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */
siteVars?: readonly string[]; 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`). */ /** Id of the theme's `<style>` (default `wb-theme-css`). */
styleId?: string; styleId?: string;
/** Name in console errors. */ /** Name in console errors. */
@ -156,6 +167,8 @@ export type ThemeHandle<Mode extends string = string> = {
resolved(): ResolvedTheme; resolved(): ResolvedTheme;
/** Calls `listener` after the theme or the site's color mode changes. */ /** Calls `listener` after the theme or the site's color mode changes. */
onChange(listener: () => void): () => void; 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 }; export type ThemeRuntimeOptions = { /** Registers bundled families (e.g. "Geist") in the page before they are used. */ loadFonts?(names: string[]): void };
@ -166,6 +179,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
const doc = win.document; const doc = win.document;
const name = site.name ?? 'wayBetter'; const name = site.name ?? 'wayBetter';
const styleId = site.styleId ?? 'wb-theme-css'; const styleId = site.styleId ?? 'wb-theme-css';
const staticId = site.staticId ?? 'wb-theme-static';
const { catalog } = site; const { catalog } = site;
// Document start (no <html> yet): the snapshot as an adopted sheet paints with the site's first // 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. // frame. It stays while the live CSS is for the same theme and site mode, and goes when they differ.
@ -226,15 +240,34 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
modeObserver.observe(doc.body, { attributes: true, attributeFilter: ['style'] }); 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) => { const render = (force = false) => {
let style = doc.getElementById(styleId) as HTMLStyleElement | null; let style = doc.getElementById(styleId) as HTMLStyleElement | null;
let fixed = doc.getElementById(staticId) as HTMLStyleElement | null;
if (doc.body) { watchMode(); syncResolved(); } if (doc.body) { watchMode(); syncResolved(); }
if (!active()) { style?.remove(); lastKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; } if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
if (!doc.body) return; if (!doc.body) return;
const snapshotKey = `${JSON.stringify(choice)}|${mode}`; const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
if (early && snapshot?.key !== snapshotKey) dropEarly(); if (early && snapshot?.key !== snapshotKey) dropEarly();
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0)}`; // The static sheet follows the theme and the mode only (and `refresh()`), never the site's rules.
if (!force && key === lastKey) return; 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; lastKey = key;
if (!style) { style = doc.createElement('style'); style.id = styleId; } 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). // The site's own values, not the ones our previous render overrode (switching themes re-reads them).
@ -245,11 +278,13 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
for (const name of site.siteVars) vars[name] = rootStyle.getPropertyValue(name).trim(); for (const name of site.siteVars) vars[name] = rootStyle.getPropertyValue(name).trim();
} }
if (style.sheet) style.sheet.disabled = false; if (style.sheet) style.sheet.disabled = false;
const css = site.css(collectRules(doc, style), choice, mode, vars); const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars);
if (style.textContent !== css) style.textContent = css; if (style.textContent !== css) style.textContent = css;
// Last in <head> so equal-specificity `!important` rules win over the site's. // Last in <head> so equal-specificity `!important` rules win over the site's; the static sheet after it.
if (style.parentNode !== doc.head || doc.head.lastElementChild !== style) (doc.head || doc.documentElement).appendChild(style); const last = fixed?.isConnected && doc.head?.lastElementChild === fixed ? fixed.previousElementSibling : doc.head?.lastElementChild;
const full = `${themeVarsCss(resolved)}\n${css}`; 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 }); } if (full !== savedCss) { savedCss = full; writeSnapshot(storage, { key: snapshotKey, choice, css: full }); }
}; };
@ -276,6 +311,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
listeners.add(listener); listeners.add(listener);
return () => { listeners.delete(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 // 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. // live CSS then already renders at DOMContentLoaded instead of after the page finished loading.