Theme engine: the site's open shadow roots get the theme too
X renders its chat inside the open shadow root of its embed host since 2026-10-01; the theme's <style> in <head> never reached it. For each root the DOM hub names (domRoots), the engine now builds the theme from that root's own rules (collectRootRules: adopted sheets and <style> elements, its own sheet excluded), adds the static sheet, adopts it last among the root's sheets, rebuilds it when the root's rules change and takes it off when the theme is off or the root is gone. Test: collectRootRules.
This commit is contained in:
parent
2c12aa01fd
commit
8bbdbecf0d
2 changed files with 71 additions and 6 deletions
|
|
@ -5,6 +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 { 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';
|
||||||
|
|
@ -61,8 +62,22 @@ function effectiveRule(rule: RuleNode, supported: (condition: string) => boolean
|
||||||
*/
|
*/
|
||||||
export function collectRules(doc: Document, own: HTMLStyleElement | null | ReadonlyArray<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 ours = (Array.isArray(own) ? own : [own]).filter(Boolean) as HTMLStyleElement[];
|
||||||
|
const sheets = Array.from(doc.styleSheets).filter(sheet => !ours.includes(sheet.ownerNode as HTMLStyleElement));
|
||||||
|
return rulesOf(sheets, (doc.defaultView as (Window & typeof globalThis) | null)?.CSS);
|
||||||
|
}
|
||||||
|
|
||||||
|
type SheetLike = { cssRules: CSSRuleList | ArrayLike<unknown> };
|
||||||
|
/**
|
||||||
|
* The same for an open shadow root the site renders a part of itself in (X's chat embed): its adopted
|
||||||
|
* sheets and its `<style>` elements, except the engine's own adopted `own` sheet.
|
||||||
|
*/
|
||||||
|
export function collectRootRules(root: { adoptedStyleSheets?: readonly SheetLike[]; styleSheets?: ArrayLike<SheetLike> }, own: SheetLike | null, css?: { supports?(condition: string): boolean }): RuleLike[] {
|
||||||
|
const sheets = [...Array.from(root.adoptedStyleSheets ?? []), ...Array.from(root.styleSheets ?? [])].filter(sheet => sheet !== own);
|
||||||
|
return rulesOf(sheets, css);
|
||||||
|
}
|
||||||
|
|
||||||
|
function rulesOf(sheets: readonly SheetLike[], css: { supports?(condition: string): boolean } | undefined): RuleLike[] {
|
||||||
const rules: RuleLike[] = [];
|
const rules: RuleLike[] = [];
|
||||||
const css = (doc.defaultView as (Window & typeof globalThis) | null)?.CSS;
|
|
||||||
const verdicts = new Map<string, boolean>();
|
const verdicts = new Map<string, boolean>();
|
||||||
const supported = (condition: string) => {
|
const supported = (condition: string) => {
|
||||||
if (!condition || !css?.supports) return true;
|
if (!condition || !css?.supports) return true;
|
||||||
|
|
@ -76,13 +91,21 @@ export function collectRules(doc: Document, own: HTMLStyleElement | null | Reado
|
||||||
else if (rule.cssRules && rule.selectorText === undefined && (!isSupports(rule) || supported(rule.conditionText ?? ''))) walk(rule.cssRules);
|
else if (rule.cssRules && rule.selectorText === undefined && (!isSupports(rule) || supported(rule.conditionText ?? ''))) walk(rule.cssRules);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
for (const sheet of Array.from(doc.styleSheets)) {
|
for (const sheet of sheets) {
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function rootRuleCount(root: ShadowRoot, own: CSSStyleSheet | null): number {
|
||||||
|
let count = 0;
|
||||||
|
for (const sheet of [...Array.from(root.adoptedStyleSheets ?? []), ...Array.from(root.styleSheets ?? [])]) {
|
||||||
|
if (sheet === own) continue;
|
||||||
|
try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ }
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
function ruleCount(doc: Document): number {
|
function ruleCount(doc: Document): number {
|
||||||
let count = 0;
|
let count = 0;
|
||||||
for (const sheet of Array.from(doc.styleSheets)) { try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ } }
|
for (const sheet of Array.from(doc.styleSheets)) { try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ } }
|
||||||
|
|
@ -242,6 +265,36 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
|
|
||||||
let staticKey = '';
|
let staticKey = '';
|
||||||
let staticText = '';
|
let staticText = '';
|
||||||
|
let siteVars: Record<string, string> = {};
|
||||||
|
// 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
|
||||||
|
// taken off when the theme is off or the root is gone.
|
||||||
|
const rootSheets = new Map<ShadowRoot, { sheet: CSSStyleSheet; key: string }>();
|
||||||
|
const detach = (root: ShadowRoot, sheet: CSSStyleSheet) => { try { root.adoptedStyleSheets = root.adoptedStyleSheets.filter(item => item !== sheet); } catch { /* Root gone. */ } };
|
||||||
|
const syncRoots = (on: boolean, snapshotKey: string, force: boolean) => {
|
||||||
|
let roots: ShadowRoot[] = [];
|
||||||
|
if (on) { try { roots = domRoots(win).slice(1) as ShadowRoot[]; } catch { roots = []; } }
|
||||||
|
for (const [root, item] of rootSheets) if (!roots.includes(root)) { detach(root, item.sheet); rootSheets.delete(root); }
|
||||||
|
const Sheet = (win as Window & typeof globalThis).CSSStyleSheet;
|
||||||
|
for (const root of roots) {
|
||||||
|
let item = rootSheets.get(root);
|
||||||
|
if (!item) {
|
||||||
|
try { item = { sheet: new Sheet(), key: '' }; } catch { continue; }
|
||||||
|
rootSheets.set(root, item);
|
||||||
|
}
|
||||||
|
const key = `${snapshotKey}|${rootRuleCount(root, item.sheet)}|${staticText.length}`;
|
||||||
|
if (force || item.key !== key) {
|
||||||
|
item.key = key;
|
||||||
|
let css = '';
|
||||||
|
try { css = site.css(collectRootRules(root, item.sheet, (win as Window & typeof globalThis).CSS), choice, mode, siteVars); } 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.
|
||||||
|
const list = root.adoptedStyleSheets;
|
||||||
|
if (list[list.length - 1] !== item.sheet) { try { root.adoptedStyleSheets = [...list.filter(sheet => sheet !== item!.sheet), item.sheet]; } catch { /* Never break the site. */ } }
|
||||||
|
}
|
||||||
|
};
|
||||||
/** The static sheet sits right after the palette sheet (its part rules are more specific anyway; order only breaks ties). */
|
/** 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) => {
|
const placeStatic = (fixed: HTMLStyleElement | null, style: HTMLStyleElement | null) => {
|
||||||
if (!fixed || !style?.isConnected) return;
|
if (!fixed || !style?.isConnected) return;
|
||||||
|
|
@ -251,7 +304,7 @@ 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(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
|
if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); syncRoots(false, '', false); 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();
|
||||||
|
|
@ -267,7 +320,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
||||||
} 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}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`;
|
||||||
if (!force && key === lastKey) { placeStatic(fixed, style); 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; }
|
||||||
// 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).
|
||||||
|
|
@ -278,12 +331,14 @@ 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;
|
||||||
|
siteVars = vars;
|
||||||
const css = site.css(collectRules(doc, [style, fixed]), 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; 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;
|
||||||
if (style.parentNode !== doc.head || last !== style) (doc.head || doc.documentElement).appendChild(style);
|
if (style.parentNode !== doc.head || last !== style) (doc.head || doc.documentElement).appendChild(style);
|
||||||
placeStatic(fixed, style);
|
placeStatic(fixed, style);
|
||||||
|
syncRoots(true, snapshotKey, force);
|
||||||
const full = `${themeVarsCss(resolved)}\n${css}${staticText ? `\n${staticText}` : ''}`;
|
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 }); }
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -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, collectRules, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
|
import { SNAPSHOT_LOCAL_MAX, collectRootRules, collectRules, 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,
|
||||||
|
|
@ -252,3 +252,13 @@ test('collectRules leaves the engine\'s own sheet out and survives a cross-origi
|
||||||
], defaultView: null } as unknown as Document;
|
], defaultView: null } as unknown as Document;
|
||||||
assert.deepEqual(collectRules(doc, own).map(rule => rule.selectorText), ['.deep']);
|
assert.deepEqual(collectRules(doc, own).map(rule => rule.selectorText), ['.deep']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('collectRootRules reads a shadow root\'s adopted sheets and <style> elements, never the engine\'s own sheet (X chat embed, 2026-10-01)', () => {
|
||||||
|
const own = { cssRules: [styleRule('.ours', { color: 'red' })] };
|
||||||
|
const rules = collectRootRules({
|
||||||
|
adoptedStyleSheets: [{ cssRules: [styleRule(':host, [data-theme="dark"]', { '--x-bg-primary': '#000' })] }, own],
|
||||||
|
styleSheets: [{ cssRules: [styleRule('.bg-white\/15', { 'background-color': 'var(--x-white)' }, [supportsRule(MIX, [{ style: decl({ 'background-color': 'color-mix(in oklab, var(--x-white) 15%, transparent)' }) }])])] }],
|
||||||
|
} as never, own as never, { supports: () => true });
|
||||||
|
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)');
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue