Theme engine: page flags instead of page-wide :has()
A theme rule gated by html:has(...) / body:not(:has(...)) made the browser restyle the whole page for every node the site inserted. Measured live on x.com under any theme: about 440 elements restyled per insertion, against 1.5 without a theme; with the gates gone, 2.5. Sites name page states as selectors (ThemeRuntimeSite.flags). The engine keeps html[data-wb-<name>] in step, checked once per DOM hub frame and also inside the site's open shadow roots. It passes the flags that hold to css(), so CSS for one state can be left out of the other. Changing flags rebuild the theme (they are part of its render key). Tests: pageFlags, flagAttribute.
This commit is contained in:
parent
42a51390bd
commit
8a2df3d17d
2 changed files with 68 additions and 8 deletions
|
|
@ -5,7 +5,7 @@
|
||||||
// the site adapter (`ThemeRuntimeSite`): X re-declares its own stylesheet rules with the theme's
|
// 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.
|
// colors (`buildThemeCss`) and adds type/shape/layout rules over its selectors.
|
||||||
|
|
||||||
import { domRoots } from './domHub.ts';
|
import { domRoots, watchDom, type DomWatchHandle } from './domHub.ts';
|
||||||
import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts';
|
import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts';
|
||||||
import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts';
|
import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts';
|
||||||
import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts';
|
import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts';
|
||||||
|
|
@ -160,7 +160,7 @@ export type ThemeRuntimeSite<Mode extends string = string> = {
|
||||||
/** 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). */
|
/** 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;
|
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. */
|
/** 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;
|
css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record<string, string>, flags: readonly string[]): string;
|
||||||
/** The active theme resolved for plugins and the UI kit (the site's own palette when the theme keeps its colors). */
|
/** 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;
|
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). */
|
||||||
|
|
@ -178,8 +178,28 @@ export type ThemeRuntimeSite<Mode extends string = string> = {
|
||||||
styleId?: string;
|
styleId?: string;
|
||||||
/** Name in console errors. */
|
/** Name in console errors. */
|
||||||
name?: string;
|
name?: string;
|
||||||
|
/**
|
||||||
|
* Page states the theme's CSS keys on, as `html[data-wb-<name>]` attributes kept by the engine:
|
||||||
|
* set while `selector` matches in the page or one of its open shadow roots (domHub `shadowHosts`).
|
||||||
|
* A theme rule gated by `html[data-wb-chat]` costs nothing when the page changes; the same gate
|
||||||
|
* as `html:has(...)` makes the browser re-match the whole page on every insertion (seen on x.com:
|
||||||
|
* 10-100 ms per inserted node under a theme instead of 0.1 ms).
|
||||||
|
*/
|
||||||
|
flags?: Readonly<Record<string, string>>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The attribute a page flag sets on `<html>`. */
|
||||||
|
export const flagAttribute = (name: string) => `data-wb-${name}`;
|
||||||
|
|
||||||
|
/** Which of `flags` hold in `roots` now (pure, for tests). */
|
||||||
|
export function pageFlags(roots: ReadonlyArray<{ querySelector(selector: string): unknown }>, flags: Readonly<Record<string, string>>): string[] {
|
||||||
|
const on: string[] = [];
|
||||||
|
for (const [name, selector] of Object.entries(flags)) {
|
||||||
|
try { if (roots.some(root => !!root.querySelector(selector))) on.push(name); } catch { /* A bad selector is never on. */ }
|
||||||
|
}
|
||||||
|
return on;
|
||||||
|
}
|
||||||
|
|
||||||
export type ThemeHandle<Mode extends string = string> = {
|
export type ThemeHandle<Mode extends string = string> = {
|
||||||
apply(choice: unknown): void;
|
apply(choice: unknown): void;
|
||||||
current(): ThemeChoice;
|
current(): ThemeChoice;
|
||||||
|
|
@ -266,6 +286,36 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
let staticKey = '';
|
let staticKey = '';
|
||||||
let staticText = '';
|
let staticText = '';
|
||||||
let siteVars: Record<string, string> = {};
|
let siteVars: Record<string, string> = {};
|
||||||
|
// Page flags (`site.flags`): checked once per hub frame after the page changed, on every page (heavy ones too).
|
||||||
|
const flagNames = Object.keys(site.flags ?? {});
|
||||||
|
let flagWatch: DomWatchHandle | null = null;
|
||||||
|
// The flags that hold now; the theme's CSS is rebuilt when they change (a rule that only applies to a
|
||||||
|
// signed-out page can then be left out of a signed-in one instead of being gated by `:has()`).
|
||||||
|
let flagState: string[] = [];
|
||||||
|
const syncFlags = () => {
|
||||||
|
const root = doc.documentElement;
|
||||||
|
if (!root || !flagNames.length) return;
|
||||||
|
let on: string[] = [];
|
||||||
|
try { on = pageFlags(domRoots(win), site.flags!); } catch { on = []; }
|
||||||
|
for (const name of flagNames) {
|
||||||
|
const attr = flagAttribute(name);
|
||||||
|
const want = on.includes(name);
|
||||||
|
if (root.hasAttribute(attr) !== want) { if (want) root.setAttribute(attr, ''); else root.removeAttribute(attr); }
|
||||||
|
}
|
||||||
|
const changed = on.join(' ') !== flagState.join(' ');
|
||||||
|
flagState = on;
|
||||||
|
return changed;
|
||||||
|
};
|
||||||
|
const flagsOn = (on: boolean) => {
|
||||||
|
if (!flagNames.length) return;
|
||||||
|
if (on) {
|
||||||
|
syncFlags();
|
||||||
|
if (!flagWatch) { try { flagWatch = watchDom(win as never, () => { if (syncFlags()) { try { render(); } catch { /* Never break the site. */ } } }, { offOnHeavy: false }); } catch { flagWatch = null; } }
|
||||||
|
} else {
|
||||||
|
flagWatch?.dispose(); flagWatch = null;
|
||||||
|
for (const name of flagNames) doc.documentElement?.removeAttribute(flagAttribute(name));
|
||||||
|
}
|
||||||
|
};
|
||||||
// Open shadow roots the site renders a part of itself in (domHub `shadowHosts`; X's chat embed since
|
// Open shadow roots the site renders a part of itself in (domHub `shadowHosts`; X's chat embed since
|
||||||
// 2026-10-01): the document's sheets do not reach inside, so each root adopts the theme built from
|
// 2026-10-01): the document's sheets do not reach inside, so each root adopts the theme built from
|
||||||
// its own rules plus the static sheet, kept last among its sheets, rebuilt when its rules change and
|
// its own rules plus the static sheet, kept last among its sheets, rebuilt when its rules change and
|
||||||
|
|
@ -283,7 +333,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
try { item = { sheet: new Sheet(), key: '' }; } catch { continue; }
|
try { item = { sheet: new Sheet(), key: '' }; } catch { continue; }
|
||||||
rootSheets.set(root, item);
|
rootSheets.set(root, item);
|
||||||
}
|
}
|
||||||
const key = `${snapshotKey}|${rootRuleCount(root, item.sheet)}|${staticText.length}`;
|
const key = `${snapshotKey}|${flagState.join(' ')}|${rootRuleCount(root, item.sheet)}|${staticText.length}`;
|
||||||
if (force || item.key !== key) {
|
if (force || item.key !== key) {
|
||||||
item.key = key;
|
item.key = key;
|
||||||
// The site's primitives as the root sees them (its own sheets may declare them; the document may not), read with our sheet off.
|
// The site's primitives as the root sees them (its own sheets may declare them; the document may not), read with our sheet off.
|
||||||
|
|
@ -295,7 +345,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
item.sheet.disabled = false;
|
item.sheet.disabled = false;
|
||||||
}
|
}
|
||||||
let css = '';
|
let css = '';
|
||||||
try { css = site.css(collectRootRules(root, item.sheet, (win as Window & typeof globalThis).CSS), choice, mode, vars); } catch (error) { console.error(`[${name}] theme (shadow root) failed`, error); }
|
try { css = site.css(collectRootRules(root, item.sheet, (win as Window & typeof globalThis).CSS), choice, mode, vars, flagState); } catch (error) { console.error(`[${name}] theme (shadow root) failed`, error); }
|
||||||
try { item.sheet.replaceSync(staticText ? `${css}\n${staticText}` : css); } catch { /* Keeps the last good rules. */ }
|
try { item.sheet.replaceSync(staticText ? `${css}\n${staticText}` : css); } catch { /* Keeps the last good rules. */ }
|
||||||
}
|
}
|
||||||
// Last, so equal-specificity `!important` rules win over the site's; the site may re-set its list.
|
// Last, so equal-specificity `!important` rules win over the site's; the site may re-set its list.
|
||||||
|
|
@ -312,8 +362,9 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
|
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
|
||||||
let fixed = doc.getElementById(staticId) 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(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); syncRoots(false, '', false); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
|
if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); syncRoots(false, '', false); flagsOn(false); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
|
||||||
if (!doc.body) return;
|
if (!doc.body) return;
|
||||||
|
flagsOn(true);
|
||||||
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
|
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
|
||||||
if (early && snapshot?.key !== snapshotKey) dropEarly();
|
if (early && snapshot?.key !== snapshotKey) dropEarly();
|
||||||
// The static sheet follows the theme and the mode only (and `refresh()`), never the site's rules.
|
// The static sheet follows the theme and the mode only (and `refresh()`), never the site's rules.
|
||||||
|
|
@ -327,7 +378,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
if (fixed.textContent !== text) fixed.textContent = text;
|
if (fixed.textContent !== text) fixed.textContent = text;
|
||||||
} else { fixed?.remove(); fixed = null; }
|
} else { fixed?.remove(); fixed = null; }
|
||||||
}
|
}
|
||||||
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`;
|
const key = `${JSON.stringify(choice)}|${mode}|${flagState.join(' ')}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`;
|
||||||
if (!force && key === lastKey) { placeStatic(fixed, style); syncRoots(true, snapshotKey, false); return; }
|
if (!force && key === lastKey) { placeStatic(fixed, style); syncRoots(true, snapshotKey, false); return; }
|
||||||
lastKey = key;
|
lastKey = key;
|
||||||
if (!style) { style = doc.createElement('style'); style.id = styleId; }
|
if (!style) { style = doc.createElement('style'); style.id = styleId; }
|
||||||
|
|
@ -340,7 +391,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
}
|
}
|
||||||
if (style.sheet) style.sheet.disabled = false;
|
if (style.sheet) style.sheet.disabled = false;
|
||||||
siteVars = vars;
|
siteVars = vars;
|
||||||
const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars);
|
const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars, flagState);
|
||||||
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; the static sheet after it.
|
// 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;
|
const last = fixed?.isConnected && doc.head?.lastElementChild === fixed ? fixed.previousElementSibling : doc.head?.lastElementChild;
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import assert from 'node:assert/strict';
|
||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.ts';
|
import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.ts';
|
||||||
import { choiceForId, createThemeCatalog, serializeChoice, MAX_USER_THEMES } from '../src/themeChoice.ts';
|
import { choiceForId, createThemeCatalog, serializeChoice, MAX_USER_THEMES } from '../src/themeChoice.ts';
|
||||||
import { SNAPSHOT_LOCAL_MAX, collectRootRules, collectRules, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
|
import { SNAPSHOT_LOCAL_MAX, collectRootRules, collectRules, flagAttribute, pageFlags, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
|
||||||
import {
|
import {
|
||||||
BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, ROLE_LIMITS, applyOverrides, backgroundLayers, ensureContrast, fontChoiceOf, fontStack, isNeutral,
|
BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, ROLE_LIMITS, applyOverrides, backgroundLayers, ensureContrast, fontChoiceOf, fontStack, isNeutral,
|
||||||
pageBackgroundCss, parseThemeJson, resolveFontRoles, sanitizeSpec, withFamily, withRoles, type ThemeSpec,
|
pageBackgroundCss, parseThemeJson, resolveFontRoles, sanitizeSpec, withFamily, withRoles, type ThemeSpec,
|
||||||
|
|
@ -262,3 +262,12 @@ test('collectRootRules reads a shadow root\'s adopted sheets and <style> element
|
||||||
assert.deepEqual(rules.map(rule => rule.selectorText), [':host, [data-theme="dark"]', '.bg-white\/15']);
|
assert.deepEqual(rules.map(rule => rule.selectorText), [':host, [data-theme="dark"]', '.bg-white\/15']);
|
||||||
assert.equal(rules[1]!.style.getPropertyValue('background-color'), 'color-mix(in oklab, var(--x-white) 15%, transparent)');
|
assert.equal(rules[1]!.style.getPropertyValue('background-color'), 'color-mix(in oklab, var(--x-white) 15%, transparent)');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('page flags: a flag holds while its selector matches in the page or one of its shadow roots', () => {
|
||||||
|
const root = (hits: string[]) => ({ querySelector: (selector: string) => (hits.includes(selector) ? {} : null) });
|
||||||
|
const flags = { chat: '[data-testid="dm-container"]', 'signed-out': 'body:not(:has(main))', bad: '::nope(' };
|
||||||
|
assert.deepEqual(pageFlags([root([]), root(['[data-testid="dm-container"]'])], flags), ['chat'], 'a match in a shadow root counts');
|
||||||
|
assert.deepEqual(pageFlags([root([])], flags), []);
|
||||||
|
assert.deepEqual(pageFlags([{ querySelector: () => { throw new Error('bad'); } }], { bad: 'x' }), [], 'a selector that throws is never on');
|
||||||
|
assert.equal(flagAttribute('chat'), 'data-wb-chat');
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue