- 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() Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
274 lines
14 KiB
TypeScript
274 lines
14 KiB
TypeScript
// The page runtime's composition helpers: what every app's runtime entry does the same way. An
|
|
// app's entry (injected at document start into its site's tabs) installs its features and then:
|
|
//
|
|
// const invoke = pageInvoke(window, SITE.product);
|
|
// const flags = createFeatureFlags({ defaults, label: SITE.product, installers, apply });
|
|
// const runtime = installSiteRuntime({ win: window, site: SITE, version, invoke, plugins, strings, features: flags, ... });
|
|
// installPanelButton(window, button, () => runtime.open()); // panelButton.ts
|
|
//
|
|
// - `pageInvoke`: the IPC bridge, read at call time.
|
|
// - `createFeatureFlags`: flag-controlled parts that install on enable and dispose on disable, the
|
|
// flags native code delivers (`features_set`) and a deck column's overrides on top of them.
|
|
// - `installSiteRuntime`: the runtime object under its window names (`window.wayBetter` and the
|
|
// app's own), the members native code calls (features, theme, fonts, pane, links, i18n, column),
|
|
// the plugin API views, developer-mode errors, the palette command report, and whatever native
|
|
// code delivered before the runtime existed (the `__bt*` / `__wb*` queues).
|
|
|
|
import { installCommandReport, devErrorReporter } from './commandReport.ts';
|
|
import type { CommandInfo } from './commands.ts';
|
|
import type { PageStrings } from './pageStrings.ts';
|
|
import type { PluginContext } from './permissions.ts';
|
|
import type { Params } from './i18n.ts';
|
|
import type { SiteAdapter } from './site.ts';
|
|
|
|
export type PageInvoke = (command: string, args: Record<string, unknown>) => Promise<unknown>;
|
|
|
|
type BridgeWindow = { __TAURI_INTERNALS__?: { invoke(cmd: string, args?: Record<string, unknown>): Promise<unknown> }; navigator: { webdriver?: boolean } };
|
|
|
|
/**
|
|
* Native commands from the page. The IPC bridge is read at call time: a runtime installed at
|
|
* document start can run before Tauri has put `__TAURI_INTERNALS__` on the page. A runtime only
|
|
* ships inside the app's site tabs; automated test browsers (`navigator.webdriver`) have no
|
|
* bridge, and the features that need it stay off there (undefined).
|
|
*/
|
|
export function pageInvoke(win: Window, product: string): PageInvoke | undefined {
|
|
const target = win as unknown as BridgeWindow;
|
|
const inApp = !!target.__TAURI_INTERNALS__ || !target.navigator.webdriver;
|
|
if (!inApp) return undefined;
|
|
return (command, args) => {
|
|
const ipc = target.__TAURI_INTERNALS__;
|
|
return ipc ? ipc.invoke(command, args) : Promise.reject(new Error(`${product}: IPC bridge not ready`));
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// Feature flags
|
|
|
|
/** A flag-controlled part of the runtime, while it is installed. */
|
|
export type Installed = { dispose(): void };
|
|
export type FlagInstaller<Flags> = readonly [flag: keyof Flags & string, install: () => Installed];
|
|
|
|
export type FeatureFlagsOptions<Flags extends Record<string, boolean>> = {
|
|
/** Every flag with its default; a flag not in here is ignored. */
|
|
defaults: Flags;
|
|
/** Console label (the app's name). */
|
|
label: string;
|
|
/** Parts that install when their flag turns on and dispose when it turns off, in install order. */
|
|
installers: ReadonlyArray<FlagInstaller<Flags>>;
|
|
/** Every applied config (the full map), before the installers (flags that are CSS, or that another part reads). */
|
|
apply?(config: Flags): void;
|
|
/**
|
|
* What owns what: given the delivered flags over the defaults, the flags that really run (an
|
|
* area whose switch is off turns its features off; featureTable `effectiveFlags`).
|
|
*/
|
|
resolve?(flags: Flags): Flags;
|
|
/** The page's document: a column's flags delivered at document start wait for `<html>` to exist. */
|
|
document?: Document;
|
|
};
|
|
|
|
export type FeatureFlags<Flags extends Record<string, boolean>> = {
|
|
/**
|
|
* The flags native code delivers (the owner's choices); a deck column's overrides stay on top.
|
|
* A delivery is the whole state, stored sparsely: a flag it does not name is at its default.
|
|
*/
|
|
apply(config: Partial<Flags>): void;
|
|
/**
|
|
* A deck column's flag overrides (allow-listed natively; unknown keys and non-booleans are
|
|
* dropped here too). Flags a column stops overriding go back to the global value, or the default
|
|
* when the global config never named them. Recorded at once; applied now, or once the document
|
|
* has its `<html>` (a new column webview gets its config at document start).
|
|
*/
|
|
setColumnFlags(flags: unknown): void;
|
|
/** Turns one installer on or off directly (a kill switch). */
|
|
set(flag: keyof Flags & string, enabled: boolean): void;
|
|
/** Whether a flag's installer is installed right now. */
|
|
installed(flag: keyof Flags & string): boolean;
|
|
/** Every flag as it runs right now (defaults, the delivery, ownership, the column). */
|
|
current(): Flags;
|
|
};
|
|
|
|
export function createFeatureFlags<Flags extends Record<string, boolean>>(options: FeatureFlagsOptions<Flags>): FeatureFlags<Flags> {
|
|
const { defaults, label, installers } = options;
|
|
const active = new Map<string, Installed>();
|
|
const installerOf = new Map(installers.map(([flag, install]) => [flag as string, install]));
|
|
|
|
const set = (flag: string, enabled: boolean) => {
|
|
const install = installerOf.get(flag);
|
|
if (!install) return;
|
|
const current = active.get(flag);
|
|
if (enabled && !current) {
|
|
try { active.set(flag, install()); }
|
|
catch (error) { console.error(`[${label}] ${flag} failed`, error); }
|
|
} else if (!enabled && current) {
|
|
current.dispose();
|
|
active.delete(flag);
|
|
}
|
|
};
|
|
// Installed at document start, before the site's bundle runs (request gates wrap its fetch).
|
|
for (const [flag] of installers) set(flag, defaults[flag]);
|
|
|
|
let globalFlags: Partial<Flags> = {};
|
|
let columnFlags: Partial<Flags> = {};
|
|
const known = (input: unknown): Partial<Flags> => {
|
|
const out: Record<string, boolean> = {};
|
|
if (input && typeof input === 'object') {
|
|
for (const [key, value] of Object.entries(input)) if (key in defaults && typeof value === 'boolean') out[key] = value;
|
|
}
|
|
return out as Partial<Flags>;
|
|
};
|
|
// What runs: the defaults, the delivered flags over them, what owns what (`resolve`), and a
|
|
// column's own choices on top.
|
|
const current = (): Flags => {
|
|
const base = { ...defaults, ...globalFlags } as Flags;
|
|
return { ...(options.resolve ? options.resolve(base) : base), ...columnFlags };
|
|
};
|
|
const applyAll = () => {
|
|
const config = current();
|
|
options.apply?.(config);
|
|
for (const [flag] of installers) set(flag, config[flag]);
|
|
};
|
|
|
|
return {
|
|
apply(config) {
|
|
globalFlags = known(config);
|
|
applyAll();
|
|
},
|
|
setColumnFlags(flags) {
|
|
const next = known(flags);
|
|
const previous = columnFlags;
|
|
columnFlags = next;
|
|
if (!Object.keys(previous).length && !Object.keys(next).length) return;
|
|
const apply = () => { try { applyAll(); } catch (error) { console.error(`[${label}] column flags failed`, error); } };
|
|
const doc = options.document;
|
|
if (!doc || doc.documentElement) apply();
|
|
else doc.addEventListener('DOMContentLoaded', apply, { once: true });
|
|
},
|
|
set,
|
|
installed: flag => active.has(flag),
|
|
current,
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// The runtime object
|
|
|
|
/** What native code and plugins reach through `window.<runtimeGlobal>`. */
|
|
export type SiteRuntime<Api extends object> = {
|
|
version: string;
|
|
/** Running plugins by file (native start/stop scripts manage this). */
|
|
plugins: Record<string, { start?: () => void; stop?: () => void }>;
|
|
/** Load errors by plugin file. */
|
|
errors: Record<string, string>;
|
|
/** Native code hands over the feature flags (`features_set`). */
|
|
features: { apply(config: unknown): void };
|
|
/** Native code hands over the owner's language: `{ locale, dir, messages }` (pageStrings.ts). */
|
|
i18n: { set(strings: unknown): void; locale(): string; t(key: string, params?: Params): string };
|
|
/** Native code hands over where clicked site pages open (`{ site: 'same' | 'pane' | 'tab' | 'browser' }`). */
|
|
links: { configure(value: unknown): void };
|
|
/** Native code says whether this pane's navigation repeats another pane's (`{ redundantNav }`). */
|
|
pane: { set(state: unknown): void };
|
|
/** Native code hands over downloaded Google Fonts (validated woff2 bytes) that this tab's theme uses. */
|
|
fonts: { provide(fonts: unknown): void };
|
|
/** Power User Mode: native code hands a deck column its config (null = an ordinary tab again). */
|
|
column: { set(config: unknown): void; markRead(): void; jumpToUnread(): void; unread(): number };
|
|
/** Opens the app's panel in the shell (at a section). */
|
|
open(section?: string): void;
|
|
/**
|
|
* Helpers for `*.plugin.js` files. Read while a plugin's code runs (its module body, constructor,
|
|
* start() and stop()), this is that plugin's view for its declared `@permissions`; elsewhere it
|
|
* is the full API.
|
|
*/
|
|
readonly api: Api;
|
|
/** Runs `fn` as plugin `id` with `grants` (null = legacy, full API; undefined = as registered). Native start/stop scripts call it. */
|
|
withPlugin<R>(id: string, grants: readonly string[] | null | undefined, fn: () => R): R;
|
|
/** Developer mode: a reloaded plugin failed to start (native `dev_start_script`); shown as a toast. */
|
|
devError(file: unknown, error: unknown): void;
|
|
};
|
|
|
|
type ApiWithUi = { ui?: { toast(message: string, options: { tone: 'danger'; duration: number }): unknown }; commands?: { list(): CommandInfo[]; onChange(callback: (list: CommandInfo[]) => void): () => void } };
|
|
|
|
export type SiteRuntimeOptions<Api extends object, Extra extends object> = {
|
|
win: Window & typeof globalThis;
|
|
site: Pick<SiteAdapter, 'product' | 'runtimeGlobal'>;
|
|
version: string;
|
|
/** Other window names for the runtime, besides `wayBetter` and `site.runtimeGlobal` (names older plugins use). */
|
|
aliases?: readonly string[];
|
|
invoke?: PageInvoke;
|
|
/** Per-plugin API views (permissions.ts `createPluginContext`). */
|
|
plugins: PluginContext<Api>;
|
|
strings: PageStrings;
|
|
/** The toast for a plugin that failed to start in developer mode ("Plugin failed: {error}"). */
|
|
pluginFailed(error: string): string;
|
|
features?: { apply(config: never): void };
|
|
/** The theme handle (themeRuntime.ts), exposed as `theme`. */
|
|
theme?: { apply(choice: unknown): void };
|
|
fonts?(fonts: unknown): void;
|
|
pane?: { set(state: unknown): void };
|
|
links?: { configure(value: unknown): void };
|
|
column?: SiteRuntime<Api>['column'];
|
|
/** The app's own members (X: alerts, fixes). */
|
|
extra?: Extra;
|
|
/** Values native code may have delivered for the app's own members before the runtime existed: queue global and receiver. */
|
|
queues?: ReadonlyArray<readonly [queue: string, deliver: (value: unknown) => void]>;
|
|
};
|
|
|
|
/**
|
|
* Builds the runtime object, publishes it under its window names (not writable, not configurable),
|
|
* takes over what native code queued before it existed, and starts the palette command report.
|
|
*/
|
|
export function installSiteRuntime<Api extends object, Extra extends object = Record<never, never>>(options: SiteRuntimeOptions<Api, Extra>): SiteRuntime<Api> & Extra {
|
|
const { win, site, plugins, strings } = options;
|
|
const label = site.product;
|
|
// A failure in one member never breaks native code's other deliveries (or the page).
|
|
const guarded = <T>(what: string, fn: (value: T) => void) => (value: T) => {
|
|
try { fn(value); } catch (error) { console.error(`[${label}] ${what} failed`, error); }
|
|
};
|
|
const runtime = {
|
|
...(options.extra ?? {}),
|
|
version: options.version,
|
|
plugins: {},
|
|
errors: {},
|
|
features: { apply: (config: unknown) => (options.features as { apply(config: unknown): void } | undefined)?.apply(config) },
|
|
...(options.theme ? { theme: options.theme } : {}),
|
|
fonts: { provide: guarded('fonts', (list: unknown) => options.fonts?.(list)) },
|
|
pane: { set: guarded('split navigation', (state: unknown) => options.pane?.set(state)) },
|
|
links: { configure: (value: unknown) => options.links?.configure(value) },
|
|
i18n: { set: guarded('language', (value: unknown) => strings.set(value)), locale: strings.locale, t: strings.t },
|
|
column: {
|
|
set: guarded('deck column', (config: unknown) => options.column?.set(config)),
|
|
markRead: () => options.column?.markRead(),
|
|
jumpToUnread: () => options.column?.jumpToUnread(),
|
|
unread: () => options.column?.unread() ?? 0,
|
|
},
|
|
open(section?: string) {
|
|
(win as unknown as BridgeWindow).__TAURI_INTERNALS__?.invoke('open_panel', { section: section ?? null }).catch(() => {});
|
|
},
|
|
withPlugin: <R>(id: string, grants: readonly string[] | null | undefined, fn: () => R) => plugins.run(id, grants, fn),
|
|
get api() { return plugins.current(); },
|
|
devError: devErrorReporter(() => {
|
|
const ui = (plugins.current() as ApiWithUi).ui;
|
|
return ui ? (message, toastOptions) => { ui.toast(message, toastOptions); } : undefined;
|
|
}, options.pluginFailed),
|
|
} as unknown as SiteRuntime<Api> & Extra & { theme?: { apply(choice: unknown): void } };
|
|
|
|
// `wayBetter` is the documented name; the app's own names stay for existing plugins.
|
|
const names = [...new Set(['wayBetter', site.runtimeGlobal, ...(options.aliases ?? [])])];
|
|
for (const name of names) Object.defineProperty(win, name, { value: runtime, configurable: false, writable: false });
|
|
|
|
// Native code may deliver before this runtime exists.
|
|
const queued = win as unknown as Record<string, unknown>;
|
|
const take = (queue: string, deliver: (value: unknown) => void) => { if (queued[queue]) deliver(queued[queue]); };
|
|
take('__wbI18n', runtime.i18n.set);
|
|
take('__btFeatures', runtime.features.apply);
|
|
take('__wbFonts', runtime.fonts.provide);
|
|
take('__btTheme', value => runtime.theme?.apply(value));
|
|
take('__btPane', runtime.pane.set);
|
|
take('__btLinks', runtime.links.configure);
|
|
take('__btColumn', runtime.column.set);
|
|
for (const [queue, deliver] of options.queues ?? []) take(queue, deliver);
|
|
|
|
// Plugin commands for the shell's command palette: ids, titles and keywords about this tab only.
|
|
const commands = (plugins.current() as ApiWithUi).commands;
|
|
if (commands) installCommandReport(commands, options.invoke);
|
|
return runtime;
|
|
}
|