waybetter/packages/runtime/src/pageStrings.ts
CRT d3ca1d7b16 runtime: the site runtime's composition (siteRuntime, pageStrings, panelButton, commandReport)
What every app's page runtime entry did by hand (moved from wayBetter for X's inject/entry.tsx):

- siteRuntime.ts: pageInvoke (the IPC bridge read at call time), createFeatureFlags (parts that
  install on enable and dispose on disable, the flags native code delivers, a deck column's
  overrides on top of them, recorded at once and applied when <html> exists) and
  installSiteRuntime (the runtime object with the members native code calls, the plugin API views,
  developer-mode errors, its window names, the queued native deliveries, the command report).
- pageStrings.ts: the page's language (English built in, deliveries checked as data, the
  bundled-plugin namespace rule).
- panelButton.ts: the way into the panel from the page (the site's own navigation entry when the
  adapter mounts one, else a floating button that hides under the site's overlays and sits above
  its bottom bar).
- commandReport.ts: the palette command report and developer-mode start errors.
- tests/siteRuntime.test.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:28:54 +07:00

100 lines
4.4 KiB
TypeScript

// The page runtime's language. Native code hands site tabs the owner's language and exactly the
// strings the page needs (the app's own page strings, the plugin UI kit's `kit.*` and the bundled
// plugins' `plugin.*`; waybetter-host `i18n::page_script`) as `<global>.i18n.set({ locale, dir,
// messages })`, queued in `__wbI18n` until the runtime exists. The messages arrive already resolved
// along the language's fallback chain by the shell; English is built into the runtime (the build
// keeps only those prefixes of the app's catalog). A switch applies live: `onChange` listeners
// re-render. Everything delivered is data: checked, bounded and inserted as text.
import { formatMessage, normalizeLocale, type Params } from './i18n.ts';
import { pluginNamespace, type I18nSource } from './pluginI18n.ts';
export type PageStringsOptions = {
/** English for every string the page shows (the app's page strings and the framework's kit words). */
english: Readonly<Record<string, string>>;
/** Key prefixes a delivery may carry (`['x.', 'kit.', 'plugin.']`); other keys are dropped. */
prefixes: readonly string[];
/** Console label (the app's name). */
label: string;
/**
* The file-name prefix the app installs its bundled plugins with (`bt-` for `bt-<name>.plugin.js`)
* when their strings are keyed by the source name (`plugin.<name>.*`).
*/
bundledPrefix?: string;
};
export type PageStrings = {
/** The active language's message for `key`, else English. */
message(key: string): string | undefined;
/** A runtime string: `t('x.media.download')`. Placeholder values are inserted as text. */
t(key: string, params?: Params): string;
locale(): string;
/** Native code delivers `{ locale, dir, messages }`; anything malformed is ignored (English stays). */
set(value: unknown): void;
onChange(listener: () => void): () => void;
/** The plugin API's view of the language (pluginI18n.ts): `api.i18n` and the UI kit's words. */
source: I18nSource;
/** A plugin file's catalog namespace (`plugin.<namespace>.*`). */
pluginNamespace(id: string): string;
};
/** A delivery holds at most this many messages, each at most this long. */
export const PAGE_STRING_LIMITS = Object.freeze({ keys: 4000, value: 2000 });
export function createPageStrings(options: PageStringsOptions): PageStrings {
const { english, prefixes, label, bundledPrefix } = options;
let delivered: Record<string, string> = {};
let active = 'en';
const listeners = new Set<() => void>();
const message = (key: string) => delivered[key] ?? english[key];
const t = (key: string, params?: Params) => {
const text = message(key);
return text === undefined ? key : formatMessage(text, params ?? {}, active);
};
function set(value: unknown) {
if (!value || typeof value !== 'object') return;
const input = value as { locale?: unknown; messages?: unknown };
const tag = normalizeLocale(input.locale);
if (!tag || !input.messages || typeof input.messages !== 'object') return;
const next: Record<string, string> = {};
let count = 0;
for (const [key, text] of Object.entries(input.messages as Record<string, unknown>)) {
if (count >= PAGE_STRING_LIMITS.keys) break;
if (typeof text !== 'string' || text.length > PAGE_STRING_LIMITS.value || !prefixes.some(prefix => key.startsWith(prefix))) continue;
next[key] = text;
count += 1;
}
const changed = tag !== active || JSON.stringify(next) !== JSON.stringify(delivered);
delivered = next;
active = tag;
if (!changed) return;
for (const listener of [...listeners]) {
try { listener(); } catch (error) { console.error(`[${label}] language listener failed`, error); }
}
}
const onChange = (listener: () => void) => {
listeners.add(listener);
return () => { listeners.delete(listener); };
};
return {
message,
t,
locale: () => active,
set,
onChange,
source: { locale: () => active, message, onChange },
// Bundled plugins are installed as `<bundledPrefix><name>.plugin.js`, but their strings are keyed
// by their source name: without this, every bundled plugin would stay English.
pluginNamespace(id) {
const namespace = pluginNamespace(id);
if (!bundledPrefix || !namespace.startsWith(bundledPrefix)) return namespace;
const bare = namespace.slice(bundledPrefix.length);
const prefix = `plugin.${bare}.`;
return Object.keys(english).some(key => key.startsWith(prefix)) ? bare : namespace;
},
};
}