Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(web): keep the Japanese catalog out of the PWA app shell

tianma-iff06f9d3a6c0d
diff --git a/apps/web/src/i18n/index.test.mjs b/apps/web/src/i18n/index.test.mjs
new file mode 100644
index 00000000..b5c33e19
--- /dev/null
+++ b/apps/web/src/i18n/index.test.mjs
@@ -0,0 +1,28 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+
+const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8");
+const mainSource = readFileSync(new URL("../main.tsx", import.meta.url), "utf8");
+const mobileEditorSource = readFileSync(new URL("../mobile-edit.tsx", import.meta.url), "utf8");
+const viteConfig = readFileSync(new URL("../../vite.config.ts", import.meta.url), "utf8");
+
+describe("lazy Japanese catalog", () => {
+ test("does not statically import Japanese into the app-shell i18n bundle", () => {
+ expect(source).not.toContain('import { ja } from "./resources/ja"');
+ expect(source).toContain('await import("./resources/ja")');
+ expect(source).toContain("partialBundledLanguages: true");
+ expect(source).toContain("export const bootstrapI18n");
+ });
+
+ test("loads Japanese before the web and mobile editor shells render", () => {
+ expect(mainSource).toContain("await bootstrapI18n()");
+ expect(mobileEditorSource).toContain("void bootstrapI18n().then(() => {");
+ });
+
+ test("keeps the Japanese chunk out of PWA precache and HTML modulepreload", () => {
+ expect(viteConfig).toContain('"**/i18n-ja-*.js"');
+ expect(viteConfig).toContain("name: \"i18n-ja\"");
+ expect(viteConfig).toContain("edgeever-optional-locales");
+ expect(viteConfig).toContain("i18n-ja-");
+ });
+});
diff --git a/apps/web/src/i18n/index.ts b/apps/web/src/i18n/index.ts
index 22c7e7e4..2a4a3106 100644
--- a/apps/web/src/i18n/index.ts
+++ b/apps/web/src/i18n/index.ts
@@ -11,7 +11,6 @@ import {
type SupportedLocale,
} from "./locales";
import { enUS } from "./resources/en-US";
-import { ja } from "./resources/ja";
import { zhCN } from "./resources/zh-CN";
export {
@@ -26,17 +25,26 @@ export {
export const resources = {
"zh-CN": { translation: zhCN },
"en-US": { translation: enUS },
- ja: { translation: ja },
} as const;
+const ensureLocaleCatalog = async (locale: SupportedLocale) => {
+ if (locale !== "ja" || i18n.hasResourceBundle("ja", "translation")) {
+ return;
+ }
+
+ const { ja } = await import("./resources/ja");
+ i18n.addResourceBundle("ja", "translation", ja, true, true);
+};
+
void i18n.use(initReactI18next).init({
resources,
- lng: getInitialLocale(),
+ lng: getInitialLocale() === "ja" ? "en-US" : getInitialLocale(),
fallbackLng: {
ja: ["en-US"],
default: [defaultLocale],
},
supportedLngs: supportedLocales,
+ partialBundledLanguages: true,
interpolation: {
escapeValue: false,
},
@@ -53,15 +61,28 @@ i18n.on("languageChanged", (locale) => {
document.documentElement.lang = i18n.resolvedLanguage ?? i18n.language ?? defaultLocale;
-export const changeAppLocale = (locale: SupportedLocale) => {
+export const bootstrapI18n = async () => {
+ const locale = getInitialLocale();
+ if (locale !== "ja") {
+ return;
+ }
+
+ await ensureLocaleCatalog(locale);
+ await i18n.changeLanguage(locale);
+};
+
+export const changeAppLocale = async (locale: SupportedLocale) => {
writeStoredLocale(locale);
+ await ensureLocaleCatalog(locale);
return i18n.changeLanguage(locale);
};
-export const changeAppLocalePreference = (preference: AppLocalePreference) => {
+export const changeAppLocalePreference = async (preference: AppLocalePreference) => {
if (preference === "system") {
clearStoredLocale();
- return i18n.changeLanguage(getBrowserLocale() ?? defaultLocale);
+ const locale = getBrowserLocale() ?? defaultLocale;
+ await ensureLocaleCatalog(locale);
+ return i18n.changeLanguage(locale);
}
return changeAppLocale(preference);
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index 5a3473ae..9a17691a 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -4,7 +4,7 @@ import { createRoot } from "react-dom/client";
import { BrowserRouter, HashRouter } from "react-router";
import { registerSW } from "virtual:pwa-register";
import { App } from "./app/App";
-import "./i18n";
+import { bootstrapI18n } from "./i18n";
import { emitPwaUpdateNotice } from "./lib/pwa-update-notice";
import { withEnvironmentTitlePrefix } from "./lib/environment-title";
import { initializeTheme, ThemeProvider } from "./components/ThemeProvider";
@@ -136,6 +136,7 @@ const mountApp = () => {
};
const bootstrap = async () => {
+ await bootstrapI18n();
if (import.meta.env.DEV) {
const reloading = await clearDevelopmentPwaState();
if (reloading) {
diff --git a/apps/web/src/mobile-edit.tsx b/apps/web/src/mobile-edit.tsx
index 0b1bdcf6..556faa94 100644
--- a/apps/web/src/mobile-edit.tsx
+++ b/apps/web/src/mobile-edit.tsx
@@ -3,8 +3,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRoot } from "react-dom/client";
import { MobileStandaloneTiptapEditor } from "@/components/MobileStandaloneTiptapEditor";
import { initializeTheme } from "@/components/ThemeProvider";
+import { bootstrapI18n } from "@/i18n";
import { defaultLocale, getBrowserLocale } from "@/i18n/locales";
-import "./i18n";
import "./styles/mobile-markdown-editor.css";
declare global {
@@ -93,12 +93,14 @@ const MobileEditorApp = () => {
);
};
-createRoot(root, {
- onUncaughtError(error, errorInfo) {
- console.error("Uncaught mobile editor error", error, errorInfo.componentStack);
- },
-}).render(
- <React.StrictMode>
- <MobileEditorApp />
- </React.StrictMode>
-);
+void bootstrapI18n().then(() => {
+ createRoot(root, {
+ onUncaughtError(error, errorInfo) {
+ console.error("Uncaught mobile editor error", error, errorInfo.componentStack);
+ },
+ }).render(
+ <React.StrictMode>
+ <MobileEditorApp />
+ </React.StrictMode>
+ );
+});
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 70bdc27c..1b40a1c1 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -199,6 +199,9 @@ export default defineConfig({
// Keep its runtime out of the install-time app-shell precache and cache
// it after first use instead.
"**/vendor~pdf-*.js",
+ // Japanese is a first-class locale but is loaded on demand so Chinese
+ // and English PWA installs do not pay for that catalog up front.
+ "**/i18n-ja-*.js",
],
navigateFallback: null,
navigationPreload: true,
@@ -233,6 +236,17 @@ export default defineConfig({
},
},
},
+ {
+ urlPattern: ({ url }) => /\/assets\/i18n-ja-/.test(url.pathname),
+ handler: "CacheFirst",
+ options: {
+ cacheName: "edgeever-optional-locales",
+ expiration: {
+ maxEntries: 8,
+ maxAgeSeconds: 60 * 60 * 24 * 30,
+ },
+ },
+ },
{
urlPattern: ({ url }) => /\/assets\/(?:.*beautiful-mermaid|vendor-mermaid|.*mermaid\.core|.*Diagram-|vendor-x6|vendor-codemirror)/.test(url.pathname),
handler: "CacheFirst",
@@ -292,7 +306,7 @@ export default defineConfig({
? false
: {
resolveDependencies: (_filename, dependencies) => dependencies.filter((dependency) =>
- !/(?:vendor-code-highlight|vendor-(?:mermaid|D3|tiptap|prosemirror|floating|codemirror|x6|zod)|vendor-radix(?!-slot)|ui-primitives|ui-button-tooltip)/.test(dependency),
+ !/(?:vendor-code-highlight|vendor-(?:mermaid|D3|tiptap|prosemirror|floating|codemirror|x6|zod)|vendor-radix(?!-slot)|ui-primitives|ui-button-tooltip|i18n-ja-)/.test(dependency),
),
},
rolldownOptions: {
@@ -324,6 +338,11 @@ export default defineConfig({
// the regular extension group so plain mobile code blocks do not
// inherit the highlighter as a startup dependency.
},
+ {
+ name: "i18n-ja",
+ test: /[\\/]i18n[\\/](?:resources[\\/])?ja\.ts$/,
+ priority: 41,
+ },
{
name: "vendor-react",
test: /node_modules[\\/](react|react-dom|scheduler|react-router)[\\/]/,
diff --git a/scripts/verify-web-performance.mjs b/scripts/verify-web-performance.mjs
index 0dcc6505..2e42480b 100644
--- a/scripts/verify-web-performance.mjs
+++ b/scripts/verify-web-performance.mjs
@@ -10,6 +10,7 @@ assert.match(serviceWorker, /edgeever-resource-blobs/, "PWA must provide a runti
assert.match(serviceWorker, /CacheFirst/, "PWA resource bytes must use a cache-first runtime strategy");
assert.match(serviceWorker, /edgeever-app-shell/, "PWA navigation must use a dedicated app-shell runtime cache");
assert.match(serviceWorker, /edgeever-optional-pdf/, "PWA must cache the optional PDF runtime after first use");
+assert.match(serviceWorker, /edgeever-optional-locales/, "PWA must cache the Japanese catalog after first use");
assert.match(serviceWorker, /NetworkFirst/, "PWA navigation must prefer the current deployment over cached HTML");
assert.match(serviceWorker, /PrecacheFallbackPlugin/, "PWA navigation must retain an offline app-shell fallback");
assert.doesNotMatch(serviceWorker, /NavigationRoute/, "PWA navigation must not always serve the precached HTML shell");
@@ -25,6 +26,7 @@ assert.match(precacheManifest, /index\.html\?edgeever-offline-shell=/, "PWA must
const optionalDiagramPattern = /(?:beautiful-mermaid|vendor-mermaid|mermaid\.core|vendor-x6|vendor-codemirror|[^"']*Diagram(?:EditorPane)?-)[^"']*\.js/;
assert.doesNotMatch(precacheManifest, optionalDiagramPattern, "Optional diagram chunks must remain out of the initial PWA precache");
assert.doesNotMatch(precacheManifest, /vendor~pdf-[^"']*\.js/, "Optional PDF.js runtime must remain out of the initial PWA precache");
+assert.doesNotMatch(precacheManifest, /i18n-ja-[^"']*\.js/, "Japanese catalog must remain out of the initial PWA precache");
assert.doesNotMatch(precacheManifest, /noto-sans-sc-[^"']*\.woff2/, "Print-only Noto Sans SC shards must remain out of the PWA precache");
const precacheURLs = [...precacheManifest.matchAll(/\{url:"([^"]+)"/g)].map((match) => match[1]);