M1.11: English message catalog for every UI string

ui/src/i18n: en.json (20 flat dotted keys) and t(key, params?) with
{name} interpolation; a missing key warns in dev and returns the key.
All template text, title/aria-label attributes, notices and frontend
error texts go through t. ESLint vue/no-bare-strings-in-template is an
error. Catalog tests: interpolation, missing key, every t() key exists,
no unused keys. Engine messages stay English (G14). Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 06:39:42 +02:00
parent 851d438e2a
commit 7c0fb312f6
21 changed files with 273 additions and 37 deletions

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([]);
});
});