The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
feat: i18n foundation - typed catalog, language picker, settings migrated
Jareereda75a9ba66c
diff --git a/TRANSLATING.md b/TRANSLATING.mdnew file mode 100644index 00000000..f18298f2--- /dev/null+++ b/TRANSLATING.md@@ -0,0 +1,46 @@+# Translating WolfCut++WolfCut's interface speaks whatever your system speaks, when a translation+exists. Adding one takes a text editor and nothing else — no build tools, no+code beyond two registry lines.++## What is translated++The desktop app's interface: menus, panels, dialogs, tooltips, toasts. Not+translated (yet): error text coming from the engine, and the website.++## Adding a language++1. Copy `desktop/src/locales/en.json` to `desktop/src/locales/<tag>.json`,+ where `<tag>` is the [BCP 47](https://en.wikipedia.org/wiki/IETF_language_tag)+ tag for your language — `zh-CN` for Simplified Chinese, `de` for German.+2. Translate the **values** only. Keys stay exactly as they are.+3. Register the language in `desktop/src/lib/i18n.ts`: one entry in `LOCALES`+ (use the language's **native** name — `简体中文`, not `Chinese`) and one+ line in `CATALOGS`.+4. Check your work: `cd desktop && npm install && npm test`. The i18n test+ names every key you missed, every stale key, and every placeholder that+ doesn't match.++Then open a pull request. That's the whole process.++## Rules that keep translations working++- **Translate whole sentences.** Word order differs between languages, which+ is why no message is ever assembled from fragments.+- **Keep `{placeholders}` exactly as written.** You can move them anywhere in+ the sentence, but the name inside the braces must survive verbatim —+ `"Save failed: {message}"` → `"保存失败:{message}"`.+- **Fill both plural forms.** Keys ending in `.one` and `.other` are plural+ pairs (`{count}` is available in both). If your language doesn't+ distinguish — Chinese doesn't — put the same text in both. The right form+ is picked by your language's own rules, not by English's.+- **Leave alone:** font names, technical units (dB, st, GB, fps), and+ keyboard shortcut hints, unless your platform's convention truly differs.++## Keeping a translation current++When new interface text lands, `en.json` gains keys and your file is+temporarily behind — the app falls back to English for those strings, and+`npm test` lists exactly which keys your file lacks. Update the file, run the+test, open a pull request.diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsxindex 4df39c92..ff2b19b0 100644--- a/desktop/src/components/SettingsDialog.tsx+++ b/desktop/src/components/SettingsDialog.tsx@@ -11,6 +11,7 @@ import {transcriberStatus,type TranscriberStatus,} from "../lib/engine";+import { LOCALES, systemLocale, useLocale, type MsgKey } from "../lib/i18n";import {getTranscriberLanguage,getTranscriberModel,@@ -21,11 +22,12 @@ import { HelpTip } from "./controls";import { Icon } from "./Icon";/** The pages of the settings dialog, in display order. */-type SettingsTab = "transcriber" | "about";+type SettingsTab = "general" | "transcriber" | "about";-const TABS: { id: SettingsTab; label: string; icon: "waveform" | "info" }[] = [- { id: "transcriber", label: "Transcriber", icon: "waveform" },- { id: "about", label: "About", icon: "info" },+const TABS: { id: SettingsTab; labelKey: MsgKey; icon: "settings" | "waveform" | "info" }[] = [+ { id: "general", labelKey: "settings.tabs.general", icon: "settings" },+ { id: "transcriber", labelKey: "settings.tabs.transcriber", icon: "waveform" },+ { id: "about", labelKey: "settings.tabs.about", icon: "info" },];/**@@ -36,7 +38,8 @@ const TABS: { id: SettingsTab; label: string; icon: "waveform" | "info" }[] = [* Settings here are app-level (this machine), never project state.*/export function SettingsDialog({ onClose }: { onClose: () => void }) {- const [tab, setTab] = useState<SettingsTab>("transcriber");+ const [tab, setTab] = useState<SettingsTab>("general");+ const { t } = useLocale();return (<div@@ -49,10 +52,10 @@ export function SettingsDialog({ onClose }: { onClose: () => void }) {<div className="surface flex h-[460px] w-full max-w-2xl flex-col rounded-2xl"><div className="flex items-center gap-2 border-b border-hairline px-5 py-3.5"><Icon name="settings" size={16} className="text-accent" />- <h2 className="flex-1 text-sm font-semibold text-primary">Settings</h2>+ <h2 className="flex-1 text-sm font-semibold text-primary">{t("settings.title")}</h2><buttontype="button"- aria-label="Close"+ aria-label={t("common.close")}onClick={onClose}className="cursor-pointer rounded p-1 text-secondary hover:bg-hover hover:text-primary">@@ -76,12 +79,13 @@ export function SettingsDialog({ onClose }: { onClose: () => void }) {}`}><Icon name={entry.icon} size={13} className="shrink-0 opacity-70" />- {entry.label}+ {t(entry.labelKey)}</button>))}</aside><div className="thin-scroll min-w-0 flex-1 overflow-y-auto px-5 py-4">+ {tab === "general" && <GeneralSettings />}{tab === "transcriber" && <TranscriberSettings />}{tab === "about" && <AboutSettings />}</div>@@ -91,6 +95,59 @@ export function SettingsDialog({ onClose }: { onClose: () => void }) {);}+function GeneralSettings() {+ const { t, preference, setLocale } = useLocale();+ // Native names, straight from LOCALES: whoever is stranded in a language+ // they cannot read must still recognise their own in this list.+ const system = LOCALES.find((entry) => entry.id === systemLocale())!;+ const choices = [+ {+ id: "system" as const,+ name: t("settings.general.systemDefault", { language: system.name }),+ },+ ...LOCALES,+ ];++ return (+ <div className="flex flex-col gap-5">+ <section>+ <h3 className="mb-2 text-[11px] font-semibold uppercase tracking-wider text-tertiary">+ {t("settings.general.language")}+ </h3>+ <div className="flex w-72 flex-col gap-1.5">+ {choices.map((entry) => {+ const selected = preference === entry.id;+ return (+ <button+ key={entry.id}+ type="button"+ role="radio"+ aria-checked={selected}+ onClick={() => setLocale(entry.id)}+ className={`flex cursor-pointer items-center gap-2.5 rounded-lg px-3 py-2 text-left+ ring-1 transition-shadow ${+ selected ? "ring-accent" : "ring-hairline hover:ring-hairline-strong"+ }`}+ >+ <span+ className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full+ ring-1 ring-hairline-strong"+ >+ {selected && <span className="h-2 w-2 rounded-full bg-accent" />}+ </span>+ <span className="truncate text-xs text-primary">{entry.name}</span>+ </button>+ );+ })}+ </div>+ <p className="mt-2 text-[11px] leading-snug text-tertiary">+ {t("settings.general.engineNote")}+ </p>+ </section>+ </div>+ );+}+/** Bytes as a short human figure for model rows. */function formatSize(bytes: number): string {return bytes >= 1_000_000_000@@ -98,12 +155,14 @@ function formatSize(bytes: number): string {: `${Math.round(bytes / 1_000_000)} MB`;}-const LANGUAGES = [- { id: "auto", label: "Auto-detect" },- { id: "en", label: "English" },-] as const;+/** Whisper input languages - what the audio is in, not what the UI speaks. */+const LANGUAGES: { id: string; labelKey: MsgKey }[] = [+ { id: "auto", labelKey: "settings.transcriber.languageAuto" },+ { id: "en", labelKey: "settings.transcriber.languageEnglish" },+];function TranscriberSettings() {+ const { t } = useLocale();const [status, setStatus] = useState<TranscriberStatus | null>(null);const [error, setError] = useState<string | null>(null);const [model, setModel] = useState(getTranscriberModel());@@ -141,9 +200,9 @@ function TranscriberSettings() {const locate = async () => {const chosen = await open({- title: "Locate whisper-cli",+ title: t("settings.transcriber.locateTitle"),multiple: false,- filters: [{ name: "Program", extensions: ["exe", "*"] }],+ filters: [{ name: t("settings.transcriber.locateFilter"), extensions: ["exe", "*"] }],});if (typeof chosen !== "string") return;try {@@ -194,7 +253,7 @@ function TranscriberSettings() {<div className="flex items-center gap-2 rounded-lg bg-sunken px-3 py-2.5"><span className="h-2 w-2 shrink-0 rounded-full bg-danger" /><span className="min-w-0 flex-1 truncate text-xs text-secondary">- Transcription engine not found in this dev build+ {t("settings.transcriber.engineMissing")}</span><buttontype="button"@@ -202,7 +261,7 @@ function TranscriberSettings() {className="shrink-0 cursor-pointer rounded-md bg-panel px-2.5 py-1 text-[11px]text-primary ring-1 ring-hairline transition-colors hover:bg-hover">- Locate...+ {t("settings.transcriber.locate")}</button></div></section>@@ -210,7 +269,7 @@ function TranscriberSettings() {<section><h3 className="mb-2 text-[11px] font-semibold uppercase tracking-wider text-tertiary">- Language+ {t("settings.transcriber.language")}</h3><div className="flex w-56 rounded-lg bg-sunken p-0.5">{LANGUAGES.map((entry) => (@@ -225,7 +284,7 @@ function TranscriberSettings() {: "text-secondary hover:text-primary"}`}>- {entry.label}+ {t(entry.labelKey)}</button>))}</div>@@ -233,11 +292,8 @@ function TranscriberSettings() {<section><h3 className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-tertiary">- Models- <HelpTip- align="start"- text="Bigger models transcribe better and slower. English-only variants beat the multilingual ones at the same size when the audio is English. The selected model is what Auto captions uses. Everything runs locally - nothing leaves this machine."- />+ {t("settings.transcriber.models")}+ <HelpTip align="start" text={t("settings.transcriber.modelsHelp")} /></h3><ul className="flex flex-col gap-1.5">@@ -262,10 +318,14 @@ function TranscriberSettings() {type="button"role="radio"aria-checked={selected}- aria-label={`Use ${entry.label}`}+ aria-label={t("settings.transcriber.useModel", { model: entry.label })}disabled={!entry.downloaded}onClick={() => chooseModel(entry.id)}- title={entry.downloaded ? "Use this model" : "Download it first"}+ title={+ entry.downloaded+ ? t("settings.transcriber.useModelHint")+ : t("settings.transcriber.downloadFirstHint")+ }className="flex h-4 w-4 shrink-0 cursor-pointer items-center justify-centerrounded-full ring-1 ring-hairline-strongdisabled:cursor-not-allowed disabled:opacity-40"@@ -292,7 +352,7 @@ function TranscriberSettings() {</span><buttontype="button"- aria-label="Cancel download"+ aria-label={t("settings.transcriber.cancelDownload")}onClick={(event) => {event.stopPropagation();void cancelModelDownload();@@ -308,8 +368,8 @@ function TranscriberSettings() {<Icon name="check" size={12} className="text-success" /><buttontype="button"- aria-label={`Delete ${entry.label}`}- title="Delete the downloaded model"+ aria-label={t("settings.transcriber.deleteModel", { model: entry.label })}+ title={t("settings.transcriber.deleteModelHint")}onClick={(event) => {event.stopPropagation();remove(entry.id);@@ -332,7 +392,7 @@ function TranscriberSettings() {text-primary ring-1 ring-hairline transition-colors hover:bg-hoverdisabled:cursor-not-allowed disabled:opacity-40">- Download+ {t("settings.transcriber.download")}</button>)}</li>@@ -347,6 +407,7 @@ function TranscriberSettings() {}function AboutSettings() {+ const { t } = useLocale();const [version, setVersion] = useState<string | null>(null);useEffect(() => {@@ -360,10 +421,12 @@ function AboutSettings() {<h3 className="mb-1 text-[11px] font-semibold uppercase tracking-wider text-tertiary">WolfCut</h3>- <p className="text-xs text-secondary">Version {version ?? "unknown"}</p>- <p className="text-[11px] leading-relaxed text-tertiary">- Local-first video editing. Media, models and renders stay on this machine.+ <p className="text-xs text-secondary">+ {t("settings.about.version", {+ version: version ?? t("settings.about.versionUnknown"),+ })}</p>+ <p className="text-[11px] leading-relaxed text-tertiary">{t("settings.about.blurb")}</p></div>);}diff --git a/desktop/src/lib/i18n.test.ts b/desktop/src/lib/i18n.test.tsnew file mode 100644index 00000000..4361fc71--- /dev/null+++ b/desktop/src/lib/i18n.test.ts@@ -0,0 +1,82 @@+/**+ * The message catalogs against each other.+ *+ * en.json is the source of truth; every other locale must define exactly its+ * key set with matching placeholders. The catalogs are read from disk, not+ * imported, so a locale file someone dropped in but forgot to register still+ * gets caught. Same enforcement style as ipc-registry.test.ts: conventions+ * the type system cannot see, held by a test that names the offenders.+ */+import { readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, test } from "vitest";++import { LOCALES } from "./i18n";++const dir = join(process.cwd(), "src", "locales");++function catalog(file: string): Record<string, string> {+ return JSON.parse(readFileSync(join(dir, file), "utf8")) as Record<string, string>;+}++/** The {name} placeholders of a message, as a sorted list. */+function placeholders(message: string): string[] {+ return (message.match(/\{\w+\}/g) ?? []).sort();+}++const files = readdirSync(dir).filter((entry) => entry.endsWith(".json"));+const en = catalog("en.json");+const enKeys = Object.keys(en);++describe("the message catalogs", () => {+ test("every locale file on disk is registered in LOCALES", () => {+ const registered = new Set<string>(LOCALES.map((entry) => entry.id));+ const unregistered = files.filter((file) => !registered.has(file.replace(/\.json$/, "")));+ expect(unregistered, "locale files LOCALES never registers").toEqual([]);+ const fileless = [...registered].filter((id) => !files.includes(`${id}.json`));+ expect(fileless, "registered locales with no file on disk").toEqual([]);+ });++ test("plural keys come in complete one/other pairs", () => {+ const widowed = enKeys.filter((key) => {+ if (key.endsWith(".one")) return !(key.replace(/\.one$/, ".other") in en);+ if (key.endsWith(".other")) return !(key.replace(/\.other$/, ".one") in en);+ return false;+ });+ expect(widowed, "plural keys missing their sibling form").toEqual([]);+ });++ test("en.json keys are sorted", () => {+ expect(enKeys, "keys out of alphabetical order").toEqual([...enKeys].sort());+ });++ for (const file of files) {+ const messages = catalog(file);++ describe(file, () => {+ test("defines every key en.json defines", () => {+ const missing = enKeys.filter((key) => !(key in messages));+ expect(missing, "keys en.json has that this locale lacks").toEqual([]);+ });++ test("defines no key en.json does not", () => {+ const stale = Object.keys(messages).filter((key) => !(key in en));+ expect(stale, "keys this locale has that en.json dropped").toEqual([]);+ });++ test("placeholders match en.json exactly", () => {+ const mismatched = enKeys.filter(+ (key) =>+ key in messages &&+ placeholders(messages[key]).join(" ") !== placeholders(en[key]).join(" "),+ );+ expect(mismatched, "keys whose {placeholders} differ from en.json").toEqual([]);+ });++ test("no value is empty", () => {+ const empty = Object.keys(messages).filter((key) => messages[key].trim() === "");+ expect(empty, "an empty string is a translation hole, not a translation").toEqual([]);+ });+ });+ }+});diff --git a/desktop/src/lib/i18n.ts b/desktop/src/lib/i18n.tsnew file mode 100644index 00000000..c1bd18de--- /dev/null+++ b/desktop/src/lib/i18n.ts@@ -0,0 +1,182 @@+import { useSyncExternalStore } from "react";++import en from "../locales/en.json";++/**+ * The UI language.+ *+ * Every string a person reads in the app comes out of a per-locale JSON+ * catalog in `src/locales/`, looked up by a typed key - a typo'd key is a+ * compile error, and `i18n.test.ts` holds every catalog to exactly the key+ * set en.json defines. Adding a language is copying en.json, translating the+ * values, and registering one entry in LOCALES and CATALOGS below; see+ * TRANSLATING.md at the repo root.+ *+ * Unlike the theme, the language *does* follow the OS by default. The theme+ * refuses to (see theme.ts) because a surround that changes on its own is+ * disorienting; language is the opposite case - an interface you cannot read+ * is not a neutral default, so first launch speaks whatever the system+ * speaks, and the explicit choice in Settings overrides it from then on.+ *+ * Switching re-renders by subscription, not remount: App owns the live+ * editing session, so rebuilding the tree under a changed `key` would dump+ * the user out of their project. Components that render text call+ * `useLocale()` and take `t` from it - the snapshot (and `t`'s identity)+ * changes per switch, so `useSyncExternalStore` re-renders subscribers+ * directly (through `React.memo`), and exhaustive-deps forces `t` into any+ * dependency array that caches a translated string. The module-level `t`/`tp`+ * exports are for non-React code and event handlers, which always run after+ * the switch and therefore always see the current language.+ */+export type MsgKey = keyof typeof en;++/** Bases of plural sets: `x.one`/`x.other` in the catalog collapse to `x`. */+export type PluralKey = MsgKey extends `${infer Base}.one` ? Base : never;++/**+ * Native names, never translated: whoever landed in a language they cannot+ * read must still be able to find their own in the picker.+ */+export const LOCALES = [{ id: "en", name: "English" }] as const;++export type LocaleId = (typeof LOCALES)[number]["id"];++// Record<MsgKey, string> makes a catalog missing keys fail `tsc`, before the+// friendlier i18n.test.ts even runs.+const CATALOGS: Record<LocaleId, Record<MsgKey, string>> = { en };++const STORAGE_KEY = "wolfcut.locale";++/** The stored preference: an explicit locale, or absence meaning "system". */+function stored(): LocaleId | "system" {+ try {+ const value = localStorage.getItem(STORAGE_KEY);+ const known = LOCALES.find((entry) => entry.id === value);+ return known ? known.id : "system";+ } catch {+ // Private mode, blocked storage, node - the system default anyway.+ return "system";+ }+}++function persist(next: LocaleId | "system"): void {+ try {+ if (next === "system") localStorage.removeItem(STORAGE_KEY);+ else localStorage.setItem(STORAGE_KEY, next);+ } catch {+ // Not being able to remember the choice is not worth failing over.+ }+}++/** "system" resolved against what we actually ship: exact id, then language prefix, then en. */+function resolve(next: LocaleId | "system"): LocaleId {+ if (next !== "system") return next;+ const wanted = typeof navigator !== "undefined" ? navigator.language : "";+ if (!wanted) return "en";+ const lower = wanted.toLowerCase();+ for (const entry of LOCALES) if (entry.id.toLowerCase() === lower) return entry.id;+ const prefix = lower.split("-")[0];+ for (const entry of LOCALES) {+ if (entry.id.split("-")[0].toLowerCase() === prefix) return entry.id;+ }+ return "en";+}++/** What "System default" would mean right now, for labelling the picker. */+export function systemLocale(): LocaleId {+ return resolve("system");+}++/**+ * Puts the language on `<html lang>`, where the OS spellchecker, screen+ * readers and CSS quotes rules key off it. index.html carries lang="en" only+ * as the pre-hydration default.+ */+function applyLocale(next: LocaleId): void {+ if (typeof document !== "undefined") document.documentElement.lang = next;+}++let preference: LocaleId | "system" = stored();+let locale: LocaleId = resolve(preference);++function interpolate(message: string, params?: Record<string, string | number>): string {+ if (!params) return message;+ // An unfilled placeholder stays visible as {name} - an on-screen bug is+ // louder and more honest than a silently swallowed one.+ return message.replace(/\{(\w+)\}/g, (whole, name: string) =>+ params[name] != null ? String(params[name]) : whole,+ );+}++/** The message for `key` in the current language, English if the catalog has a hole. */+export function t(key: MsgKey, params?: Record<string, string | number>): string {+ const message = CATALOGS[locale][key] ?? CATALOGS.en[key];+ return interpolate(message, params);+}++/**+ * The plural form of `key` for `count`, per the language's own rules+ * (Intl.PluralRules - English says "one"/"other", Chinese only "other").+ * `{count}` is available as a placeholder without passing it again.+ */+export function tp(key: PluralKey, count: number, params?: Record<string, string | number>): string {+ const category = new Intl.PluralRules(locale).select(count);+ const exact = `${key}.${category}` as MsgKey;+ const other = `${key}.other` as MsgKey;+ const message = CATALOGS[locale][exact] ?? CATALOGS[locale][other] ?? CATALOGS.en[other];+ return interpolate(message, { count, ...params });+}++export function getLocale(): LocaleId {+ return locale;+}++export type LocaleSnapshot = {+ locale: LocaleId;+ preference: LocaleId | "system";+ setLocale: (next: LocaleId | "system") => void;+ t: typeof t;+ tp: typeof tp;+};++// The snapshot is rebuilt (new identities throughout) on every switch, so a+// `t` taken from useLocale() is a reactive value the linter refuses to let+// out of dependency arrays - stale memoized strings become lint errors.+function buildSnapshot(): LocaleSnapshot {+ return {+ locale,+ preference,+ setLocale,+ t: (key, params) => t(key, params),+ tp: (key, count, params) => tp(key, count, params),+ };+}++const listeners = new Set<() => void>();++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++export function setLocale(next: LocaleId | "system"): void {+ persist(next);+ preference = next;+ locale = resolve(next);+ applyLocale(locale);+ snapshot = buildSnapshot();+ for (const listener of listeners) listener();+}++let snapshot = buildSnapshot();++// At import time, before React renders anything, so the first paint is+// already in the right language - same move as theme.ts.+applyLocale(locale);++/** The current language for React: subscribes the component to switches. */+export function useLocale(): LocaleSnapshot {+ return useSyncExternalStore(subscribe, () => snapshot);+}diff --git a/desktop/src/locales/en.json b/desktop/src/locales/en.jsonnew file mode 100644index 00000000..aa0bd1eb--- /dev/null+++ b/desktop/src/locales/en.json@@ -0,0 +1,29 @@+{+ "common.close": "Close",+ "settings.about.blurb": "Local-first video editing. Media, models and renders stay on this machine.",+ "settings.about.version": "Version {version}",+ "settings.about.versionUnknown": "unknown",+ "settings.general.engineNote": "Some text from the engine appears in English.",+ "settings.general.language": "Language",+ "settings.general.systemDefault": "System default ({language})",+ "settings.tabs.about": "About",+ "settings.tabs.general": "General",+ "settings.tabs.transcriber": "Transcriber",+ "settings.title": "Settings",+ "settings.transcriber.cancelDownload": "Cancel download",+ "settings.transcriber.deleteModel": "Delete {model}",+ "settings.transcriber.deleteModelHint": "Delete the downloaded model",+ "settings.transcriber.download": "Download",+ "settings.transcriber.downloadFirstHint": "Download it first",+ "settings.transcriber.engineMissing": "Transcription engine not found in this dev build",+ "settings.transcriber.language": "Language",+ "settings.transcriber.languageAuto": "Auto-detect",+ "settings.transcriber.languageEnglish": "English",+ "settings.transcriber.locate": "Locate...",+ "settings.transcriber.locateFilter": "Program",+ "settings.transcriber.locateTitle": "Locate whisper-cli",+ "settings.transcriber.models": "Models",+ "settings.transcriber.modelsHelp": "Bigger models transcribe better and slower. English-only variants beat the multilingual ones at the same size when the audio is English. The selected model is what Auto captions uses. Everything runs locally - nothing leaves this machine.",+ "settings.transcriber.useModel": "Use {model}",+ "settings.transcriber.useModelHint": "Use this model"+}