Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
docs(skills): give translating-locales a script instead of snippets
Elian Doran0e4c3e257973
diff --git a/.claude/skills/translating-locales/SKILL.md b/.claude/skills/translating-locales/SKILL.mdindex 284d29b1c1..ce7dd652a4 100644--- a/.claude/skills/translating-locales/SKILL.md+++ b/.claude/skills/translating-locales/SKILL.md@@ -1,13 +1,25 @@---name: translating-locales-description: Use when filling in or improving a lagging UI translation locale in Trilium (e.g. "Romanian is behind", "bring <locale> to 100% coverage", "translate the missing strings"). Covers measuring the gap vs English, drafting translations that preserve i18next placeholders, merging without diff churn, locale grammar rules (Romanian plurals/gender), the source-side pluralization workflow, how Weblate sync actually works (merging is picked up), and validation.+description: Use when filling in or improving a lagging UI translation locale in Trilium (e.g. "Romanian is behind", "bring <locale> to 100% coverage", "translate the missing strings"). Covers measuring the gap vs English, drafting translations that preserve i18next placeholders, merging without diff churn, locale grammar rules (Romanian plurals/gender), the source-side pluralization workflow, how Weblate sync actually works (merging is picked up), and validation. Includes locale.mjs — don't hand-roll a JSON walker.---# Translating / improving a locale in TriliumTrilium's UI is localized with **i18next**. English is the source of truth; other locales are normally crowd-translated via **Hosted Weblate**. This skill is for the *maintainer* case: deliberately filling a locale that lags behind (the recurring one is Romanian, `ro`).-Read [romanian.md](romanian.md) for Romanian grammar rules and [scripts.md](scripts.md) for the copy-paste Node snippets used in every step below.+Every mechanical step is [locale.mjs](locale.mjs) — measure, export, validate, merge, audit. Read [romanian.md](romanian.md) for Romanian grammar and terminology.++```bash+S=.claude/skills/translating-locales/locale.mjs+node $S measure # coverage of every locale, both catalogs+node $S measure ro -v # one locale, listing missing + untranslated keys+node $S export ro client --chunk 150 # work list (English source) → a temp dir+node $S validate ro client <files…> # placeholders / whitespace / plural categories+node $S merge ro client <files…> # apply, preserving key order + formatting+node $S audit-plurals ro client # groups missing a category the locale requires+```++`export` writes `{ key: englishValue }`; translate into a flat `{ key: translatedValue }` file and feed it to `validate` then `merge`. Chunking matters: a locale that is 1000+ strings behind does not fit one drafting pass, and `validate`/`merge` both take a list of files.## How Weblate sync works here (merging a PR IS picked up — no separate upload needed)@@ -22,62 +34,84 @@ Weblate is linked to this repo with the **GitHub pull-request push method**: `.g## File locations-| Scope | English source | Target locale |+| Catalog | English source | Target locale ||---|---|---|-| Client UI | `apps/client/src/translations/en/translation.json` | `apps/client/src/translations/<locale>/translation.json` |-| Everything else (hidden subtree titles, dialogs, migration/search messages) | `apps/server/src/assets/translations/en/server.json` | `apps/server/src/assets/translations/<locale>/server.json` |+| `client` — the browser UI | `apps/client/src/translations/en/translation.json` | `apps/client/src/translations/<locale>/translation.json` |+| `entry` — setup wizard, login, password reset | `apps/client/src/translations/en/entry.json` | `apps/client/src/translations/<locale>/entry.json` |+| `server` — everything else | `apps/server/src/assets/translations/en/server.json` | `apps/server/src/assets/translations/<locale>/server.json` |-Both have their own EN↔locale pair — check **both**.+All three have their own EN↔locale pair — do **all three**; `measure` reports them side by side. `entry` is easy to forget: it is a separate i18next namespace loaded on its own by the three pre-login pages, so a locale can read 100% on `client` while its login screen is entirely English. Several of its keys (`login.*`, the SSO errors) are near-duplicates of `server.json` ones — translate them the same way.`server.json` is misnamed: it is the catalog for **every** runtime outside the browser UI — `apps/server`, the Electron main process, `packages/trilium-core`, and the standalone worker, which loads it with `ns: "server"` from the copy of `apps/server/src/assets` that its vite build emits under `server-assets`. Translating it therefore covers the standalone and mobile builds too, and a missing key there is not "server-only" breakage.## Workflow### 1. Measure the gap-Flatten EN and the locale, then report **missing** keys (not in locale) and **identical-to-EN** keys (present but never translated — excluding proper nouns). See `scripts.md` → *measure*. Romanian has historically sat ~73% client / ~87% server.+`node $S measure <locale> -v`. Two numbers matter: **missing** (absent from the locale) and **untranslated** (present but byte-identical to English). The latter is mostly legitimate proper nouns — `-v` lists them so you can tell.### 2. Export the work list-Dump `{ key: englishValue }` for every missing-or-identical string to a temp file so you can translate against the real source text. See `scripts.md` → *export*.+`node $S export <locale> <catalog> --chunk 150`. Chunks of ~150 strings keep each drafting pass reviewable; `--out DIR` if you want them somewhere specific (default: a fresh temp dir).### 3. Draft the translations-- Match the **terminology and tone already in the file** (probe existing entries first — e.g. RO uses `notiță` for "note", `Anulează` for "Cancel"). Don't invent new terms.-- **Keep proper nouns and kept technical terms in English**: ETAPI, MCP, OAuth/OpenID, Markdown, Widget, Mermaid, Bing/Google/Gantt/Kanban/…, and words spelled the same in the target language.-- **Preserve every placeholder exactly** (this is the #1 source of bugs):- - `{{var}}`, `{{- var}}` (unescaped — keep the hyphen), `{keyword}` (single-brace, e.g. search-engine URLs)- - JSX/`<Trans>` tags: `<buildRevision />`, `<Note/>`, `<code>…</code>`+- **Probe the existing file first and match its terminology and tone.** RO uses `notiță` for "note", `Anulează` for "Cancel", formal-plural address (`Selectați`). Don't invent a second term for something the file already names.+- **Keep proper nouns and kept technical terms in English**: ETAPI, MCP, OAuth/OpenID, Markdown, Widget, Mermaid, Bing/Google/Gantt/Kanban/…, and words spelled the same in the target language. Also keep **literal UI labels of other products** quoted in English (Notion's "Create folders for subpages") — the user has to find that exact control.+- **Preserve every placeholder exactly** (the #1 source of bugs) — `validate` checks all of these:+ - `{{var}}`, `{{- var}}` (unescaped — keep the hyphen), `{keyword}` (single-brace, e.g. date patterns and search-engine URLs)+ - JSX/`<Trans>` tags: `<buildRevision />`, `<Note/>`, `<code>…</code>`; HTML entities like `→`- `\n` line breaks, leading/trailing spaces, trailing punctuation-- Honor i18next **plural suffixes** (`_one`/`_other`, plus locale-specific like `_few`) — see grammar reference for the target language.+- Honor i18next **plural suffixes** — the locale's required categories, not English's two. See below.+- **Copy each form's placeholders from its own English key, not from the group.** English often writes `_one` without `{{count}}` ("An archived note was copied here", "1 hidden note") while `_other` has it. `validate` compares a locale-only `_few` against `_other`, so put `{{count}}` in `_few`/`_other` and leave `_one` as English left it.-### 4. Merge back — WITHOUT churning the diff-- **Do NOT alphabetize.** The EN file is *not* sorted and locale files have their own historical order. Sorting produces a 2500-line diff for a 600-string change. Preserve existing key order; update changed values in place; append genuinely-new keys to the end of their parent object.-- **Preserve file formatting:** 2-space indent, **CRLF** line endings, trailing newline. `JSON.stringify(obj, null, 2)` then `.replace(/\n/g,"\r\n") + "\r\n"`.-- See `scripts.md` → *merge*.+### 4. Validate, then merge+`node $S validate` must print **0 errors** before you merge. Then `node $S merge`, and check `git diff --stat`: a 600-string change is ~600 added lines, **not** thousands.-### 5. Validate-- **Placeholder integrity** (programmatic — catches dropped/extra `{{…}}`, tags, `{keyword}`): `scripts.md` → *validate*. Must be 0 errors.-- **JSON + duplicate keys:** `pnpm --filter client test src/services/i18n.spec.ts` (the repo's only translation test — checks valid JSON and no duplicate keys; there's **no** locale-parity test and **no** typed-i18next, so adding `_few` not present in EN is fine and won't break typecheck).-- Re-run *measure* to confirm 100% (remaining "identical" entries should all be legitimate proper nouns).+`merge` preserves what a naive `JSON.stringify` round-trip destroys:+- **Key order.** Never alphabetize — neither the EN file nor the locale files are sorted, and sorting turns a 600-string change into a 2500-line diff. New keys are appended to their parent object.+- **Formatting.** Indent, EOL and the trailing newline are detected from the file being written. The catalogs are currently **LF**; do not hard-code CRLF (an earlier version of this skill did, and it rewrites every line).++### 5. Final checks+```bash+node $S audit-plurals <locale> <catalog>+node $S measure <locale> # expect 100%; leftovers should be proper nouns+pnpm --filter client test src/services/i18n.spec.ts+```+`i18n.spec.ts` is the repo's only translation test — valid JSON, no duplicate keys, plus the CKEditor message-catalog check. There is **no** locale-parity test and **no** typed-i18next, so adding a `_few` that English lacks is fine and won't break `pnpm typecheck`.## Pluralization is a SOURCE-SIDE decisioni18next only pluralizes when **(a)** the translation has plural-suffixed keys **and (b)** the call site passes `{ count }`. So:-- You may freely add locale-specific plural categories (e.g. Romanian `_few`) to an existing plural group — EN supplies `_one`/`_other`, the locale supplies `_one`/`_few`/`_other`.+- You may freely add locale-specific plural categories (Romanian `_few`, Russian `_many`) to an existing plural group — EN supplies `_one`/`_other`, the locale supplies its own set. `locale.mjs` derives the required set from `Intl.PluralRules`, so `validate` accepts exactly the categories the locale uses and rejects the ones it doesn't.- To pluralize a string that EN keeps as a **single form** (e.g. `"{{count}} notes"`), you must:1. Verify the call site passes `count` (`grep` for the key; look for `t("…", { count })`). If it doesn't, or the key is unused, **don't** pluralize.2. Convert the **English** key from base → `_one`/`_other` in `en/translation.json` (this is the sanctioned place to edit EN).- 3. Add the locale's `_one`/`_few`/`_other`.+ 3. Add the locale's own categories.4. No code change needed — `t("key", {count})` resolves to the suffixed keys automatically.- ⚠️ **Cross-locale cost:** converting an EN base key to plural removes the base key, so *all other locales* fall back to English for that string until Weblate migrates them. Call this out in the PR. Don't unilaterally edit the other ~36 locale files — let Weblate migrate.- Skip strings i18next can't handle: more than one count-like variable (e.g. `"{{count}} sources from {{sites}} sites"` — only `count` triggers plurals).-## Auditing existing plurals+### Editing the English file by hand++For a handful of in-place EN edits (pluralizing one key, fixing a typo), do **text-level** replacement — never `JSON.parse → stringify` the EN file, which can reformat or re-escape unrelated lines:-To find plural groups missing a locale-required category (e.g. Romanian `_few`) or the wrong `_other` form, enumerate EN keys with both `_one` and `_other`, then check the locale has all required categories. See `scripts.md` → *audit-plurals*.+```js+const fs = require("fs");+function replaceOnce(path, pairs) { // pairs: [[oldLine, [newLine1, newLine2, …]], …]+ let s = fs.readFileSync(path, "utf8");+ const E = s.includes("\r\n") ? "\r\n" : "\n";+ for (const [oldL, newLines] of pairs) {+ if (s.indexOf(oldL) === -1) throw new Error("NOT FOUND: " + oldL);+ if (s.split(oldL).length > 2) throw new Error("NOT UNIQUE: " + oldL);+ s = s.replace(oldL, newLines.join(E));+ }+ fs.writeFileSync(path, s, "utf8");+}+```## Common pitfalls-- Alphabetizing the file (massive diff) — don't.-- Writing LF instead of CRLF (whole-file diff) — convert to CRLF.-- Dropping a trailing `.` or a placeholder when copying a reviewer's suggestion — diff each suggestion carefully.-- Putting server strings in the client file or vice-versa — they're separate namespaces with separate EN sources.+- Alphabetizing the file (massive diff) — `merge` won't, don't do it by hand either.+- Writing the wrong EOL (whole-file diff) — `merge` detects it; a hand-written `stringify` won't.+- Dropping a trailing `.` or a placeholder when copying a reviewer's suggestion — re-run `validate` after applying review feedback, not just after the first draft.+- Putting server strings in the client file or vice-versa — separate namespaces, separate EN sources.+- Translating a string whose English *is* a foreign UI label the user must click.diff --git a/.claude/skills/translating-locales/locale.mjs b/.claude/skills/translating-locales/locale.mjsnew file mode 100644index 0000000000..fd9cc1787e--- /dev/null+++ b/.claude/skills/translating-locales/locale.mjs@@ -0,0 +1,262 @@+#!/usr/bin/env node+/**+ * Locale workbench for Trilium's i18next catalogs.+ *+ * node .claude/skills/translating-locales/locale.mjs <command> [args]+ *+ * measure [locale] [-v] coverage of one locale (both catalogs), or all locales+ * export <locale> <catalog> [opts] write the work list (English source) to translate+ * validate <locale> <catalog> <file...> placeholder / whitespace / plural-category integrity+ * merge <locale> <catalog> <file...> apply translations, preserving order + formatting+ * audit-plurals <locale> <catalog> plural groups missing a category the locale requires+ *+ * catalog: client | server (measure covers both)+ * export opts: --chunk N --out DIR --only missing|identical|all+ *+ * Everything here exists so a translation pass never hand-rolls a JSON walker: the+ * traps (key order, EOL, locale-only plural categories, `{{- var}}`) are all handled.+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const SKILL_DIR = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(SKILL_DIR, "../../..");++const CATALOGS = {+ client: { en: "apps/client/src/translations/en/translation.json", loc: (l) => `apps/client/src/translations/${l}/translation.json` },+ // Separate namespace loaded on its own by the setup wizard, login and password-reset pages.+ entry: { en: "apps/client/src/translations/en/entry.json", loc: (l) => `apps/client/src/translations/${l}/entry.json` },+ server: { en: "apps/server/src/assets/translations/en/server.json", loc: (l) => `apps/server/src/assets/translations/${l}/server.json` }+};++/** Catalog directory names that aren't valid BCP-47 tags. */+const LOCALE_TO_BCP47 = { cn: "zh-CN", tw: "zh-TW", md: "ro-MD", pt_br: "pt-BR" };++const [, , cmd, ...rest] = process.argv;+const flags = {};+const args = [];+for (let i = 0; i < rest.length; i++) {+ if (rest[i].startsWith("--")) flags[rest[i].slice(2)] = rest[i + 1]?.startsWith("--") === false ? rest[++i] : true;+ else if (rest[i] === "-v") flags.verbose = true;+ else args.push(rest[i]);+}++const COMMANDS = { measure, export: exportTodo, validate, merge, "audit-plurals": auditPlurals };+const run = COMMANDS[cmd];+if (!run) {+ console.log(fs.readFileSync(fileURLToPath(import.meta.url), "utf8").split("*/")[0].split("/**")[1].replace(/^ \* ?/gm, ""));+ process.exit(cmd ? 1 : 0);+}+run(...args);++// ---------------------------------------------------------------- commands++function measure(locale) {+ const locales = locale ? [locale] : listLocales();+ for (const l of locales) {+ const parts = [];+ for (const name of Object.keys(CATALOGS)) {+ const p = resolvePair(l, name);+ if (!fs.existsSync(p.locPath)) { parts.push(`${name}: (absent)`); continue; }+ const { en, loc } = readPair(p);+ const keys = Object.keys(en);+ const missing = keys.filter((k) => !(k in loc));+ const identical = keys.filter((k) => isUntranslated(k, en, loc));+ parts.push(`${name}: ${pct(keys.length - missing.length, keys.length)} (missing ${missing.length}, untranslated ${identical.length}, of ${keys.length})`);+ if (flags.verbose && locale) {+ if (missing.length) console.log(` ${name} missing:`, missing.slice(0, 40).join(", "), missing.length > 40 ? `… +${missing.length - 40}` : "");+ if (identical.length) console.log(` ${name} identical to EN (check these are proper nouns):`, identical.join(", "));+ }+ }+ console.log(`${l.padEnd(6)} ${parts.join(" ")}`);+ }+}++function exportTodo(locale, catalog) {+ const p = requirePair(locale, catalog);+ const { en, loc } = readPair(p);+ const only = flags.only ?? "all";+ const todo = {};+ for (const k of Object.keys(en)) {+ if (typeof en[k] !== "string") continue;+ const missing = !(k in loc);+ const identical = !missing && isUntranslated(k, en, loc);+ if ((only === "all" && (missing || identical)) || (only === "missing" && missing) || (only === "identical" && identical)) todo[k] = en[k];+ }+ const outDir = flags.out ?? fs.mkdtempSync(path.join(process.env.TMPDIR ?? "/tmp", `loc-${locale}-`));+ fs.mkdirSync(outDir, { recursive: true });+ const keys = Object.keys(todo);+ const chunk = parseInt(flags.chunk ?? "0", 10);+ const written = [];+ if (!chunk) {+ written.push(writeJson(path.join(outDir, `todo-${catalog}.json`), todo));+ } else {+ for (let i = 0, n = 0; i < keys.length; i += chunk) {+ const part = Object.fromEntries(keys.slice(i, i + chunk).map((k) => [k, todo[k]]));+ written.push(writeJson(path.join(outDir, `todo-${catalog}-${String(++n).padStart(2, "0")}.json`), part));+ }+ }+ console.log(`${keys.length} strings →`);+ written.forEach((f) => console.log(" " + f));+ console.log(`\nTranslate each into a flat { key: "translation" } file, then:\n validate ${locale} ${catalog} <files…>\n merge ${locale} ${catalog} <files…>`);+}++function validate(locale, catalog, ...files) {+ const p = requirePair(locale, catalog);+ const { en } = readPair(p);+ const categories = pluralCategories(locale);+ let errors = 0;+ let count = 0;+ const seen = new Set();+ for (const file of files) {+ const done = JSON.parse(fs.readFileSync(file, "utf8"));+ for (const [k, v] of Object.entries(done)) {+ count++;+ const fail = (msg) => { console.log(`! ${k}: ${msg}`); errors++; };+ if (seen.has(k)) fail(`duplicated across the input files`);+ seen.add(k);+ const source = en[k] ?? en[pluralBase(k, categories)];+ if (source === undefined) { fail(`not a key in the English catalog`); continue; }+ if (typeof v !== "string") { fail(`not a string`); continue; }+ if (!v.trim()) { fail(`empty`); continue; }+ for (const ph of placeholders(source)) if (!placeholders(v).has(ph)) fail(`dropped placeholder ${JSON.stringify(ph)}\n EN: ${source}\n ${locale.toUpperCase()}: ${v}`);+ for (const ph of placeholders(v)) if (!placeholders(source).has(ph)) fail(`invented placeholder ${JSON.stringify(ph)}\n EN: ${source}\n ${locale.toUpperCase()}: ${v}`);+ if (/^\s/.test(source) !== /^\s/.test(v)) fail("leading whitespace differs from EN");+ if (/\s$/.test(source) !== /\s$/.test(v)) fail("trailing whitespace differs from EN");+ if (countOf(source, "\n") !== countOf(v, "\n")) fail("number of line breaks differs from EN");+ const cat = k.match(/_(zero|one|two|few|many|other)$/)?.[1];+ if (cat && !categories.includes(cat)) fail(`plural category "_${cat}" is not used by ${locale} (needs ${categories.map((c) => "_" + c).join("/")})`);+ }+ }+ console.log(`checked ${count} strings from ${files.length} file(s): ${errors} error(s)`);+ if (errors) process.exitCode = 1;+}++function merge(locale, catalog, ...files) {+ const p = requirePair(locale, catalog);+ const raw = fs.readFileSync(p.locPath, "utf8");+ const loc = JSON.parse(raw);+ let n = 0;+ for (const file of files) {+ for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(file, "utf8")))) { setDeep(loc, k, v); n++; }+ }+ // Preserve the file's own formatting — writing CRLF into an LF file (or vice versa) rewrites every line.+ const eol = raw.includes("\r\n") ? "\r\n" : "\n";+ const indent = raw.match(/^[^\n]*\n(\s+)"/)?.[1].replace("\r", "").length ?? 2;+ let out = JSON.stringify(loc, null, indent);+ if (eol === "\r\n") out = out.replace(/\n/g, "\r\n");+ fs.writeFileSync(p.locPath, out + (raw.endsWith("\n") || raw.endsWith("\r\n") ? eol : ""), "utf8");+ console.log(`merged ${n} strings into ${p.loc} (indent ${indent}, ${eol === "\n" ? "LF" : "CRLF"})`);+ console.log("Now check `git diff --stat`: it should be ~the number of changed strings, not thousands.");+}++function auditPlurals(locale, catalog) {+ const p = requirePair(locale, catalog);+ const { en, loc } = readPair(p);+ const categories = pluralCategories(locale);+ const bases = new Set();+ for (const k of Object.keys(en)) { const m = k.match(/^(.*)_(zero|one|two|few|many|other)$/); if (m) bases.add(m[1]); }+ const groups = [...bases].filter((b) => `${b}_one` in en && `${b}_other` in en);+ let n = 0;+ for (const b of groups) {+ if (!categories.some((c) => `${b}_${c}` in loc)) continue; // untranslated group — the export covers it+ const problems = categories.filter((c) => loc[`${b}_${c}`] === undefined).map((c) => `no _${c}`);+ // Romanian: `_other` (≥20) takes "de" before the noun, `_few` (2–19) must not.+ if (locale.startsWith("ro") || locale === "md") {+ const other = loc[`${b}_other`];+ if (typeof other === "string" && /\{\{count\}\}\s+[a-zA-ZăâîșțĂÂÎȘȚ]/.test(other) && !/\{\{count\}\}\s+de\s/.test(other)) problems.push(`_other missing "de": ${JSON.stringify(other)}`);+ const few = loc[`${b}_few`];+ if (typeof few === "string" && /\{\{count\}\}\s+de\s/.test(few)) problems.push(`_few must not use "de": ${JSON.stringify(few)}`);+ }+ if (problems.length) { console.log(`${b} [${problems.join("] [")}]`); n++; }+ }+ console.log(`${n} of ${groups.length} translated plural groups need attention (${locale} requires ${categories.map((c) => "_" + c).join("/")})`);+}++// ---------------------------------------------------------------- helpers++function resolvePair(locale, catalog) {+ const c = CATALOGS[catalog];+ if (!c) { console.error(`unknown catalog "${catalog}" — use client or server`); process.exit(1); }+ return { enPath: path.join(ROOT, c.en), locPath: path.join(ROOT, c.loc(locale)), en: c.en, loc: c.loc(locale) };+}++function requirePair(locale, catalog) {+ if (!locale || !catalog) { console.error("usage: <command> <locale> <client|server> …"); process.exit(1); }+ const p = resolvePair(locale, catalog);+ if (!fs.existsSync(p.locPath)) { console.error(`no such locale file: ${p.loc}`); process.exit(1); }+ return p;+}++function readPair(p) {+ return { en: flatten(JSON.parse(fs.readFileSync(p.enPath, "utf8"))), loc: flatten(JSON.parse(fs.readFileSync(p.locPath, "utf8"))) };+}++function listLocales() {+ return fs.readdirSync(path.join(ROOT, "apps/client/src/translations")).filter((d) => d !== "en" && fs.statSync(path.join(ROOT, "apps/client/src/translations", d)).isDirectory()).sort();+}++/** A string present in the locale but byte-identical to English — untranslated, unless it's a proper noun. */+function isUntranslated(k, en, loc) {+ return k in loc && typeof en[k] === "string" && loc[k] === en[k] && /[a-zA-Z]{4,}/.test(en[k]);+}++function pluralCategories(locale) {+ const tag = LOCALE_TO_BCP47[locale] ?? locale.replace("_", "-");+ try {+ return new Intl.PluralRules(tag).resolvedOptions().pluralCategories;+ } catch {+ console.error(`warning: "${locale}" is not a recognised locale tag; assuming one/other`);+ return ["one", "other"];+ }+}++/** `key_few` has no English counterpart when English only has one/other — fall back to `_other`. */+function pluralBase(k, categories) {+ const m = k.match(/^(.*)_(zero|one|two|few|many|other)$/);+ return m && categories.includes(m[2]) ? `${m[1]}_other` : k;+}++function placeholders(s) {+ const set = new Set();+ (s.match(/\{\{[^}]*\}\}/g) ?? []).forEach((x) => set.add(x.replace(/\s+/g, " ").trim())); // {{var}} and {{- var}}+ (s.match(/(?<!\{)\{[a-zA-Z_][^}{]*\}(?!\})/g) ?? []).forEach((x) => set.add(x)); // single-brace {keyword}+ // <Note/>, <code>, <buildRevision /> — must start with a letter, so the "<- and ->" of a prose+ // sentence about operators isn't mistaken for a tag.+ (s.match(/<\/?[A-Za-z][\w:.-]*(\s[^<>]*)?\/?>/g) ?? []).forEach((x) => set.add(x.replace(/\s+/g, "")));+ (s.match(/%\d/g) ?? []).forEach((x) => set.add(x)); // CKEditor-style %0+ return set;+}++function flatten(o, p = "", out = {}) {+ for (const k of Object.keys(o)) {+ const key = p ? `${p}.${k}` : k;+ if (o[k] && typeof o[k] === "object" && !Array.isArray(o[k])) flatten(o[k], key, out);+ else out[key] = o[k];+ }+ return out;+}++function setDeep(obj, dotted, val) {+ const ks = dotted.split(".");+ let o = obj;+ for (const k of ks.slice(0, -1)) {+ if (typeof o[k] !== "object" || o[k] === null) o[k] = {};+ o = o[k];+ }+ o[ks[ks.length - 1]] = val;+}++function writeJson(file, obj) {+ fs.writeFileSync(file, JSON.stringify(obj, null, 2) + "\n", "utf8");+ return file;+}++function countOf(s, ch) {+ return s.split(ch).length - 1;+}++function pct(done, total) {+ return `${((done / total) * 100).toFixed(1)}%`;+}diff --git a/.claude/skills/translating-locales/romanian.md b/.claude/skills/translating-locales/romanian.mdindex 1e4a3bf5e9..5848c5126c 100644--- a/.claude/skills/translating-locales/romanian.md+++ b/.claude/skills/translating-locales/romanian.md@@ -62,7 +62,37 @@ Adjectives and past participles **must agree** with the noun's gender and number| Enable / Disable | Activează / Dezactivează || Search | Căutare / Caută || code (note type) | Cod sursă |-| backup | copie de rezervă |+| backup | copie de siguranță || Preview | Previzualizare |-Keep in English: ETAPI, MCP, OAuth/OpenID, Markdown, Widget, Mermaid, search-engine names, and words identical in Romanian (Text, Editor, Calendar, Vertical, Zoom, August, Logo, Alias).+Settled in later passes — the file is not always self-consistent, so prefer these:++| English | Romanian | note |+|---|---|---|+| backup | copie de siguranță | the dominant form in both catalogs; `backup.title` still says "Copie de rezervă" |+| hoist / hoisted | focalizează / focalizat | `tree-context-menu.hoist-note` = "Focalizează notița" |+| board (Kanban) | tablă | `book_properties.board` = "Tablă Kanban" |+| marker (geo map) | marcaj | |+| snippet | fragment (de text / de cod) | |+| saved search | căutare salvată | |+| backlink | legătură de retur | |+| launcher / launch bar / spacer | lansator / bară de lansare / separator | |+| day, week, month note | notiță zilnică, săptămânală, lunară | |+| workspace | spațiu de lucru | |+| knowledge base | bază de cunoștințe | |+| ribbon | panglică | |+| promoted attribute | atribut evidențiat | |+| notebook (OneNote, Evernote) | blocnotes | |+| collection | colecție | |+| pin / unpin (tab) | fixează / anulează fixarea | |+| erase (permanently) | șterge definitiv | vs. plain `delete` = șterge |+| tray, tab, widget, token, log | tray, tab, widget, token, log | already borrowed in the file; decline with a hyphen (tab-ul, widget-uri, log-uri) |++**Interpolated foreign UI labels stay in English.** When the string tells the user to click something in *another* product ("re-export with **Create folders for subpages** enabled", OneNote's "Password Protection → Remove Password"), leave that label untranslated — the user has to find that exact control.++Keep in English: ETAPI, MCP, OAuth/OpenID, Markdown, Widget, Mermaid, search-engine names, keyboard key names (Ctrl, Shift, Enter, Delete, Home, Insert…), and words identical in Romanian (Text, Editor, Calendar, Vertical, Zoom, August, Logo, Alias, Original, Important, Card, Beta, Format, Prefix, Script).++## Typography++- Quotation marks are **„…”** (opening low, closing high), not `"…"` — e.g. `Ștergeți atributul „{{name}}”?`.+- Put a space between a number and its unit: `Interval: {{seconds}} s`.diff --git a/.claude/skills/translating-locales/scripts.md b/.claude/skills/translating-locales/scripts.mddeleted file mode 100644index 100b09df7d..0000000000--- a/.claude/skills/translating-locales/scripts.md+++ /dev/null@@ -1,156 +0,0 @@-# Reusable scripts--Copy-paste Node snippets used by the workflow in `SKILL.md`. Run from the repo root (or a worktree). All assume the shared `flatten` helper:--```js-function flatten(o, p = "", out = {}) {- for (const k in o) {- const key = p ? p + "." + k : k;- if (o[k] && typeof o[k] === "object" && !Array.isArray(o[k])) flatten(o[k], key, out);- else out[key] = o[k];- }- return out;-}-```--Set the pair you're working on:-```js-const EN = "apps/client/src/translations/en/translation.json";-const LOC = "apps/client/src/translations/ro/translation.json";-// server pair: apps/server/src/assets/translations/{en/server.json, ro/server.json}-```--## measure — coverage gap--```js-const fs = require("fs");-const en = flatten(JSON.parse(fs.readFileSync(EN, "utf8")));-const loc = flatten(JSON.parse(fs.readFileSync(LOC, "utf8")));-const keys = Object.keys(en);-const missing = keys.filter(k => !(k in loc));-// "identical" = present but never translated; ignore proper nouns (no 4+ letter run is a heuristic)-const identical = keys.filter(k => k in loc && loc[k] === en[k] && typeof en[k] === "string" && /[a-zA-Z]{4,}/.test(en[k]));-console.log(`missing=${missing.length} identical=${identical.length} coverage=${(((keys.length - missing.length) / keys.length) * 100).toFixed(1)}%`);-console.log("missing sample:", missing.slice(0, 20));-console.log("identical (check these are proper nouns):", identical);-```--## export — work list to translate--```js-const fs = require("fs");-const en = flatten(JSON.parse(fs.readFileSync(EN, "utf8")));-const loc = flatten(JSON.parse(fs.readFileSync(LOC, "utf8")));-const todo = {};-for (const k of Object.keys(en)) {- if (typeof en[k] !== "string") continue;- const missing = !(k in loc);- const identical = (k in loc) && loc[k] === en[k] && en[k].trim() !== "";- if (missing || identical) todo[k] = en[k];-}-fs.writeFileSync(".loc-todo.json", JSON.stringify(todo, null, 2));-console.log("todo:", Object.keys(todo).length);-```--Then translate into a flat `{ key: translatedValue }` file, e.g. `.loc-done.json`.--## validate — placeholder integrity (run BEFORE merging)--Catches dropped/extra `{{var}}`, `{{- var}}`, `{keyword}`, and tags. Must print 0 errors.--```js-const fs = require("fs");-function placeholders(s) {- const set = new Set();- (s.match(/\{\{[^}]*\}\}/g) || []).forEach(x => set.add(x.replace(/\s+/g, " ").trim())); // {{x}} and {{- x}}- (s.match(/(?<!\{)\{[a-zA-Z_][^}{]*\}(?!\})/g) || []).forEach(x => set.add(x)); // single-brace {keyword}- (s.match(/<[^>]+>/g) || []).forEach(x => set.add(x.replace(/\s+/g, ""))); // <Note/>, <code>, <buildRevision />- return set;-}-const en = flatten(JSON.parse(fs.readFileSync(EN, "utf8")));-const done = JSON.parse(fs.readFileSync(".loc-done.json", "utf8"));-let errors = 0;-for (const k of Object.keys(done)) {- if (!(k in en)) { console.log("! NOT IN EN:", k); errors++; continue; }- const ep = placeholders(en[k]), rp = placeholders(done[k]);- for (const p of ep) if (!rp.has(p)) { console.log(`! ${k}: missing ${JSON.stringify(p)}`); errors++; }- for (const p of rp) if (!ep.has(p)) { console.log(`! ${k}: extra ${JSON.stringify(p)}`); errors++; }-}-console.log("placeholder errors:", errors);-```--## merge — apply translations WITHOUT churning the diff--Preserves existing key order (no sorting), updates values in place, appends new keys to their parent object, and keeps 2-space indent + CRLF + trailing newline.--```js-const fs = require("fs");-function setDeep(obj, path, val) {- const ks = path.split(".");- let o = obj;- for (let i = 0; i < ks.length - 1; i++) {- if (typeof o[ks[i]] !== "object" || o[ks[i]] === null) o[ks[i]] = {};- o = o[ks[i]];- }- o[ks[ks.length - 1]] = val;-}-const loc = JSON.parse(fs.readFileSync(LOC, "utf8"));-const done = JSON.parse(fs.readFileSync(".loc-done.json", "utf8"));-for (const k of Object.keys(done)) setDeep(loc, k, done[k]);-fs.writeFileSync(LOC, JSON.stringify(loc, null, 2).replace(/\n/g, "\r\n") + "\r\n", "utf8");-console.log("merged", Object.keys(done).length);-```--Then `git diff --stat` — a ~600-string change should be roughly that many added lines, **not** thousands. If it's thousands, you accidentally re-sorted or changed EOLs. Clean up temp files: `rm -f .loc-todo.json .loc-done.json`.--## targeted plural/grammar edits--For a handful of in-place fixes (e.g. converting one base key to plurals in **both** EN and locale, or fixing gender), do **text-level** replacement so unrelated lines stay byte-identical — never `JSON.parse → stringify` the EN file (it can reformat/re-escape). This helper replaces exact unique line(s) and preserves the file's EOL:--```js-const fs = require("fs");-function replaceOnce(path, pairs) { // pairs: [[oldLine, [newLine1, newLine2, ...]], ...]- let s = fs.readFileSync(path, "utf8");- const E = s.includes("\r\n") ? "\r\n" : "\n";- for (const [oldL, newLines] of pairs) {- if (s.indexOf(oldL) === -1) throw new Error("NOT FOUND: " + oldL);- if (s.split(oldL).length > 2) throw new Error("NOT UNIQUE: " + oldL);- s = s.replace(oldL, newLines.join(E));- }- fs.writeFileSync(path, s, "utf8");-}-// Example: pluralize a single EN key (4-space indent for a 2-level-deep key)-const I = " ";-replaceOnce(EN, [[- I + '"total_notes": "{{count}} notes",',- [I + '"total_notes_one": "{{count}} note",', I + '"total_notes_other": "{{count}} notes",']-]]);-```--## audit-plurals — find groups missing a required category--Lists plural groups (EN has both `_one` and `_other`) where the locale lacks `_few`, or whose `_other` looks like it's missing "de" (Romanian heuristic).--```js-const fs = require("fs");-const en = flatten(JSON.parse(fs.readFileSync(EN, "utf8")));-const loc = flatten(JSON.parse(fs.readFileSync(LOC, "utf8")));-const bases = new Set();-for (const k of Object.keys(en)) { const m = k.match(/^(.*)_(one|few|other|two|many)$/); if (m) bases.add(m[1]); }-const plural = [...bases].filter(b => (b + "_one") in en && (b + "_other") in en);-for (const b of plural) {- if (!((b + "_one") in loc || (b + "_other") in loc)) continue; // untranslated, skip- const other = loc[b + "_other"];- const missingFew = loc[b + "_few"] === undefined;- const missingDe = typeof other === "string"- && /\{\{count\}\}\s+[a-zaăâîșțA-ZĂÂÎȘȚ]/.test(other) && !/\{\{count\}\}\s+de\s/.test(other);- if (missingFew || missingDe) console.log(b, missingFew ? "[no _few]" : "", missingDe ? "[_other missing 'de']" : "");-}-```--## final validation--```bash-pnpm --filter client test src/services/i18n.spec.ts # valid JSON + no duplicate keys (the only translation test)-```-Then re-run *measure* → expect 100%, with remaining "identical" entries all legitimate proper nouns.