From a6a9d52ed8867f2d5c7b5547e1d3ea3965f8e2e4 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 12:25:15 +0000 Subject: [PATCH] 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 [--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 --- packages/create-waybetter/src/app.js | 119 ++++++++++++++++-- .../create-waybetter/tests/create.test.mjs | 8 +- packages/runtime/src/featureModules.ts | 25 +++- packages/runtime/tests/features.test.ts | 17 +++ packages/shell/src/panel/PluginFeatures.tsx | 7 +- packages/shell/src/panel/panelMessages.ts | 3 +- packages/shell/src/panel/plugins.css | 5 +- packages/waybetter/cli/i18n.mjs | 61 ++++++++- packages/waybetter/locales/en.json | 5 +- packages/waybetter/tests/i18n-cli.test.mjs | 27 +++- 10 files changed, 248 insertions(+), 29 deletions(-) diff --git a/packages/create-waybetter/src/app.js b/packages/create-waybetter/src/app.js index aec4ccb..2f2b80a 100644 --- a/packages/create-waybetter/src/app.js +++ b/packages/create-waybetter/src/app.js @@ -812,19 +812,23 @@ function runtimeTs(o) { "import { createPageStrings } from 'waybetter/runtime/pageStrings';", "import { installPanelButton } from 'waybetter/runtime/panelButton';", "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 { createFeatureFlags, installSiteRuntime, pageInvoke, type FlagInstaller } from 'waybetter/runtime/siteRuntime';", "import { KIT_MESSAGES } from 'waybetter/runtime/ui';", + "import { TABLE } from '../features.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', - ' * (waybetter/shell/panel `useFeatures` + `FeatureGroups`; native `features_set` delivers them); a part that', - ' * installs when its flag turns on and disposes when it turns off goes into `INSTALLERS`.', + ' * The flags are the feature table\'s (src/features.ts): the owner toggles them on the panel\'s', + ' * area cards and native `features_set` delivers them. A feature module (src/runtime/modules.ts)', + ' * 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 = {};', - 'const INSTALLERS: FlagInstaller[] = [];', + 'const INSTALLERS: FlagInstaller[] = [];', '', '/** 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(``)}`)};`, @@ -834,12 +838,24 @@ function runtimeTs(o) { ' if ((window as unknown as Record)[SITE.runtimeGlobal]) return;', ' configureRuntime(SITE);', ' const invoke = pageInvoke(window, SITE.product);', - ' const flags = createFeatureFlags({ defaults: FLAGS, label: SITE.product, installers: INSTALLERS, document });', + ' let registry: FeatureRegistry | null = null;', + ' const flags = createFeatureFlags({', + ' 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).', " 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 }`', ' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.', ' 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.', ' const plugins = createPluginContext(api, undefined, (full, id) => ({ i18n: full.i18n.namespace(strings.pluginNamespace(id)) }));', ' const links = SITE.links ? installLinkRouting(window, SITE.links) : undefined;', @@ -881,7 +897,9 @@ function shellTs(o) { "import { isSiteUrl } from 'waybetter/runtime/site';", "import { parseAddress } from 'waybetter/shell/addressModel';", "import { createShell, type ShellSite } from 'waybetter/shell/frame';", + "import { openOnboardingWhenDue } from 'waybetter/shell/panel';", "import { ADDRESS_SITE } from '../address.ts';", + "import { MESSAGES } from '../features.ts';", "import { SITE } from '../site.ts';", "import { Panel } from './Panel.tsx';", "import './app.css';", @@ -889,7 +907,7 @@ function shellTs(o) { `const ORIGIN = ${str(o.origin)};`, '', '/** English; merge `waybetter/locales/.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 = {', ` 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,', ' // plugins::commands): the frame shows nothing of them until they are switched on here.', ' 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__;', @@ -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 = {', + " '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> = [', + ' {', + " 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) { return lines( '// 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', - '// 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', '// section, `backup` and `updates` theirs, `sections` the app\'s own (see `PanelSite`).', '', "import { createPanel } from 'waybetter/shell/panel';", + "import { TABLE } from '../features.ts';", "import { SITE } from '../site.ts';", '', 'export const Panel = createPanel({', @@ -953,6 +1041,8 @@ function panelTsx(o) { " { 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.', ` 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/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/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', @@ -1124,8 +1216,9 @@ function readme(o) { '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,', ' 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', - ' `useFeatures` and `FeatureGroups` (waybetter/shell/panel) to `sections` in `src/shell/Panel.tsx`.', + '4. Features: add a row to `TABLE` in `src/features.ts` (an area is a card in Plugins; a feature', + ' 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', ' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes', ' (`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: 'src/site.ts', content: siteTs(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/modules.ts', content: modulesTs() }, { path: 'src/shell/main.tsx', content: shellTs(o) }, { path: 'src/shell/Panel.tsx', content: panelTsx(o) }, { path: 'src/shell/index.html', content: indexHtml(o) }, diff --git a/packages/create-waybetter/tests/create.test.mjs b/packages/create-waybetter/tests/create.test.mjs index 0c95ad7..ab7f9c7 100644 --- a/packages/create-waybetter/tests/create.test.mjs +++ b/packages/create-waybetter/tests/create.test.mjs @@ -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(JSON.parse(readFileSync(join(PACKAGE, 'package.json'), 'utf8')).files.includes('windows'), 'and publishes it'); // 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`); // 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, /); // 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', '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.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips'); // Icons Tauri decodes at compile time. diff --git a/packages/runtime/src/featureModules.ts b/packages/runtime/src/featureModules.ts index fb6838b..b4a2b80 100644 --- a/packages/runtime/src/featureModules.ts +++ b/packages/runtime/src/featureModules.ts @@ -35,8 +35,12 @@ export const AREA_COMMAND_BUDGET = 5; 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 = { /** The stored values, normalized by the schema. */ @@ -56,6 +60,8 @@ export type FeatureContext = { 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`. */ @@ -73,8 +79,11 @@ export type FeatureContext = { 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. */ - t(key: string, params?: Params): string; + /** + * The feature's word `key`: `plugin...` 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). */ readonly storage: PluginStorage; /** Its settings (a module with a `settings` schema; otherwise empty values). */ @@ -250,6 +259,7 @@ export function createFeatureRegistry(options: FeatureR 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)); } @@ -276,7 +286,7 @@ export function createFeatureRegistry(options: FeatureR scope.commands.register(definition); 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}`); }, settings: entry.settings, selector: probe => selectorOf(module, probe), @@ -330,6 +340,11 @@ export function createFeatureRegistry(options: FeatureR 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); diff --git a/packages/runtime/tests/features.test.ts b/packages/runtime/tests/features.test.ts index aa49e9a..89c004c 100644 --- a/packages/runtime/tests/features.test.ts +++ b/packages/runtime/tests/features.test.ts @@ -374,6 +374,23 @@ test('registry: a probe that reads an English label waits for an English page in 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', () => { const env = page(); const seen: string[] = []; diff --git a/packages/shell/src/panel/PluginFeatures.tsx b/packages/shell/src/panel/PluginFeatures.tsx index 212f6d4..b811976 100644 --- a/packages/shell/src/panel/PluginFeatures.tsx +++ b/packages/shell/src/panel/PluginFeatures.tsx @@ -133,11 +133,12 @@ function AreaPluginsOf({ table, notify }: { table: FeatureTable; notify: Notify return
- + {card.total > 0 && } {card.settings && hasFeature('pluginCommands') && } void choose({ [areaFlag(card.area.id)]: next })}/>
diff --git a/packages/shell/src/panel/panelMessages.ts b/packages/shell/src/panel/panelMessages.ts index d02881c..dbde832 100644 --- a/packages/shell/src/panel/panelMessages.ts +++ b/packages/shell/src/panel/panelMessages.ts @@ -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.pluginFile': 'plugin file', '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.fonts.asSite': 'As {site} draws it', 'wb.fonts.builtIn': 'Built-in & system', @@ -468,7 +469,7 @@ export const PANEL_MESSAGES = { 'wb.modes.current': 'in use', 'wb.modes.existing': 'You already set {app} up. Nothing changes unless you pick a mode.', '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.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.', diff --git a/packages/shell/src/panel/plugins.css b/packages/shell/src/panel/plugins.css index bac7aed..b0a5235 100644 --- a/packages/shell/src/panel/plugins.css +++ b/packages/shell/src/panel/plugins.css @@ -26,6 +26,9 @@ .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: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-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; } @@ -36,7 +39,7 @@ .wbf-ask small { flex-basis: 100%; color: var(--c-muted); } /* 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 > img { border-radius: 22%; } .wbm-onboarding h1 { margin: 8px 0 0; font-size: 24px; font-weight: 680; letter-spacing: -.01em; text-wrap: balance; } diff --git a/packages/waybetter/cli/i18n.mjs b/packages/waybetter/cli/i18n.mjs index a9f550b..269f254 100644 --- a/packages/waybetter/cli/i18n.mjs +++ b/packages/waybetter/cli/i18n.mjs @@ -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, // plural forms, no markup or control characters, length warnings), the files generated from them, // 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 // English keys no literal lookup names // waybetter i18n extract --missing only the missing keys +// waybetter i18n rename --map renames keys in every catalog ({ "old.key": "new.key" }), values carried +// waybetter i18n rename --map --copy the same, keeping the old keys too // // Config: waybetter.i18n.json in the app's root (or --config ); 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). waybetter i18n extract [--missing] [--config ] Keys the code looks up that English lacks, and English keys without a literal lookup. + waybetter i18n rename --map [--copy] [--config ] + 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, bundledPlugins, runtimeKeys, native).`; @@ -302,16 +307,66 @@ export function extractKeys(config, { onlyMissing = false } = {}) { 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 ------------------------------------------------------------------------------------ -/** `waybetter i18n …`; returns the exit code. */ +/** `waybetter i18n …`; returns the exit code. */ export async function i18nCommand(args, { cwd = process.cwd(), log = console.log } = {}) { const [action, ...rest] = args; const flags = new Set(rest.filter(arg => arg.startsWith('--'))); const configAt = rest.indexOf('--config'); const configFile = configAt >= 0 ? rest[configAt + 1] : undefined; 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 '); + 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') { 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); diff --git a/packages/waybetter/locales/en.json b/packages/waybetter/locales/en.json index 422c5d4..268372a 100644 --- a/packages/waybetter/locales/en.json +++ b/packages/waybetter/locales/en.json @@ -1112,7 +1112,7 @@ "wb.modes.current": "in use", "wb.modes.existing": "You already set {app} up. Nothing changes unless you pick a mode.", "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.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.", @@ -1122,6 +1122,7 @@ "wb.modes.sectionHint": "A starting point, not a lock. Changing it never takes a switch away.", "wb.modes.start": "Start with {mode}", "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." } } diff --git a/packages/waybetter/tests/i18n-cli.test.mjs b/packages/waybetter/tests/i18n-cli.test.mjs index f58dd5a..627f02a 100644 --- a/packages/waybetter/tests/i18n-cli.test.mjs +++ b/packages/waybetter/tests/i18n-cli.test.mjs @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; 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'; 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.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/); +});