PM: merge M1.11 message catalog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 15:24:11 +02:00
commit 5d3a4486e4
21 changed files with 273 additions and 37 deletions

View file

@ -2,7 +2,7 @@
**Stage: pre-alpha (M1 in progress)** · next: the rest of M1 (recovery, palette, settings, themes), then M2 syntax and search; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (cycle C1 review: estimates recalibrated) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M1.11: English UI catalog) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
@ -30,12 +30,12 @@ Dimension hours overlap: language, framework and tooling hours are part of the f
| PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) |
| Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) |
| Tooling (Git, terminal, debugger, tests, Composer, DB) | 0% | ~730 (in features) | [tooling-parity.md](docs/tooling-parity.md) |
| Localization (en, de) | 0% | ~40 | [localization-parity.md](docs/localization-parity.md) |
| Localization (en, de) | 5% | ~38 | [localization-parity.md](docs/localization-parity.md) |
| Performance | 0% | ~100 | [gaps.md › G12](docs/gaps.md) |
| Stability | 5% | ~100 | [gaps.md › G11](docs/gaps.md) |
| Agent automation | 10% | ~60 | AGENTS.md |
Stability 5%: no-panic lints, the engine guard and a fuzzed control protocol exist; the recovery journal does not. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works; MCP and the CLI do not exist yet. Both are estimated.
Stability 5%: no-panic lints, the engine guard and a fuzzed control protocol exist; the recovery journal does not. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works; MCP and the CLI do not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing.
## Features
@ -77,6 +77,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | What landed |
|---|---|
| 2026-10-15 | M1.11: every interface string comes from an English message catalog (`ui/src/i18n/en.json`), enforced by a lint rule and a catalog test; the groundwork for German. |
| 2026-10-15 | M1.6: files open in tabs with a CodeMirror editor synced to the engine; save, save all, close with a Save / Don't Save / Cancel question, a notice when a file with unsaved changes changes on disk; a 1 MB file opens in about 90 ms. |
| 2026-10-15 | M1 so far: text buffer, VFS with native watching, engine workspace (files, buffers, edit protocol, events), desktop bridge: open a folder by picker or command line, browse it in the project tree with live updates from disk. |
| 2026-10-14 | M0 foundation: Cargo workspace with layered crates, no-panic lints with a self-test, `cargo xtask ci` (fmt, clippy, tests, layers, assets, clean-room, licences, frontend lint/typecheck/tests), Vue frontend, command registry with panic guard (`app.about`, `app.quit`), JSON control channel, Tauri window themed from Rust tokens, CI workflow. First estimates. |
@ -86,6 +87,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | minor | M1.11: localization 5% (English UI catalog), progress log |
| 2026-10-15 | minor | Cycle C1 review: stage line, breadth estimate, hours recalibrated ×0.1 |
| 2026-10-15 | minor | Feature depth ~1.4%: tabs and editor (M1.6) |
| 2026-10-15 | minor | Feature depth above 0%: project tree runs against the engine (M1.4) |

View file

