Compare commits
No commits in common. "966a28cae664f4b75a3f011f4a15694faea5dc16" and "f6deac4145f0c4c0cb6328ed2e62ba3960ad65e9" have entirely different histories.
966a28cae6
...
f6deac4145
6 changed files with 15 additions and 109 deletions
|
|
@ -5,7 +5,6 @@
|
|||
// 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 { 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';
|
||||
|
|
@ -62,22 +61,8 @@ function effectiveRule(rule: RuleNode, supported: (condition: string) => boolean
|
|||
*/
|
||||
export function collectRules(doc: Document, own: HTMLStyleElement | null | ReadonlyArray<HTMLStyleElement | null>): RuleLike[] {
|
||||
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 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;
|
||||
|
|
@ -91,21 +76,13 @@ function rulesOf(sheets: readonly SheetLike[], css: { supports?(condition: strin
|
|||
else if (rule.cssRules && rule.selectorText === undefined && (!isSupports(rule) || supported(rule.conditionText ?? ''))) walk(rule.cssRules);
|
||||
}
|
||||
};
|
||||
for (const sheet of sheets) {
|
||||
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 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 {
|
||||
let count = 0;
|
||||
for (const sheet of Array.from(doc.styleSheets)) { try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ } }
|
||||
|
|
@ -265,44 +242,6 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
|||
|
||||
let staticKey = '';
|
||||
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;
|
||||
// The site's primitives as the root sees them (its own sheets may declare them; the document may not), read with our sheet off.
|
||||
const vars = { ...siteVars };
|
||||
if (site.siteVars?.length) {
|
||||
const probe = root.firstElementChild ?? root.host;
|
||||
item.sheet.disabled = true;
|
||||
try { const style = win.getComputedStyle(probe); for (const name of site.siteVars) { const value = style.getPropertyValue(name).trim(); if (value) vars[name] = value; } } catch { /* Keep the document's. */ }
|
||||
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 { 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). */
|
||||
const placeStatic = (fixed: HTMLStyleElement | null, style: HTMLStyleElement | null) => {
|
||||
if (!fixed || !style?.isConnected) return;
|
||||
|
|
@ -312,7 +251,7 @@ export function installThemeRuntime<Mode extends string>(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(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
|
||||
if (!doc.body) return;
|
||||
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
|
||||
if (early && snapshot?.key !== snapshotKey) dropEarly();
|
||||
|
|
@ -328,7 +267,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
|||
} 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); syncRoots(true, snapshotKey, false); return; }
|
||||
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).
|
||||
|
|
@ -339,14 +278,12 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
|
|||
for (const name of site.siteVars) vars[name] = rootStyle.getPropertyValue(name).trim();
|
||||
}
|
||||
if (style.sheet) style.sheet.disabled = false;
|
||||
siteVars = vars;
|
||||
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);
|
||||
syncRoots(true, snapshotKey, force);
|
||||
const full = `${themeVarsCss(resolved)}\n${css}${staticText ? `\n${staticText}` : ''}`;
|
||||
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 { 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, collectRules, 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,
|
||||
|
|
@ -252,13 +252,3 @@ test('collectRules leaves the engine\'s own sheet out and survives a cross-origi
|
|||
], defaultView: null } as unknown as Document;
|
||||
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)');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -306,7 +306,7 @@ export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
|
|||
case 'store': return item(id, section(t('wb.panel.section.store')), 'bag', { run: () => shell.openPanelSection('store') });
|
||||
case 'strings': return item(id, section(menuText('strings')), 'globe', { run: () => shell.openPanelSection('languages') });
|
||||
case 'workspaces': return item(id, t('wb.ws.title'), 'layout', { submenu: true, hint: workspaces.store.items.find(entry => entry.id === workspaces.active)?.name });
|
||||
case 'find': return item(id, menuText('find'), 'search', { shortcut: 'Ctrl+F', disabled: !(shell.api?.panels ?? []).some(panel => isWeb(panel) && panel.api.isVisible), run: () => shell.shortcut('find') });
|
||||
case 'find': return item(id, menuText('find'), 'search', { shortcut: 'Ctrl+F', disabled: !active || !isWeb(active), run: () => shell.shortcut('find') });
|
||||
case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) });
|
||||
case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') });
|
||||
case 'developer': return item(id, menuText('developer'), 'code', { submenu: true });
|
||||
|
|
|
|||
|
|
@ -46,17 +46,10 @@ export function FindBar({ tabId, url, onClose }: { tabId: string; url: string; o
|
|||
|
||||
// The shell takes the keyboard (Ctrl+F was pressed in the page); closing clears the highlights.
|
||||
useEffect(() => {
|
||||
const focusField = () => { if (input.current && document.activeElement !== input.current) input.current.focus(); };
|
||||
invoke('shell_focus').then(focusField, () => {});
|
||||
focusField();
|
||||
invoke('shell_focus').catch(() => {});
|
||||
input.current?.focus();
|
||||
diag(`find bar open: hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`);
|
||||
// The page may keep the keyboard (the keys that opened the bar were pressed in it): if the shell
|
||||
// still does not have it a moment later, ask once more, so typing never lands in the page.
|
||||
const retry = setTimeout(() => {
|
||||
diag(`find bar +250ms: hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`);
|
||||
if (!document.hasFocus()) invoke('shell_focus').then(() => { focusField(); diag(`find bar refocused: hasFocus=${document.hasFocus()}`); }, () => {});
|
||||
else focusField();
|
||||
}, 250);
|
||||
setTimeout(() => diag(`find bar +300ms: hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`), 300);
|
||||
const again = (event: Event) => { if ((event as CustomEvent<string>).detail === tabId) { input.current?.focus(); input.current?.select(); } };
|
||||
const onStep = (event: Event) => { const detail = (event as CustomEvent<{ id: string; direction: 1 | -1 }>).detail; if (detail.id === tabId) step(detail.direction); };
|
||||
window.addEventListener('bt-find', again);
|
||||
|
|
@ -68,7 +61,6 @@ export function FindBar({ tabId, url, onClose }: { tabId: string; url: string; o
|
|||
}).then(dispose => { if (disposed) dispose(); else unlisten = dispose; }).catch(() => {});
|
||||
return () => {
|
||||
disposed = true;
|
||||
clearTimeout(retry);
|
||||
unlisten?.();
|
||||
window.removeEventListener('bt-find', again);
|
||||
window.removeEventListener('bt-find-step', onStep);
|
||||
|
|
|
|||
|
|
@ -149,18 +149,6 @@ function openAccount(profile: string, options: { force?: boolean; url?: string }
|
|||
const deckPanelId = (deckId: string) => `deck-${deckId}`;
|
||||
/** The last focused tab that is not a deck, for Ctrl+Shift+D back and forth. */
|
||||
let lastNonDeck: string | null = null;
|
||||
/** The last web tab that was in front (Ctrl+F from the app's own tab searches it). */
|
||||
let lastWeb: string | null = null;
|
||||
|
||||
/**
|
||||
* The web tab Ctrl+F searches: the one given, else the last web tab that was in front and is still
|
||||
* on screen, else the first web tab on screen. The app's own tab has no page to search.
|
||||
*/
|
||||
function findTarget(panel: IDockviewPanel | undefined): IDockviewPanel | undefined {
|
||||
if (panel && isWeb(panel)) return panel;
|
||||
const shown = (shell.api?.panels ?? []).filter(item => isWeb(item) && item.api.isVisible);
|
||||
return shown.find(item => item.id === lastWeb) ?? shown[0];
|
||||
}
|
||||
|
||||
/** Opens (or focuses) a deck tab; with no deck yet, creates one. */
|
||||
function openDeck(deckId?: string) {
|
||||
|
|
@ -320,8 +308,8 @@ function runShortcut(shortcut: string, id?: string) {
|
|||
switch (shortcut) {
|
||||
case 'new-tab': addStart(); break;
|
||||
// Find in page: the find bar of that tab (the one the keys were pressed in, else the one in front).
|
||||
case 'find': { const target = findTarget(panel); if (target && hasFeature('find')) { target.api.setActive(); openFind(target.id); } break; }
|
||||
case 'find-next': case 'find-previous': { const target = findTarget(panel); if (target) stepFind(target.id, shortcut === 'find-next' ? 1 : -1); break; }
|
||||
case 'find': if (panel && isWeb(panel) && hasFeature('find')) { panel.api.setActive(); openFind(panel.id); } break;
|
||||
case 'find-next': case 'find-previous': if (panel && isWeb(panel)) stepFind(panel.id, shortcut === 'find-next' ? 1 : -1); break;
|
||||
case 'close-tab': if (panel) closeTab(panel); break;
|
||||
case 'reopen-tab': { const tab = shell.closed.pop(); if (tab) addWeb(tab.url, undefined, true, tab.profile); break; }
|
||||
case 'focus-address': if (panel && (isWeb(panel) || (panel.params as TabParams).kind === 'start')) focusAddress(panel.id); break;
|
||||
|
|
@ -834,7 +822,6 @@ export default function Shell() {
|
|||
const paneChanged = () => window.dispatchEvent(new CustomEvent('bt-active-pane'));
|
||||
api.onDidActivePanelChange(event => {
|
||||
if (event && (event.params as TabParams | undefined)?.kind !== 'deck') lastNonDeck = event.id;
|
||||
if (event && isWeb(event)) lastWeb = event.id;
|
||||
notePanelActive(event?.id);
|
||||
scheduleSync();
|
||||
paneChanged();
|
||||
|
|
|
|||
|
|
@ -171,12 +171,12 @@ test('terms file: comments skipped, short terms get the account rule, generic ac
|
|||
|
||||
test('allowlist: a reviewed context is skipped; the file may not hold a term', () => {
|
||||
const root = dir();
|
||||
writeFileSync(join(root, 'allow.txt'), '# a generated identifier\nsrc/**/*.rs: <term>-Id\n');
|
||||
writeFileSync(join(root, 'allow.txt'), '# HTTP header names\nsrc/**/*.rs: <term>-Age\n');
|
||||
const matcher = createMatcher(TERMS);
|
||||
const allow = loadAllowlist(join(root, 'allow.txt'), matcher);
|
||||
const scan = createScan({ terms: TERMS, allow });
|
||||
scan.content('src/net/cookie.rs', Buffer.from('header("Qix-Id=3600")\n// Qix wrote this\n'));
|
||||
scan.content('docs/cookie.md', Buffer.from('Qix-Id\n'));
|
||||
scan.content('src/net/cookie.rs', Buffer.from('header("Qix-Age=3600")\n// Qix wrote this\n'));
|
||||
scan.content('docs/cookie.md', Buffer.from('Qix-Age\n'));
|
||||
const report = scan.report();
|
||||
assert.deepEqual(report.files.map(entry => [entry.file, entry.hits.map(hit => hit.where)]), [['src/net/cookie.rs', ['2:4']], ['docs/cookie.md', ['1:1']]]);
|
||||
writeFileSync(join(root, 'bad.txt'), 'src/**: by zorblat\n');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue