Feature modules in a new app, i18n rename, and what the first area port needed

- create-waybetter: the generated app has a feature table (one area, one feature, three modes), a feature module, the registry in its runtime, the cards and the first-run screen in its panel
- waybetter i18n rename --map <file> [--copy]: keys move or are copied in every catalog with each language's own value
- feature context: win (no globals in a module), text() for a feature's words (t('...') is read as a whole catalog key by the i18n tools)
- probes: `when` (only counts while the part of the page it lives in is there)
- cards: a caret, an empty area says its features come later; the first-run screen takes the whole panel
This commit is contained in:
CRTkafa 2026-09-30 19:25:15 +07:00
parent c7c25fa8bc
commit 513200b707
10 changed files with 248 additions and 29 deletions

View file

@ -812,19 +812,23 @@ function runtimeTs(o) {
"import { createPageStrings } from 'waybetter/runtime/pageStrings';", "import { createPageStrings } from 'waybetter/runtime/pageStrings';",
"import { installPanelButton } from 'waybetter/runtime/panelButton';", "import { installPanelButton } from 'waybetter/runtime/panelButton';",
"import { createPluginContext } from 'waybetter/runtime/permissions';", "import { createPluginContext } from 'waybetter/runtime/permissions';",
"import { createCorePluginApi } from 'waybetter/runtime/pluginApi';", "import { createFeatureRegistry, type FeatureRegistry } from 'waybetter/runtime/featureModules';",
"import { effectiveFlags, tableDefaults, type Flags } from 'waybetter/runtime/featureTable';",
"import { createCorePluginApi, type CorePluginApi } from 'waybetter/runtime/pluginApi';",
"import { configureRuntime, isSiteUrl } from 'waybetter/runtime/site';", "import { configureRuntime, isSiteUrl } from 'waybetter/runtime/site';",
"import { createFeatureFlags, installSiteRuntime, pageInvoke, type FlagInstaller } from 'waybetter/runtime/siteRuntime';", "import { createFeatureFlags, installSiteRuntime, pageInvoke, type FlagInstaller } from 'waybetter/runtime/siteRuntime';",
"import { KIT_MESSAGES } from 'waybetter/runtime/ui';", "import { KIT_MESSAGES } from 'waybetter/runtime/ui';",
"import { TABLE } from '../features.ts';",
"import { SITE } from '../site.ts';", "import { SITE } from '../site.ts';",
"import { MODULES } from './modules.ts';",
'', '',
'/**', '/**',
' * PLACEHOLDER: the app\'s page tweaks. Each flag is a boolean the owner toggles in the panel', ' * The flags are the feature table\'s (src/features.ts): the owner toggles them on the panel\'s',
' * (waybetter/shell/panel `useFeatures` + `FeatureGroups`; native `features_set` delivers them); a part that', ' * area cards and native `features_set` delivers them. A feature module (src/runtime/modules.ts)',
' * installs when its flag turns on and disposes when it turns off goes into `INSTALLERS`.', ' * is started by the registry; a part of the runtime that must install on a flag at document',
' * start (a request gate) goes into `INSTALLERS` with `backing: \'app\'` in the table.',
' */', ' */',
'const FLAGS: Record<string, boolean> = {};', 'const INSTALLERS: FlagInstaller<Flags>[] = [];',
'const INSTALLERS: FlagInstaller<typeof FLAGS>[] = [];',
'', '',
'/** The app\'s logo for the floating panel button (a data URI: the site\'s CSP may block other images). */', '/** The app\'s logo for the floating panel button (a data URI: the site\'s CSP may block other images). */',
`const LOGO = ${str(`data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="${o.site.accent}"/></svg>`)}`)};`, `const LOGO = ${str(`data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="${o.site.accent}"/></svg>`)}`)};`,
@ -834,12 +838,24 @@ function runtimeTs(o) {
' if ((window as unknown as Record<string, unknown>)[SITE.runtimeGlobal]) return;', ' if ((window as unknown as Record<string, unknown>)[SITE.runtimeGlobal]) return;',
' configureRuntime(SITE);', ' configureRuntime(SITE);',
' const invoke = pageInvoke(window, SITE.product);', ' const invoke = pageInvoke(window, SITE.product);',
' const flags = createFeatureFlags({ defaults: FLAGS, label: SITE.product, installers: INSTALLERS, document });', ' let registry: FeatureRegistry<CorePluginApi> | null = null;',
' const flags = createFeatureFlags<Flags>({',
' defaults: tableDefaults(TABLE), label: SITE.product, installers: INSTALLERS, document,',
' // An area that is switched off turns off the features it owns.',
' resolve: all => effectiveFlags(TABLE, all),',
' apply: config => registry?.setFlags(config),',
' });',
' // English for the plugin UI kit\'s own words; native code delivers the owner\'s language (i18n_set).', ' // English for the plugin UI kit\'s own words; native code delivers the owner\'s language (i18n_set).',
" const strings = createPageStrings({ english: { ...KIT_MESSAGES }, prefixes: ['kit.', 'plugin.'], label: SITE.product });", " const strings = createPageStrings({ english: { ...KIT_MESSAGES }, prefixes: ['kit.', 'plugin.'], label: SITE.product });",
' // No theme engine yet: `api.theme` reports the page\'s own colors. Pass `{ theme: source }`', ' // No theme engine yet: `api.theme` reports the page\'s own colors. Pass `{ theme: source }`',
' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.', ' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.',
' const api = createCorePluginApi(window, SITE.plugins, { i18n: strings.source });', ' const api = createCorePluginApi(window, SITE.plugins, { i18n: strings.source });',
' // The feature modules: each runs only while its flag and its area are on. `surfaces` names the',
' // parts of the site the page is (PLACEHOLDER: classify location.pathname; a feature that lists',
' // surfaces in the table only runs on those).',
" registry = createFeatureRegistry({ win: window, table: TABLE, api, label: SITE.product, surfaces: () => ['page'], message: strings.message, locale: strings.locale });",
' for (const module of MODULES) registry.define(module);',
' registry.setFlags(flags.current());',
' // Each plugin gets an API view for its declared @permissions, with its own strings.', ' // Each plugin gets an API view for its declared @permissions, with its own strings.',
' const plugins = createPluginContext(api, undefined, (full, id) => ({ i18n: full.i18n.namespace(strings.pluginNamespace(id)) }));', ' const plugins = createPluginContext(api, undefined, (full, id) => ({ i18n: full.i18n.namespace(strings.pluginNamespace(id)) }));',
' const links = SITE.links ? installLinkRouting(window, SITE.links) : undefined;', ' const links = SITE.links ? installLinkRouting(window, SITE.links) : undefined;',
@ -881,7 +897,9 @@ function shellTs(o) {
"import { isSiteUrl } from 'waybetter/runtime/site';", "import { isSiteUrl } from 'waybetter/runtime/site';",
"import { parseAddress } from 'waybetter/shell/addressModel';", "import { parseAddress } from 'waybetter/shell/addressModel';",
"import { createShell, type ShellSite } from 'waybetter/shell/frame';", "import { createShell, type ShellSite } from 'waybetter/shell/frame';",
"import { openOnboardingWhenDue } from 'waybetter/shell/panel';",
"import { ADDRESS_SITE } from '../address.ts';", "import { ADDRESS_SITE } from '../address.ts';",
"import { MESSAGES } from '../features.ts';",
"import { SITE } from '../site.ts';", "import { SITE } from '../site.ts';",
"import { Panel } from './Panel.tsx';", "import { Panel } from './Panel.tsx';",
"import './app.css';", "import './app.css';",
@ -889,7 +907,7 @@ function shellTs(o) {
`const ORIGIN = ${str(o.origin)};`, `const ORIGIN = ${str(o.origin)};`,
'', '',
'/** English; merge `waybetter/locales/<tag>.json` (and your own catalog) for other languages. */', '/** English; merge `waybetter/locales/<tag>.json` (and your own catalog) for other languages. */',
"const i18n = createI18n({ source: en.messages, available: ['en'] });", "const i18n = createI18n({ source: { ...en.messages, ...MESSAGES }, available: ['en'] });",
'', '',
'const site: ShellSite = {', 'const site: ShellSite = {',
` name: ${str(o.label)},`, ` name: ${str(o.label)},`,
@ -922,6 +940,8 @@ function shellTs(o) {
' // Native features this app does not wire up yet (waybetter-host workspaces, sync, devmode,', ' // Native features this app does not wire up yet (waybetter-host workspaces, sync, devmode,',
' // plugins::commands): the frame shows nothing of them until they are switched on here.', ' // plugins::commands): the frame shows nothing of them until they are switched on here.',
' features: { workspaces: false, sync: false, developer: false, pluginCommands: false },', ' features: { workspaces: false, sync: false, developer: false, pluginCommands: false },',
' // The first-run screen (the modes of src/features.ts) is the panel\'s: open it when it is due.',
' start() { openOnboardingWhenDue(); return undefined; },',
'};', '};',
'', '',
'const { core, event, window: tauriWindow } = window.__TAURI__;', 'const { core, event, window: tauriWindow } = window.__TAURI__;',
@ -930,15 +950,83 @@ function shellTs(o) {
); );
} }
/** @param {AppOptions} o */
function featuresTs(o) {
return lines(
'// The feature table: everything the owner can switch, as data (waybetter/runtime/featureTable).',
'// An AREA is one card in the panel\'s Plugins section with a switch of its own; a FEATURE is one',
'// flag, owned by an area or by nobody (a core flag: listed under "Fixes"); a MODE is a preset the',
'// first-run screen offers. The page runtime (src/runtime/main.ts) and the panel',
'// (src/shell/Panel.tsx) both read this table, so they cannot disagree. A flag\'s id never changes',
'// once it shipped: it is in the owner\'s features.json and backups.',
'',
"import type { FeatureTable } from 'waybetter/runtime/featureTable';",
'',
'/** PLACEHOLDER: one example area with one feature; its code is in src/runtime/modules.ts. */',
'export const TABLE: FeatureTable = {',
' areas: [',
` { id: 'reading', name: 'Reading+', description: 'area.reading.description', owner: ${str(`${o.prefix}-reading-plus.plugin.js`)}, namespace: 'reading-plus' },`,
' ],',
' features: [',
" // `backing: 'module'`: a feature module the registry starts while the flag is on. Other kinds:",
" // 'app' (a part of the runtime that installs on the flag) and 'plugin' (a plugin file).",
" { id: 'reading.focusRing', area: 'reading', default: false, backing: 'module', label: 'feature.focusRing.label', description: 'feature.focusRing.description' },",
' ],',
' modes: [',
" { id: 'basic', name: 'mode.basic.name', description: 'mode.basic.description', flags: { 'area.reading': false } },",
" { id: 'advanced', name: 'mode.advanced.name', description: 'mode.advanced.description', recommended: true, flags: {} },",
" { id: 'power', name: 'mode.power.name', description: 'mode.power.description', flags: { 'reading.focusRing': true } },",
' ],',
'};',
'',
'/** The table\'s words in English (merged into the shell\'s catalog in src/shell/main.tsx). */',
'export const MESSAGES: Record<string, string> = {',
" 'area.reading.description': 'Reading the page: small comforts.',",
" 'feature.focusRing.label': 'Mark the focused item',",
" 'feature.focusRing.description': 'Draws a ring around the item that has keyboard focus.',",
" 'mode.basic.name': 'Basic',",
` 'mode.basic.description': ${str(`Only the app around ${o.label}. The page looks the way the site ships it.`)},`,
" 'mode.advanced.name': 'Advanced',",
" 'mode.advanced.description': 'Every plugin on with calm defaults.',",
" 'mode.power.name': 'Power User',",
" 'mode.power.description': 'Advanced, plus the keyboard helpers.',",
'};',
);
}
function modulesTs() {
return lines(
'// Feature modules: the code of the table\'s features (src/features.ts). The registry starts a',
'// module only while its flag is on, its area is on and the page is on one of its surfaces, and',
'// undoes everything the module did through its context when any of those stops being true.',
'',
"import type { FeatureModule } from 'waybetter/runtime/featureModules';",
"import type { CorePluginApi } from 'waybetter/runtime/pluginApi';",
"import { SITE } from '../site.ts';",
'',
'export const MODULES: ReadonlyArray<FeatureModule<CorePluginApi>> = [',
' {',
" id: 'reading.focusRing',",
' start(ctx) {',
' // One stylesheet while the feature is on; removed when it stops.',
' ctx.css(`${SITE.plugins.itemSelector}:focus-within { outline: 2px solid Highlight; outline-offset: 2px; }`);',
' },',
' },',
'];',
);
}
function panelTsx(o) { function panelTsx(o) {
return lines( return lines(
'// The app\'s own tab (Ctrl+Shift+W, the brand button, the floating button in the site\'s page,', '// The app\'s own tab (Ctrl+Shift+W, the brand button, the floating button in the site\'s page,',
'// Ctrl+K "Plugins"): the wayBetter panel (waybetter/shell/panel). The framework brings the', '// Ctrl+K "Plugins"): the wayBetter panel (waybetter/shell/panel). The framework brings the',
'// sections this app serves: Home, Plugins (with custom CSS), Accounts and Settings. It grows', '// sections this app serves: Home, Plugins (the area cards of src/features.ts, plugin files and',
'// custom CSS), Accounts and Settings. It grows',
'// with the app: `themes` adds Appearance and the Theme Builder, `store` the Store, `make` the Make', '// with the app: `themes` adds Appearance and the Theme Builder, `store` the Store, `make` the Make',
'// section, `backup` and `updates` theirs, `sections` the app\'s own (see `PanelSite`).', '// section, `backup` and `updates` theirs, `sections` the app\'s own (see `PanelSite`).',
'', '',
"import { createPanel } from 'waybetter/shell/panel';", "import { createPanel } from 'waybetter/shell/panel';",
"import { TABLE } from '../features.ts';",
"import { SITE } from '../site.ts';", "import { SITE } from '../site.ts';",
'', '',
'export const Panel = createPanel({', 'export const Panel = createPanel({',
@ -953,6 +1041,8 @@ function panelTsx(o) {
" { section: 'accounts', title: () => 'Accounts', text: () => 'Real logins side by side, one per profile.' },", " { section: 'accounts', title: () => 'Accounts', text: () => 'Real logins side by side, one per profile.' },",
' ],', ' ],',
' },', ' },',
' // Area plugins, the Fixes list and the modes (first-run screen, Settings): src/features.ts.',
' features: { table: TABLE },',
' // Placeholder CSS in the custom CSS editor, written with this site\'s own selectors.', ' // Placeholder CSS in the custom CSS editor, written with this site\'s own selectors.',
` cssExamples: { custom: ${str(`/* Example */\n${o.site.selectors.item} { outline: 1px dashed; }`)} },`, ` cssExamples: { custom: ${str(`/* Example */\n${o.site.selectors.item} { outline: 1px dashed; }`)} },`,
'});', '});',
@ -1097,7 +1187,9 @@ function readme(o) {
'```', '```',
'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)', 'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)',
'src/address.ts address bar chips for the site\'s pages', 'src/address.ts address bar chips for the site\'s pages',
'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, tweaks, account report, the panel button', 'src/features.ts the feature table: areas (plugin cards), feature flags, modes (first-run presets)',
'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, feature flags and modules, account report, the panel button',
'src/runtime/modules.ts feature modules: the code of the table\'s features',
'src/shell/main.tsx the shell: the wayBetter shell frame (createShell) with this site\'s pages', 'src/shell/main.tsx the shell: the wayBetter shell frame (createShell) with this site\'s pages',
'src/shell/Panel.tsx the app\'s own tab: the wayBetter panel (createPanel) with this app\'s home page', 'src/shell/Panel.tsx the app\'s own tab: the wayBetter panel (createPanel) with this app\'s home page',
'plugins/example.plugin.js written (disabled) into a new plugins folder', 'plugins/example.plugin.js written (disabled) into a new plugins folder',
@ -1124,8 +1216,9 @@ function readme(o) {
'2. Keep `hosts` and the runtime global identical in `site.ts` and `site.rs`.', '2. Keep `hosts` and the runtime global identical in `site.ts` and `site.rs`.',
'3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,', '3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,',
' then list them in `build.rs`, `capabilities/site-tab.json` and `tests/security.rs`.', ' then list them in `build.rs`, `capabilities/site-tab.json` and `tests/security.rs`.',
'4. Page tweaks: add flags to `FLAGS` in `src/runtime/main.ts` and a section with', '4. Features: add a row to `TABLE` in `src/features.ts` (an area is a card in Plugins; a feature',
' `useFeatures` and `FeatureGroups` (waybetter/shell/panel) to `sections` in `src/shell/Panel.tsx`.', ' a toggle on it; `area: null` lists it under Fixes) and its module to `src/runtime/modules.ts`.',
' The modes of the first-run screen are `TABLE.modes`.',
'5. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes', '5. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes',
' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes', ' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes',
' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`updater: true` in the', ' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`updater: true` in the',
@ -1195,7 +1288,9 @@ export function appFiles(o) {
{ path: 'scripts/build.mjs', content: buildMjs() }, { path: 'scripts/build.mjs', content: buildMjs() },
{ path: 'src/site.ts', content: siteTs(o) }, { path: 'src/site.ts', content: siteTs(o) },
{ path: 'src/address.ts', content: addressTs(o) }, { path: 'src/address.ts', content: addressTs(o) },
{ path: 'src/features.ts', content: featuresTs(o) },
{ path: 'src/runtime/main.ts', content: runtimeTs(o) }, { path: 'src/runtime/main.ts', content: runtimeTs(o) },
{ path: 'src/runtime/modules.ts', content: modulesTs() },
{ path: 'src/shell/main.tsx', content: shellTs(o) }, { path: 'src/shell/main.tsx', content: shellTs(o) },
{ path: 'src/shell/Panel.tsx', content: panelTsx(o) }, { path: 'src/shell/Panel.tsx', content: panelTsx(o) },
{ path: 'src/shell/index.html', content: indexHtml(o) }, { path: 'src/shell/index.html', content: indexHtml(o) },

View file

@ -335,13 +335,19 @@ test('app: every site skeleton is consistent across its native and page halves',
assert.ok(existsSync(join(PACKAGE, 'windows', 'installer.nsi')), 'the package has the installer template'); assert.ok(existsSync(join(PACKAGE, 'windows', 'installer.nsi')), 'the package has the installer template');
assert.ok(JSON.parse(readFileSync(join(PACKAGE, 'package.json'), 'utf8')).files.includes('windows'), 'and publishes it'); assert.ok(JSON.parse(readFileSync(join(PACKAGE, 'package.json'), 'utf8')).files.includes('windows'), 'and publishes it');
// Every `waybetter/...` import is a published subpath of the package. // Every `waybetter/...` import is a published subpath of the package.
const sources = ['src/site.ts', 'src/address.ts', 'src/runtime/main.ts', 'src/shell/main.tsx', 'src/shell/Panel.tsx', 'scripts/build.mjs'].map(path => file(...path.split('/'))).join('\n'); const sources = ['src/site.ts', 'src/address.ts', 'src/features.ts', 'src/runtime/main.ts', 'src/runtime/modules.ts', 'src/shell/main.tsx', 'src/shell/Panel.tsx', 'scripts/build.mjs'].map(path => file(...path.split('/'))).join('\n');
for (const [, specifier] of sources.matchAll(/from '(waybetter\/[^']+)'/g)) assert.ok(exported(specifier), `${specifier} is exported`); for (const [, specifier] of sources.matchAll(/from '(waybetter\/[^']+)'/g)) assert.ok(exported(specifier), `${specifier} is exported`);
// The shell is the framework's shell frame (createShell), not a copy; it needs the window calls. // The shell is the framework's shell frame (createShell), not a copy; it needs the window calls.
assert.match(file('src', 'shell', 'main.tsx'), /createShell\(site, /); assert.match(file('src', 'shell', 'main.tsx'), /createShell\(site, /);
// The app's tab is the framework's panel (createPanel); the page runtime is composed by the framework. // The app's tab is the framework's panel (createPanel); the page runtime is composed by the framework.
assert.match(file('src', 'shell', 'Panel.tsx'), /export const Panel = createPanel\(\{/); assert.match(file('src', 'shell', 'Panel.tsx'), /export const Panel = createPanel\(\{/);
assert.match(file('src', 'runtime', 'main.ts'), /installSiteRuntime\(\{/); assert.match(file('src', 'runtime', 'main.ts'), /installSiteRuntime\(\{/);
// The example of a feature module and of modes: one table read by the runtime and the panel.
assert.match(file('src', 'features.ts'), /export const TABLE: FeatureTable = \{/);
assert.match(file('src', 'runtime', 'main.ts'), /createFeatureRegistry\(\{ win: window, table: TABLE/);
assert.match(file('src', 'runtime', 'modules.ts'), /id: 'reading\.focusRing'/);
assert.match(file('src', 'shell', 'Panel.tsx'), /features: \{ table: TABLE \}/);
assert.match(file('src', 'shell', 'main.tsx'), /openOnboardingWhenDue\(\)/);
assert.match(file('src-tauri', 'src', 'desktop.rs'), /AppConfig::new\(&SITE, SITE\.product, &plugins::HOST\)/); assert.match(file('src-tauri', 'src', 'desktop.rs'), /AppConfig::new\(&SITE, SITE\.product, &plugins::HOST\)/);
assert.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips'); assert.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips');
// Icons Tauri decodes at compile time. // Icons Tauri decodes at compile time.

View file

@ -35,8 +35,12 @@ export const AREA_COMMAND_BUDGET = 5;
export const PROBE_STRIKES = 3; 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. */ /**
export type Probe = string | { selector: string; english?: boolean }; * 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 = { export type FeatureSettings = {
/** The stored values, normalized by the schema. */ /** The stored values, normalized by the schema. */
@ -56,6 +60,8 @@ export type FeatureContext<Api> = {
readonly area: AreaSpec; readonly area: AreaSpec;
/** The app's plugin API, unrestricted: a feature module is the app's own code. */ /** The app's plugin API, unrestricted: a feature module is the app's own code. */
readonly api: Api; 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). */ /** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). */
css(css: string, name?: string): void; 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`. */ /** `callback` once per element matching `selector`, through the shared hub; paused on heavy pages unless the feature says `heavy`. */
@ -73,8 +79,11 @@ export type FeatureContext<Api> = {
readonly ui: UiKit; readonly ui: UiKit;
/** A palette command under the area's name (counts towards `AREA_COMMAND_BUDGET`), removed on stop. */ /** A palette command under the area's name (counts towards `AREA_COMMAND_BUDGET`), removed on stop. */
command(definition: CommandDefinition): void; command(definition: CommandDefinition): void;
/** The feature's word `key`: `plugin.<area namespace>.<name>.<key>` in the app's catalog. */ /**
t(key: string, params?: Params): string; * The feature's word `key`: `plugin.<area namespace>.<name>.<key>` in the app's catalog. (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). */ /** The feature's storage (its module's `storage` namespace). */
readonly storage: PluginStorage; readonly storage: PluginStorage;
/** Its settings (a module with a `settings` schema; otherwise empty values). */ /** Its settings (a module with a `settings` schema; otherwise empty values). */
@ -250,6 +259,7 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
name, name,
area, area,
api, api,
win,
css(css, part = '') { css(css, part = '') {
const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`; const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`;
if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); } if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); }
@ -276,7 +286,7 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
scope.commands.register(definition); scope.commands.register(definition);
entry.commands += 1; entry.commands += 1;
}, },
t: (key, params) => words(area).t(`${name}.${key}`, params), text: (key, params) => words(area).t(`${name}.${key}`, params),
get storage() { return api.storage(module.storage ?? `${area.namespace}.${name}`); }, get storage() { return api.storage(module.storage ?? `${area.namespace}.${name}`); },
settings: entry.settings, settings: entry.settings,
selector: probe => selectorOf(module, probe), selector: probe => selectorOf(module, probe),
@ -330,6 +340,11 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
const inEnglish = english(); const inEnglish = english();
for (const [name, probe] of Object.entries(entry.module.probes ?? {})) { 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.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; let found = false;
try { found = !!doc.querySelector(selectorOf(entry.module, name)); } catch { found = false; } try { found = !!doc.querySelector(selectorOf(entry.module, name)); } catch { found = false; }
if (!found) missing.push(name); if (!found) missing.push(name);

View file

@ -374,6 +374,23 @@ test('registry: a probe that reads an English label waits for an English page in
registry.dispose(); registry.dispose();
}); });
test('registry: a probe with `when` only counts while the part of the page it lives in is there', () => {
const env = page();
const timers = fakeTimers();
const registry = registryFor(env, { timers, surfaces: () => ['timeline'] });
registry.define({ id: 'hideTrends', probes: { trend: { selector: '[data-testid="trend"]', when: '[data-testid="sidebarColumn"]' } }, start() {} });
registry.setFlags({ hideTrends: true });
// A narrow window: no right column, so no verdict, however often.
for (let n = 0; n < 4; n += 1) { env.go(n % 2 ? '/home' : '/explore'); timers.advance(3500); }
assert.deepEqual(registry.active(), ['hideTrends']);
// The column is there and the selector still matches nothing: that is the site's markup changing.
env.matches.set('[data-testid="sidebarColumn"]', [{}]);
for (let n = 0; n < 3; n += 1) { env.go(n % 2 ? '/home' : '/explore'); timers.advance(3500); }
assert.deepEqual(registry.active(), []);
assert.equal(registry.health()[0]!.state, 'paused');
registry.dispose();
});
test('observeSelector: heavy pages skip observers that ask for it', () => { test('observeSelector: heavy pages skip observers that ask for it', () => {
const env = page(); const env = page();
const seen: string[] = []; const seen: string[] = [];

View file

@ -133,11 +133,12 @@ function AreaPluginsOf({ table, notify }: { table: FeatureTable; notify: Notify
return <div key={card.area.id} className={`wbf-area ${card.enabled ? '' : 'is-off'}`} data-area={card.area.id}> return <div key={card.area.id} className={`wbf-area ${card.enabled ? '' : 'is-off'}`} data-area={card.area.id}>
<div className="wbf-head"> <div className="wbf-head">
<span className="wbf-icon" aria-hidden="true"><NavIcon d={card.area.icon ?? AREA_ICON}/></span> <span className="wbf-icon" aria-hidden="true"><NavIcon d={card.area.icon ?? AREA_ICON}/></span>
<button type="button" className="wbf-title" aria-expanded={expanded} onClick={() => setOpen({ ...open, [card.area.id]: !expanded })}> <button type="button" className="wbf-title" aria-expanded={expanded} disabled={card.total === 0} onClick={() => setOpen({ ...open, [card.area.id]: !expanded })}>
<strong>{card.area.name}</strong> <strong>{card.area.name}</strong>
<span className="wbf-count">{t('wb.features.count', { on: card.on, total: card.total })}</span> {card.total > 0 && <span className="wbf-count">{t('wb.features.count', { on: card.on, total: card.total })}</span>}
<small>{card.enabled ? tx(card.area.description, undefined, '') : t('wb.features.off')}</small> <small>{card.enabled ? tx(card.area.description, undefined, '') : t('wb.features.off')}{card.total === 0 && ` ${t('wb.features.soon')}`}</small>
</button> </button>
{card.total > 0 && <span className={`wbf-caret ${expanded ? 'is-open' : ''}`} aria-hidden="true"><svg width="12" height="12" viewBox="0 0 12 12"><path d="M3 4.5 6 7.5l3-3" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg></span>}
{card.settings && hasFeature('pluginCommands') && <Button size="sm" tone="ghost" onClick={() => openSettings(card)}>{t('wb.panel.section.settings')}</Button>} {card.settings && hasFeature('pluginCommands') && <Button size="sm" tone="ghost" onClick={() => openSettings(card)}>{t('wb.panel.section.settings')}</Button>}
<Toggle label={t('wb.plugins.enabled', { name: card.area.name })} checked={card.enabled} onChange={next => void choose({ [areaFlag(card.area.id)]: next })}/> <Toggle label={t('wb.plugins.enabled', { name: card.area.name })} checked={card.enabled} onChange={next => void choose({ [areaFlag(card.area.id)]: next })}/>
</div> </div>

View file

@ -294,6 +294,7 @@ export const PANEL_MESSAGES = {
'wb.features.ownCopyAsk': 'Your own copy of {name} is on. Turn it off and use the built-in one?', 'wb.features.ownCopyAsk': 'Your own copy of {name} is on. Turn it off and use the built-in one?',
'wb.features.pluginFile': 'plugin file', 'wb.features.pluginFile': 'plugin file',
'wb.features.settingsNoTab': 'Open a {site} tab first, then choose Settings again.', 'wb.features.settingsNoTab': 'Open a {site} tab first, then choose Settings again.',
'wb.features.soon': 'Its features arrive in a later update.',
'wb.features.useBuiltIn': 'Use the built-in one', 'wb.features.useBuiltIn': 'Use the built-in one',
'wb.fonts.asSite': 'As {site} draws it', 'wb.fonts.asSite': 'As {site} draws it',
'wb.fonts.builtIn': 'Built-in & system', 'wb.fonts.builtIn': 'Built-in & system',
@ -468,7 +469,7 @@ export const PANEL_MESSAGES = {
'wb.modes.current': 'in use', 'wb.modes.current': 'in use',
'wb.modes.existing': 'You already set {app} up. Nothing changes unless you pick a mode.', 'wb.modes.existing': 'You already set {app} up. Nothing changes unless you pick a mode.',
'wb.modes.keep': 'Keep my changes', 'wb.modes.keep': 'Keep my changes',
'wb.modes.keepHint': '{count, plural, one {# setting you changed would be replaced.} other {# settings you changed would be replaced.}}', 'wb.modes.keepHint': 'Changed by hand: {count}. Those would be replaced.',
'wb.modes.keepQuestion': 'Keep your manual changes?', 'wb.modes.keepQuestion': 'Keep your manual changes?',
'wb.modes.keepSetup': 'Keep my current setup', 'wb.modes.keepSetup': 'Keep my current setup',
'wb.modes.lede': 'Pick a starting point. Every plugin and feature stays individually switchable, and you can change the mode later in Settings.', 'wb.modes.lede': 'Pick a starting point. Every plugin and feature stays individually switchable, and you can change the mode later in Settings.',

View file

@ -26,6 +26,9 @@
.wbf-title strong { font-size: 14px; font-weight: 620; } .wbf-title strong { font-size: 14px; font-weight: 620; }
.wbf-title small { grid-column: 1 / -1; margin-top: 2px; color: var(--c-muted); font-size: 12px; line-height: 1.45; } .wbf-title small { grid-column: 1 / -1; margin-top: 2px; color: var(--c-muted); font-size: 12px; line-height: 1.45; }
.wbf-title:focus-visible { outline: 2px solid var(--c-accent); outline-offset: 4px; border-radius: 6px; } .wbf-title:focus-visible { outline: 2px solid var(--c-accent); outline-offset: 4px; border-radius: 6px; }
.wbf-title:disabled { cursor: default; }
.wbf-caret { flex: none; display: grid; color: var(--c-muted); transition: transform .14s var(--ease, ease); }
.wbf-caret.is-open { transform: rotate(180deg); }
.wbf-count { color: var(--c-muted); font: 500 11px/1 var(--f-mono, ui-monospace, monospace); } .wbf-count { color: var(--c-muted); font: 500 11px/1 var(--f-mono, ui-monospace, monospace); }
.wbf-body { border-top: 1px solid var(--c-line-soft); background: color-mix(in srgb, var(--c-field) 45%, transparent); } .wbf-body { border-top: 1px solid var(--c-line-soft); background: color-mix(in srgb, var(--c-field) 45%, transparent); }
.wbf-area.is-off .wbf-body .bt-row-copy { opacity: .6; } .wbf-area.is-off .wbf-body .bt-row-copy { opacity: .6; }
@ -36,7 +39,7 @@
.wbf-ask small { flex-basis: 100%; color: var(--c-muted); } .wbf-ask small { flex-basis: 100%; color: var(--c-muted); }
/* Modes (Modes.tsx): the first-run screen and its cards. */ /* Modes (Modes.tsx): the first-run screen and its cards. */
.btp.is-onboarding { display: grid; place-items: center; overflow: auto; } .btp.is-onboarding { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(min-content, 1fr); justify-items: center; align-items: center; overflow: auto; }
.wbm-onboarding { display: flex; flex-direction: column; align-items: center; gap: 10px; width: min(880px, 100%); padding: 40px 24px; text-align: center; } .wbm-onboarding { display: flex; flex-direction: column; align-items: center; gap: 10px; width: min(880px, 100%); padding: 40px 24px; text-align: center; }
.wbm-onboarding > img { border-radius: 22%; } .wbm-onboarding > img { border-radius: 22%; }
.wbm-onboarding h1 { margin: 8px 0 0; font-size: 24px; font-weight: 680; letter-spacing: -.01em; text-wrap: balance; } .wbm-onboarding h1 { margin: 8px 0 0; font-size: 24px; font-weight: 680; letter-spacing: -.01em; text-wrap: balance; }

View file

@ -1,4 +1,4 @@
// `waybetter i18n check|extract`: an app's locale catalogs against the framework's rules // `waybetter i18n check|extract|rename`: an app's locale catalogs against the framework's rules
// (waybetter/i18n/check: file shape, keys English does not have, ICU syntax, placeholder parity, // (waybetter/i18n/check: file shape, keys English does not have, ICU syntax, placeholder parity,
// plural forms, no markup or control characters, length warnings), the files generated from them, // plural forms, no markup or control characters, length warnings), the files generated from them,
// and the keys the app's code looks up. // and the keys the app's code looks up.
@ -10,6 +10,8 @@
// waybetter i18n extract keys the code looks up that English lacks (exit 1), then // waybetter i18n extract keys the code looks up that English lacks (exit 1), then
// English keys no literal lookup names // English keys no literal lookup names
// waybetter i18n extract --missing only the missing keys // waybetter i18n extract --missing only the missing keys
// waybetter i18n rename --map <file> renames keys in every catalog ({ "old.key": "new.key" }), values carried
// waybetter i18n rename --map <file> --copy the same, keeping the old keys too
// //
// Config: waybetter.i18n.json in the app's root (or --config <file>); every path is relative to it. // Config: waybetter.i18n.json in the app's root (or --config <file>); every path is relative to it.
// //
@ -41,6 +43,9 @@ export const I18N_USAGE = `Usage:
regenerates languages.json and the native localization files (macOS, Linux). regenerates languages.json and the native localization files (macOS, Linux).
waybetter i18n extract [--missing] [--config <file>] waybetter i18n extract [--missing] [--config <file>]
Keys the code looks up that English lacks, and English keys without a literal lookup. Keys the code looks up that English lacks, and English keys without a literal lookup.
waybetter i18n rename --map <file> [--copy] [--config <file>]
Renames keys in every catalog of the app (and en.meta.json) by a { "old.key": "new.key" } map,
carrying each language's value; --copy keeps the old keys as well.
Config: ${I18N_CONFIG_FILE} in the app's root (locales, framework, sources, nativeSources, Config: ${I18N_CONFIG_FILE} in the app's root (locales, framework, sources, nativeSources,
bundledPlugins, runtimeKeys, native).`; bundledPlugins, runtimeKeys, native).`;
@ -302,16 +307,66 @@ export function extractKeys(config, { onlyMissing = false } = {}) {
return { missing: missing.map(([key]) => key), lines }; return { missing: missing.map(([key]) => key), lines };
} }
// ---- rename -----------------------------------------------------------------------------------------
const KEY = /^[a-z][A-Za-z0-9_.-]{0,127}$/;
/**
* Renames (or, with `copy`, duplicates) keys in every catalog of the app by `map` ({ old: new }),
* carrying each language's own value, so a moved string is never retranslated. A catalog that lacks
* the old key is left as it is for that key (it falls back to English, as before). The translator
* notes (en.meta.json) follow. Refuses a map that would overwrite an existing English key with a
* different value, or that names a key English does not have.
*/
export function renameKeys(config, map, { copy = false } = {}) {
const entries = Object.entries(map);
const en = read(join(config.locales, 'en.json'));
for (const [from, to] of entries) {
if (typeof to !== 'string' || !KEY.test(from) || !KEY.test(to)) throw new I18nError(`invalid entry ${JSON.stringify(from)}: ${JSON.stringify(to)}`);
if (!(from in en.messages)) throw new I18nError(`${from} is not in en.json`);
if (to in en.messages && en.messages[to] !== en.messages[from]) throw new I18nError(`${to} already exists in en.json with another value`);
}
const lines = [];
const rewrite = (file, messagesOf) => {
const path = join(config.locales, file);
if (!existsSync(path)) return;
const raw = readFileSync(path, 'utf8');
const data = JSON.parse(raw);
const messages = messagesOf(data);
let changed = 0;
for (const [from, to] of entries) {
if (!(from in messages)) continue;
if (messages[to] !== messages[from]) { messages[to] = messages[from]; changed += 1; }
if (!copy && from !== to) { delete messages[from]; changed += 1; }
}
if (!changed) return;
writeFileSync(path, `${JSON.stringify(data, null, 2)}${raw.endsWith('\n') ? '\n' : ''}`);
lines.push(`${file}: ${changed} change(s)`);
};
for (const file of catalogFiles(config.locales)) rewrite(file, data => data.messages);
rewrite('en.meta.json', data => data);
lines.push(`${copy ? 'copied' : 'renamed'} ${entries.length} key(s) in ${lines.length} file(s).`);
return { lines };
}
// ---- The command ------------------------------------------------------------------------------------ // ---- The command ------------------------------------------------------------------------------------
/** `waybetter i18n <check|extract> …`; returns the exit code. */ /** `waybetter i18n <check|extract|rename> …`; returns the exit code. */
export async function i18nCommand(args, { cwd = process.cwd(), log = console.log } = {}) { export async function i18nCommand(args, { cwd = process.cwd(), log = console.log } = {}) {
const [action, ...rest] = args; const [action, ...rest] = args;
const flags = new Set(rest.filter(arg => arg.startsWith('--'))); const flags = new Set(rest.filter(arg => arg.startsWith('--')));
const configAt = rest.indexOf('--config'); const configAt = rest.indexOf('--config');
const configFile = configAt >= 0 ? rest[configAt + 1] : undefined; const configFile = configAt >= 0 ? rest[configAt + 1] : undefined;
if (configAt >= 0 && !configFile) throw new I18nError('--config needs a file'); if (configAt >= 0 && !configFile) throw new I18nError('--config needs a file');
const positional = rest.filter((arg, index) => !arg.startsWith('--') && (configAt < 0 || index !== configAt + 1)); const mapAt = rest.indexOf('--map');
const positional = rest.filter((arg, index) => !arg.startsWith('--') && (configAt < 0 || index !== configAt + 1) && (mapAt < 0 || index !== mapAt + 1));
if (action === 'rename') {
const mapFile = mapAt >= 0 ? rest[mapAt + 1] : undefined;
if (!mapFile) throw new I18nError('rename needs --map <file>');
const result = renameKeys(loadI18nConfig(cwd, configFile), read(isAbsolute(mapFile) ? mapFile : resolve(cwd, mapFile)), { copy: flags.has('--copy') });
for (const line of result.lines) log(line);
return 0;
}
if (action === 'check') { if (action === 'check') {
const result = await checkCatalogs(loadI18nConfig(cwd, configFile), { write: flags.has('--write'), verbose: flags.has('--verbose'), only: positional }); const result = await checkCatalogs(loadI18nConfig(cwd, configFile), { write: flags.has('--write'), verbose: flags.has('--verbose'), only: positional });
for (const line of result.lines) log(line); for (const line of result.lines) log(line);

View file

@ -1112,7 +1112,7 @@
"wb.modes.current": "in use", "wb.modes.current": "in use",
"wb.modes.existing": "You already set {app} up. Nothing changes unless you pick a mode.", "wb.modes.existing": "You already set {app} up. Nothing changes unless you pick a mode.",
"wb.modes.keep": "Keep my changes", "wb.modes.keep": "Keep my changes",
"wb.modes.keepHint": "{count, plural, one {# setting you changed would be replaced.} other {# settings you changed would be replaced.}}", "wb.modes.keepHint": "Changed by hand: {count}. Those would be replaced.",
"wb.modes.keepQuestion": "Keep your manual changes?", "wb.modes.keepQuestion": "Keep your manual changes?",
"wb.modes.keepSetup": "Keep my current setup", "wb.modes.keepSetup": "Keep my current setup",
"wb.modes.lede": "Pick a starting point. Every plugin and feature stays individually switchable, and you can change the mode later in Settings.", "wb.modes.lede": "Pick a starting point. Every plugin and feature stays individually switchable, and you can change the mode later in Settings.",
@ -1122,6 +1122,7 @@
"wb.modes.sectionHint": "A starting point, not a lock. Changing it never takes a switch away.", "wb.modes.sectionHint": "A starting point, not a lock. Changing it never takes a switch away.",
"wb.modes.start": "Start with {mode}", "wb.modes.start": "Start with {mode}",
"wb.modes.title": "How much should {app} change {site}?", "wb.modes.title": "How much should {app} change {site}?",
"wb.modes.use": "Use this mode" "wb.modes.use": "Use this mode",
"wb.features.soon": "Its features arrive in a later update."
} }
} }

View file

@ -6,7 +6,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path'; import { join } from 'node:path';
import test from 'node:test'; import test from 'node:test';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { checkCatalogs, extractKeys, i18nCommand, loadI18nConfig } from '../cli/i18n.mjs'; import { checkCatalogs, extractKeys, i18nCommand, loadI18nConfig, renameKeys } from '../cli/i18n.mjs';
import { NSIS_KEYS, NSIS_LANGUAGES, nsisText, renderInstallerLanguages, syncInstallerLanguages } from '../scripts/installer-languages.mjs'; import { NSIS_KEYS, NSIS_LANGUAGES, nsisText, renderInstallerLanguages, syncInstallerLanguages } from '../scripts/installer-languages.mjs';
const BIN = fileURLToPath(new URL('../bin/waybetter.mjs', import.meta.url)); const BIN = fileURLToPath(new URL('../bin/waybetter.mjs', import.meta.url));
@ -133,3 +133,28 @@ test('installer languages: generated from the framework catalogs, up to date, on
assert.equal(nsisText('{product} {version} "x"\n$1 {installed} {error} {code}'), '${PRODUCTNAME} ${VERSION} $\\"x$\\"$\\n$$1 $R4 $0 $1'); assert.equal(nsisText('{product} {version} "x"\n$1 {installed} {error} {code}'), '${PRODUCTNAME} ${VERSION} $\\"x$\\"$\\n$$1 $R4 $0 $1');
assert.ok(existsSync(fileURLToPath(new URL('../windows/installer.nsi', import.meta.url))), 'next to the installer template'); assert.ok(existsSync(fileURLToPath(new URL('../windows/installer.nsi', import.meta.url))), 'next to the installer template');
}); });
test('rename: keys move (or are copied) in every catalog with each language\'s own value', async () => {
const dir = app();
const config = loadI18nConfig(dir);
// Copy first: the old key stays (a plugin file that still ships reads it), the new one carries the value.
renameKeys(config, { 'app.hello': 'area.greeting.hello' }, { copy: true });
assert.equal(read(join(dir, 'locales/en.json')).messages['area.greeting.hello'], 'Hello {name}');
assert.equal(read(join(dir, 'locales/tr.json')).messages['area.greeting.hello'], 'Merhaba {name}');
assert.equal(read(join(dir, 'locales/tr.json')).messages['app.hello'], 'Merhaba {name}');
assert.equal(read(join(dir, 'locales/en.meta.json'))['area.greeting.hello'], 'Greeting; {name} is the account.');
// Rename: the old key is gone everywhere; a catalog that never had it is left alone.
const map = join(dir, 'renames.json');
json(map, { 'app.hello': 'app.welcome', 'app.unused': 'app.spare' });
const lines = [];
assert.equal(await i18nCommand(['rename', '--map', 'renames.json'], { cwd: dir, log: line => lines.push(line) }), 0);
const en = read(join(dir, 'locales/en.json')).messages;
const tr = read(join(dir, 'locales/tr.json')).messages;
assert.ok(!('app.hello' in en) && !('app.hello' in tr) && !('app.unused' in en));
assert.deepEqual([en['app.welcome'], tr['app.welcome'], en['app.spare'], tr['app.spare']], ['Hello {name}', 'Merhaba {name}', 'Never looked up', undefined]);
assert.match(lines.at(-1), /renamed 2 key\(s\)/);
// Refused: a key English does not have, and a target that exists with another value.
assert.throws(() => renameKeys(config, { 'app.nope': 'app.x' }), /app\.nope is not in en\.json/);
assert.throws(() => renameKeys(config, { 'app.welcome': 'app.count' }), /already exists/);
assert.throws(() => renameKeys(config, { 'app.welcome': 'Bad Key' }), /invalid entry/);
});