@ -1,6 +1,6 @@
# Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor documented · **Last updated:** 2026-10-15
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs, editor and message catalog documented · **Last updated:** 2026-10-15
## Overview
@ -101,6 +101,13 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Lutra saves only on request for now (no autosave).
- Theme: the editor reads colours only from `--lt-*` tokens. Tokens the theme does not have yet are read as `var(--lt-new-token, <fallback from existing tokens>)` so they take effect once added in Rust.
### Message catalog (M1.11)
- Every interface string comes from `ui/src/i18n/en.json`: flat dotted keys grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`), kept sorted. Components and stores call `t(key, params?)` from `ui/src/i18n`; `{name}` placeholders are filled from `params`, a placeholder without a value stays as it is. A missing key returns the key itself and warns on the console in development builds; it never throws. `hasMessage(key)` tells whether a key exists, for keys that arrive at runtime (settings `labelKey`, notification `messageKey`).
- No i18n dependency: the helper is ~20 lines, and plurals, a reactive locale and a second language are G14 work. `vue-i18n` (MIT) remains an option then.
- Enforcement: ESLint `vue/no-bare-strings-in-template` is an error (bare text and `title`/`aria-label`/`placeholder`/`alt` attributes); the allowlist is the rule's punctuation plus `;`, `…` and `×`. The test `ui/tests/i18n/catalog.test.ts` scans `ui/src` for `t("…")` calls and fails on a key that is not in `en.json` and on a catalog key that no source uses. Keys used only at runtime need an exception there when they arrive.
- Engine messages (`EngineError.message`, the `app.about` slogan, `watchFailed`) are English text from the engine and shown as they are; they move to message keys with G14. Frontend-made errors (`unexpected result of …`) use the catalog.
## Decisions (M0)
| Question | Decision | Why |
@ -118,6 +125,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | minor | M1.11: message catalog (`t`, lint rule, catalog test, engine messages stay English) |
| 2026-10-15 | minor | M1.6: tabs and editor (buffer sync, CRLF offsets, shortcuts from command specs) |
| 2026-10-15 | minor | M1.4: desktop bridge (engine://event, engine_ready replay, folder picker, capabilities), UI contract fix |
| 2026-10-14 | minor | M1.3: workspace commands, edit protocol, events, events.subscribe, watched-directory limits |

View file

@ -1,6 +1,6 @@
# Gaps
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app); G3 project tree works in the app · **Last updated:** 2026-10-15
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app); G3 project tree works in the app; G14 English UI catalog in place · **Last updated:** 2026-10-15
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
@ -19,12 +19,14 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| G11 | Stability: crash-free operation on real projects and machines | ongoing | ~100 h |
| G12 | Performance budgets: start, open, type, search, index | ongoing | ~100 h |
| G13 | Frameworks: Symfony, Laravel, Shopware, WordPress | M6 | ~300 h |
| G14 | Localization: English and German interface | later | ~40 h |
| G14 | Localization: English and German interface: ~~English message catalog for UI strings~~ (M1.11), engine messages (`EngineError.message`) as message keys, language switch, plurals, German catalog | later | ~38 h |
| G15 | Database tools, HTTP client, Docker and remote | later | ~430 h |
| G16 | Plug-ins and ecosystem | later | ~120 h |
G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. Still open: the recovery journal, tab management beyond open/close, a conflict UI (compare and merge with the disk version), autosave, editor settings (font size, soft wrap); estimate lowered to ~18 h.
G14 progress: M1.11 moved every UI string in `ui/src` into the English catalog `ui/src/i18n/en.json` behind `t(key, params?)`, enforced by `vue/no-bare-strings-in-template` and a catalog test. Messages the engine sends (`EngineError.message`, the slogan from `app.about`) are still English text; they need message keys with params before a second language can cover them.
Known smaller items from M0:
- The CI workflow has never run: the repository has no remote until the owner decides on hosting.
@ -35,6 +37,7 @@ Known smaller items from M0:
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | minor | G14 note: English message catalog (M1.11) |
| 2026-10-15 | minor | G2 shrunk: tabs and editor (M1.6) |
| 2026-10-15 | minor | G3 shrunk: project tree wired to the engine (M1.4) |
| 2026-10-14 | minor | G2 shrunk, G3 note: engine workspace (M1.3) |

View file

@ -1,16 +1,29 @@
# Localization checklist
> **Status:** baseline · **Last updated:** 2026-10-13
> **Status:** English catalog covers 100% of UI strings (M1.11); German not started · **Last updated:** 2026-10-15
| Language | Code | Status | Translated |
|---|---|---|---:|
| English | `en` | source | 0% |
| German | `de` | planned | 0% |
| English | `en` | source catalog (`ui/src/i18n/en.json`) | 100% of UI strings (20 keys, measured by the catalog test) |
| German | `de` | planned (G14) | 0% |
All interface strings go through the message catalog from the first UI task on; no hard-coded labels.
All interface strings go through the message catalog: `t(key, params?)` from `ui/src/i18n`, flat dotted keys grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`), `{name}` placeholders. Lint (`vue/no-bare-strings-in-template`, error) rejects bare text in templates; a Vitest scan checks that every key passed to `t` exists in `en.json` and that the catalog has no unused keys.
## Checklist
- [x] English message catalog and `t` helper (M1.11)
- [x] Lint rule against bare template strings (M1.11)
- [x] Every UI string in `ui/src` from the catalog: templates, `title` and `aria-label` attributes, notices, frontend error texts (M1.11)
- [ ] Engine messages: `EngineError.message` and other texts the engine sends are English only; they need message keys and params (G14)
- [ ] Setting labels and descriptions from `settings.list` (`labelKey`, `descriptionKey`) in the catalog (M1.9b)
- [ ] Language switch through `ui.language`; the catalog becomes reactive (G14)
- [ ] Plural forms and number/date formatting per locale (G14)
- [ ] German catalog (G14)
- [ ] Native menus and dialogs of the desktop shell (folder picker title, app menu) (G14)
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | minor | M1.11: English catalog, lint rule, checklist; engine-message gap |
| 2026-10-13 | major | Baseline |

