// Feature modules: the code side of the feature table (featureTable.ts). An app's area plugins // ("Navigation+") are sets of small modules, one per feature; the registry starts a module only // while its flag is on, its area's switch is on and the page is on one of its surfaces, and // disposes everything it did when any of those stops being true. A hundred features then cost what // the ones on screen cost: // // const registry = createFeatureRegistry({ win, table, api, label, surfaces, message }); // registry.define({ id: 'navigation.keyboardPlus', start(ctx) { ctx.onKey(...); } }); // registry.setFlags(effectiveFlags(table, flags)); // from the app's feature flags // // A module's `start(ctx)` gets a context whose every helper is undone on stop: CSS, listeners, // nodes, DOM watching through the shared hub (one MutationObserver for every feature, domHub.ts), // palette commands under its area's name, its words, its storage and its settings. A module with a // `settings` schema gets a settings dialog drawn from the UI kit (settingsForm.ts); each area with // such a feature gets one "settings" palette command. // // Health: a module names the selectors it depends on (`probes`). After the page has settled, a // probe that matches nothing is a miss; three misses in a row (three visits) pause that one feature // for the session, with one toast and a note in the settings dialog. The site's markup changed; the // rest of the area keeps working. A signed hotfix may replace a probe's selector // (`selectors["."]`) or switch a feature off (`flags[""] = false`). import { isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts'; import { areaFlag, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts'; import { formatMessage, type Params } from './i18n.ts'; import type { CommandDefinition } from './commands.ts'; import type { PluginI18n } from './pluginI18n.ts'; import type { Dispose, PluginScope, PluginStorage } from './pluginApi.ts'; import { buildSettingsForm, normalizeSettings, validateSchema, type SettingValues, type SettingsSchema } from './settingsForm.ts'; import { KIT_MESSAGES, type KitKey, type UiKit } from './ui.ts'; /** Palette commands one area may register: its "settings" entry and four actions (the tab reports at most 48). */ export const AREA_COMMAND_BUDGET = 5; /** Misses in a row (separate visits) before a feature pauses itself. */ export const PROBE_STRIKES = 3; /** * A selector a feature depends on. `english`: it reads an English label, so it only counts on an * English page. `when`: it only counts while this selector matches (the part of the page it lives * in is there: a column the site drops in a narrow window is no verdict). */ export type Probe = string | { selector: string; english?: boolean; when?: string }; export type FeatureSettings = { /** The stored values, normalized by the schema. */ get(): SettingValues; /** Saves (merged over the current values). False when storage refused it. */ set(patch: SettingValues): boolean; /** Calls `callback(values)` after a save, until the feature stops. */ onChange(callback: (values: SettingValues) => void): void; /** Opens this feature's settings dialog. */ open(): void; }; export type FeatureContext = { /** The flag id and the feature's own name (`navigation.focusMode` -> `focusMode`). */ readonly id: string; readonly name: string; readonly area: AreaSpec; /** The app's plugin API, unrestricted: a feature module is the app's own code. */ readonly api: Api; /** The page's window (use it and its `document` instead of the globals: tests run without them). */ readonly win: Window & typeof globalThis; /** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). */ css(css: string, name?: string): void; /** `callback` once per element matching `selector`, through the shared hub; paused on heavy pages unless the feature says `heavy`. */ observe(selector: string, callback: (element: Element) => void): void; /** A raw hub subscription (domHub `watchDom`), disposed on stop. */ watch(run: () => void, options?: DomWatch): DomWatchHandle; on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; onKey(callback: (event: KeyboardEvent, item: Element | null) => void): void; onRouteChange(callback: (href: string, previous: string) => void): void; /** Tracks a node the feature inserted; removed on stop. */ add(node: T): T; /** Runs `fn` on stop. */ defer(fn: Dispose): void; /** The UI kit; what the feature opened is closed on stop. */ readonly ui: UiKit; /** A palette command under the area's name (counts towards `AREA_COMMAND_BUDGET`), removed on stop. */ command(definition: CommandDefinition): void; /** * The feature's word `key`: `plugin...` in the app's catalog, or * `plugin..` for a module that names its own namespace (`words`). (Not * named `t`: the i18n tools read `t('…')` as a whole catalog key.) */ text(key: string, params?: Params): string; /** The feature's storage (its module's `storage` namespace). */ readonly storage: PluginStorage; /** Its settings (a module with a `settings` schema; otherwise empty values). */ readonly settings: FeatureSettings; /** The selector of probe `name` (a hotfix override wins). */ selector(name: string): string; /** The surfaces the page is on right now. */ surfaces(): readonly string[]; }; export type FeatureModule = { /** The flag id; the table must list it with `backing: 'module'`. */ id: string; /** Selectors it depends on, by name (read them back with `ctx.selector(name)`). */ probes?: Readonly>; /** * Where its words are in the catalog. Default: `plugin...`. A feature * ported from a plugin names that plugin's namespace (`focus-mode`) and keeps its keys * (`plugin.focus-mode.`, its label `plugin.focus-mode.name`): nothing is retranslated. */ words?: string; /** Storage namespace (default `.`; a ported plugin keeps its old one). */ storage?: string; /** The key its settings are stored under (default `settings`). */ settingsKey?: string; settings?: SettingsSchema; start(ctx: FeatureContext): void; }; /** What the registry needs of the plugin API (the core API has all of it). */ export type RegistryApi = { scope(): PluginScope; injectCSS(id: string, css: string): void; clearCSS(id: string): void; storage(namespace: string): PluginStorage; onRouteChange(callback: (href: string, previous: string) => void): Dispose; ui: UiKit; i18n: PluginI18n; commands: { withOwner(owner: string, fn: () => T): T }; }; export type HotfixData = { selectors?: Readonly>; flags?: Readonly> }; export type FeatureHealth = { id: string; area: string; state: 'paused' | 'needs-english'; probes: string[] }; export type FeatureRegistryOptions = { win: Window & typeof globalThis; table: FeatureTable; api: Api; /** Console prefix (the app's name). */ label: string; /** The surfaces the page is on (`['timeline', 'home']`); the app's classifier. */ surfaces(): readonly string[]; /** The app catalog's message for `key` in the active language (the registry's words are the kit's: `kit.feature.*`, `kit.save`). */ message?(key: string): string | undefined; locale?(): string; /** The signed hotfix data, when the app has any (selector overrides and kill flags). */ hotfix?(): HotfixData | null | undefined; /** The page has rendered its content (the site's main column is there); default: the body has children. */ settled?(): boolean; /** The page's language is English (probes marked `english` only count then); default: `` starts with `en`. */ english?(): boolean; /** ms after the page settled before probes are judged (default 3000) and between settle checks (default 500). */ settleMs?: number; pollMs?: number; timers?: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(id: unknown): void }; }; export type FeatureRegistry = { define(module: FeatureModule): void; /** The effective flags (featureTable `effectiveFlags`): starts and stops modules to match. */ setFlags(flags: Readonly): void; /** Re-checks surfaces (the registry also does it on every route change). */ refresh(): void; /** The ids of the modules running right now. */ active(): string[]; /** Paused features and features waiting for an English page. */ health(): FeatureHealth[]; /** Opens the settings dialog of an area (or of one feature). False when nothing in it has settings right now. */ openSettings(area: string, feature?: string): boolean; /** Stops everything (the runtime is going away; tests). */ dispose(): void; }; type Running = { module: FeatureModule; spec: FeatureSpec; area: AreaSpec; scope: PluginScope; commands: number; listeners: Set<(values: SettingValues) => void>; settings: FeatureSettings; visit: number; timer: unknown; }; const featureName = (id: string) => id.slice(id.indexOf('.') + 1); export function createFeatureRegistry(options: FeatureRegistryOptions): FeatureRegistry { const { win, table, api, label } = options; const doc = win.document; const timers = options.timers ?? { setTimeout: (fn: () => void, ms: number) => win.setTimeout(fn, ms), clearTimeout: (id: unknown) => win.clearTimeout(id as number) }; const settleMs = options.settleMs ?? 3000; const pollMs = options.pollMs ?? 500; const specs = new Map(table.features.map(feature => [feature.id, feature])); const areas = new Map(table.areas.map(area => [area.id, area])); const modules = new Map>(); const running = new Map>(); const areaScopes = new Map(); const strikes = new Map(); const paused = new Map(); const waiting = new Map(); let flags: Readonly = {}; let stopRoutes: Dispose | null = null; let visit = 0; // The registry's own words are the kit's (`kit.feature.*`, `kit.save`): English unless the app delivers them. const text = (key: KitKey, params: Params = {}) => formatMessage(options.message?.(key) ?? KIT_MESSAGES[key], params, options.locale?.() ?? 'en'); const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } }; const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en'); const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild; const words = (area: AreaSpec) => api.i18n.namespace(area.namespace); /** A feature's word `key`: under its own namespace when it names one (`words`), else under its area's. */ const wordOf = (module: FeatureModule, area: AreaSpec, key: string, params?: Params) => (module.words ? api.i18n.namespace(module.words).t(key, params) : words(area).t(`${featureName(module.id)}.${key}`, params)); /** A feature's label in the page, when the page has it (`plugin.*` words only reach a site tab). */ const featureLabel = (spec: FeatureSpec, area: AreaSpec) => { const legacy = modules.get(spec.id)?.words; if (legacy) { const own = api.i18n.namespace(legacy); return own.has('name') ? own.t('name') : null; } const i18n = words(area); const key = `feature.${featureName(spec.id)}.label`; return i18n.has(key) ? i18n.t(key) : null; }; const selectorOf = (module: FeatureModule, name: string) => { const override = hotfix().selectors?.[`${module.id}.${name}`]; if (typeof override === 'string' && override.trim()) return override; const probe = module.probes?.[name]; if (probe === undefined) throw new Error(`${module.id}: no probe named ${JSON.stringify(name)}`); return typeof probe === 'string' ? probe : probe.selector; }; function wanted(module: FeatureModule): boolean { const spec = specs.get(module.id)!; if (flags[module.id] !== true || paused.has(module.id) || hotfix().flags?.[module.id] === false) return false; if (!spec.heavy && isHeavyPath(win.location.pathname ?? '')) return false; if (!spec.surfaces?.length) return true; const on = options.surfaces(); return spec.surfaces.some(surface => on.includes(surface)); } function settingsOf(module: FeatureModule, area: AreaSpec, listeners: Set<(values: SettingValues) => void>): FeatureSettings { const schema = module.settings ?? []; const store = () => api.storage(module.storage ?? `${area.namespace}.${featureName(module.id)}`); const key = module.settingsKey ?? 'settings'; const get = () => normalizeSettings(schema, store().get(key, null)); return { get, set(patch) { const next = normalizeSettings(schema, { ...get(), ...patch }); const saved = store().set(key, next); for (const listener of [...listeners]) { try { listener(next); } catch (error) { console.error(`[${label}] ${module.id} settings listener failed`, error); } } return saved; }, onChange(callback) { listeners.add(callback); }, open() { openSettings(area.id, module.id); }, }; } function start(module: FeatureModule) { const spec = specs.get(module.id)!; const area = areas.get(spec.area!)!; const scope = api.commands.withOwner(area.owner, () => api.scope()); const listeners = new Set<(values: SettingValues) => void>(); const entry: Running = { module, spec, area, scope, commands: 0, listeners, settings: settingsOf(module, area, listeners), visit: -1, timer: null }; const name = featureName(module.id); const domWin = win as unknown as DomWindow; const styles = new Set(); const ctx: FeatureContext = { id: module.id, name, area, api, win, css(css, part = '') { const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`; if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); } if (css) api.injectCSS(styleId, css); else api.clearCSS(styleId); }, observe(selector, callback) { scope.defer(observeSelector(domWin, selector, callback, { offOnHeavy: !spec.heavy, report: error => console.error(`[${label}] ${module.id} failed`, error) })); }, watch(run, watchOptions = {}) { const handle = watchDom(domWin, run, { offOnHeavy: !spec.heavy, ...watchOptions }); scope.defer(() => handle.dispose()); return handle; }, on: (target, type, listener, listenerOptions) => scope.on(target, type, listener, listenerOptions), onKey: callback => scope.onKey(callback), onRouteChange: callback => scope.onRouteChange(callback), add: node => scope.add(node), defer: fn => scope.defer(fn), get ui() { return scope.ui; }, command(definition) { const reserved = table.features.some(feature => feature.area === area.id && feature.settings) ? 1 : 0; const used = [...running.values()].filter(other => other.area.id === area.id).reduce((sum, other) => sum + other.commands, 0); if (used + reserved >= AREA_COMMAND_BUDGET) throw new Error(`${area.name}: at most ${AREA_COMMAND_BUDGET} palette commands per area`); scope.commands.register(definition); entry.commands += 1; }, text: (key, params) => wordOf(module, area, key, params), get storage() { return api.storage(module.storage ?? `${area.namespace}.${name}`); }, settings: entry.settings, selector: probe => selectorOf(module, probe), surfaces: () => options.surfaces(), }; running.set(module.id, entry); try { module.start(ctx); } catch (error) { console.error(`[${label}] ${module.id} failed`, error); stop(module.id); return; } scheduleProbes(entry); } function stop(id: string) { const entry = running.get(id); if (!entry) return; running.delete(id); if (entry.timer !== null) timers.clearTimeout(entry.timer); entry.listeners.clear(); entry.scope.dispose(); } // ---- Health ---------------------------------------------------------------------------------- function scheduleProbes(entry: Running) { if (!entry.module.probes || !Object.keys(entry.module.probes).length || entry.visit === visit) return; entry.visit = visit; if (entry.timer !== null) timers.clearTimeout(entry.timer); const mine = visit; let tries = 0; const waitForSettle = () => { entry.timer = null; if (running.get(entry.module.id) !== entry || mine !== visit) return; if (!settled()) { tries += 1; // A page that never settles (an error page, a sign-in wall) is no verdict. if (tries <= 20) entry.timer = timers.setTimeout(waitForSettle, pollMs); return; } entry.timer = timers.setTimeout(judge, settleMs); }; const judge = () => { entry.timer = null; if (running.get(entry.module.id) !== entry || mine !== visit) return; const id = entry.module.id; const missing: string[] = []; const needEnglish: string[] = []; const inEnglish = english(); for (const [name, probe] of Object.entries(entry.module.probes ?? {})) { if (typeof probe !== 'string' && probe.english && !inEnglish) { needEnglish.push(name); continue; } if (typeof probe !== 'string' && probe.when) { let there = false; try { there = !!doc.querySelector(probe.when); } catch { there = false; } if (!there) continue; } let found = false; try { found = !!doc.querySelector(selectorOf(entry.module, name)); } catch { found = false; } if (!found) missing.push(name); } if (needEnglish.length) waiting.set(id, needEnglish); else waiting.delete(id); if (!missing.length) { strikes.delete(id); return; } const count = (strikes.get(id) ?? 0) + 1; strikes.set(id, count); if (count < PROBE_STRIKES) return; paused.set(id, missing); stop(id); syncAreas(); console.warn(`[${label}] ${id} paused: nothing matches ${missing.join(', ')}`); const feature = featureLabel(entry.spec, entry.area); try { api.ui.toast(feature ? text('kit.feature.paused', { feature, area: entry.area.name }) : text('kit.feature.pausedOne', { area: entry.area.name }), { tone: 'warning', duration: 8000 }); } catch { /* a page without a body yet: the note in the settings dialog remains */ } }; entry.timer = timers.setTimeout(waitForSettle, pollMs); } // ---- Settings dialog and the area's command -------------------------------------------------- function openSettings(areaId: string, only?: string): boolean { const area = areas.get(areaId); if (!area) return false; const entries = [...running.values()].filter(entry => entry.area.id === areaId && entry.module.settings?.length && (!only || entry.module.id === only)); const notes = health().filter(note => note.area === areaId); if (!entries.length && !notes.length) return false; const ui = api.ui; const h = ui.h; const forms = entries.map(entry => { const name = featureName(entry.module.id); return { entry, title: featureLabel(entry.spec, area) ?? name, form: buildSettingsForm(h, entry.module.settings!, entry.settings.get(), key => wordOf(entry.module, area, key)) }; }); const single = forms.length === 1 && !notes.length ? forms[0]! : null; ui.dialog({ title: text('kit.feature.settings', { name: single ? single.title : area.name }), content: body => { forms.forEach((item, index) => { if (index > 0) body.append(h('div', { class: 'wb-divider' })); if (!single) body.append(h('p', { class: 'wb-label' }, item.title)); body.append(...item.form.nodes); }); for (const note of notes) { const spec = specs.get(note.id)!; const feature = featureLabel(spec, area) ?? featureName(note.id); body.append(h('p', { class: 'wb-hint' }, note.state === 'paused' ? text('kit.feature.paused', { feature, area: area.name }) : text('kit.feature.needsEnglish', { feature }))); } }, actions: forms.length ? [ { label: text('kit.cancel') }, { label: text('kit.save'), tone: 'primary', default: true, onClick: handle => { const failed = forms.filter(item => !item.entry.settings.set(item.form.read())); if (failed.length) { handle.setError(text('kit.failed')); return false; } return undefined; }, }, ] : undefined, }); return true; } /** Each area with a running feature that has settings gets its one "settings" palette command. */ function syncAreas() { for (const area of table.areas) { const needs = [...running.values()].some(entry => entry.area.id === area.id && entry.module.settings?.length); const scope = areaScopes.get(area.id); if (needs && !scope) { const created = api.commands.withOwner(area.owner, () => api.scope()); areaScopes.set(area.id, created); try { created.commands.register({ id: 'settings', title: text('kit.feature.settings', { name: area.name }), keywords: `settings options configure ${area.name}`, run: () => { openSettings(area.id); } }); } catch (error) { console.error(`[${label}] ${area.name} settings command failed`, error); } } else if (!needs && scope) { scope.dispose(); areaScopes.delete(area.id); } } } function health(): FeatureHealth[] { const out: FeatureHealth[] = []; for (const [id, probes] of paused) out.push({ id, area: specs.get(id)!.area!, state: 'paused', probes }); for (const [id, probes] of waiting) if (!paused.has(id)) out.push({ id, area: specs.get(id)!.area!, state: 'needs-english', probes }); return out; } function refresh() { for (const module of modules.values()) { const on = running.has(module.id); const want = wanted(module); if (want && !on) start(module); else if (!want && on) stop(module.id); else if (want && on) scheduleProbes(running.get(module.id)!); } syncAreas(); } return { define(module) { const spec = specs.get(module.id); if (!spec || spec.backing !== 'module' || spec.area === null || !areas.has(spec.area)) throw new Error(`${label}: ${module.id} is not a feature module in the table`); if (modules.has(module.id)) throw new Error(`${label}: ${module.id} is defined twice`); const problems = validateSchema(module.settings ?? []); if (problems.length) throw new Error(`${label}: ${module.id} settings: ${problems.join('; ')}`); if (!!module.settings?.length !== !!spec.settings) throw new Error(`${label}: ${module.id}: the table's "settings" and the module's schema disagree`); modules.set(module.id, module); stopRoutes ??= api.onRouteChange(() => { visit += 1; refresh(); }); if (wanted(module)) { start(module); syncAreas(); } }, setFlags(next) { flags = { ...next }; refresh(); }, refresh, active: () => [...running.keys()], health, openSettings, dispose() { stopRoutes?.(); stopRoutes = null; for (const id of [...running.keys()]) stop(id); for (const scope of areaScopes.values()) scope.dispose(); areaScopes.clear(); modules.clear(); }, }; } /** Whether an area's switch is on in `flags` (a missing value counts as on). */ export const areaEnabled = (flags: Readonly, area: string) => flags[areaFlag(area)] !== false;