From 9fbfa791b4d06437e15f031d904d810774d2546e Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 1 Oct 2026 10:42:45 +0700 Subject: [PATCH 1/3] 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-] 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. Co-Authored-By: Claude Opus 5.5 --- packages/runtime/src/themeRuntime.ts | 65 +++++++++++++++++++--- packages/runtime/tests/themeEngine.test.ts | 11 +++- 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/packages/runtime/src/themeRuntime.ts b/packages/runtime/src/themeRuntime.ts index c938b5a..e0326d2 100644 --- a/packages/runtime/src/themeRuntime.ts +++ b/packages/runtime/src/themeRuntime.ts @@ -5,7 +5,7 @@ // 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 { 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 type { ThemeCatalog, ThemeChoice } from './themeChoice.ts'; import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts'; @@ -160,7 +160,7 @@ export type ThemeRuntimeSite = { /** 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; + css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record, 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). */ resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme; /** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */ @@ -178,8 +178,28 @@ export type ThemeRuntimeSite = { styleId?: string; /** Name in console errors. */ name?: string; + /** + * Page states the theme's CSS keys on, as `html[data-wb-]` 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>; }; +/** The attribute a page flag sets on ``. */ +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>): 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 = { apply(choice: unknown): void; current(): ThemeChoice; @@ -266,6 +286,36 @@ export function installThemeRuntime(win: Window, site: Them let staticKey = ''; let staticText = ''; let siteVars: Record = {}; + // 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 // 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 @@ -283,7 +333,7 @@ export function installThemeRuntime(win: Window, site: Them try { item = { sheet: new Sheet(), key: '' }; } catch { continue; } 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) { 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. @@ -295,7 +345,7 @@ export function installThemeRuntime(win: Window, site: Them item.sheet.disabled = false; } 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. */ } } // 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(win: Window, site: Them 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(); 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; + flagsOn(true); 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. @@ -327,7 +378,7 @@ export function installThemeRuntime(win: Window, site: Them 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)}`; + 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; } lastKey = key; if (!style) { style = doc.createElement('style'); style.id = styleId; } @@ -340,7 +391,7 @@ export function installThemeRuntime(win: Window, site: Them } if (style.sheet) style.sheet.disabled = false; 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; // Last in 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; diff --git a/packages/runtime/tests/themeEngine.test.ts b/packages/runtime/tests/themeEngine.test.ts index e145ce3..a6808a1 100644 --- a/packages/runtime/tests/themeEngine.test.ts +++ b/packages/runtime/tests/themeEngine.test.ts @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.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 { 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, @@ -262,3 +262,12 @@ test('collectRootRules reads a shadow root\'s adopted sheets and