From e9c59f28defbec319f9d94362ba1ce9c4d55e376 Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Wed, 28 Oct 2026 12:00:24 -0700 Subject: [PATCH] Send the remaining interface text through the catalog and audit it Phase 4f. - scripts/i18nAudit.mjs runs in pnpm check. It fails for a key that the catalog does not have, a catalog key that the code does not use, and a row without all four languages. - message() marks a key that a variable carries to the translation call later: table formats, formula errors, and browser status messages. - 53 new rows with French, Japanese, and Simplified Chinese text for the status and error messages of the workbench, the tree, Settings, theme import, images, the built-in browser, and code blocks. The backlinks toggle now translates too. - 13 unused rows are gone. - Errors of the plugin API stay in English. docs/development.md has the rule in "Interface text". pnpm check, pnpm test (350 of 350), and the full smoke suite pass, except two tests that failed one time under load and passed on retry and 3 of 3 times alone. --- CLAUDE.md | 2 +- docs/development.md | 17 ++- package.json | 2 +- scripts/i18nAudit.mjs | 76 ++++++++++++++ src/lib/browser/Browser.svelte | 2 +- src/lib/browser/WebData.svelte | 2 +- src/lib/browser/index.ts | 17 +-- src/lib/browser/tabSession.ts | 11 +- src/lib/editor/DocumentEditor.svelte | 4 +- src/lib/editor/codeMenu.ts | 2 +- src/lib/editor/imageControls.ts | 2 +- src/lib/editor/markdownMenu.ts | 4 +- src/lib/editor/tableCellActions.ts | 6 +- src/lib/formulas/engine.ts | 19 ++-- src/lib/i18n/index.ts | 2 + src/lib/i18n/messages.ts | 133 ++++++++++-------------- src/lib/layout/FileTree.svelte | 30 +++--- src/lib/layout/SettingsWindow.svelte | 5 +- src/lib/layout/Workbench.svelte | 32 +++--- src/lib/theme/AppearanceSettings.svelte | 4 +- src/lib/theme/backgroundImages.ts | 5 +- src/lib/theme/customThemes.ts | 19 ++-- src/lib/workspace/documents.svelte.ts | 3 +- src/lib/workspace/noteHtml.ts | 5 +- src/lib/workspace/session.svelte.ts | 3 +- src/lib/workspace/settings.ts | 3 +- src/lib/workspace/tabTransfer.ts | 7 +- src/lib/workspace/templates.ts | 3 +- 28 files changed, 249 insertions(+), 171 deletions(-) create mode 100644 scripts/i18nAudit.mjs diff --git a/CLAUDE.md b/CLAUDE.md index 47ffc57..ae4b537 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,7 +20,7 @@ The [development guide](docs/development.md#architecture) maps the source folder | --- | --- | | `pnpm install --frozen-lockfile` | Install dependencies | | `pnpm tauri dev` | Run the desktop app with hot reload | -| `pnpm check` | Type checks of the app and the unit tests | +| `pnpm check` | Type checks of the app and the unit tests, then the translation catalog audit | | `pnpm test` | Unit tests (`tests/unit/`) | | `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests | | `pnpm check:menus` | Menu surface inventory | diff --git a/docs/development.md b/docs/development.md index d49f5df..bdbe3c8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -170,14 +170,15 @@ Run these commands from the repository folder. They do not need an installer. | Command | Checks | | --- | --- | -| `pnpm check` | Svelte and TypeScript types of the app, the unit tests (`tests/tsconfig.json`), the plugin SDK, and the example plugin | +| `pnpm check` | Svelte and TypeScript types of the app, the unit tests (`tests/tsconfig.json`), the plugin SDK, and the example plugin. Then the catalog audit. See [Interface text](#interface-text). | | `pnpm test` | Unit tests in `tests/unit/` | | `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust unit tests | | `pnpm smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). | | `pnpm build` | The production frontend build | | `pnpm check:menus` | The inventory of menu surfaces. See [Interface design](ui-design.md). | -To run one test file, use `node --experimental-strip-types --test tests/unit/tables/selection.spec.ts`. +To run one test file, use `node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test tests/unit/tables/selection.spec.ts`. +The `--import` hook compiles `.svelte.ts` modules, so a test can import them. For type errors while you edit, run `pnpm check:watch`. Some tests need files from outside this repository. Without those files, the tests skip and state the reason: @@ -185,6 +186,18 @@ Some tests need files from outside this repository. Without those files, the tes - `tests/unit/release/installerVersion.spec.ts` needs the NSIS compiler that the Tauri CLI downloads on Windows. - The Rust terminal tests start the real shells on the computer. +### Interface text + +All text that a user reads goes through the catalog in `src/lib/i18n/messages.ts`. Each row has the English key and the French, Japanese, and Simplified Chinese text. + +1. Translate the text with `$t("…")` in a Svelte component or `tr("…")` in a TypeScript module. +2. For a value in the text, use a placeholder: `tr("Created {path}", { path })`. Do not join strings. +3. When a variable carries a key to the call, mark the key where you write it: `message("Bold")`. +4. Add a catalog row with all four languages. + +Errors of the plugin API stay in English, because they are for plugin developers. +`pnpm check` runs `scripts/i18nAudit.mjs`. It fails for a key that the catalog does not have, a catalog key that the code does not use, and a row without all translations. + ## Plugin SDK The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types. diff --git a/package.json b/package.json index 2018e38..658594f 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "build:installer": "node scripts/buildInstaller.mjs", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json && tsc -p packages/plugin-sdk/tsconfig.json --noEmit && tsc -p fixtures/plugins/tsconfig.json", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json && tsc -p packages/plugin-sdk/tsconfig.json --noEmit && tsc -p fixtures/plugins/tsconfig.json && node scripts/i18nAudit.mjs", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "check:menus": "node scripts/menuSurfaceAudit.mjs", "tauri": "tauri", diff --git a/scripts/i18nAudit.mjs b/scripts/i18nAudit.mjs new file mode 100644 index 0000000..a3eacb8 --- /dev/null +++ b/scripts/i18nAudit.mjs @@ -0,0 +1,76 @@ +// Check the translation catalog (src/lib/i18n/messages.ts) against the code: +// - unknown: the code translates a key that the catalog does not have, +// - unused: the catalog has a key that the code never translates, +// - untranslated: a catalog row has an empty or missing translation. +// The code translates a key with `$t("…")` in Svelte, `tr("…")` in TypeScript, or marks it with `message("…")` +// when a variable carries it to the translation call later. Every string literal in the first argument counts, +// so `tr(open ? "Close" : "Open")` uses both keys. +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const catalogFile = path.join(root, "src/lib/i18n/messages.ts"); +const calls = /(?:\$t|\btr|\bmessage)\(/g; + +async function sources(dir) { + const entries = await readdir(dir, { withFileTypes: true }); + const nested = await Promise.all(entries.map(entry => entry.isDirectory() + ? sources(path.join(dir, entry.name)) + : /\.(svelte|ts)$/.test(entry.name) ? [path.join(dir, entry.name)] : [])); + return nested.flat(); +} + +/** The string literals of the first argument that starts at `start`. A literal in a comparison is not a key. */ +function argumentKeys(source, start) { + const keys = []; + let depth = 0; + for (let index = start; index < source.length; index++) { + const char = source[index]; + if (char === "\"" || char === "'" || char === "`") { + let value = "", end = index + 1, dynamic = false; + for (; end < source.length && source[end] !== char; end++) { + if (source[end] === "\\") { value += source[++end]; continue; } + if (char === "`" && source[end] === "$" && source[end + 1] === "{") dynamic = true; + value += source[end]; + } + const compared = /[=!]==?\s*$/.test(source.slice(start, index)) || /^\s*[=!]==?/.test(source.slice(end + 1)); + if (!dynamic && !compared) keys.push(value); + index = end; + } else if ("([{".includes(char)) depth++; + else if (")]}".includes(char)) { if (depth === 0) break; depth--; } + else if (char === "," && depth === 0) break; + } + return keys; +} + +export async function auditCatalog() { + const { messageRows } = await import(pathToFileURL(catalogFile).href); + const catalog = new Map(messageRows.map(row => [row[0], row])); + const used = new Set(); + const failures = []; + for (const file of await sources(path.join(root, "src"))) { + if (file === catalogFile) continue; + const source = await readFile(file, "utf8"); + for (const match of source.matchAll(calls)) { + for (const key of argumentKeys(source, match.index + match[0].length)) { + used.add(key); + if (!catalog.has(key)) { + const line = source.slice(0, match.index).split("\n").length; + failures.push(`Unknown key: ${path.relative(root, file).replaceAll("\\", "/")}:${line}: ${key}`); + } + } + } + } + for (const [key, row] of catalog) { + if (!used.has(key)) failures.push(`Unused key: ${key}`); + if (row.length < 4 || row.slice(1).some(value => !value?.trim())) failures.push(`Untranslated key: ${key}`); + } + return { failures, keys: catalog.size, used: used.size }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const { failures, keys } = await auditCatalog(); + if (failures.length) { console.error(failures.join("\n")); process.exitCode = 1; } + else console.log(`PASS: the code uses all ${keys} catalog keys, and each key has every translation.`); +} diff --git a/src/lib/browser/Browser.svelte b/src/lib/browser/Browser.svelte index eb9a50a..49ed1cd 100644 --- a/src/lib/browser/Browser.svelte +++ b/src/lib/browser/Browser.svelte @@ -261,7 +261,7 @@ oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }} oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }} onblur={stopScroll}> - {#if image && ready && !blank}Web page rendered by the browser{/if} + {#if image && ready && !blank}{$t("Web{/if} {#if scrollAnchor}{/if} diff --git a/src/lib/browser/WebData.svelte b/src/lib/browser/WebData.svelte index d6e0cd1..ef0b6df 100644 --- a/src/lib/browser/WebData.svelte +++ b/src/lib/browser/WebData.svelte @@ -48,7 +48,7 @@ {#if busy}

{$t("Please wait…")}

{/if}
{#if kind === 'cookies'} - {#each cookies as cookie (cookie.id)}
{cookie.name || '(unnamed cookie)'}{cookie.domain} · {cookie.path}
{/each} + {#each cookies as cookie (cookie.id)}
{cookie.name || $t("(unnamed cookie)")}{cookie.domain} · {cookie.path}
{/each} {#if data && !cookies.length}

{$t("No matching cookies.")}

{/if} {:else} {#each history as visit (visit.id)}
{visit.title || visit.url}{visit.url}{new Date(visit.at).toLocaleString()}
{/each} diff --git a/src/lib/browser/index.ts b/src/lib/browser/index.ts index da98e05..dd60ee2 100644 --- a/src/lib/browser/index.ts +++ b/src/lib/browser/index.ts @@ -1,3 +1,4 @@ +import { tr } from "../i18n/index.ts"; import { mount, unmount } from 'svelte'; import { get } from 'svelte/store'; import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'; @@ -60,13 +61,13 @@ export async function activate(api: PluginApi) { const web = ready && /^https?:\/\//.test(current?.url || ''); return [ { separator: true }, - { label: 'Move to new window', icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) }, - { label: 'Split right', icon: 'split-right', disabled: !ready, run: () => split('right') }, - { label: 'Split down', icon: 'split-down', disabled: !ready, run: () => split('down') }, + { label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) }, + { label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') }, + { label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') }, { separator: true }, - { label: 'Find…', icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } }, - { label: 'Open in default browser', icon: 'external', disabled: !web, run: () => run('openExternal') }, - { label: 'Bookmark', icon: 'bookmark', disabled: !web, run: () => run('bookmark') }, + { label: tr("Find…"), icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } }, + { label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') }, + { label: tr("Bookmark"), icon: 'bookmark', disabled: !web, run: () => run('bookmark') }, ]; }, mount: container => { let runtimeId = ''; @@ -106,12 +107,12 @@ export async function activate(api: PluginApi) { }); api.registerTabDrop?.(async data => { const payload = JSON.parse(data); - if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error('Invalid browser tab transfer.'); + if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error(tr("Invalid browser tab transfer.")); const existing = owners.get(payload.tabId); if (existing) { api.openView(existing.view); return; } const snapshot = await request('adoptTab', { tabId: payload.tabId, transferToken: payload.transferToken }); const current = snapshot.tabs.find(tab => tab.id === payload.tabId); - if (!current) throw new Error('The browser tab is unavailable.'); + if (!current) throw new Error(tr("The browser tab is unavailable.")); await open(current.profileId, current.url, undefined, current.id, payload.pinned === true); }); const incoming = new URLSearchParams(location.search).get('browserTab'); diff --git a/src/lib/browser/tabSession.ts b/src/lib/browser/tabSession.ts index 7efccaf..b9bb1ac 100644 --- a/src/lib/browser/tabSession.ts +++ b/src/lib/browser/tabSession.ts @@ -1,3 +1,4 @@ +import { message, tr } from "../i18n/index.ts"; import type { Snapshot } from './client'; type Transport = (command: string, args?: Record) => Promise; @@ -32,9 +33,9 @@ export class TabSession { } } private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') { - this.update({ phase, message: phase === 'ready' ? 'The browser could not complete this request. Check the error details.' : connectionLost(error) - ? 'This tab lost its browser connection. Select Reconnect to restore the page.' - : 'The browser could not complete this request. Check the details, then select Reconnect.', + this.update({ phase, message: phase === 'ready' ? message('The browser could not complete this request. Check the error details.') : connectionLost(error) + ? message('This tab lost its browser connection. Select Reconnect to restore the page.') + : message('The browser could not complete this request. Check the details, then select Reconnect.'), detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } }); } connect(): Promise { @@ -44,7 +45,7 @@ export class TabSession { return this.pending; } private async restore() { - this.update({ phase: 'connecting', message: this.value.tabId ? 'Reconnecting browser…' : 'Opening browser…' }); + this.update({ phase: 'connecting', message: this.value.tabId ? message('Reconnecting browser…') : message('Opening browser…') }); let operation = 'state'; // The host discards a failed transport before the next request. for (let attempt = 0; attempt < 2; attempt++) { @@ -66,7 +67,7 @@ export class TabSession { if (current.tabs.some(tab => tab.id === result.tabId)) { this.observe(current); this.update({ phase: 'ready', message: '' }); return; } - if (attempt === 1) throw new Error('The runtime restarted twice while opening this tab.'); + if (attempt === 1) throw new Error(tr("The runtime restarted twice while opening this tab.")); } catch (error) { if (this.closed) return; if (attempt === 0 && connectionLost(error)) continue; diff --git a/src/lib/editor/DocumentEditor.svelte b/src/lib/editor/DocumentEditor.svelte index acd2b01..6d8f9ec 100644 --- a/src/lib/editor/DocumentEditor.svelte +++ b/src/lib/editor/DocumentEditor.svelte @@ -166,14 +166,14 @@ for (const path of linkCandidates(buffer.relPath, image.dataset.mdSrc || "", "md")) { try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ } } - throw new Error("Could not find this image in the workspace."); + throw new Error($t("Could not find this image in the workspace.")); }, validate: async source => { if (isRemoteImage(source)) return; for (const path of linkCandidates(buffer.relPath, source, "md")) { try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ } } - throw new Error("Choose an image that exists in the workspace."); + throw new Error($t("Choose an image that exists in the workspace.")); }, report: message => { error = message; }, }), diff --git a/src/lib/editor/codeMenu.ts b/src/lib/editor/codeMenu.ts index aa38a5f..e4fc432 100644 --- a/src/lib/editor/codeMenu.ts +++ b/src/lib/editor/codeMenu.ts @@ -29,7 +29,7 @@ export function codeMenu(view: EditorView, report: (message: string) => void) { try { if (kind === "paste") replace(await navigator.clipboard.readText()); else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); } - } catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); } + } catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); } }; const changeAll = () => { if (!valid() || !word) return; diff --git a/src/lib/editor/imageControls.ts b/src/lib/editor/imageControls.ts index 5b75127..c43e9f3 100644 --- a/src/lib/editor/imageControls.ts +++ b/src/lib/editor/imageControls.ts @@ -24,7 +24,7 @@ async function copyImage(image: HTMLImageElement) { const canvas = document.createElement("canvas"); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; const context = canvas.getContext("2d"); - if (!context) throw new Error("Image clipboard is unavailable."); + if (!context) throw new Error(tr("Image clipboard is unavailable.")); context.drawImage(image, 0, 0); return await new Promise((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png")); })(); diff --git a/src/lib/editor/markdownMenu.ts b/src/lib/editor/markdownMenu.ts index 1fe79ed..beef5e5 100644 --- a/src/lib/editor/markdownMenu.ts +++ b/src/lib/editor/markdownMenu.ts @@ -77,7 +77,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc if (!value) value = await navigator.clipboard.readText(); if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n"))); } - } catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); } + } catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); } }); } const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) }); @@ -126,7 +126,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc if (!suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true }); suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => { close(); - void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary.")); + void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report(tr("Could not add the word to the dictionary."))); } }); const focusedLabel = opened.element.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined; opened.close(); diff --git a/src/lib/editor/tableCellActions.ts b/src/lib/editor/tableCellActions.ts index b289345..4a25a15 100644 --- a/src/lib/editor/tableCellActions.ts +++ b/src/lib/editor/tableCellActions.ts @@ -1,4 +1,4 @@ -import { tr } from '../i18n/index.ts'; +import { message, tr } from '../i18n/index.ts'; import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core"; import { requestText } from "../workspace/dialogs.svelte"; import { extractedCellMarkdown } from "./tableCellMarkdown"; @@ -14,8 +14,8 @@ export type TableContextActions = { }; export const cellFormats = [ - ["Bold", "bold"], ["Italic", "italic"], ["Strikethrough", "strike"], ["Highlight", "highlight"], - ["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"], + [message("Bold"), "bold"], [message("Italic"), "italic"], [message("Strikethrough"), "strike"], [message("Highlight"), "highlight"], + [message("Code"), "code"], [message("Math"), "math"], [message("Comment"), "comment"], [message("Clear formatting"), "clear"], ] as const; export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] { diff --git a/src/lib/formulas/engine.ts b/src/lib/formulas/engine.ts index ba14721..5f35a36 100644 --- a/src/lib/formulas/engine.ts +++ b/src/lib/formulas/engine.ts @@ -1,14 +1,14 @@ // The table formula engine. Formulas are plain Markdown cell text. // The engine does not evaluate JavaScript and does not read external data. export const formulaErrors = { - "#ERROR!": "Invalid formula syntax or function arguments", - "#REF!": "Cell reference is outside this table", - "#VALUE!": "Expected a number", - "#NAME?": "Unknown function or cell name", - "#DIV/0!": "Cannot divide by zero or average an empty range", - "#CYCLE!": "Circular cell reference", - "#NUM!": "Result is not a finite number", - "#LIMIT!": "Formula is too complex", + "#ERROR!": message("Invalid formula syntax or function arguments"), + "#REF!": message("Cell reference is outside this table"), + "#VALUE!": message("Expected a number"), + "#NAME?": message("Unknown function or cell name"), + "#DIV/0!": message("Cannot divide by zero or average an empty range"), + "#CYCLE!": message("Circular cell reference"), + "#NUM!": message("Result is not a finite number"), + "#LIMIT!": message("Formula is too complex"), } as const; export type FormulaErrorCode = keyof typeof formulaErrors; type ErrorCode = FormulaErrorCode; @@ -150,4 +150,5 @@ export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[ return { formula, text: code, error: code }; } })); -} +}import { message } from "../i18n/index.ts"; + diff --git a/src/lib/i18n/index.ts b/src/lib/i18n/index.ts index 8edb31c..8978c4b 100644 --- a/src/lib/i18n/index.ts +++ b/src/lib/i18n/index.ts @@ -17,6 +17,8 @@ export function translate(language: Locale, message: string, values: Record Object.hasOwn(values, key) ? String(values[key]) : match); } export const t = derived(locale, language => (message: string, values?: Record) => translate(language, message, values)); +/** Mark a catalog key that a variable carries to `$t` or `tr` later. The catalog audit counts it as used. */ +export const message = (text: T): T => text; export function tr(message: string, values?: Record): string { return translate(get(locale), message, values); } diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index 160672a..bb086ff 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -653,12 +653,6 @@ export const messageRows: [string, string, string, string][] = [ "一致するファイルはありません。", "没有匹配的文件。" ], - [ - "{count} files", - "{count} fichiers", - "{count}個のファイル", - "{count} 个文件" - ], [ " · indexing…", " · indexation…", @@ -671,12 +665,6 @@ export const messageRows: [string, string, string, string][] = [ "↑ ↓ 選択 · Enter {action} · Esc 閉じる", "↑ ↓ 选择 · Enter {action} · Esc 关闭" ], - [ - "open", - "ouvrir", - "開く", - "打开" - ], [ "Window controls", "Commandes de la fenêtre", @@ -1697,12 +1685,6 @@ export const messageRows: [string, string, string, string][] = [ "再読み込み", "重新加载" ], - [ - "Stop", - "Arrêter", - "停止", - "停止" - ], [ "Address or search", "Adresse ou recherche", @@ -2489,30 +2471,6 @@ export const messageRows: [string, string, string, string][] = [ "書式をクリア", "清除格式" ], - [ - "Superscript", - "Exposant", - "上付き文字", - "上标" - ], - [ - "Subscript", - "Indice", - "下付き文字", - "下标" - ], - [ - "Underline", - "Souligner", - "下線", - "下划线" - ], - [ - "Style", - "Style", - "スタイル", - "样式" - ], [ "Change all occurrences", "Modifier toutes les occurrences", @@ -2681,18 +2639,6 @@ export const messageRows: [string, string, string, string][] = [ "右に列を追加", "在右侧插入列" ], - [ - "Add column left", - "Ajouter une colonne à gauche", - "左に列を追加", - "在左侧插入列" - ], - [ - "Add column right", - "Ajouter une colonne à droite", - "右に列を追加", - "在右侧插入列" - ], [ "Move column left", "Déplacer la colonne à gauche", @@ -2729,18 +2675,6 @@ export const messageRows: [string, string, string, string][] = [ "列で降順に並べ替え", "按列降序排序" ], - [ - "Delete table", - "Supprimer le tableau", - "表を削除", - "删除表格" - ], - [ - "Insert table", - "Insérer un tableau", - "表を挿入", - "插入表格" - ], [ "Clear selected values and keep the cells.", "Effacer les valeurs sélectionnées et conserver les cellules.", @@ -2855,18 +2789,6 @@ export const messageRows: [string, string, string, string][] = [ "{name}をアンインストールしますか?", "卸载 {name}?" ], - [ - "{name} installed.", - "{name} installé.", - "{name}をインストールしました。", - "已安装 {name}。" - ], - [ - "{name} installed and enabled.", - "{name} installé et activé.", - "{name}をインストールして有効にしました。", - "已安装并启用 {name}。" - ], [ "{name} uninstalled. Settings and workspace documents were kept.", "{name} désinstallé. Les paramètres et documents ont été conservés.", @@ -3490,7 +3412,60 @@ export const messageRows: [string, string, string, string][] = [ ["Tables", "Tableaux", "表", "表格"], ["Table formulas", "Formules de tableau", "表の数式", "表格公式"], ["Calculate table cells that start with =. When this is off, formulas show as text.", "Calculer les cellules de tableau qui commencent par =. Désactivé, les formules s’affichent comme du texte.", "=で始まる表のセルを計算します。オフにすると、数式は文字列として表示されます。", "计算以 = 开头的表格单元格。关闭后,公式显示为文本。"], - ["Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.", "Les formules de tableau sont maintenant intégrées. Vous pouvez supprimer cet ancien paquet. Vos formules restent dans vos fichiers. Pour activer ou désactiver les formules, ouvrez Paramètres → Général.", "表の数式は内蔵されました。この古いパッケージは削除できます。数式はファイルに残ります。数式のオン/オフは「設定 → 一般」で切り替えます。", "表格公式现已内置。可以移除此旧包。公式保留在文件中。要打开或关闭公式,请前往“设置 → 常规”。"] + ["Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.", "Les formules de tableau sont maintenant intégrées. Vous pouvez supprimer cet ancien paquet. Vos formules restent dans vos fichiers. Pour activer ou désactiver les formules, ouvrez Paramètres → Général.", "表の数式は内蔵されました。この古いパッケージは削除できます。数式はファイルに残ります。数式のオン/オフは「設定 → 一般」で切り替えます。", "表格公式现已内置。可以移除此旧包。公式保留在文件中。要打开或关闭公式,请前往“设置 → 常规”。"], + ["Could not close settings: {reason}", "Impossible de fermer les paramètres : {reason}", "設定を閉じられませんでした: {reason}", "无法关闭设置:{reason}"], + ["Could not read your settings. Default settings apply until you save new settings.", "Impossible de lire vos paramètres. Les paramètres par défaut s’appliquent jusqu’à ce que vous en enregistriez de nouveaux.", "設定を読み込めませんでした。新しい設定を保存するまで既定の設定が適用されます。", "无法读取您的设置。在您保存新设置之前,将使用默认设置。"], + ["The new window did not accept the tab. The source tab remains open.", "La nouvelle fenêtre n’a pas accepté l’onglet. L’onglet d’origine reste ouvert.", "新しいウィンドウがタブを受け付けませんでした。元のタブは開いたままです。", "新窗口未接受该标签页。原标签页保持打开。"], + ["Could not read your layout. Default layout applies for this window.", "Impossible de lire votre disposition. La disposition par défaut s’applique à cette fenêtre.", "レイアウトを読み込めませんでした。このウィンドウには既定のレイアウトが適用されます。", "无法读取您的布局。此窗口将使用默认布局。"], + ["Could not save your layout. Layout changes apply for this window only.", "Impossible d’enregistrer votre disposition. Les modifications ne s’appliquent qu’à cette fenêtre.", "レイアウトを保存できませんでした。変更はこのウィンドウにのみ適用されます。", "无法保存您的布局。布局更改仅适用于此窗口。"], + ["Invalid tab transfer.", "Transfert d’onglet non valide.", "タブの移動が無効です。", "标签页转移无效。"], + ["Move tabs only between windows of the same workspace.", "Déplacez les onglets uniquement entre les fenêtres du même espace de travail.", "タブは同じワークスペースのウィンドウ間でのみ移動できます。", "只能在同一工作区的窗口之间移动标签页。"], + ["This tab is already open in this window. The source tab remains open.", "Cet onglet est déjà ouvert dans cette fenêtre. L’onglet d’origine reste ouvert.", "このタブはこのウィンドウですでに開いています。元のタブは開いたままです。", "此标签页已在此窗口中打开。原标签页保持打开。"], + ["Enable this tab's plugin before moving it to this window.", "Activez le plug-in de cet onglet avant de le déplacer vers cette fenêtre.", "このウィンドウに移動する前に、このタブのプラグインを有効にしてください。", "将此标签页移到此窗口之前,请先启用其插件。"], + ["The plugin did not open this tab.", "Le plug-in n’a pas ouvert cet onglet.", "プラグインがこのタブを開きませんでした。", "插件未打开此标签页。"], + ["The plugin did not open this document.", "Le plug-in n’a pas ouvert ce document.", "プラグインがこのドキュメントを開きませんでした。", "插件未打开此文档。"], + ["This note is no longer available.", "Cette note n’est plus disponible.", "このノートは利用できなくなりました。", "此笔记已不可用。"], + ["The workspace changed. Open the link menu again.", "L’espace de travail a changé. Ouvrez de nouveau le menu du lien.", "ワークスペースが変更されました。リンクメニューをもう一度開いてください。", "工作区已更改。请重新打开链接菜单。"], + ["Enter a relative workspace path without reserved characters.", "Saisissez un chemin relatif dans l’espace de travail, sans caractères réservés.", "予約文字を含まないワークスペースの相対パスを入力してください。", "请输入不含保留字符的工作区相对路径。"], + ["Open a workspace before renaming a document.", "Ouvrez un espace de travail avant de renommer un document.", "ドキュメント名を変更する前にワークスペースを開いてください。", "重命名文档前,请先打开工作区。"], + ["The workspace changed. Reopen the document.", "L’espace de travail a changé. Rouvrez le document.", "ワークスペースが変更されました。ドキュメントを開き直してください。", "工作区已更改。请重新打开文档。"], + ["Could not open the app browser.", "Impossible d’ouvrir le navigateur de l’application.", "アプリのブラウザーを開けませんでした。", "无法打开应用内浏览器。"], + ["Could not add the word to the dictionary.", "Impossible d’ajouter le mot au dictionnaire.", "単語を辞書に追加できませんでした。", "无法将该词添加到词典。"], + ["Copied workspace paths", "Chemins dans l’espace de travail copiés", "ワークスペースのパスをコピーしました", "已复制工作区路径"], + ["Copied system paths", "Chemins système copiés", "システムのパスをコピーしました", "已复制系统路径"], + ["Created {path}", "{path} créé", "{path} を作成しました", "已创建 {path}"], + ["Moved {count} of {total} items", "{count} élément(s) sur {total} déplacé(s)", "{total} 個中 {count} 個の項目を移動しました", "已移动 {count}/{total} 个项目"], + ["Copied {count} of {total} items", "{count} élément(s) sur {total} copié(s)", "{total} 個中 {count} 個の項目をコピーしました", "已复制 {count}/{total} 个项目"], + ["The workspace changed. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"], + ["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"], + ["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"], + ["Split right", "Scinder à droite", "右に分割", "向右拆分"], + ["Split down", "Scinder vers le bas", "下に分割", "向下拆分"], + ["Find…", "Rechercher…", "検索…", "查找…"], + ["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"], + ["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"], + ["The browser tab is unavailable.", "L’onglet du navigateur n’est pas disponible.", "ブラウザータブを利用できません。", "浏览器标签页不可用。"], + ["Web page rendered by the browser", "Page web affichée par le navigateur", "ブラウザーが表示したウェブページ", "由浏览器呈现的网页"], + ["Mermaid diagram", "Diagramme Mermaid", "Mermaid 図", "Mermaid 图表"], + ["Diagram source", "Source du diagramme", "図のソース", "图表源代码"], + ["The runtime restarted twice while opening this tab.", "Le moteur a redémarré deux fois pendant l’ouverture de cet onglet.", "このタブを開く間にランタイムが2回再起動しました。", "打开此标签页时运行时重启了两次。"], + ["Could not find this image in the workspace.", "Impossible de trouver cette image dans l’espace de travail.", "この画像がワークスペースに見つかりません。", "在工作区中找不到此图像。"], + ["Choose an image that exists in the workspace.", "Choisissez une image qui existe dans l’espace de travail.", "ワークスペースにある画像を選択してください。", "请选择工作区中已有的图像。"], + ["Image clipboard is unavailable.", "Le presse-papiers d’images n’est pas disponible.", "画像のクリップボードを利用できません。", "图像剪贴板不可用。"], + ["Choose an image of 50 MiB or less.", "Choisissez une image de 50 Mio au plus.", "50 MiB 以下の画像を選択してください。", "请选择 50 MiB 或更小的图像。"], + ["Choose a RuneStone theme JSON file.", "Choisissez un fichier de thème RuneStone au format JSON.", "RuneStone のテーマ JSON ファイルを選択してください。", "请选择 RuneStone 主题 JSON 文件。"], + ["The theme needs schema 2, an ID, and a name.", "Le thème nécessite le schéma 2, un identifiant et un nom.", "テーマにはスキーマ 2、ID、名前が必要です。", "主题需要架构 2、ID 和名称。"], + ["The theme needs {mode} colors.", "Le thème nécessite des couleurs {mode}.", "テーマには {mode} の色が必要です。", "主题需要 {mode} 颜色。"], + ["Unknown theme color: {key}", "Couleur de thème inconnue : {key}", "不明なテーマの色: {key}", "未知的主题颜色:{key}"], + ["Use a hexadecimal color for {key}.", "Utilisez une couleur hexadécimale pour {key}.", "{key} には16進数の色を使用してください。", "请为 {key} 使用十六进制颜色。"], + ["The {mode} palette needs bg, text, and accent.", "La palette {mode} nécessite bg, text et accent.", "{mode} パレットには bg、text、accent が必要です。", "{mode} 调色板需要 bg、text 和 accent。"], + ["Use an object for theme fonts.", "Utilisez un objet pour les polices du thème.", "テーマのフォントにはオブジェクトを使用してください。", "主题字体请使用对象。"], + ["Unknown theme font: {role}", "Police de thème inconnue : {role}", "不明なテーマのフォント: {role}", "未知的主题字体:{role}"], + ["Use a font family stack for {role}.", "Utilisez une liste de familles de polices pour {role}.", "{role} にはフォントファミリーのリストを使用してください。", "请为 {role} 使用字体系列列表。"], + ["Resolve the disk changes before saving.", "Résolvez les modifications sur le disque avant d’enregistrer.", "保存する前にディスク上の変更を解決してください。", "保存前请先处理磁盘上的更改。"], + ["Open a workspace first.", "Ouvrez d’abord un espace de travail.", "先にワークスペースを開いてください。", "请先打开工作区。"], + ["Collapse backlinks", "Réduire les liens entrants", "バックリンクを折りたたむ", "折叠反向链接"], + ["Expand backlinks", "Développer les liens entrants", "バックリンクを展開", "展开反向链接"] ]; export const catalogs: Record, Record> = { fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), diff --git a/src/lib/layout/FileTree.svelte b/src/lib/layout/FileTree.svelte index 7068fe1..f887a1f 100644 --- a/src/lib/layout/FileTree.svelte +++ b/src/lib/layout/FileTree.svelte @@ -354,7 +354,7 @@ expanded = folders; } - async function copyText(text: string, label: string) { + async function copyText(text: string, done: string) { try { await navigator.clipboard.writeText(text); } catch { @@ -365,7 +365,7 @@ document.execCommand("copy"); area.remove(); } - onStatus?.(`Copied ${label}`); + onStatus?.(done); } async function persistMarks(change: (current: Marks) => Marks) { @@ -416,7 +416,7 @@ await load(parentRel(from)); selectOnly(plan.to); await focusTreePath(plan.to); - onStatus?.(`Renamed to ${plan.to}`); + onStatus?.($t("Renamed to {path}", { path: plan.to })); } catch (err) { error = err instanceof Error ? err.message : String(err); } finally { moving = false; } @@ -512,7 +512,7 @@ } await load(parent); if (workspaceRoot !== operationRoot) return; - onStatus?.(`Created ${rel}`); + onStatus?.($t("Created {path}", { path: rel })); if (kind === "folder") { startRename({ name: finalName, rel_path: rel, kind: "folder" }); } else { @@ -554,7 +554,7 @@ const paths = new Map(entries.map(entry => [entry.rel_path, entry.rel_path])); moving = true; const result = await runTreeActions(place === "after" ? [...entries].reverse() : entries, async entry => { - if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped."); + if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped.")); const plan = planDrop(entry.rel_path, target, place, namesIn); if (plan.action === "noop") return; if (plan.action === "reorder") { @@ -567,7 +567,7 @@ const next = moveMarks(current, plan.from, plan.to); return { ...next, order: { ...next.order, [plan.fromParent]: plan.orderFrom, [plan.toParent]: plan.orderTo } }; }); - if (!moved || workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped."); + if (!moved || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped.")); moves.push({ from: plan.from, to: plan.to }); paths.set(plan.from, plan.to); await load(plan.fromParent); @@ -578,7 +578,7 @@ if (place === "inside") expanded = new Set([...expanded, destination]); selection = { paths: new Set(paths.values()), anchor: paths.values().next().value ?? null }; error = result.failures.length ? result.failures.join("\n") : null; - onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`); + onStatus?.($t("Moved {count} of {total} items", { count: result.completed.length, total: entries.length })); if (moves.length || JSON.stringify(before.order) !== JSON.stringify(marks.order)) { undoMoves = [...undoMoves, { moves, before, after: session.marks.snapshot() }]; redoMoves = []; @@ -621,13 +621,13 @@ const applied: { from: string; to: string }[] = []; try { for (const move of redo ? batch.moves : [...batch.moves].reverse()) { - if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped."); + if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped.")); const from = redo ? move.from : move.to, to = redo ? move.to : move.from; // The batch restores the marks after all moves, so each move leaves them alone. - if (!await session.rename(from, to, null) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped."); + if (!await session.rename(from, to, null) || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped.")); applied.push({ from, to }); } - if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped."); + if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped.")); await persistMarks(current => replayMoveMarks(current, batch.before, batch.after, batch.moves, redo)); if (redo) { redoMoves = redoMoves.slice(0, -1); undoMoves = [...undoMoves, batch]; } else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; } @@ -657,11 +657,11 @@ const moves: MoveBatch["moves"] = []; moving = true; const result = await runTreeActions(source.paths.map(rel_path => ({ rel_path, name: rel_path.split("/").pop()!, kind: "file" as const })), async entry => { - if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped."); + if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. Paste stopped.")); if (source.cut) { const to = joinRel(parent, entry.name); if (to === entry.rel_path) return; - if (!await session.rename(entry.rel_path, to) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped."); + if (!await session.rename(entry.rel_path, to) || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. Paste stopped.")); moves.push({ from: entry.rel_path, to }); } else await workspaceCopy(entry.rel_path, parent, operationRoot); }); @@ -677,7 +677,7 @@ const result = await runTreeActions(roots, entry => workspaceCopy(entry.rel_path)); for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent); error = result.failures.length ? result.failures.join("\n") : null; - onStatus?.(`Copied ${result.completed.length} of ${roots.length} items`); + onStatus?.($t("Copied {count} of {total} items", { count: result.completed.length, total: roots.length })); } // Delete moves items to the system trash. One file needs no confirmation, because the @@ -838,7 +838,7 @@ label: multiple ? $t("Copy workspace paths") : $t("Copy workspace path"), icon: "copy", run: () => { - void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path"); + void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? $t("Copied workspace paths") : $t("Copied workspace path")); }, }, { @@ -849,7 +849,7 @@ void (async () => { try { const paths = await Promise.all(entries.map(item => workspaceAbsPath(item.rel_path))); - await copyText(paths.join("\n"), multiple ? "system paths" : "system path"); + await copyText(paths.join("\n"), multiple ? $t("Copied system paths") : $t("Copied system path")); } catch (err) { error = err instanceof Error ? err.message : String(err); } diff --git a/src/lib/layout/SettingsWindow.svelte b/src/lib/layout/SettingsWindow.svelte index 25656b0..ff8b41f 100644 --- a/src/lib/layout/SettingsWindow.svelte +++ b/src/lib/layout/SettingsWindow.svelte @@ -1,4 +1,5 @@ diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte index 6de3b04..57541f0 100644 --- a/src/lib/layout/Workbench.svelte +++ b/src/lib/layout/Workbench.svelte @@ -286,27 +286,27 @@ * The source tab closes only after this window accepts the tab. */ async function acceptTabTransfer(id: string, { index, startup = false }: { index?: number; startup?: boolean } = {}) { - if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer."); + if (!TAB_TRANSFER_ID.test(id)) throw new Error($t("Invalid tab transfer.")); const current = documents; - if (!workspace || !current || (switching && !startup)) throw new Error("Move tabs only between windows of the same workspace."); + if (!workspace || !current || (switching && !startup)) throw new Error($t("Move tabs only between windows of the same workspace.")); const payload = await takeTabTransfer(id, workspace.root); let accepted = false; try { const transfer = parseTabTransfer(payload); let path = ""; if ("buffer" in transfer) { - if (!current.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open."); + if (!current.importTab(transfer.buffer)) throw new Error($t("This tab is already open in this window. The source tab remains open.")); path = transfer.buffer.relPath; if (!startup) selectTab(path); } else { // A new window starts its plugins after the workspace opens. Wait for them there. const deadline = Date.now() + (startup ? 15000 : 0); while (!await restorePluginTab(transfer.plugin as Parameters[0])) { - if (Date.now() >= deadline) throw new Error("Enable this tab's plugin before moving it to this window."); + if (Date.now() >= deadline) throw new Error($t("Enable this tab's plugin before moving it to this window.")); await new Promise(resolve => setTimeout(resolve, 100)); } if (index !== undefined) { - if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab."); + if (!$pluginView || $pluginView.placement !== "editor") throw new Error($t("The plugin did not open this tab.")); path = `plugin:${$pluginView.key}`; } } @@ -450,7 +450,7 @@ if (tab.plugin && await openPluginDocument(tab.path)) { await tick(); const opened = $pluginEditors.find(view => view.document?.path === tab.path); - if (!opened) throw new Error("The plugin did not open this document."); + if (!opened) throw new Error($t("The plugin did not open this document.")); if (tab.pinned !== !!opened.pinned) pinPluginEditor(opened.key); order.push(opened.key); paths.set(tab.path, `plugin:${opened.key}`); @@ -567,7 +567,7 @@ const offered = offerTabTransfer(token, workspace!.root, { ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }); // A drag cannot wait for the offer. Report a failed drag offer here. `detachTab` reports its own. offered.catch(reason => { finish(false); if (!reportTimeout) error = String(reason); }); - timer = setTimeout(() => { finish(); if (reportTimeout) error = "The new window did not accept the tab. The source tab remains open."; }, 30000); + timer = setTimeout(() => { finish(); if (reportTimeout) error = $t("The new window did not accept the tab. The source tab remains open."); }, 30000); return { token, finish, offered }; } catch (reason) { finish(); throw reason; } } @@ -902,7 +902,7 @@ async function renameNoteTitle(id: string, title: string) { const current = documents; const note = current?.buffers.find(tab => tab.id === id); - if (!current || !note || switching) throw new Error("This note is no longer available."); + if (!current || !note || switching) throw new Error($t("This note is no longer available.")); const from = note.relPath; const plan = planMarkdownTitleRename(from, title); if (plan.action === "error") throw new Error(plan.message); @@ -947,7 +947,7 @@ const targets = await session.linkTargets(origin, link.target, link.kind); if ("ambiguous" in targets) throw new Error($t("More than one note matches {path}. Use its workspace path: {candidates}", { path: link.target, candidates: targets.ambiguous.join(", ") })); for (const path of targets.paths) { - if (!valid()) throw new Error("The workspace changed. Open the link menu again."); + if (!valid()) throw new Error($t("The workspace changed. Open the link menu again.")); const parent = path.split("/").slice(0, -1).join("/"); let files: TreeEntry[]; try { files = await workspaceList(parent); } catch { continue; } @@ -965,7 +965,7 @@ if (!typed || !valid()) return; let to = typed.trim().replaceAll("\\", "/"); if (move) { - if (!to || to.startsWith("/") || to.split("/").some(part => !part || part === "." || part === "..") || /[<>:"|?*\u0000-\u001f]/.test(to)) throw new Error("Enter a relative workspace path without reserved characters."); + if (!to || to.startsWith("/") || to.split("/").some(part => !part || part === "." || part === "..") || /[<>:"|?*\u0000-\u001f]/.test(to)) throw new Error($t("Enter a relative workspace path without reserved characters.")); } else { const plan = planRename(file.rel_path, to); if (plan.action === "noop") return; @@ -1071,18 +1071,18 @@ ({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout); if (transferredWindow) { leftOpen = false; rightOpen = false; } layoutReady = true; - } catch { error = "Could not read your layout. Default layout applies for this window."; } + } catch { error = $t("Could not read your layout. Default layout applies for this window."); } }); $effect(() => { if (!layoutReady || transferredWindow) return; try { saveWorkbenchLayout(localStorage, { leftOpen, rightOpen, leftWidth, rightWidth, leftView }); } - catch { error = "Could not save your layout. Layout changes apply for this window only."; } + catch { error = $t("Could not save your layout. Layout changes apply for this window only."); } }); onMount(() => { try { settings = readSettings(); } - catch { error = "Could not read your settings. Default settings apply until you save new settings."; } + catch { error = $t("Could not read your settings. Default settings apply until you save new settings."); } error = takeSettingsNotice() ?? error; settingsReady = true; const stopSettings = onSettingsChange("general", () => { settings = readSettings(); }); @@ -1109,11 +1109,11 @@ })); unlisteners.push(handlePluginDocumentRename(async (from, name) => { const current = documents; - if (!current || switching) throw new Error("Open a workspace before renaming a document."); + if (!current || switching) throw new Error($t("Open a workspace before renaming a document.")); const plan = planDocumentTitleRename(from, name); if (plan.action === "error") throw new Error(plan.message); if (plan.action === "noop") return from; - if (!await session.rename(from, plan.to) || documents !== current) throw new Error("The workspace changed. Reopen the document."); + if (!await session.rename(from, plan.to) || documents !== current) throw new Error($t("The workspace changed. Reopen the document.")); return plan.to; })); unlisteners.push(guardPluginWrites(path => { @@ -1365,7 +1365,7 @@ onRenameTitle={renameNoteTitle} tableActions={{ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) }} linkActions={{ - browser: browserContribution ? async target => { if (!await browserContribution?.open(target)) throw new Error("Could not open the app browser."); } : undefined, + browser: browserContribution ? async target => { if (!await browserContribution?.open(target)) throw new Error($t("Could not open the app browser.")); } : undefined, defaultBrowser: target => openUrl(target), workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id), }} diff --git a/src/lib/theme/AppearanceSettings.svelte b/src/lib/theme/AppearanceSettings.svelte index 72242c1..ea6f68d 100644 --- a/src/lib/theme/AppearanceSettings.svelte +++ b/src/lib/theme/AppearanceSettings.svelte @@ -126,8 +126,8 @@ {#if appearance.theme.startsWith('custom:')} { - try { removeTheme(appearance.theme.slice(7)).catch(() => { error = 'Could not remove this theme.'; }); installed = customThemes(); change({ ...appearance, theme: 'default' }); } - catch { error = 'Could not remove this theme.'; } + try { removeTheme(appearance.theme.slice(7)).catch(() => { error = $t("Could not remove this theme."); }); installed = customThemes(); change({ ...appearance, theme: 'default' }); } + catch { error = $t("Could not remove this theme."); } }} />{/if}

{$t("Edit the exported JSON colors and fonts, then choose Install theme. The template contains one color palette and font families.")}

diff --git a/src/lib/theme/backgroundImages.ts b/src/lib/theme/backgroundImages.ts index 549ebfa..d09c310 100644 --- a/src/lib/theme/backgroundImages.ts +++ b/src/lib/theme/backgroundImages.ts @@ -8,7 +8,7 @@ function database(): Promise { }); } export async function saveBackgroundImage(file: Blob): Promise { - if (file.size > BACKGROUND_IMAGE_LIMIT) throw new Error('Choose an image of 50 MiB or less.'); + if (file.size > BACKGROUND_IMAGE_LIMIT) throw new Error(tr("Choose an image of 50 MiB or less.")); const db = await database(); const id = crypto.randomUUID(); try { @@ -43,4 +43,5 @@ export async function removeBackgroundImage(id: string): Promise { transaction.onabort = () => reject(transaction.error); }); } finally { db.close(); } -} +}import { tr } from "../i18n/index.ts"; + diff --git a/src/lib/theme/customThemes.ts b/src/lib/theme/customThemes.ts index 1f0ab75..f2fe286 100644 --- a/src/lib/theme/customThemes.ts +++ b/src/lib/theme/customThemes.ts @@ -1,3 +1,4 @@ +import { tr } from "../i18n/index.ts"; import { readSection, writeSection } from '../settings/store.ts'; /** The old localStorage key. The customThemes section of the settings file replaces it. */ @@ -10,31 +11,31 @@ export type CustomTheme = { schema: 2; id: string; name: string; colors: ThemeCo export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors }; export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = "dark"): CustomTheme { - if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file."); + if (!input || typeof input !== "object") throw new Error(tr("Choose a RuneStone theme JSON file.")); const value = input as Record; if ((value.schema !== 1 && value.schema !== 2) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id) - || typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 2, an ID, and a name."); + || typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error(tr("The theme needs schema 2, an ID, and a name.")); const colors = (mode: string): ThemeColors => { const source = value[mode]; - if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`); + if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(tr("The theme needs {mode} colors.", { mode })); const result: ThemeColors = {}; for (const [key, color] of Object.entries(source)) { - if (!(COLOR_TOKENS as readonly string[]).includes(key)) throw new Error(`Unknown theme color: ${key}`); - if (typeof color !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) throw new Error(`Use a hexadecimal color for ${key}.`); + if (!(COLOR_TOKENS as readonly string[]).includes(key)) throw new Error(tr("Unknown theme color: {key}", { key })); + if (typeof color !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) throw new Error(tr("Use a hexadecimal color for {key}.", { key })); result[key as keyof ThemeColors] = color; } - if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`); + if (!result.bg || !result.text || !result.accent) throw new Error(tr("The {mode} palette needs bg, text, and accent.", { mode })); return result; }; if (value.schema === 1) { colors("light"); colors("dark"); } let fonts: ThemeFonts | undefined; if (value.fonts !== undefined) { - if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error('Use an object for theme fonts.'); + if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error(tr("Use an object for theme fonts.")); fonts = {}; for (const [role, stack] of Object.entries(value.fonts)) { - if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(`Unknown theme font: ${role}`); + if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(tr("Unknown theme font: {role}", { role })); if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim() - || stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(`Use a font family stack for ${role}.`); + || stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(tr("Use a font family stack for {role}.", { role })); fonts[role as keyof ThemeFonts] = stack.trim(); } } diff --git a/src/lib/workspace/documents.svelte.ts b/src/lib/workspace/documents.svelte.ts index d3c7a4a..264b958 100644 --- a/src/lib/workspace/documents.svelte.ts +++ b/src/lib/workspace/documents.svelte.ts @@ -1,3 +1,4 @@ +import { tr } from "../i18n/index.ts"; import type { OpenBuffer, TreeEntry } from "./types"; export type DocumentIO = { @@ -171,7 +172,7 @@ export class Documents { if (this.disposed) return; const b = this.buffers.find(b => b.id === id); if (!b || b.kind !== "text") return; - if (b.diskContents !== undefined || b.diskError) throw new Error("Resolve the disk changes before saving."); + if (b.diskContents !== undefined || b.diskError) throw new Error(tr("Resolve the disk changes before saving.")); if (b.contents === b.saved) return; const contents = b.contents; const path = b.relPath; diff --git a/src/lib/workspace/noteHtml.ts b/src/lib/workspace/noteHtml.ts index 48bbbbf..3423dec 100644 --- a/src/lib/workspace/noteHtml.ts +++ b/src/lib/workspace/noteHtml.ts @@ -1,3 +1,4 @@ +import { tr } from "../i18n/index.ts"; import MarkdownIt from "markdown-it"; import type { Token } from "markdown-it"; import { inlineMathEnd } from "./inlineMath.ts"; @@ -147,9 +148,9 @@ markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => markdown.renderer.rules.fence = (tokens, index) => { const token = tokens[index]; const language = token.info.trim().split(/\s+/)[0]; - const code = `
${escapeHtml(token.content)}
\n`; + const code = `
${escapeHtml(token.content)}
\n`; return language.toLowerCase() === "mermaid" - ? `
Diagram source${code}
\n` + ? `
${tr("Diagram source")}${code}
\n` : code; }; diff --git a/src/lib/workspace/session.svelte.ts b/src/lib/workspace/session.svelte.ts index d6862fd..f64c28d 100644 --- a/src/lib/workspace/session.svelte.ts +++ b/src/lib/workspace/session.svelte.ts @@ -1,3 +1,4 @@ +import { tr } from "../i18n/index.ts"; import { workspaceList, workspaceRead, workspaceReadMany, workspaceRename } from "./api"; import { MARKS_PATH, type Marks } from "./marks"; import { linkCandidates } from "./markdownLinks"; @@ -139,7 +140,7 @@ export class WorkspaceSession { */ async rename(from: string, to: string, marks: ((current: Marks) => Marks) | null = current => moveMarks(current, from, to)): Promise { const root = this.root; - if (!root) throw new Error("Open a workspace first."); + if (!root) throw new Error(tr("Open a workspace first.")); await workspaceRename(from, to, root); if (this.root !== root) return false; this.index.rename(from, to); diff --git a/src/lib/workspace/settings.ts b/src/lib/workspace/settings.ts index 6d9befa..e32bc7f 100644 --- a/src/lib/workspace/settings.ts +++ b/src/lib/workspace/settings.ts @@ -1,3 +1,4 @@ +import { tr } from "../i18n/index.ts"; import { readSection, writeSection } from "../settings/store.ts"; /** The old localStorage key. The general section of the settings file replaces it. */ @@ -47,7 +48,7 @@ export function readSettings(): AppSettings { /** Check and save the settings. Throws at once for invalid values. The promise reports a failed save. */ export function saveSettings(settings: AppSettings): Promise { if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") { - throw new Error("Choose a whole number from 1 to 300 seconds."); + throw new Error(tr("Choose a whole number from 1 to 300 seconds.")); } return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true, tableFormulas: settings.tableFormulas !== false }); } diff --git a/src/lib/workspace/tabTransfer.ts b/src/lib/workspace/tabTransfer.ts index 70aa937..4ec9b91 100644 --- a/src/lib/workspace/tabTransfer.ts +++ b/src/lib/workspace/tabTransfer.ts @@ -1,6 +1,7 @@ // Tab transfer between windows of one workspace. The host keeps each offer in memory (src-tauri/src/tab_transfer.rs). // The source window offers a tab and closes it only after `tab-transfer-accepted`. // The receiving window takes the offer, opens the tab, and then finishes the offer. +import { tr } from "../i18n/index.ts"; import { invoke } from "@tauri-apps/api/core"; import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { getCurrentWindow } from "@tauri-apps/api/window"; @@ -16,7 +17,7 @@ export type TabTransferOffer = { reading: boolean } & ({ buffer: OpenBuffer } | /** Check the state of a taken offer. The new window and the tab ribbon use this one check. */ export function parseTabTransfer(payload: string): TabTransfer { let value: unknown; - try { value = JSON.parse(payload); } catch { throw new Error("Invalid tab transfer."); } + try { value = JSON.parse(payload); } catch { throw new Error(tr("Invalid tab transfer.")); } const transfer = value && typeof value === "object" ? value as Record : {}; const reading = transfer.reading === true; const buffer = transfer.buffer as Record | undefined; @@ -25,7 +26,7 @@ export function parseTabTransfer(payload: string): TabTransfer { return { buffer: buffer as unknown as OpenBuffer, reading }; } if (transfer.plugin && typeof transfer.plugin === "object") return { plugin: transfer.plugin, reading }; - throw new Error("Invalid tab transfer."); + throw new Error(tr("Invalid tab transfer.")); } /** Offer a tab with the ID `id`. The window creates the ID, because a drag needs it at once. */ @@ -35,7 +36,7 @@ export function offerTabTransfer(id: string, root: string, offer: TabTransferOff /** Take an offer once. Fails when the offer expired or belongs to another workspace. */ export async function takeTabTransfer(id: string, root: string): Promise { - if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer."); + if (!TAB_TRANSFER_ID.test(id)) throw new Error(tr("Invalid tab transfer.")); return invoke("tab_transfer_take", { id, root }); } diff --git a/src/lib/workspace/templates.ts b/src/lib/workspace/templates.ts index badf493..75be5f4 100644 --- a/src/lib/workspace/templates.ts +++ b/src/lib/workspace/templates.ts @@ -1,3 +1,4 @@ +import { tr } from "../i18n/index.ts"; import { workspaceCreate, workspaceList, workspaceRead, workspaceWrite } from "./api"; import { uniqueName, joinRel } from "./treeDrop"; @@ -14,7 +15,7 @@ export async function noteTemplates(): Promise { export async function saveNoteTemplate(name: string, contents: string): Promise { const title = name.trim().replace(/\.md$/i, ""); - if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) throw new Error("Enter a valid template name."); + if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) throw new Error(tr("Enter a valid template name.")); const existing = await noteTemplates(); const file = uniqueName(existing.map(template => template.name + ".md"), title + ".md"); const path = joinRel(TEMPLATE_FOLDER, file);