waybetter/packages/runtime/src/pluginApi.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

400 lines
17 KiB
TypeScript

// `window.<Runtime>.api`: small helpers shared by `*.plugin.js` files so each plugin does not
// re-implement DOM watching, route tracking, local storage and cleanup. Everything here is local to
// the page: no network requests, no account actions. A site adapter adds its own readers (e.g. a
// post/message parser) on top of this core.
//
// `ui` (toasts, alerts, confirmations, prompts, dialogs; ui.ts) and `theme` (the active theme as
// values; themeApi.ts) are part of the core: the site adapter only supplies its theme source.
import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts';
import { createUiKit, type UiKit } from './ui.ts';
import { adoptStyles, type RootStyles } from './styles.ts';
import { observeSelector } from './domHub.ts';
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
import { createPluginI18n, type I18nSource, type PluginI18n, type PluginMessages } from './pluginI18n.ts';
export type { ThemeApi, ThemeSource, UiKit, CommandDefinition, CommandInfo, CommandRegistry, RootStyles, I18nSource, PluginI18n, PluginMessages };
export type Dispose = () => void;
export type PluginStorage = {
get<T>(key: string, fallback: T): T;
/** Returns false when the value could not be stored (quota, storage disabled). */
set(key: string, value: unknown): boolean;
remove(key: string): void;
keys(): string[];
};
/** Collects disposers so a plugin's `stop()` is a single `scope.dispose()`. */
export type PluginScope = {
css(id: string, css: string): void;
/** `api.adoptCSS`, taken off the root on dispose. */
adoptCSS(root: ShadowRoot | Document, css: string): RootStyles;
on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
observe(selector: string, callback: (element: Element) => void): void;
onRouteChange(callback: (href: string, previous: string) => void): void;
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): void;
/** Tracks a node the plugin inserted; it is removed on dispose. */
add<T extends Node>(node: T): T;
/** Runs `fn` on dispose (restore attributes, clear timers, ...). */
defer(fn: Dispose): void;
/** Calls `callback(theme)` after the theme changes, until dispose. */
onThemeChange(callback: Parameters<ThemeApi['onChange']>[0]): void;
/** The UI kit, scoped: dialogs and toasts it opened are closed on dispose. */
readonly ui: UiKit;
/** Command palette entries of the plugin that created this scope, removed on dispose. */
readonly commands: { register(definition: CommandDefinition): Dispose };
dispose(): void;
};
export type CorePluginApi = {
injectCSS(id: string, css: string): void;
clearCSS(id: string): void;
/**
* Styles a shadow root the plugin created (or the document) with a constructable stylesheet:
* the page's Content-Security-Policy cannot refuse it, it is parsed once, and it stays with the
* root wherever its host is moved. Falls back to a `<style>` element where unsupported.
*/
adoptCSS(root: ShadowRoot | Document, css: string): RootStyles;
waitFor(selector: string, timeoutMs?: number): Promise<Element>;
/** Namespaced JSON storage in this tab's localStorage (`<storagePrefix><namespace>:<key>`). */
storage(namespace: string): PluginStorage;
/** Called after the page changes route (pushState/replaceState/back/forward). */
onRouteChange(callback: (href: string, previous: string) => void): Dispose;
/**
* Calls `callback` once for every element matching `selector`, now and as the page renders more.
* Page-wide observers share one MutationObserver (domHub.ts); pass `root` only for a tree of your own.
*/
observe(selector: string, callback: (element: Element) => void, root?: ParentNode): Dispose;
/**
* Single-key shortcuts: `callback(event, focusedItem)` runs only when the user is not typing, no
* Ctrl/Meta/Alt is held and the key is not the second half of one of the site's chords.
*/
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): Dispose;
copyText(text: string): Promise<boolean>;
/** A short status message (the UI kit's toast; `ms` is how long it stays). */
toast(message: string, ms?: number): void;
/** Toasts, alerts, confirmations, prompts and dialogs in the active theme (see ui.ts). */
ui: UiKit;
/** The active theme as values: `current()` and `onChange(fn)` (see themeApi.ts). */
theme: ThemeApi;
/**
* Commands in the shell's command palette (Ctrl+K), listed under the plugin's name and run in
* this page (see commands.ts). Removed when the plugin stops.
*/
commands: CommandRegistry;
/**
* The app's language and the plugin's own strings in it (see pluginI18n.ts). In a plugin's view
* it is bound to that plugin (`plugin.<file name>.*` in the app catalog); `namespace(name)` binds
* it explicitly.
*/
i18n: PluginI18n;
scope(): PluginScope;
};
/** What the site adapter adds to the core: its theme engine, when it has one. */
export type CorePluginExtras = {
theme?: ThemeSource;
/** The app's active locale and catalog (plugin strings, the UI kit's own words). English without it. */
i18n?: I18nSource;
};
export type PluginApiSite = {
/** The runtime global, for error messages (`<name>.waitFor timed out`). */
name: string;
/** Console prefix, e.g. "wayBetter for X". */
product: string;
/** localStorage key prefix, e.g. `bt-plugin:`. */
storagePrefix: string;
/** `data-*` key (camelCase) marking plugin `<style>` elements with their id. */
styleDataKey: string;
/** Id of the kit's shadow host element (`<wb-ui id=…>`), kept from the old single toast. */
toastId: string;
/** Accent used when the site has no theme source (and the page shows none). */
toastBackground: string;
/** The item a single-key shortcut acts on: the focused element's closest match (a post, a message). */
itemSelector: string;
/** Keys that start a two-key chord of the site's own (their second key is never a shortcut). */
chordKeys: readonly string[];
};
const NAMESPACE = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
const ROUTE_POLL_MS = 300;
const CHORD_MS = 1500;
/** True when a key event belongs to text entry, not to page shortcuts. */
export function isTypingTarget(target: EventTarget | null): boolean {
let element = target as (Element & { isContentEditable?: boolean }) | null;
// Focus inside a shadow root (the UI kit's dialogs) reports its host; look at what is focused in it.
while (element && (element as Element).shadowRoot?.activeElement) element = (element as Element).shadowRoot!.activeElement as Element;
if (!element || typeof element.closest !== 'function') return false;
return Boolean(element.isContentEditable) || /^(INPUT|TEXTAREA|SELECT)$/i.test(element.nodeName) || Boolean(element.closest('[contenteditable="true"]'));
}
export function createCorePluginApi(win: Window & typeof globalThis, site: PluginApiSite, extras: CorePluginExtras = {}): CorePluginApi {
const doc = win.document;
const theme = createThemeApi(win, extras.theme, /^#[0-9a-f]{6}$/i.test(site.toastBackground) ? site.toastBackground : undefined);
// Created on first use: the kit touches the DOM only when something is shown.
let kit: ReturnType<typeof createUiKit> | null = null;
const i18n = createPluginI18n(extras.i18n);
const uiKit = () => kit ??= createUiKit(win, { theme, product: site.product, hostId: site.toastId, text: key => extras.i18n?.message(key) });
const ui: UiKit = Object.freeze({
toast: (...args: Parameters<UiKit['toast']>) => uiKit().toast(...args),
alert: (...args: Parameters<UiKit['alert']>) => uiKit().alert(...args),
confirm: (...args: Parameters<UiKit['confirm']>) => uiKit().confirm(...args),
prompt: (...args: Parameters<UiKit['prompt']>) => uiKit().prompt(...args),
dialog: (...args: Parameters<UiKit['dialog']>) => uiKit().dialog(...args),
modal: (...args: Parameters<UiKit['modal']>) => uiKit().modal(...args),
h: (...args: Parameters<UiKit['h']>) => uiKit().h(...args),
});
const styleNodes = new Map<string, HTMLStyleElement>();
const adoptedFallbacks = new Map<string, RootStyles>();
const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error);
const registry = createCommandRegistry({ target: doc, isTyping: event => isTypingTarget(event.target) || isTypingTarget(doc.activeElement), report });
const commands: CommandRegistry = Object.freeze({
register: registry.register,
list: registry.list,
run: registry.run,
onChange: registry.onChange,
withOwner: registry.withOwner,
removeOwner: registry.removeOwner,
});
const routeListeners = new Set<(href: string, previous: string) => void>();
let lastHref = win.location.href;
let routeTimer: ReturnType<typeof setInterval> | null = null;
const checkRoute = () => {
const href = win.location.href;
if (href === lastHref) return;
const previous = lastHref;
lastHref = href;
for (const listener of [...routeListeners]) {
try { listener(href, previous); } catch (error) { report(error); }
}
};
const api: CorePluginApi = {
injectCSS(id, css) {
let node = styleNodes.get(id);
if (!node?.isConnected) {
node = doc.createElement('style');
node.dataset[site.styleDataKey] = id;
(doc.head || doc.documentElement).appendChild(node);
styleNodes.set(id, node);
}
node.textContent = css;
// A CSP that refuses inline styles leaves the element without a sheet: the same rules as an
// adopted sheet instead (CSP does not govern constructed sheets).
const blocked = 'sheet' in node && node.sheet === null && css.trim() !== '';
const fallback = adoptedFallbacks.get(id);
if (blocked) {
if (fallback) fallback.update(css);
else adoptedFallbacks.set(id, adoptStyles(doc, css));
} else if (fallback) {
fallback.remove();
adoptedFallbacks.delete(id);
}
},
clearCSS(id) {
styleNodes.get(id)?.remove();
styleNodes.delete(id);
adoptedFallbacks.get(id)?.remove();
adoptedFallbacks.delete(id);
},
adoptCSS(root, css) {
return adoptStyles(root, css);
},
waitFor(selector, timeoutMs = 15000) {
return new Promise((resolve, reject) => {
const found = doc.querySelector(selector);
if (found) return resolve(found);
const observer = new win.MutationObserver(() => {
const match = doc.querySelector(selector);
if (match) { observer.disconnect(); clearTimeout(timer); resolve(match); }
});
const timer = setTimeout(() => { observer.disconnect(); reject(new Error(`${site.name}.waitFor timed out: ${selector}`)); }, timeoutMs);
observer.observe(doc.documentElement, { childList: true, subtree: true });
});
},
storage(namespace) {
if (!NAMESPACE.test(namespace)) throw new Error(`${site.name}.storage: invalid namespace ${JSON.stringify(namespace)}`);
const prefix = `${site.storagePrefix}${namespace}:`;
const store = () => { try { return win.localStorage; } catch { return null; } };
return {
get(key, fallback) {
try {
const raw = store()?.getItem(prefix + key);
return raw == null ? fallback : JSON.parse(raw);
} catch { return fallback; }
},
set(key, value) {
try {
const target = store();
if (!target) return false;
target.setItem(prefix + key, JSON.stringify(value));
return true;
} catch { return false; }
},
remove(key) {
try { store()?.removeItem(prefix + key); } catch { /* storage unavailable */ }
},
keys() {
const target = store();
if (!target) return [];
const keys: string[] = [];
for (let i = 0; i < target.length; i += 1) {
const key = target.key(i);
if (key?.startsWith(prefix)) keys.push(key.slice(prefix.length));
}
return keys;
},
};
},
onRouteChange(callback) {
routeListeners.add(callback);
if (!routeTimer) {
lastHref = win.location.href;
routeTimer = setInterval(checkRoute, ROUTE_POLL_MS);
win.addEventListener('popstate', checkRoute);
}
return () => {
routeListeners.delete(callback);
if (routeListeners.size === 0 && routeTimer) {
clearInterval(routeTimer);
routeTimer = null;
win.removeEventListener('popstate', checkRoute);
}
};
},
observe(selector, callback, root) {
// The whole page: the shared hub (one MutationObserver and one frame for every plugin and
// feature). A root of the caller's own (a shadow root, a detached tree) keeps its own observer.
if (!root || root === doc) return observeSelector(win, selector, callback, { report });
const seen = new WeakSet<Element>();
let frame = 0;
let disposed = false;
const scan = () => {
frame = 0;
if (disposed) return;
for (const element of Array.from(root.querySelectorAll(selector))) {
if (seen.has(element)) continue;
seen.add(element);
try { callback(element); } catch (error) { report(error); }
}
};
const observer = new win.MutationObserver(() => {
if (!frame) frame = win.requestAnimationFrame(scan);
});
observer.observe(root as Node, { childList: true, subtree: true });
scan();
return () => {
disposed = true;
observer.disconnect();
if (frame) win.cancelAnimationFrame(frame);
};
},
onKey(callback) {
let chordAt = 0;
const listener = (event: KeyboardEvent) => {
if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || event.repeat) return;
if (isTypingTarget(event.target) || isTypingTarget(doc.activeElement)) return;
const now = Date.now();
const inChord = now - chordAt < CHORD_MS;
const chordKey = site.chordKeys.includes(event.key);
chordAt = chordKey && !inChord ? now : 0;
if (inChord || chordKey) return;
const item = doc.activeElement?.closest?.(site.itemSelector) ?? null;
try { callback(event, item); } catch (error) { report(error); }
};
doc.addEventListener('keydown', listener);
return () => doc.removeEventListener('keydown', listener);
},
async copyText(text) {
try {
await win.navigator.clipboard.writeText(text);
return true;
} catch {
const area = doc.createElement('textarea');
area.value = text;
Object.assign(area.style, { position: 'fixed', opacity: '0', pointerEvents: 'none' });
doc.body.appendChild(area);
area.select();
let ok = false;
try { ok = doc.execCommand('copy'); } catch { ok = false; }
area.remove();
return ok;
}
},
toast(message, ms = 2200) {
// The old toast vanished after `ms`; 0 or less meant "at once", so it never means "stay".
ui.toast(String(message), { duration: Number.isFinite(ms) && ms > 0 ? ms : 1 });
},
ui,
theme,
commands,
i18n,
scope() {
let disposers: Dispose[] = [];
let scopedUi: UiKit | null = null;
// A scope belongs to the plugin being started when it is created (usually in start()).
const owner = registry.currentOwner();
return {
css(id, css) {
api.injectCSS(id, css);
disposers.push(() => api.clearCSS(id));
},
adoptCSS(root, css) {
const styles = api.adoptCSS(root, css);
disposers.push(() => styles.remove());
return styles;
},
on(target, type, listener, options) {
target.addEventListener(type, listener, options);
disposers.push(() => target.removeEventListener(type, listener, options));
},
observe(selector, callback) {
disposers.push(api.observe(selector, callback));
},
onRouteChange(callback) {
disposers.push(api.onRouteChange(callback));
},
onKey(callback) {
disposers.push(api.onKey(callback));
},
add(node) {
disposers.push(() => (node as unknown as ChildNode).remove?.());
return node;
},
defer(fn) {
disposers.push(fn);
},
onThemeChange(callback) {
disposers.push(theme.onChange(callback));
},
get ui() {
if (!scopedUi) {
const scoped = uiKit().scoped();
scopedUi = scoped.kit;
disposers.push(() => { scoped.dispose(); scopedUi = null; });
}
return scopedUi;
},
commands: Object.freeze({
register(definition: CommandDefinition) {
const dispose = registry.registerFor(owner, definition);
disposers.push(dispose);
return dispose;
},
}),
dispose() {
const pending = disposers.reverse();
disposers = [];
for (const fn of pending) {
try { fn(); } catch (error) { report(error); }
}
},
};
},
};
return api;
}