View file

@ -7,7 +7,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
| Milestone | Goal | State | Hours |
|---|---|---|---:|
| M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) |
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor) | ~6 (2.5 measured for M1.1–M1.6) |
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog) | ~6 (2.5 measured for M1.1–M1.6) |
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~5 |
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
@ -31,6 +31,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | minor | M1.11 message catalog |
| 2026-10-15 | minor | Cycle C1 review: M1–M3 hours recalibrated ×0.1, M0 CI note |
| 2026-10-15 | minor | M1.6 tabs and editor |
| 2026-10-15 | minor | M1.4 desktop bridge |

View file

@ -4,6 +4,10 @@
* Type-aware TypeScript rules apply to `.ts` and `.vue` files. Floating and
* misused promises are errors so that no rejection goes unhandled, `any`
* is an error, and inline comments are banned in favour of TSDoc blocks.
*
* Templates may not contain bare text: every interface string comes from the
* message catalog (`src/i18n`). The rule's default punctuation allowlist is
* extended by `;`, `…` and `×`.
*/
import js from "@eslint/js";
import { defineConfig } from "eslint/config";
@ -33,6 +37,15 @@ export default defineConfig(
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/no-explicit-any": "error",
"no-inline-comments": "error",
"vue/no-bare-strings-in-template": [
"error",
{
allowlist: [
"(", ")", ",", ".", "&", "+", "-", "=", "*", "/", "#", "%", "!", "?", ":", "[", "]",
"{", "}", "<", ">", "|", ";", "·", "•", "‐", "–", "—", "−", "…", "×",
],
},
],
},
},
{

View file

@ -4,6 +4,7 @@
* version, or the last engine error.
*/
import { computed } from "vue";
import { t } from "../i18n";
import { useAppStore } from "../stores/app";
const app = useAppStore();
@ -13,7 +14,7 @@ const label = computed(() => {
if (app.lastError) {
return app.lastError.message;
}
return app.about ? `${app.about.name} ${app.about.version}` : "";
return app.about ? t("app.statusBar.version", { name: app.about.name, version: app.about.version }) : "";
});
</script>

View file

@ -4,6 +4,7 @@
* Don't Save or Cancel. Escape cancels; Save has the focus.
*/
import { nextTick, ref, watch } from "vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
const editor = useEditorStore();
@ -52,7 +53,7 @@ function onKeydown(event: KeyboardEvent): void {
id="lt-close-prompt-title"
class="close-prompt__text"
>
Save changes to {{ editor.closePrompt.name }} before closing?
{{ t("editor.closePrompt.question", { name: editor.closePrompt.name }) }}
</p>
<div class="close-prompt__buttons">
<button
@ -62,7 +63,7 @@ function onKeydown(event: KeyboardEvent): void {
data-test="close-save"
@click="editor.resolveClose('save')"
>
Save
{{ t("common.save") }}
</button>
<button
type="button"
@ -70,7 +71,7 @@ function onKeydown(event: KeyboardEvent): void {
data-test="close-discard"
@click="editor.resolveClose('discard')"
>
Don't Save
{{ t("common.dontSave") }}
</button>
<button
type="button"
@ -78,7 +79,7 @@ function onKeydown(event: KeyboardEvent): void {
data-test="close-cancel"
@click="editor.resolveClose('cancel')"
>
Cancel
{{ t("common.cancel") }}
</button>
</div>
</div>

View file

@ -8,6 +8,7 @@
* CodeMirror has the focus.
*/
import { onBeforeUnmount, onMounted } from "vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import ClosePrompt from "./ClosePrompt.vue";
import CodeEditor from "./CodeEditor.vue";
@ -83,7 +84,7 @@ onBeforeUnmount(() => {
data-test="notice-dismiss"
@click="editor.dismissNotice(editor.activeTab.id)"
>
Dismiss
{{ t("common.dismiss") }}
</button>
</div>
<CodeEditor />
@ -106,7 +107,7 @@ onBeforeUnmount(() => {
class="editor-area__dismiss"
@click="editor.lastError = null"
>
Dismiss
{{ t("common.dismiss") }}
</button>
</div>
<ClosePrompt />

View file

@ -7,6 +7,7 @@
* dirty tab asks first (see the editor store).
*/
import { X } from "@lucide/vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
const editor = useEditorStore();
@ -47,7 +48,7 @@ function onKeydown(event: KeyboardEvent): void {
<div
class="tabs"
role="tablist"
aria-label="Editor tabs"
:aria-label="t('editor.tabs.label')"
data-test="editor-tabs"
@keydown="onKeydown"
>
@ -70,14 +71,14 @@ function onKeydown(event: KeyboardEvent): void {
<span
v-if="tab.dirty"
class="tabs__dirty"
aria-label="unsaved changes"
:aria-label="t('editor.tabs.unsaved')"
data-test="tab-dirty"
/>
<button
class="tabs__close"
type="button"
tabindex="-1"
:aria-label="`Close ${tab.name}`"
:aria-label="t('editor.tabs.close', { name: tab.name })"
data-test="tab-close"
@click.stop="editor.requestClose(tab.id)"
>

View file

@ -24,6 +24,7 @@ import {
type TransactionSpec,
} from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { t } from "../../i18n";
import { run, type EngineError, type RunResult } from "../../ipc";
import { diffDocs, EngineText, separatorOf, type EngineEdit } from "./engineText";
@ -333,7 +334,7 @@ export class BufferSync {
}
if (!result.ok || !isBufferInfo(result.value)) {
this.onError(
result.ok ? { code: "ipc", message: "unexpected result of buffer.get" } : result.error,
result.ok ? { code: "ipc", message: t("common.error.unexpectedResult", { command: "buffer.get" }) } : result.error,
);
this.settle(true);
return;

View file

@ -7,6 +7,7 @@
* with context (the active buffer): saving, saving all and closing a tab.
* Nothing here hard-codes a key.
*/
import { t } from "../../i18n";
import { listCommands, type CommandInfo, type RunResult } from "../../ipc";
/** Engine commands the editor area runs with the active buffer as context. */
@ -126,7 +127,7 @@ export async function loadEditorKeymap(mac = isMac()): Promise<RunResult<EditorK
}
const list: unknown = result.value;
if (!Array.isArray(list)) {
return { ok: false, error: { code: "ipc", message: "unexpected result of listCommands" } };
return { ok: false, error: { code: "ipc", message: t("common.error.unexpectedResult", { command: "listCommands" }) } };
}
const commands = (list as unknown[]).filter(
(c): c is CommandInfo => typeof c === "object" && c !== null && "id" in c,

View file

@ -7,6 +7,7 @@
* placeholder without touching the layout.
*/
import { ref } from "vue";
import { t } from "../../i18n";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import ToolWindow from "./ToolWindow.vue";
@ -23,7 +24,7 @@ const leftOpen = ref(true);
<ToolWindow
v-model:width="leftWidth"
v-model:open="leftOpen"
title="Project"
:title="t('project.toolWindow.title')"
>
<ProjectToolWindow />
</ToolWindow>

View file

@ -11,6 +11,7 @@
*/
import { PanelLeftClose, PanelLeftOpen } from "@lucide/vue";
import { computed } from "vue";
import { t } from "../../i18n";
/** Props of the tool window. */
const props = withDefaults(
@ -105,8 +106,8 @@ function onSplitterKey(event: KeyboardEvent): void {
<button
type="button"
class="tool-window__button"
:title="`Hide ${title}`"
:aria-label="`Hide ${title}`"
:title="t('common.toolWindow.hide', { title })"
:aria-label="t('common.toolWindow.hide', { title })"
data-test="tool-window-hide"
@click="emit('update:open', false)"
>
@ -124,7 +125,7 @@ function onSplitterKey(event: KeyboardEvent): void {
:aria-valuenow="width"
:aria-valuemin="minWidth"
:aria-valuemax="maxWidth"
:aria-label="`Resize ${title}`"
:aria-label="t('common.toolWindow.resize', { title })"
data-test="tool-window-splitter"
@pointerdown="onSplitterDown"
@keydown="onSplitterKey"
@ -138,8 +139,8 @@ function onSplitterKey(event: KeyboardEvent): void {
<button
type="button"
class="tool-window__button"
:title="`Show ${title}`"
:aria-label="`Show ${title}`"
:title="t('common.toolWindow.show', { title })"
:aria-label="t('common.toolWindow.show', { title })"
data-test="tool-window-show"
@click="emit('update:open', true)"
>

View file

@ -7,6 +7,7 @@
*/
import { FolderOpen } from "@lucide/vue";
import { onBeforeUnmount, onMounted } from "vue";
import { t } from "../../i18n";
import { useProjectStore } from "../../stores/project";
import ProjectTree from "./ProjectTree.vue";
@ -30,7 +31,7 @@ onBeforeUnmount(() => {
data-test="project-empty"
>
<p class="project-view__hint">
No folder is open.
{{ t("project.empty.noFolder") }}
</p>
<button
type="button"
@ -39,7 +40,7 @@ onBeforeUnmount(() => {
@click="project.openFolder()"
>
<FolderOpen :size="16" />
<span>Open Folder…</span>
<span>{{ t("project.openFolder") }}</span>
</button>
</div>
<p

View file

@ -10,6 +10,7 @@
*/
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
import { computed, nextTick, ref } from "vue";
import { t } from "../../i18n";
import { parentOf, useProjectStore, type TreeRow } from "../../stores/project";
import { useEditorStore } from "../../stores/editor";
import type { TreeEntry } from "./engineEvents";
@ -283,7 +284,7 @@ function onFocus(): void {
:style="{ '--tree-depth': row.depth }"
data-test="tree-loading"
>
Loading…
{{ t("project.tree.loading") }}
</div>
<div
v-else

22
ui/src/i18n/en.json Normal file
View file

@ -0,0 +1,22 @@
{
"app.statusBar.version": "{name} {version}",
"common.cancel": "Cancel",
"common.dismiss": "Dismiss",
"common.dontSave": "Don't Save",
"common.error.unexpectedResult": "unexpected result of {command}",
"common.save": "Save",
"common.toolWindow.hide": "Hide {title}",
"common.toolWindow.resize": "Resize {title}",
"common.toolWindow.show": "Show {title}",
"editor.closePrompt.question": "Save changes to {name} before closing?",
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
"editor.saveFailed": "save failed",
"editor.tabs.close": "Close {name}",
"editor.tabs.label": "Editor tabs",
"editor.tabs.unsaved": "unsaved changes",
"project.empty.noFolder": "No folder is open.",
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",
"project.tree.loading": "Loading…"
}

57
ui/src/i18n/index.ts Normal file
View file

@ -0,0 +1,57 @@
/**
* Message catalog of the frontend.
*
* Every interface string comes from a catalog keyed by flat dotted ids
* grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`). English
* (`en.json`) is the source catalog; other languages follow with G14.
* Messages that come from the engine (`EngineError.message`) are not in
* the catalog yet and stay English.
*/
import en from "./en.json";
/** A key of the English catalog. */
export type MessageKey = keyof typeof en;
/** Values for the `{name}` placeholders of a message. */
export type MessageParams = Readonly<Record<string, string | number>>;
/** The active catalog. */
const catalog: Readonly<Record<string, string>> = en;
/**
* Whether a key exists in the active catalog.
*
* @param key - the message key.
*/
export function hasMessage(key: string): boolean {
return Object.hasOwn(catalog, key);
}
/**
* Looks up a message and fills in its placeholders.
*
* A placeholder is a name in braces (`{name}`). A placeholder without a
* value in `params` stays as it is. A missing key never throws: it logs a
* warning in development builds and returns the key itself, so the gap is
* visible in the interface.
*
* @param key - the message key, for example `project.openFolder`.
* @param params - values for the placeholders.
* @returns the message text.
*/
export function t(key: string, params?: MessageParams): string {
const message = hasMessage(key) ? catalog[key] : undefined;
if (message === undefined) {
if (import.meta.env.DEV) {
console.warn(`[i18n] missing message key: ${key}`);
}
return key;
}
if (!params) {
return message;
}
return message.replace(/\{(\w+)\}/g, (placeholder, name: string) => {
const value = Object.hasOwn(params, name) ? params[name] : undefined;
return value === undefined ? placeholder : String(value);
});
}

View file

@ -11,6 +11,7 @@
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { t } from "../i18n";
import { run, type EngineError, type RunResult } from "../ipc";
import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync";
import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents";
@ -220,7 +221,7 @@ export const useEditorStore = defineStore("editor", () => {
return;
}
if (!isBufferInfo(result.value)) {
lastError.value = { code: "ipc", message: `unexpected result of ${EDITOR_COMMANDS.open}` };
lastError.value = { code: "ipc", message: t("common.error.unexpectedResult", { command: EDITOR_COMMANDS.open }) };
return;
}
lastError.value = null;
@ -373,7 +374,7 @@ export const useEditorStore = defineStore("editor", () => {
? {
code: "save_failed",
message: failed
.map((f) => (typeof f.message === "string" ? f.message : "save failed"))
.map((f) => (typeof f.message === "string" ? f.message : t("editor.saveFailed")))
.join("; "),
}
: null;
@ -459,12 +460,12 @@ export const useEditorStore = defineStore("editor", () => {
if (event.removed) {
tab.notice = {
kind: "removedOnDisk",
message: `${tab.name} was deleted on disk. Your text is kept; saving writes it again.`,
message: t("editor.notice.removedOnDisk", { name: tab.name }),
};
} else {
tab.notice = {
kind: "changedOnDisk",
message: `${tab.name} changed on disk. Your unsaved changes are kept; saving overwrites the file.`,
message: t("editor.notice.changedOnDisk", { name: tab.name }),
};
}
break;

View file

@ -9,6 +9,7 @@
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { t } from "../i18n";
import { run, type EngineError } from "../ipc";
import {
onEngineEvent,
@ -156,7 +157,7 @@ export const useProjectStore = defineStore("project", () => {
prune(dir, listing.entries);
} else {
const error = result.ok
? { code: "ipc", message: `unexpected result of ${PROJECT_COMMANDS.children}` }
? { code: "ipc", message: t("common.error.unexpectedResult", { command: PROJECT_COMMANDS.children }) }
: result.error;
dirs.value[dir] = { entries: cachedEntries(dir), loading: false, error, truncated };
}

View file

@ -0,0 +1,105 @@
/**
* Tests of the message catalog: the `t` helper (lookup, interpolation,
* missing keys) and a scan of the frontend source that every literal key
* passed to `t` exists in `en.json`.
*/
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import en from "../../src/i18n/en.json";
import { hasMessage, t } from "../../src/i18n";
/** Root of the frontend source tree. */
const SRC = join(import.meta.dirname, "..", "..", "src");
/**
* Lists the `.ts` and `.vue` files below a directory.
*
* @param dir - the directory.
*/
function sourceFiles(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const path = join(dir, entry.name);
if (entry.isDirectory()) {
return sourceFiles(path);
}
return /\.(ts|vue)$/.test(entry.name) ? [path] : [];
});
}
/** Every call of `t` with a literal first argument, by file. */
const usedKeys = sourceFiles(SRC).flatMap((file) =>
[...readFileSync(file, "utf8").matchAll(/\bt\(\s*(["'`])([^"'`]*)\1/g)].map((m) => ({
file,
key: m[2] ?? "",
})),
);
afterEach(() => {
vi.restoreAllMocks();
});
describe("t", () => {
it("returns the message of a key", () => {
expect(t("common.cancel")).toBe("Cancel");
});
it("fills in placeholders", () => {
expect(t("editor.tabs.close", { name: "index.php" })).toBe("Close index.php");
expect(t("app.statusBar.version", { name: "Lutra", version: "0.1.0" })).toBe("Lutra 0.1.0");
});
it("formats numbers", () => {
expect(t("common.toolWindow.hide", { title: 3 })).toBe("Hide 3");
});
it("keeps a placeholder without a value", () => {
expect(t("editor.tabs.close")).toBe("Close {name}");
expect(t("editor.tabs.close", { other: "x" })).toBe("Close {name}");
});
it("does not resolve placeholders from the prototype", () => {
expect(t("editor.tabs.close", {})).toBe("Close {name}");
expect(t("common.error.unexpectedResult", { command: "{name}" })).toBe(
"unexpected result of {name}",
);
});
it("returns the key and warns on a missing key", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
expect(t("no.such.key")).toBe("no.such.key");
expect(warn).toHaveBeenCalledWith(expect.stringContaining("no.such.key"));
});
it("does not treat prototype names as keys", () => {
vi.spyOn(console, "warn").mockImplementation(() => undefined);
expect(hasMessage("toString")).toBe(false);
expect(t("toString")).toBe("toString");
});
});
describe("en.json", () => {
it("uses flat dotted keys of known areas with string values", () => {
for (const [key, value] of Object.entries(en)) {
expect(key).toMatch(/^(app|project|editor|common)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/);
expect(typeof value).toBe("string");
expect(value.trim()).not.toBe("");
}
});
it("is sorted by key", () => {
const keys = Object.keys(en);
expect(keys).toEqual([...keys].sort());
});
it("contains every key the source passes to t", () => {
expect(usedKeys.length).toBeGreaterThan(0);
const missing = usedKeys.filter(({ key }) => !hasMessage(key));
expect(missing).toEqual([]);
});
it("has no unused keys", () => {
const used = new Set(usedKeys.map(({ key }) => key));
expect(Object.keys(en).filter((key) => !used.has(key))).toEqual([]);
});
});