# Internationalization Guide (i18n) ## YTDescGen — Adding & Managing Languages --- ## Overview YTDescGen has **two independent language contexts**: 1. **UI Language** — the app interface (buttons, labels, tooltips). Stored as `appLanguage` in the settings store (`src/store/settings-store.ts`); changed from the top bar, Settings or the command palette. Affects how the app _looks_. 2. **Output Language** — the generated title/description/tags. Stored as `language` in the editor store (`src/store/editor-store.ts`), per draft; a new draft starts in **Settings › Default Output Language**. Affects what the app _produces_. The Output page, Batch and Social can also render several output languages at once. These are independent: a Vietnamese user can browse the app in Vietnamese (UI) while generating descriptions in Japanese (output). Both defaults follow the browser's language when it is one of the eight, otherwise English. ## Locales (8) | Code | Language | Authoring | | ------- | -------------------- | ----------------------------------------------------- | | `en` | English | Source locale; the only one bundled in the main chunk | | `vi` | Vietnamese | Reviewed by the maintainer, a native speaker | | `ja` | Japanese | AI-translated, not native-reviewed | | `es` | Spanish | AI-translated, not native-reviewed | | `ko` | Korean | AI-translated, not native-reviewed | | `zh` | Chinese (Simplified) | AI-translated, not native-reviewed | | `pt-BR` | Portuguese (Brazil) | AI-translated, not native-reviewed | | `id` | Indonesian | AI-translated, not native-reviewed | The authoring status of each locale is recorded in [DISCLAIMER.md](../DISCLAIMER.md). ## Two Namespaces | Namespace | File | Holds | Rendered in | | ----------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------- | | `ui` | `ui.json` | Everything the interface shows | the UI language | | `templates` | `templates.json` | Everything the engine writes: title patterns, description blocks, rig labels (`description.rigLabels`), timestamp keywords (`timeline.keywords`), pinned comments, playlist copy, hashtags | the output language | **Rule: generated text lives in `templates.json`.** A sentence or label the engine writes into a title, description or caption is looked up in `templates.json`, in the output language, through the `t` the engine is given (`i18n.getFixedT(language, "templates")`, see `src/hooks/use-generated-output.ts`) — it is never typed into `src/engine/`. v1.0.0 moved the rig labels there (`description.rigLabels.*`); they used to print as English field names in every language. What stays in code is per-language data that isn't a sentence: - the tag pools `CORE_TAGS_BY_LANG` and `MULTILINGUAL_TAGS` in `src/engine/tag-generator.ts` (search terms), and - the patterns in `src/engine/channel-phrase.ts` that remove the words going with an empty channel name ("on", "trên kênh", "による"…). Both are typed `Record`, so a new language is a compile error until it has an entry — see Steps 5 and 6. ## File Structure ``` src/i18n/ ├── index.ts # i18next init + SUPPORTED_LANGUAGES (en eager, others lazy-loaded) └── locales/ ├── _schema.json # Every required key, per namespace ├── en/ │ ├── ui.json # UI strings (buttons, labels, errors, tooltips) │ └── templates.json # Generated content (titles, description blocks, …) ├── vi/ ├── ja/ ├── es/ ├── ko/ ├── zh/ ├── pt-BR/ └── id/ # Each with the same ui.json + templates.json ``` `_schema.json` lists, for each object path in each namespace, the keys it must contain — an excerpt: ```json { "ui": { "sidebar": ["expand", "collapse"] }, "templates": { "title.separators": ["emDash", "hyphen", "colon", "pipe"] } } ``` Adding or removing a key means editing `_schema.json` **and** all 8 locales. ## Adding a New Language — Checklist The examples use French (`fr`), one of the locales on the [roadmap](./ROADMAP.md). ### Step 1: Create locale files ```bash # Generate empty locale from the English source npm run generate:locale -- --lang fr # This creates: # src/i18n/locales/fr/ui.json (all keys, empty values) # src/i18n/locales/fr/templates.json (all keys, empty values) # Prefer editing in place over working from blanks? Pre-fill with English: npm run generate:locale -- --lang fr --copy-english # Overwrite an existing locale directory: npm run generate:locale -- --lang fr --force ``` The output is key-for-key identical to English, so `npm run validate:locales` passes the moment the files are written — it checks key parity, not whether the values were actually translated. Or copy from English and translate: ```bash cp -r src/i18n/locales/en src/i18n/locales/fr ``` ### Step 2: Translate ui.json What a finished file looks like — an excerpt of `src/i18n/locales/es/ui.json` (locale files are plain JSON: no comments, no trailing commas): ```json { "tabs": { "editor": "Editor", "output": "Resultado", "profiles": "Perfiles", "history": "Historial", "settings": "Ajustes", "batch": "Lote", "social": "Redes", "playlist": "Playlist", "logs": "Registros", "about": "Acerca de", "reportBug": "Reportar bug" }, "output": { "title": "Título", "description": "Descripción", "tags": "Etiquetas", "copyTitle": "Copiar Título", "copyAll": "Copiar Todo", "copied": "¡Copiado!", "charCount": "{{count}}/{{limit}}" } } ``` ### Step 3: Translate templates.json An excerpt of `src/i18n/locales/es/templates.json`: ```json { "title": { "separator": " — ", "suffix": "Gameplay No Commentary", "videoType": { "full": "", "part": "Parte {{partNumber}}", "boss": "{{bossName}} Pelea de Jefe", "dlc": "{{dlcName}} DLC" } }, "description": { "intro": { "full": "Este video presenta el gameplay completo de {{gameName}} en {{channelName}}.", "part": "Este video presenta la Parte {{partNumber}} de {{gameName}} en {{channelName}}." }, "noCommentaryLine": "Sin Comentarios — gameplay puro para tu disfrute.", "sections": { "timestamps": "⏱ MARCAS DE TIEMPO", "rig": "💻 MI EQUIPO", "cta": "👍 Me gusta | 🔔 Suscríbete | ↗️ Comparte" }, "rigLabels": { "cpu": "CPU", "gpu": "GPU", "os": "Sistema Operativo" } }, "timeline": { "keywords": { "chapter": "Capítulo {{n}}", "boss": "Jefe {{n}}", "final_boss": "Jefe Final", "credits": "Créditos" } } } ``` - Keep every `{{variable}}` exactly as it is; only the text around it is translated. - Sentences that name the channel (`{{channelName}}`) must still read naturally when the channel phrase is removed — see Step 5. - Don't use i18next plural suffixes (`_one`, `_other`, …). Languages need different plural forms, so the key sets would differ between locales and `validate:locales` would fail. Write count-neutral text instead (`"{{n}} damaged item(s) skipped"`). ### Step 4: Register the language Registering a locale touches several files, and two of them fail **silently** if missed. `tests/i18n/locale-registration.test.ts` guards the picker list against the locale folders on disk, in both directions. ```typescript // 1. src/engine/types.ts — the union the whole engine is typed against export type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh" | "pt-BR" | "id" | "fr"; // 2. src/i18n/index.ts — every language picker shows `nativeName (id)`. // `flag` is no longer displayed, but the registration test requires it. export const SUPPORTED_LANGUAGES = [ // … { id: "fr", label: "French", flag: "🇫🇷", nativeName: "Français" }, ] as const satisfies readonly { id: SupportedLanguage; label: string; flag: string; nativeName: string; }[]; // 3. src/store/settings-heal.ts — detectBrowserLanguage's own copy of the list. // Bare codes go in `supported`, region-qualified ones (like "pt-BR") in `REGIONAL`. // Miss this and the language works, but is never auto-selected for a // first-time visitor whose browser is set to it. const supported: SupportedLanguage[] = ["en", "vi", "ja", "es", "ko", "zh", "id", "fr"]; // 4. src/engine/tag-generator.ts — CORE_TAGS_BY_LANG + MULTILINGUAL_TAGS (Step 6) // 5. src/engine/channel-phrase.ts — DROP + FALLBACK (Step 5) ``` The `satisfies` clause makes an id that isn't in the union a compile error. Items 4 and 5 are `Record`, so TypeScript catches those too once the union has the new code. Two more places, outside `src/`: - **`worker/gate-i18n.ts`** — the Turnstile gate page, the first screen every web visitor sees, has its own copy of the languages: add the code to `GateLang`, its strings to `GATE_STRINGS`, and its `Accept-Language` prefix to `PREFIX_TO_LANG`. `GateLang` is not tied to `SupportedLanguage`, so a miss is **silent** — those visitors get the gate page in English. Update `tests/worker/gate-i18n.test.ts` too; it pins the list of gate languages. - **`DISCLAIMER.md`** (and `docs/i18n/vi/DISCLAIMER.md`) — add the locale to the translation-quality table. Optional: if the new locale is human-reviewed, add it to `TRANSLATION_TRUSTED` in `src/engine/description-builder.ts` so it doesn't get the AI-translation note, and update `description.translationQuality.intro` (which names the reviewed languages) in every locale. `npm run generate:locale` prints a shorter checklist on success; the list above is the complete one. No import or `resources` edits needed (v0.26+): locales are lazy-loaded through a dynamic `import("./locales//.json")`, so Vite picks the new files up automatically as async chunks — **the file names must stay exactly `ui.json` and `templates.json`**. Only English is eagerly bundled (it's the `fallbackLng` and the engine's bilingual `tEn` source); don't add static imports for other languages, that would drag them back into the main chunk. ### Step 5: Channel-phrase patterns Without a channel name, sentences such as "…of Hades on {{channelName}}." must not end in "on ." (fixed in v1.0.0). The engine renders `{{channelName}}` as a placeholder, then removes the words that go with it, per language: ```typescript // src/engine/channel-phrase.ts const DROP: Record = { // … "pt-BR": [new RegExp(`\\s+no ${S}`, "g")], // "…de Hades no {{channelName}}." → "…de Hades." }; /** For a sentence shape none of the patterns covers: a neutral stand-in. */ const FALLBACK: Record = { // … "pt-BR": "este canal", }; ``` Write the patterns for the phrases your `templates.json` actually uses. Then add the code to `LANGS` in `tests/engine/channel-phrase.test.ts`: it renders every template that names the channel with an empty channel and fails on any leftover. ### Step 6: Tag pools ```typescript // src/engine/tag-generator.ts export const CORE_TAGS_BY_LANG: Record string[]> = { // … "pt-BR": (g) => [ `${g} gameplay`, `${g} sem comentários`, "gameplay sem comentários", `${g} detonado`, `${g} jogo completo`, `${g} gameplay sem comentarios`, ], }; export const MULTILINGUAL_TAGS: Record string[]> = { // … "pt-BR": (g) => [`${g} português`, `${g} em português`, "gameplay em português"], }; ``` Core tags come right after the game name in the tag list; multilingual tags are added when **Settings › Include Multilingual Tags** is on, for the output language only. Tags longer than 30 characters are dropped, and the registration test checks that each language's core tags use the game name. ### Step 7: Check the font The bundled Inter font covers Latin (including Vietnamese), Cyrillic and Greek. Other scripts use the system fonts in `--font-sans-stack` (`src/styles/globals.css`), which already lists Noto Sans JP / KR / SC for CJK — add a fallback there if the new language uses another script. ### Step 8: Validate ```bash npm run validate:locales # Checks all locale files have the same keys as _schema.json # Reports missing/extra keys per language ``` ### Step 9: Test ```bash npm run test:run -- tests/i18n tests/engine/channel-phrase.test.ts tests/engine/tag-generator.test.ts tests/worker/gate-i18n.test.ts # Then the whole suite and the type check npm run test:run npm run typecheck && npm run typecheck:all ``` ## Locale Validation Script The `scripts/validate-locales.ts` script checks every locale folder against `_schema.json`. At v1.3.0 (1,264 UI + 584 template keys per locale): ``` ✓ en/ui.json — 1264/1264 keys ✓ en/templates.json — 584/584 keys ✓ es/ui.json — 1264/1264 keys ✓ es/templates.json — 584/584 keys … ✓ zh/templates.json — 584/584 keys All locale files are complete! ``` A gap fails the run and names the keys: ``` ✗ fr/ui.json — 1245/1247 keys Missing: editor.quick.nextPart, editor.quick.newVideo ``` ## Template Interpolation Templates use `{{variable}}` syntax (i18next default): ```json "intro": "This video features the full gameplay of {{gameName}} on {{channelName}}." ``` The engine gets a `t` fixed to the output language and passes the variables: ```typescript // src/hooks/use-generated-output.ts const t = i18n.getFixedT(input.language, "templates"); // src/engine/description-builder.ts const intro = t(`description.intro.${input.videoType}`, { gameName, channelName: channelOrSlot(input.channelName), // a placeholder when there is no channel partNumber: input.partNumber ?? "", // … }); sections.push(withoutEmptyChannel(intro, input.language)); ``` ## RTL Language Support (Arabic) Not supported yet. Arabic (`ar`) would need `dir="rtl"` on `` — set next to `lang`, which `src/main.tsx` updates on every `languageChanged` — and a right-to-left pass over the layout. ## Contributing Translations Community members can contribute translations by: 1. Fork the repository 2. Run `npm run generate:locale -- --lang {code}` (or copy `src/i18n/locales/en/` to `src/i18n/locales/{code}/`) 3. Translate all strings in both files 4. Register the language (Step 4 above) 5. Run `npm run validate:locales` and the tests in Step 9 6. Submit a PR with the new locale files Native-speaker corrections to the AI-translated locales are the most welcome contribution of all. `src/i18n/locales//*.json` can be edited straight from GitHub's web UI; see [CONTRIBUTING.md](../CONTRIBUTING.md).