Merge pull request #92 from poli0981/claude/v0.26.0

feat(v0.26.0): lazy-load locale bundles per language
This commit is contained in:
poli0981 authored and GitHub committed 2026-06-12 07:55:15 +07:00
commit c02464cafb
25 files changed
+401 -86

No files matched your search

+22
View File
@@ -2,6 +2,28 @@
All notable changes to YTDescGen ship as tagged releases on `main`.
## v0.26.0 — 2026-06-11
Performance release: locale bundles are now lazy-loaded per language, so
visitors only download the languages they actually use. **Main chunk drops
594.0 → 264.0 kB minified (204.3 → 82.0 kB gzip)** — back under Rollup's
500 kB warning threshold (outstanding since ~v0.23) and the project's
bundle budget. No feature changes.
### Changed
- **Lazy-loaded locale bundles** ([src/i18n/index.ts](src/i18n/index.ts)) — the 10 non-English locale JSONs (5 languages × `ui`/`templates`) left the main chunk and are fetched on first use as Vite async chunks (~27–40 kB min / ~12–17 kB gzip each) via [`i18next-resources-to-backend`](https://github.com/i18next/i18next-resources-to-backend) + a statically-analysable dynamic `import()`. English stays eagerly bundled (`partialBundledLanguages`): it is the `fallbackLng` and the engine's bilingual `tEn` translator, both of which must work synchronously.
- **Generation is gated on bundle readiness** — `getFixedT` for an unloaded language silently serves English fallback strings, which would have let the Output page auto-save a *wrong-language history entry*. A new [`useLanguagesReady`](src/hooks/use-languages-ready.ts) hook holds every reactive generator (output preview, multi-language tabs, social captions, playlist, pinned-comment template, title variants) on a placeholder until the bundle is in memory, and the Batch / Social bulk handlers `await ensureLanguagesLoaded(selectedLangs)` before their multi-language loops.
- **Cold-start preload** ([src/main.tsx](src/main.tsx)) — the persisted UI + output languages are fetched before first paint (capped at 2 s), so a non-English user never sees an English flash; `react: { useSuspense: false }` keeps lazily-ready namespaces from suspending the app shell, which has no Suspense boundary.
- **Failure degrades, never hangs** — a locale chunk that cannot be fetched (offline, stale deploy HTML) is retried once by importing the chunk directly into the resource store (i18next marks a failed language permanently and both `loadLanguages` and `reloadResources` skip it forever after), then logged to the in-app Log page, and the UI falls back to English.
### Under the hood
- **+4 tests (490 → 494)** — [tests/i18n/lazy-locales.test.ts](tests/i18n/lazy-locales.test.ts) pins the contract: `en` available synchronously at import, non-English absent until `ensureLanguagesLoaded`, real strings served after, idempotent reloads.
- [src/utils/platform.ts](src/utils/platform.ts) — `IS_TAURI` now guards `typeof window`, keeping the i18n module importable in vitest's node environment.
- Adding a language no longer touches `src/i18n/index.ts` imports — drop `ui.json`/`templates.json` into `locales/<code>/` and register the code in `SUPPORTED_LANGUAGES` ([docs/I18N.md](docs/I18N.md) checklist simplified).
- Five manifests bumped 0.25.0 → 0.26.0.
## v0.25.0 — 2026-06-10
Adds 41 content warnings, including two new groups — **Dialogue / Language**
+3 -1
View File
@@ -278,6 +278,8 @@ i18n/locales/
**Adding a new language** = 2 JSON files + 1 line registration. See docs/I18N.md.
**Lazy loading (v0.26+)**: only English is bundled into the main chunk — it is the `fallbackLng` and the engine's bilingual `tEn` translator, both of which must resolve synchronously. Every other language is fetched on first use as a Vite async chunk via `i18next-resources-to-backend` + dynamic `import()`. Generation paths gate on bundle readiness (`useLanguagesReady` hook / `ensureLanguagesLoaded`): an unloaded language would otherwise silently render English fallback output. A chunk that fails to fetch degrades to English and logs to the in-app Log page — it never hangs the UI.
**UI language vs Output language**: These are independent. User can browse the app in English but generate descriptions in Japanese. UI language follows `SettingsStore.defaultLanguage`, output language follows `EditorStore.language`.
## 5. Desktop Packaging (Tauri)
@@ -313,7 +315,7 @@ Tauri advantages over Electron:
| What | How to Extend | Files to Touch |
|------|--------------|----------------|
| New language | Add `locales/{code}/ui.json` + `templates.json`, register in `i18n/index.ts` | 3 files |
| New language | Add `locales/{code}/ui.json` + `templates.json`, register in `SUPPORTED_LANGUAGES` (lazy-loaded automatically) | 3 files |
| New genre | Add entry to `config/genres.ts`, add tag pool to `engine/tag-generator.ts` | 2 files |
| New video type | Add to `config/video-types.ts`, add patterns to all `templates.json` | 1 + N locale files |
| New platform/store | Add entry to `config/platforms.ts` | 1 file |
+4
View File
@@ -130,6 +130,10 @@ Disable corporate VPNs / proxies that block the npm registry. The lock file is c
Locale JSON is bundled at build time, not watched. Restart the dev server after editing `src/i18n/locales/*`.
Since v0.26, only English ships in the main chunk; the other languages are
lazy-loaded async chunks fetched on first use (see `src/i18n/index.ts` and
docs/I18N.md). The restart advice above still applies to all of them.
### Pre-commit hook fails on `validate:locales` but I didn't touch locales
You probably added a new key to `_schema.json` indirectly via the engine types (`src/engine/types.ts` → `CONTENT_WARNINGS`). New IDs require translations in all 6 locales.
+10 -12
View File
@@ -17,7 +17,7 @@ These are independent: a Vietnamese user can browse the app in Vietnamese (UI) w
```
src/i18n/
├── index.ts # i18next initialization + language registration
├── index.ts # i18next init + SUPPORTED_LANGUAGES (en eager, others lazy-loaded)
├── locales/
│ ├── _schema.json # JSON Schema defining all required keys
│ ├── en/
@@ -206,25 +206,23 @@ cp -r src/i18n/locales/en src/i18n/locales/es
### Step 4: Register the language
```typescript
// src/i18n/index.ts — add to SUPPORTED_LANGUAGES
// src/i18n/index.ts — add to SUPPORTED_LANGUAGES (the only registration step)
export const SUPPORTED_LANGUAGES = [
{ id: "en", label: "English", flag: "🇬🇧", nativeName: "English" },
{ id: "vi", label: "Vietnamese", flag: "🇻🇳", nativeName: "Tiếng Việt" },
{ id: "ja", label: "Japanese", flag: "🇯🇵", nativeName: "日本語" },
{ id: "es", label: "Spanish", flag: "🇪🇸", nativeName: "Español" }, // ← Add here
] as const;
// Add resource import
import esUI from "./locales/es/ui.json";
import esTemplates from "./locales/es/templates.json";
// Add to i18next resources
resources: {
// ...existing
es: { ui: esUI, templates: esTemplates },
}
```
No import or `resources` edits needed (v0.26+): locales are lazy-loaded
through a dynamic `import("./locales/<code>/<ns>.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: Add multilingual tag pool
```typescript
+4
View File
@@ -132,6 +132,10 @@ Tắt VPN/proxy doanh nghiệp chặn npm registry. Lock file đã commit; insta
Locale JSON bundle vào lúc build, không được watch. Restart dev server sau khi sửa `src/i18n/locales/*`.
Từ v0.26, chỉ tiếng Anh nằm trong main chunk; các ngôn ngữ khác là async
chunk lazy-load, tải khi dùng lần đầu (xem `src/i18n/index.ts` và
docs/I18N.md). Lời khuyên restart ở trên vẫn áp dụng cho tất cả.
### Pre-commit hook fail ở `validate:locales` mà mình không động đến locale
Có thể bạn vô tình thêm key mới vào `_schema.json` thông qua `src/engine/types.ts` → `CONTENT_WARNINGS`. ID mới cần dịch ở cả 6 locale.
+12 -2
View File
@@ -1,12 +1,12 @@
{
"name": "yt-desc-gen",
"version": "0.25.0",
"version": "0.26.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "yt-desc-gen",
"version": "0.25.0",
"version": "0.26.0",
"license": "Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.11.0",
@@ -16,6 +16,7 @@
"@tauri-apps/plugin-shell": "^2.0.0",
"clsx": "^2.1.0",
"i18next": "^23.15.0",
"i18next-resources-to-backend": "^1.2.1",
"lucide-react": "^0.400.0",
"react": "^18.3.0",
"react-dom": "^18.3.0",
@@ -3943,6 +3944,15 @@
"@babel/runtime": "^7.23.2"
}
},
"node_modules/i18next-resources-to-backend": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/i18next-resources-to-backend/-/i18next-resources-to-backend-1.2.1.tgz",
"integrity": "sha512-okHbVA+HZ7n1/76MsfhPqDou0fptl2dAlhRDu2ideXloRRduzHsqDOznJBef+R3DFZnbvWoBW+KxJ7fnFjd6Yw==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.23.2"
}
},
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "yt-desc-gen",
"version": "0.25.0",
"version": "0.26.0",
"private": true,
"license": "Apache-2.0",
"type": "module",
@@ -30,6 +30,7 @@
"@tauri-apps/plugin-shell": "^2.0.0",
"clsx": "^2.1.0",
"i18next": "^23.15.0",
"i18next-resources-to-backend": "^1.2.1",
"lucide-react": "^0.400.0",
"react": "^18.3.0",
"react-dom": "^18.3.0",
+1 -1
View File
@@ -5535,7 +5535,7 @@ dependencies = [
[[package]]
name = "yt-desc-gen"
version = "0.25.0"
version = "0.26.0"
dependencies = [
"tauri",
"tauri-build",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "yt-desc-gen"
version = "0.25.0"
version = "0.26.0"
description = "YouTube Gameplay Description Generator"
authors = ["poli0981"]
edition = "2021"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-cli/schema.json",
"productName": "YTDescGen",
"version": "0.25.0",
"version": "0.26.0",
"identifier": "com.skullmute.ytdescgen",
"build": {
"beforeBuildCommand": "npm run build",
+8 -1
View File
@@ -4,6 +4,7 @@ import i18n from "i18next";
import { useEditorStore } from "@store/editor-store";
import { useSettingsStore } from "@store/settings-store";
import { useCurrentGeneratorInput } from "@hooks/use-current-generator-input";
import { useLanguagesReady } from "@hooks/use-languages-ready";
import { buildPinnedComment } from "@engine/pinned-comment-builder";
import { GENRES } from "@config/genres";
import type { Genre } from "@engine/types";
@@ -40,8 +41,13 @@ export function OutputExtras() {
return map;
}, [t]);
// Lazy-loaded locales (v0.26): the OutputPage flow normally has this
// language loaded already, but the component is standalone by design —
// gate it rather than rely on the page.
const ready = useLanguagesReady([input.language]);
const templateText = useMemo(() => {
if (!showPinnedCommentTemplate) return "";
if (!ready || !showPinnedCommentTemplate) return "";
const tFn = i18n.getFixedT(input.language, "templates");
return buildPinnedComment(input, tFn, {
includeAskNextGame,
@@ -50,6 +56,7 @@ export function OutputExtras() {
genreLabels,
});
}, [
ready,
showPinnedCommentTemplate,
input,
includeAskNextGame,
+7 -1
View File
@@ -5,6 +5,7 @@ import { Modal } from "@components/ui/Modal";
import { CopyButton } from "./CopyButton";
import { CharCounter } from "./CharCounter";
import { buildTitleVariants } from "@engine/title-variants";
import { useLanguagesReady } from "@hooks/use-languages-ready";
import { useEditorStore } from "@store/editor-store";
import { useSettingsStore } from "@store/settings-store";
import { YT_LIMITS, type GeneratorInput } from "@engine/types";
@@ -24,8 +25,12 @@ export function VariantPicker({ open, onClose }: VariantPickerProps) {
const state = useEditorStore();
const showQualityBadge = useSettingsStore((s) => s.showQualityBadge);
// Lazy-loaded locales (v0.26): only request the bundle while the modal
// is actually open; the list fills in on the ready flip.
const ready = useLanguagesReady(open ? [state.language] : []);
const variants = useMemo(() => {
if (!open) return [];
if (!open || !ready) return [];
const input: GeneratorInput = {
videoType: state.videoType,
language: state.language,
@@ -52,6 +57,7 @@ export function VariantPicker({ open, onClose }: VariantPickerProps) {
return buildTitleVariants(input, tFn, showQualityBadge);
}, [
open,
ready,
showQualityBadge,
state.videoType,
state.language,
+15
View File
@@ -836,6 +836,21 @@ export interface GeneratorOutput {
warnings: CharLimitWarning[];
}
/**
* Pending/placeholder output rendered while a locale bundle is still being
* fetched (v0.26 lazy-loaded locales). `title === ""` doubles as the gate
* for OutputPage's history-save effect, so no wrong-language entry can be
* recorded from a not-yet-loaded translator.
*/
export const EMPTY_GENERATOR_OUTPUT: GeneratorOutput = {
title: "",
description: "",
tags: [],
tagString: "",
charCounts: { title: 0, description: 0, tags: 0 },
warnings: [],
};
export interface CharLimitWarning {
field: "title" | "description" | "tags";
current: number;
+26 -16
View File
@@ -2,8 +2,9 @@ import { useMemo } from "react";
import i18n from "i18next";
import { useSettingsStore } from "@store/settings-store";
import { renderAll } from "@engine/template-renderer";
import type { GeneratorOutput } from "@engine/types";
import { EMPTY_GENERATOR_OUTPUT, type GeneratorOutput } from "@engine/types";
import { useCurrentGeneratorInput } from "./use-current-generator-input";
import { useLanguagesReady } from "./use-languages-ready";
export function useGeneratedOutput(): GeneratorOutput {
const input = useCurrentGeneratorInput();
@@ -21,29 +22,38 @@ export function useGeneratedOutput(): GeneratorOutput {
titleFormat,
} = useSettingsStore();
// Lazy-loaded locales (v0.26): block generation until the output
// language's bundle is in memory — getFixedT would otherwise silently
// render English, and OutputPage would save that as a history entry.
const ready = useLanguagesReady([input.language]);
const t = useMemo(() => i18n.getFixedT(input.language, "templates"), [input.language]);
// Always-English `t` for the v0.11 bilingual content-warning block.
// Built once per render so the engine receives a stable function ref;
// the engine falls back to `t` when this is undefined.
// the engine falls back to `t` when this is undefined. `en` is eagerly
// bundled, so it never needs the readiness gate.
const tEn = useMemo(() => i18n.getFixedT("en", "templates"), []);
return useMemo(
() =>
renderAll(input, t, {
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
tEn,
}),
!ready
? EMPTY_GENERATOR_OUTPUT
: renderAll(input, t, {
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
tEn,
}),
[
ready,
input,
t,
tEn,
+47
View File
@@ -0,0 +1,47 @@
import { useEffect, useMemo, useState } from "react";
import { ensureLanguagesLoaded, hasLanguageBundles } from "@i18n/index";
import type { SupportedLanguage } from "@engine/types";
/**
* Returns true once every requested language has its locale bundles in
* memory (v0.26 lazy-loaded locales). Until then the caller must render a
* pending placeholder instead of generating — an unloaded language would
* otherwise silently produce English fallback output.
*
* Resolves to true even when a bundle fails to fetch (offline, stale
* deploy): `ensureLanguagesLoaded` logs the failure and the app degrades
* to English rather than hanging the UI.
*/
export function useLanguagesReady(
langs: readonly SupportedLanguage[],
): boolean {
const joined = langs.join(",");
// Stable identity for the requested set — callers pass fresh array
// literals on every render.
const key = useMemo(
() => [...new Set(joined ? joined.split(",") : [])].sort().join(","),
[joined],
);
const [readyKey, setReadyKey] = useState<string | null>(() =>
langs.every(hasLanguageBundles) ? key : null,
);
useEffect(() => {
const wanted = (key ? key.split(",") : []) as SupportedLanguage[];
if (wanted.every(hasLanguageBundles)) {
setReadyKey(key);
return;
}
let cancelled = false;
void ensureLanguagesLoaded(wanted).finally(() => {
if (!cancelled) setReadyKey(key);
});
return () => {
cancelled = true;
};
}, [key]);
// Comparing against the current key means a late resolve for a
// superseded language set can never mark the new set ready.
return readyKey === key;
}
+7
View File
@@ -4,11 +4,16 @@ import { useSettingsStore } from "@store/settings-store";
import { renderAll } from "@engine/template-renderer";
import type { GeneratorOutput, SupportedLanguage } from "@engine/types";
import { useCurrentGeneratorInput } from "./use-current-generator-input";
import { useLanguagesReady } from "./use-languages-ready";
export function useMultilangOutput(
languages: SupportedLanguage[],
): Record<string, GeneratorOutput> {
const baseInput = useCurrentGeneratorInput();
// Lazy-loaded locales (v0.26): all-or-nothing gate — OutputPage already
// renders nothing for an absent tab entry, and the per-language chunks
// load in parallel, so partial results aren't worth the complexity.
const ready = useLanguagesReady(languages);
const {
includeMultilingualTags,
includeTrendingTags,
@@ -23,6 +28,7 @@ export function useMultilangOutput(
return useMemo(() => {
const results: Record<string, GeneratorOutput> = {};
if (!ready) return results;
for (const lang of languages) {
const tFn = i18n.getFixedT(lang, "templates");
const input = { ...baseInput, language: lang };
@@ -40,6 +46,7 @@ export function useMultilangOutput(
}
return results;
}, [
ready,
languages,
baseInput,
includeMultilingualTags,
+13 -6
View File
@@ -8,6 +8,7 @@ import {
import { SOCIAL_PLATFORMS } from "@config/social-platforms";
import type { SupportedLanguage } from "@engine/types";
import { useCurrentGeneratorInput } from "./use-current-generator-input";
import { useLanguagesReady } from "./use-languages-ready";
/**
* Memoised editor-state → cross-post captions hook (v0.24.0). Mirrors
@@ -22,6 +23,10 @@ export function useSocialPosts(
const input = useCurrentGeneratorInput(languageOverride);
const { showCopyright, showSponsorCredit } = useSettingsStore();
// Lazy-loaded locales (v0.26): no caption until the output language's
// bundle is in memory — SocialPage renders nothing for an empty record.
const ready = useLanguagesReady([input.language]);
const t = useMemo(
() => i18n.getFixedT(input.language, "templates"),
[input.language],
@@ -32,11 +37,13 @@ export function useSocialPosts(
return useMemo(
() =>
buildAllSocialPosts(input, t, SOCIAL_PLATFORMS, {
showCopyright,
showSponsorCredit,
tEn,
}),
[input, t, tEn, showCopyright, showSponsorCredit],
!ready
? {}
: buildAllSocialPosts(input, t, SOCIAL_PLATFORMS, {
showCopyright,
showSponsorCredit,
tEn,
}),
[ready, input, t, tEn, showCopyright, showSponsorCredit],
);
}
+80 -26
View File
@@ -1,18 +1,11 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import resourcesToBackend from "i18next-resources-to-backend";
import type { SupportedLanguage } from "@engine/types";
import { logger } from "@utils/logger";
import enUI from "./locales/en/ui.json";
import enTemplates from "./locales/en/templates.json";
import viUI from "./locales/vi/ui.json";
import viTemplates from "./locales/vi/templates.json";
import jaUI from "./locales/ja/ui.json";
import jaTemplates from "./locales/ja/templates.json";
import esUI from "./locales/es/ui.json";
import esTemplates from "./locales/es/templates.json";
import koUI from "./locales/ko/ui.json";
import koTemplates from "./locales/ko/templates.json";
import zhUI from "./locales/zh/ui.json";
import zhTemplates from "./locales/zh/templates.json";
export const SUPPORTED_LANGUAGES = [
{ id: "en", label: "English", flag: "🇬🇧", nativeName: "English" },
@@ -23,21 +16,82 @@ export const SUPPORTED_LANGUAGES = [
{ id: "zh", label: "Chinese", flag: "🇨🇳", nativeName: "简体中文" },
] as const;
i18n.use(initReactI18next).init({
resources: {
en: { ui: enUI, templates: enTemplates },
vi: { ui: viUI, templates: viTemplates },
ja: { ui: jaUI, templates: jaTemplates },
es: { ui: esUI, templates: esTemplates },
ko: { ui: koUI, templates: koTemplates },
zh: { ui: zhUI, templates: zhTemplates },
},
ns: ["ui", "templates"],
defaultNS: "ui",
fallbackLng: "en",
interpolation: {
escapeValue: false,
},
});
i18n
.use(initReactI18next)
.use(
// Vite statically analyses this template literal and emits one async
// chunk per locale JSON, fetched on first use. `en` is also statically
// imported above, so Rollup keeps it in the main chunk — and i18next
// never asks the backend for it because bundled namespaces are served
// from `resources` (see `partialBundledLanguages`).
resourcesToBackend(
(lng: string, ns: string) => import(`./locales/${lng}/${ns}.json`),
),
)
.init({
resources: { en: { ui: enUI, templates: enTemplates } },
partialBundledLanguages: true,
ns: ["ui", "templates"],
defaultNS: "ui",
fallbackLng: "en",
interpolation: {
escapeValue: false,
},
react: {
// react-i18next defaults this to true; with lazily-loaded bundles an
// unready namespace would suspend Header/AppShell, which sit outside
// every Suspense boundary. Readiness is handled explicitly instead
// (useLanguagesReady / ensureLanguagesLoaded).
useSuspense: false,
},
});
const NAMESPACES = ["ui", "templates"] as const;
/** Both bundles for a language are in memory. */
export function hasLanguageBundles(lang: string): boolean {
return NAMESPACES.every((ns) => i18n.hasResourceBundle(lang, ns));
}
/**
* Resolve once every requested language has its `ui` + `templates` bundles
* in memory — the contract every `getFixedT` call site relies on, since
* i18next silently serves English fallback strings for unloaded languages.
*
* Never rejects: a language whose chunk cannot be fetched (offline, stale
* deploy HTML) is logged and left to the `fallbackLng` English degrade.
*/
export async function ensureLanguagesLoaded(
langs: readonly SupportedLanguage[],
): Promise<void> {
const wanted = [...new Set(langs)].filter((l) => !hasLanguageBundles(l));
if (wanted.length === 0) return;
await i18n.loadLanguages(wanted);
// A failed fetch leaves the connector state at -1, and BOTH loadLanguages
// and reloadResources skip state<0 entries forever after — one transient
// blip would otherwise pin the whole session to English. Retry once by
// importing the chunk directly and feeding the store (public API; the
// template literal matches the backend loader's, so no extra chunks).
const failed: SupportedLanguage[] = [];
for (const lng of wanted.filter((l) => !hasLanguageBundles(l))) {
for (const ns of NAMESPACES) {
if (i18n.hasResourceBundle(lng, ns)) continue;
try {
const mod = (await import(`./locales/${lng}/${ns}.json`)) as {
default: Record<string, unknown>;
};
i18n.addResourceBundle(lng, ns, mod.default);
} catch {
if (!failed.includes(lng)) failed.push(lng);
}
}
}
if (failed.length > 0) {
logger.warn(
"i18n",
`Locale bundle load failed: ${failed.join(", ")} — falling back to English`,
);
}
}
export default i18n;
+36 -7
View File
@@ -2,20 +2,49 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { ErrorBoundary } from "./components/ErrorBoundary";
import i18n, { ensureLanguagesLoaded } from "@i18n/index";
import { useSettingsStore } from "@store/settings-store";
import { useEditorStore } from "@store/editor-store";
import "./styles/globals.css";
const root = document.getElementById("root");
if (!root) throw new Error("Root element not found");
/**
* Lazy-loaded locales (v0.26): fetch the persisted UI + output languages
* before first paint so a non-English user never sees an English flash
* (and the Output page never renders a placeholder on cold start).
* zustand persist hydrates synchronously from localStorage, so these
* reads already hold the user's values; Tauri's async settings-file
* rehydrate is bridged later by App's store subscription.
*
* `en` resolves from the eagerly-bundled resources, so English users pay
* zero extra latency. The 2 s race cap means a dead network can delay —
* but never block — first paint; the readiness hooks re-gate after render.
*/
async function preloadLocales(): Promise<void> {
const { appLanguage, defaultOutputLanguage } = useSettingsStore.getState();
const outputLanguage = useEditorStore.getState().language;
await Promise.race([
Promise.all([
i18n.changeLanguage(appLanguage),
ensureLanguagesLoaded([defaultOutputLanguage, outputLanguage]),
]),
new Promise<void>((resolve) => setTimeout(resolve, 2000)),
]).catch(() => undefined);
}
// Top-level safety net. Per-route boundaries in App.tsx catch most
// errors with route-specific labels; this outer one only fires if
// something explodes *before* the router mounts (e.g. i18n init, store
// rehydrate). Without it, a top-level crash still produces a black
// page — defeating the point of per-route boundaries.
createRoot(root).render(
<StrictMode>
<ErrorBoundary label="app">
<App />
</ErrorBoundary>
</StrictMode>,
);
void preloadLocales().finally(() => {
createRoot(root).render(
<StrictMode>
<ErrorBoundary label="app">
<App />
</ErrorBoundary>
</StrictMode>,
);
});
+20 -3
View File
@@ -8,7 +8,7 @@ import { CopyButton } from "@components/output/CopyButton";
import { CharCounter } from "@components/output/CharCounter";
import { useEditorStore } from "@store/editor-store";
import { useSettingsStore } from "@store/settings-store";
import { SUPPORTED_LANGUAGES } from "@i18n/index";
import { SUPPORTED_LANGUAGES, ensureLanguagesLoaded } from "@i18n/index";
import { renderAll } from "@engine/template-renderer";
import { buildPinnedComment } from "@engine/pinned-comment-builder";
import { YT_LIMITS } from "@engine/types";
@@ -51,6 +51,7 @@ export function BatchPage() {
const [endPart, setEndPart] = useState("5");
const [selectedLangs, setSelectedLangs] = useState<SupportedLanguage[]>([state.language]);
const [results, setResults] = useState<BatchResult[]>([]);
const [generating, setGenerating] = useState(false);
const toggleLang = (lang: SupportedLanguage) => {
setSelectedLangs((prev) => {
@@ -61,7 +62,7 @@ export function BatchPage() {
});
};
const handleGenerate = () => {
const generate = () => {
const start = parseInt(startPart) || 1;
const end = parseInt(endPart) || start;
const outputs: BatchResult[] = [];
@@ -105,6 +106,19 @@ export function BatchPage() {
setResults(outputs);
};
const handleGenerate = async () => {
setGenerating(true);
try {
// Lazy-loaded locales (v0.26): batch generates across multiple
// languages in one pass — every selected bundle must be in memory
// before the loop, or getFixedT silently renders English.
await ensureLanguagesLoaded(selectedLangs);
generate();
} finally {
setGenerating(false);
}
};
const allCombined = useMemo(
() =>
results
@@ -162,7 +176,10 @@ export function BatchPage() {
value={endPart}
onChange={(e) => setEndPart(e.target.value)}
/>
<Button onClick={handleGenerate} disabled={!state.gameName}>
<Button
onClick={() => void handleGenerate()}
disabled={!state.gameName || generating}
>
{t("batch.generateBatch")}
</Button>
</div>
+7 -1
View File
@@ -10,6 +10,7 @@ import { Select } from "@components/ui/Select";
import { CopyButton } from "@components/output/CopyButton";
import { useEditorStore } from "@store/editor-store";
import { SUPPORTED_LANGUAGES } from "@i18n/index";
import { useLanguagesReady } from "@hooks/use-languages-ready";
import {
buildPlaylistTitle,
buildPlaylistDescription,
@@ -66,13 +67,18 @@ export function PlaylistPage() {
[editor.gameName, editor.channelName, status, contentType, totalVideos, editor.storeLinks, customNote],
);
// Lazy-loaded locales (v0.26): the dropdown can pick a language whose
// bundle isn't fetched yet — hold the placeholder until it is.
const ready = useLanguagesReady([language]);
const output = useMemo(() => {
if (!ready) return { title: "", description: "" };
const tFn = i18n.getFixedT(language, "templates");
return {
title: buildPlaylistTitle(playlistInput, tFn),
description: buildPlaylistDescription(playlistInput, tFn),
};
}, [playlistInput, language]);
}, [ready, playlistInput, language]);
return (
<div className="mx-auto flex max-w-5xl flex-col gap-6 p-6 lg:flex-row">
+23 -4
View File
@@ -9,7 +9,7 @@ import { CopyButton } from "@components/output/CopyButton";
import { CharCounter } from "@components/output/CharCounter";
import { useEditorStore } from "@store/editor-store";
import { useSettingsStore } from "@store/settings-store";
import { SUPPORTED_LANGUAGES } from "@i18n/index";
import { SUPPORTED_LANGUAGES, ensureLanguagesLoaded } from "@i18n/index";
import { SOCIAL_PLATFORMS } from "@config/social-platforms";
import { useSocialPosts } from "@hooks/use-social-posts";
import {
@@ -73,6 +73,7 @@ export function SocialPage() {
language,
]);
const [bulkResults, setBulkResults] = useState<BulkRow[]>([]);
const [generating, setGenerating] = useState(false);
// Import display (read-only)
const [imported, setImported] = useState<SocialExportBundle | null>(null);
@@ -140,14 +141,16 @@ export function SocialPage() {
});
};
const handleBulkGenerate = () => {
const bulkGenerate = () => {
const start = parseInt(startPart) || 1;
const end = parseInt(endPart) || start;
const rows: BulkRow[] = [];
// Loop-invariant English translator for the bilingual content-warnings
// block — `en` is eagerly bundled, so it needs no readiness gate.
const tEn = i18n.getFixedT("en", "templates");
for (let i = start; i <= Math.min(end, start + 99); i++) {
for (const lang of selectedLangs) {
const tFn = i18n.getFixedT(lang, "templates");
const tEn = i18n.getFixedT("en", "templates");
const input = {
...baseInput,
videoType: "part" as const,
@@ -169,6 +172,19 @@ export function SocialPage() {
setBulkResults(rows);
};
const handleBulkGenerate = async () => {
setGenerating(true);
try {
// Lazy-loaded locales (v0.26): bulk generates across multiple
// languages in one pass — every selected bundle must be in memory
// before the loop, or getFixedT silently renders English.
await ensureLanguagesLoaded(selectedLangs);
bulkGenerate();
} finally {
setGenerating(false);
}
};
const bulkCombined = useMemo(
() =>
bulkResults
@@ -373,7 +389,10 @@ export function SocialPage() {
value={endPart}
onChange={(e) => setEndPart(e.target.value)}
/>
<Button onClick={handleBulkGenerate} disabled={!gameName}>
<Button
onClick={() => void handleBulkGenerate()}
disabled={!gameName || generating}
>
{t("common.generate")}
</Button>
</div>
+4 -1
View File
@@ -1 +1,4 @@
export const IS_TAURI = "__TAURI_INTERNALS__" in window;
// The `typeof` guard keeps this module importable outside a browser
// context (vitest's node environment) — no `window` means no Tauri.
export const IS_TAURI =
typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
+47
View File
@@ -0,0 +1,47 @@
import { describe, it, expect } from "vitest";
import i18n, { ensureLanguagesLoaded } from "@i18n/index";
import viTemplates from "../../src/i18n/locales/vi/templates.json";
/**
* v0.26 lazy-loaded locales: `en` ships in the main bundle (the engine's
* bilingual `tEn` fallback must work synchronously), every other language
* is fetched on demand via dynamic import. These tests pin both halves of
* that contract against the real i18next singleton.
*
* Order matters: the "not bundled at import time" assertion must run
* before anything calls `ensureLanguagesLoaded(["vi"])`.
*/
describe("lazy locale loading", () => {
it("bundles en eagerly and synchronously", () => {
expect(i18n.isInitialized).toBe(true);
expect(i18n.hasResourceBundle("en", "ui")).toBe(true);
expect(i18n.hasResourceBundle("en", "templates")).toBe(true);
expect(i18n.getFixedT("en", "templates")("title.suffix")).toBe(
"Gameplay No Commentary",
);
});
it("does not bundle non-English languages at import time", () => {
expect(i18n.hasResourceBundle("vi", "ui")).toBe(false);
expect(i18n.hasResourceBundle("vi", "templates")).toBe(false);
});
it("loads a language on demand and serves its real strings", async () => {
await ensureLanguagesLoaded(["vi"]);
expect(i18n.hasResourceBundle("vi", "ui")).toBe(true);
expect(i18n.hasResourceBundle("vi", "templates")).toBe(true);
const t = i18n.getFixedT("vi", "templates");
// Compare against the JSON on disk, not a hardcoded copy, so locale
// edits can't silently invalidate the test.
expect(t("title.videoType.part", { partNumber: "2" })).toBe(
viTemplates.title.videoType.part.replace("{{partNumber}}", "2"),
);
});
it("is idempotent for already-loaded and bundled languages", async () => {
await expect(
ensureLanguagesLoaded(["vi", "en"]),
).resolves.toBeUndefined();
expect(i18n.hasResourceBundle("vi", "templates")).toBe(true);
});
});
+1 -1
View File
@@ -26,7 +26,7 @@ export default defineConfig({
manualChunks: {
react: ["react", "react-dom"],
router: ["react-router-dom"],
i18n: ["i18next", "react-i18next"],
i18n: ["i18next", "react-i18next", "i18next-resources-to-backend"],
},
},
},