waybetter/packages/runtime/src/domHub.ts
CRT 5982f8ba98 Feature modules: a feature table (areas, flags, modes), a registry that runs a module only on its surfaces, one shared observer for every feature and plugin, settings from a schema, selector health with self-pause
- featureTable.ts: areas, per-feature flags, core flags, modes as presets; sparse storage, ownership (an area that is off turns off what it owns), mode switching that keeps or drops manual changes, table validation
- featureModules.ts: createFeatureRegistry (flag + surface gating, scoped context, palette commands under the area with a budget of 5, settings dialog, probes, hotfix selector overrides and kill flags)
- settingsForm.ts: a settings schema normalizes stored values and draws the controls from the UI kit
- domHub observeSelector; api.observe goes through the shared hub (a root of the caller's own keeps its observer)
- createFeatureFlags: a delivery is the whole state (a flag it does not name is at its default), resolve() for ownership, current()
2026-09-30 11:11:42 +00:00

193 lines
7.8 KiB
TypeScript

// One MutationObserver and one animation frame per page for every DOM feature of a site runtime.
// Without it, each feature (nav items, tweaks, buttons, fixes, viewers) observes the whole <body>
// subtree and schedules its own frame, so every mutation the site makes costs one callback and one
// frame of scans per feature. Here a mutation marks the features interested in its kind (child list,
// text, a named attribute) and they run together in the next frame: layout readers first, then DOM
// writers, so a reader never forces a synchronous layout behind another feature's write. Features
// marked `offOnHeavy` do not run on the site's heavy pages (see `configureDomHub`), e.g. a WASM chat.
export type DomWatch = {
/** Also run on text changes (characterData). */
characterData?: boolean;
/** Also run when one of these attributes changes. */
attributes?: string[];
/** Skip on the site's heavy pages (`DomHubConfig.heavyPath`). */
offOnHeavy?: boolean;
/** 'read' features (layout reads) run before 'write' features (the default) in a frame. */
phase?: 'read' | 'write';
};
export type DomWatchHandle = { schedule(): void; dispose(): void };
export type DomHubConfig = {
/** Console prefix for feature failures, e.g. "wayBetter for X". */
label: string;
/** Pathnames where `offOnHeavy` features are skipped; null = none. */
heavyPath: RegExp | null;
};
export type DomWindow = {
document: Document;
location: { pathname: string };
MutationObserver: typeof MutationObserver;
requestAnimationFrame(callback: FrameRequestCallback): number;
};
type Sub = { run: () => void; opts: DomWatch; pending: boolean };
type Hub = { subs: Sub[]; mark(sub: Sub): void; refresh(): void };
const config: DomHubConfig = { label: 'wayBetter', heavyPath: null };
const hubs = new WeakMap<object, Hub>();
/** Set once by the site adapter, before features register. */
export function configureDomHub(next: Partial<DomHubConfig>): void {
Object.assign(config, next);
}
export function isHeavyPath(pathname: string): boolean {
return !!config.heavyPath && config.heavyPath.test(pathname);
}
function hubFor(win: DomWindow): Hub {
const existing = hubs.get(win);
if (existing) return existing;
const doc = win.document;
let frameRequested = false;
let observer: MutationObserver | null = null;
let observing = '';
const frame = () => {
frameRequested = false;
const heavy = isHeavyPath(win.location.pathname ?? '');
for (const phase of ['read', 'write'] as const) {
for (const sub of hub.subs.slice()) {
if (!sub.pending || (sub.opts.phase ?? 'write') !== phase) continue;
sub.pending = false;
if (heavy && sub.opts.offOnHeavy) continue;
try { sub.run(); } catch (error) { console.error(`[${config.label}] DOM feature failed`, error); }
}
}
};
const onRecords = (records: MutationRecord[]) => {
let childList = false;
let characterData = false;
let attributes: Set<string> | null = null;
const known = Array.isArray(records) && records.length > 0;
if (known) {
for (const record of records) {
if (record.type === 'childList') childList = true;
else if (record.type === 'characterData') characterData = true;
else if (record.type === 'attributes' && record.attributeName) (attributes ??= new Set()).add(record.attributeName);
}
}
for (const sub of hub.subs) {
if (!known || childList || (characterData && sub.opts.characterData)
|| (attributes && sub.opts.attributes?.some(name => attributes!.has(name)))) hub.mark(sub);
}
};
const start = () => {
if (!doc.body || !hub.subs.length) return;
const characterData = hub.subs.some(sub => sub.opts.characterData);
const filter = [...new Set(hub.subs.flatMap(sub => sub.opts.attributes ?? []))].sort();
const key = `${characterData}|${filter.join(',')}`;
if (observer && observing === key) return;
observer ??= new win.MutationObserver(onRecords);
observing = key;
// Re-observing the same node replaces its options.
observer.observe(doc.body, {
childList: true, subtree: true,
...(characterData ? { characterData: true } : {}),
...(filter.length ? { attributes: true, attributeFilter: filter } : {}),
});
};
const hub: Hub = {
subs: [],
mark(sub) {
sub.pending = true;
if (!frameRequested) { frameRequested = true; win.requestAnimationFrame(frame); }
},
refresh() {
if (!hub.subs.length) {
observer?.disconnect();
observer = null;
observing = '';
doc.removeEventListener('DOMContentLoaded', start);
hubs.delete(win);
return;
}
if (doc.body) start();
else doc.addEventListener('DOMContentLoaded', start, { once: true });
},
};
hubs.set(win, hub);
return hub;
}
type SelectorSub = { selector: string; callback: (element: Element) => void; seen: WeakSet<Element>; report(error: unknown): void };
type SelectorHub = { subs: SelectorSub[]; handle: DomWatchHandle | null };
// One per window and heavy-page behaviour: every selector observer of that kind shares its watch.
const selectorHubs = new WeakMap<object, Map<boolean, SelectorHub>>();
export type ObserveOptions = {
/** Skip on the site's heavy pages (default false). */
offOnHeavy?: boolean;
/** A callback that throws is handed here (default: the hub's console line). */
report?(error: unknown): void;
};
/**
* Calls `callback` once for every element matching `selector`, now and as the page renders more.
* Every call shares the hub's one MutationObserver and one frame: a page with a hundred selector
* observers still has one observer, and a mutation costs one frame in which each observer looks
* for elements it has not seen yet. Returns the disposer.
*/
export function observeSelector(win: DomWindow, selector: string, callback: (element: Element) => void, options: ObserveOptions = {}): () => void {
const offOnHeavy = !!options.offOnHeavy;
let kinds = selectorHubs.get(win);
if (!kinds) { kinds = new Map(); selectorHubs.set(win, kinds); }
let hub = kinds.get(offOnHeavy);
if (!hub) { hub = { subs: [], handle: null }; kinds.set(offOnHeavy, hub); }
const owner = hub;
const report = options.report ?? ((error: unknown) => console.error(`[${config.label}] DOM feature failed`, error));
const sub: SelectorSub = { selector, callback, seen: new WeakSet(), report };
const scan = (target: SelectorSub) => {
for (const element of Array.from(win.document.querySelectorAll(target.selector))) {
if (target.seen.has(element)) continue;
target.seen.add(element);
try { target.callback(element); } catch (error) { target.report(error); }
}
};
owner.subs.push(sub);
owner.handle ??= watchDom(win, () => { for (const item of owner.subs.slice()) scan(item); }, { offOnHeavy });
if (!(offOnHeavy && isHeavyPath(win.location.pathname ?? ''))) scan(sub);
let active = true;
return () => {
if (!active) return;
active = false;
const index = owner.subs.indexOf(sub);
if (index >= 0) owner.subs.splice(index, 1);
if (!owner.subs.length) { owner.handle?.dispose(); owner.handle = null; }
};
}
/**
* Runs `run` in the next animation frame after body mutations of the watched kinds (child list
* always), or whenever `schedule()` is called (scroll, popstate, input, ...). Several calls in one
* frame run it once.
*/
export function watchDom(win: DomWindow, run: () => void, opts: DomWatch = {}): DomWatchHandle {
const hub = hubFor(win);
const sub: Sub = { run, opts, pending: false };
hub.subs.push(sub);
hub.refresh();
let active = true;
return {
schedule: () => { if (active) hub.mark(sub); },
dispose() {
if (!active) return;
active = false;
const index = hub.subs.indexOf(sub);
if (index >= 0) hub.subs.splice(index, 1);
hub.refresh();
},
};
}