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:
parent
c7c25fa8bc
commit
513200b707
10 changed files with 248 additions and 29 deletions
|
|
@ -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 <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.
|
||||
//
|
||||
|
|
@ -41,6 +43,9 @@ export const I18N_USAGE = `Usage:
|
|||
regenerates languages.json and the native localization files (macOS, Linux).
|
||||
waybetter i18n extract [--missing] [--config <file>]
|
||||
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,
|
||||
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 <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 } = {}) {
|
||||
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 <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') {
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -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."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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/);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue