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): add translating-locales skill
Elian Dorane2f8446eabf9
diff --git a/.claude/skills/translating-locales/SKILL.md b/.claude/skills/translating-locales/SKILL.mdnew file mode 100644index 0000000000..ce27faeb1e--- /dev/null+++ b/.claude/skills/translating-locales/SKILL.md@@ -0,0 +1,81 @@+---+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.+---++# Translating / improving a locale in Trilium++Trilium'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.++## How Weblate sync works here (merging a PR IS picked up — no separate upload needed)++Weblate is linked to this repo with the **GitHub pull-request push method**: `.github/workflows/i18n.yml` triggers on `push` to `weblate:*` branches, and Weblate opens PRs into the repo (the recurring `Translations update from Hosted Weblate (#…)` PRs). The locale `translation.json` / `server.json` files are tracked Weblate **components**. Consequently:++- **Merging a PR that edits a locale file IS picked up by Weblate.** On its next pull of the default branch, Weblate imports the new/changed translations into its database — they persist and show up for other contributors. They are **not** discarded or overwritten. With the PR-based push method Weblate never force-pushes the default branch, so the repo is authoritative and Weblate merges *from* it.+- A direct-to-repo PR is therefore a fully valid, durable way to land translations. **You do NOT need to separately upload the file into Weblate.**+- This is the opposite of arbitrary repo files (README, docs): those aren't part of any Weblate component, so Weblate simply ignores them.+- Real (narrow) caveat: a true conflict only arises if the **same key** is edited simultaneously in Weblate (pending, un-pushed) *and* in the repo — then Weblate's merge/rebase conflict handling picks the winner. Filling previously-empty/untranslated strings doesn't conflict.+- `CLAUDE.md`'s "only add new keys to `en/translation.json`" rule is about where *new source strings* originate (so they enter the translation pipeline), **not** a prohibition on landing translations for an existing locale via the repo.+- Changing an **English source** string (e.g. pluralizing a key) makes Weblate flag the matching translations in *other* locales as needing review and drop orphaned removed-key entries — normal, and it doesn't affect the locale you just filled.++## File locations++| Scope | English source | Target locale |+|---|---|---|+| Client UI | `apps/client/src/translations/en/translation.json` | `apps/client/src/translations/<locale>/translation.json` |+| Server (hidden subtree titles, dialogs, migration/search messages) | `apps/server/src/assets/translations/en/server.json` | `apps/server/src/assets/translations/<locale>/server.json` |++Both client and server have their own EN↔locale pair — check **both**.++## 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.++### 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*.++### 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>`+ - `\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.++### 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*.++### 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).++## Pluralization is a SOURCE-SIDE decision++i18next 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`.+- 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`.+ 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++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*.++## 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.diff --git a/.claude/skills/translating-locales/romanian.md b/.claude/skills/translating-locales/romanian.mdnew file mode 100644index 0000000000..1e4a3bf5e9--- /dev/null+++ b/.claude/skills/translating-locales/romanian.md@@ -0,0 +1,68 @@+# Romanian (`ro`) grammar rules++The recurring lagging locale. These rules came out of real review feedback (Gemini Code Assist) on the Romanian PR — get them right up front.++## Diacritics+Use proper Romanian diacritics: **ă â î ș ț** (comma-below ș/ț, not cedilla). Capitalize months and standalone nouns as the existing file does (e.g. `"August"`, `"Septembrie"`).++## Plurals — Romanian needs THREE CLDR categories: `one` / `few` / `other`++i18next knows Romanian's plural rule. Every count+noun string needs all three:++| Category | Applies to (count) | Form |+|---|---|---|+| `_one` | exactly 1 | singular noun: `{{count}} notiță` |+| `_few` | 0, and 2–19 (and n%100 in 1–19) | plain plural, **no "de"**: `{{count}} notițe` |+| `_other` | ≥ 20 (20, 21, 100, …) | **plural noun preceded by "de"**: `{{count}} de notițe` |++The single most-missed rule: **`_other` must use the preposition "de"** before the noun ("21 **de** notițe"), and `_few` must **not** ("5 notițe"). The file already follows this (e.g. pre-existing `"{{count}} de taburi"`).++Examples that shipped:+```jsonc+"annotations_one": "{{count}} adnotare",+"annotations_few": "{{count}} adnotări",+"annotations_other": "{{count}} de adnotări",++"pages_one": "{{count}} pagină",+"pages_few": "{{count}} pagini",+"pages_other": "{{count}} de pagini",+```+For strings with no number-modified noun (e.g. a tooltip), `_few` and `_other` are identical and may both omit "de".++## Gender & number agreement++Adjectives and past participles **must agree** with the noun's gender and number. Watch feminine nouns — `clonă`/`clone` (clone), `căutare` (search), `notiță`/`notițe` (note), `opțiune` (option) are all **feminine**.++| Wrong (masculine/neuter) | Right (feminine) | Why |+|---|---|---|+| `Poate fi anulat` | `Poate fi anulată` (sg.) / `Pot fi anulate` (pl.) | "clonă/clone" feminine |+| `Indisponibil pe modelele…` | `Indisponibilă pe modelele…` | subject is "căutarea (web)", feminine |+| `{{count}} notițe au fost convertit` | `…au fost convertite` (pl.) / `o notiță a fost convertită` (sg.) | participle agrees with notiță(e) |++**Interpolated noun of unknown gender** (e.g. `{{settingLabel}}` which can be "Consolă SQL" *or* "Execuția scripturilor"): don't try to agree with it. Prefix a **known-gender head noun** so agreement is fixed:+```jsonc+// EN: "{{settingLabel}} will be disabled."+"disable-message": "Opțiunea {{settingLabel}} va fi dezactivată." // "Opțiunea" is feminine → "dezactivată"+```++## Terminology (match the existing file)++| English | Romanian |+|---|---|+| note | notiță (pl. notițe) |+| child note / subnote | subnotiță |+| label / attribute | etichetă / atribut |+| relation | relație |+| attachment | atașament |+| revision | revizie (pl. revizii) |+| Cancel | Anulează |+| Save | Salvează |+| Delete | Șterge |+| Close | Închide |+| Enable / Disable | Activează / Dezactivează |+| Search | Căutare / Caută |+| code (note type) | Cod sursă |+| backup | copie de rezervă |+| 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).diff --git a/.claude/skills/translating-locales/scripts.md b/.claude/skills/translating-locales/scripts.mdnew file mode 100644index 0000000000..100b09df7d--- /dev/null+++ b/.claude/skills/translating-locales/scripts.md@@ -0,0 +1,156 @@+# 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.