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): defer optional locale and UI startup dependencies (#770)

tianma-if4235f3f2f1f6
diff --git a/apps/web/src/i18n/index.test.mjs b/apps/web/src/i18n/index.test.mjs
index 8cfd66cf..b26bec22 100644
--- a/apps/web/src/i18n/index.test.mjs
+++ b/apps/web/src/i18n/index.test.mjs
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8");
const mainSource = readFileSync(new URL("../main.tsx", import.meta.url), "utf8");
@@ -23,7 +24,7 @@ describe("lazy Japanese catalog", () => {
expect(viteConfig).toContain("globPatterns: []");
expect(viteConfig).toContain("name: \"i18n-ja\"");
expect(viteConfig).toContain("edgeever-optional-locales");
- expect(viteConfig).toContain("i18n-(?:ja|pl|ru)-");
+ expect(viteConfig).toContain("i18n-(?:en-US|ja|pl|ru)-");
});
test("loads Polish on demand like Japanese", () => {
@@ -38,3 +39,30 @@ describe("lazy Japanese catalog", () => {
expect(viteConfig).toContain("name: \"i18n-ru\"");
});
});
+
+
+describe("optional English catalog", () => {
+ test("loads the selected locale and English fallback before rendering", () => {
+ for (const locale of ["en-US", "ja", "pl", "ru", "zh-CN"]) {
+ const result = spawnSync(process.execPath, ["-e", `
+ import assert from "node:assert/strict";
+ globalThis.document = { documentElement: { lang: "" } };
+ globalThis.window = { localStorage: {
+ getItem: (key) => key === "edgeever.locale.preference" ? ${JSON.stringify(locale)} : null,
+ setItem() {}, removeItem() {},
+ } };
+ const { default: i18n, bootstrapI18n, changeAppLocale } = await import(${JSON.stringify(new URL("./index.ts", import.meta.url).pathname)});
+ await bootstrapI18n();
+ assert.equal(i18n.language, ${JSON.stringify(locale)});
+ assert.notEqual(i18n.t("common.save"), "common.save");
+ if (${JSON.stringify(locale)} !== "zh-CN") assert.ok(i18n.hasResourceBundle("en-US", "translation"));
+ await changeAppLocale("en-US");
+ assert.equal(i18n.t("common.save"), "Save");
+ await changeAppLocale("zh-CN");
+ assert.equal(i18n.t("common.save"), "保存");
+ `], { encoding: "utf8" });
+ expect(result.stderr).toBe("");
+ expect(result.status).toBe(0);
+ }
+ });
+});
diff --git a/apps/web/src/i18n/index.ts b/apps/web/src/i18n/index.ts
index a78e6c02..7feb79ec 100644
--- a/apps/web/src/i18n/index.ts
+++ b/apps/web/src/i18n/index.ts
@@ -10,7 +10,6 @@ import {
type AppLocalePreference,
type SupportedLocale,
} from "./locales";
-import { enUS } from "./resources/en-US";
import { zhCN } from "./resources/zh-CN";
export {
@@ -24,15 +23,17 @@ export {
export const resources = {
"zh-CN": { translation: zhCN },
- "en-US": { translation: enUS },
} as const;
type OptionalLocale = Exclude<SupportedLocale, keyof typeof resources>;
const isOptionalLocale = (locale: SupportedLocale): locale is OptionalLocale =>
- locale === "ja" || locale === "pl" || locale === "ru";
+ locale === "en-US" || locale === "ja" || locale === "pl" || locale === "ru";
const loadOptionalCatalog = async (locale: OptionalLocale) => {
+ if (locale === "en-US") {
+ return (await import("./resources/en-US")).enUS;
+ }
if (locale === "ja") {
return (await import("./resources/ja")).ja;
}
@@ -47,12 +48,15 @@ const ensureLocaleCatalog = async (locale: SupportedLocale) => {
return;
}
+ if (locale !== "en-US") {
+ await ensureLocaleCatalog("en-US");
+ }
i18n.addResourceBundle(locale, "translation", await loadOptionalCatalog(locale), true, true);
};
void i18n.use(initReactI18next).init({
resources,
- lng: isOptionalLocale(getInitialLocale()) ? "en-US" : getInitialLocale(),
+ lng: isOptionalLocale(getInitialLocale()) ? defaultLocale : getInitialLocale(),
fallbackLng: {
ja: ["en-US"],
pl: ["en-US"],
diff --git a/apps/web/src/lib/error-screen-copy.ts b/apps/web/src/lib/error-screen-copy.ts
index 3c154be7..64ccaf02 100644
--- a/apps/web/src/lib/error-screen-copy.ts
+++ b/apps/web/src/lib/error-screen-copy.ts
@@ -1,7 +1,7 @@
import i18n, { type i18n as I18n } from "i18next";
-import { enUS } from "@edgeever/shared/i18n/en-US";
+import { errorScreensEnUS } from "@edgeever/shared/i18n/error-screens-en-US";
-export type ErrorScreenKey = keyof typeof enUS.errorScreens;
+export type ErrorScreenKey = keyof typeof errorScreensEnUS;
/**
* Text for screens shown after a render failure. They can appear before
@@ -11,5 +11,5 @@ export type ErrorScreenKey = keyof typeof enUS.errorScreens;
export const errorScreenText = (key: ErrorScreenKey, instance: I18n = i18n): string => {
const path = `errorScreens.${key}`;
const text = instance.isInitialized ? instance.t(path) : "";
- return text && text !== path ? text : enUS.errorScreens[key];
+ return text && text !== path ? text : errorScreensEnUS[key];
};
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 11658278..96f0d7b1 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -226,7 +226,7 @@ export default defineConfig({
},
},
{
- urlPattern: ({ url }) => /\/assets\/i18n-(?:ja|pl|ru)-/.test(url.pathname),
+ urlPattern: ({ url }) => /\/assets\/i18n-(?:en-US|ja|pl|ru)-/.test(url.pathname),
handler: "CacheFirst",
options: {
cacheName: "edgeever-optional-locales",
@@ -297,7 +297,7 @@ export default defineConfig({
? false
: {
resolveDependencies: (_filename, dependencies) => dependencies.filter((dependency) =>
- !/(?:vendor-code-highlight|vendor-(?:mermaid|D3|tiptap|prosemirror|floating|codemirror|x6|infographic|zod|streamdown)|vendor~(?:wasm|emacs-lisp)-|vendor-radix(?!-slot)|ui-primitives|ui-button-tooltip|i18n-(?:ja|pl|ru)-)/.test(dependency),
+ !/(?:vendor-code-highlight|vendor-(?:mermaid|D3|tiptap|prosemirror|floating|codemirror|x6|infographic|zod|streamdown)|vendor~(?:wasm|emacs-lisp)-|vendor-radix(?!-slot)|ui-primitives|ui-button-tooltip|i18n-(?:en-US|ja|pl|ru)-)/.test(dependency),
),
},
rolldownOptions: {
@@ -342,6 +342,11 @@ export default defineConfig({
// the regular extension group so plain mobile code blocks do not
// inherit the highlighter as a startup dependency.
},
+ {
+ name: "i18n-en-US",
+ test: /[\\/]i18n[\\/](?:resources[\\/])?en-US\.ts$/,
+ priority: 41,
+ },
{
name: "i18n-ja",
test: /[\\/]i18n[\\/](?:resources[\\/])?ja\.ts$/,
@@ -436,6 +441,7 @@ export default defineConfig({
name: "vendor-floating",
test: /node_modules[\\/](@floating-ui|tippy\.js)[\\/]/,
priority: 28,
+ entriesAware: true,
},
{
name: "vendor-query",
@@ -474,6 +480,7 @@ export default defineConfig({
name: "vendor-radix",
test: /node_modules[\\/](@radix-ui|cmdk|vaul)[\\/]/,
priority: 15,
+ entriesAware: true,
},
{
name: "vendor-ui-utils",
@@ -514,9 +521,11 @@ export default defineConfig({
priority: 12,
},
{
+ // Shell tooltips must not pull every lazy screen's UI into startup.
name: "ui-primitives",
test: /src[\\/]components[\\/]ui[\\/]/,
priority: 10,
+ entriesAware: true,
},
{
name: "vendor",
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 959de69d..1e03cbd0 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -18,6 +18,7 @@
"./image-gallery-editing": "./src/image-gallery-editing.ts",
"./native-image-gallery": "./src/native-image-gallery.ts",
"./i18n": "./src/i18n/index.ts",
+ "./i18n/error-screens-en-US": "./src/i18n/error-screens-en-US.ts",
"./i18n/en-US": "./src/i18n/en-US.ts",
"./i18n/zh-CN": "./src/i18n/zh-CN.ts",
"./i18n/ja": "./src/i18n/ja.ts",
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 3dd64d20..373c9747 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -1,3 +1,4 @@
+import { errorScreensEnUS } from "./error-screens-en-US";
import { noteImportEnUS } from "./note-import";
import { memoTemplateSeedTranslations } from "../memo-template-seeds";
@@ -457,28 +458,8 @@ export const enUS = {
process: "Thinking",
trace: "Run · {{count}} steps",
},
- errorScreens: {
- noteTitle: "This note cannot be displayed",
- noteBody: "The failure was isolated to this note. The note list and the rest of the app remain available. Choose another note or retry this one.",
- backToNoteList: "Back to note list",
- retryNote: "Retry this note",
- safeModeTitle: "Safe startup mode is active",
- safeModeBody: "EdgeEver did not reopen the note that failed last time. Choose another note from the list to continue; safe mode will then turn off automatically.",
- pageTitle: "EdgeEver encountered a page error",
- pageRecordedBody: "The problem was recorded on this device. Reloading will enter safe startup mode instead of reopening the previous note.",
- pageReloadBody: "A safe reload will avoid reopening the previous note. If the problem persists, check the browser console.",
- reloadSafely: "Reload safely",
- opening: "Opening…",
- reportToGithub: "Report to GitHub",
- aiSidebarTitle: "The AI sidebar cannot open",
- aiSidebarBody: "You can still view and edit your note. Retry the sidebar or close it to continue.",
- retrySidebar: "Retry sidebar",
- close: "Close",
- editorTitle: "The editor encountered an error",
- editorBody: "Your note is safe. Retry the editor or return to the note list.",
- back: "Back",
- retry: "Retry",
- },
+ errorScreens: errorScreensEnUS,
+
common: {
appName: "EdgeEver",
close: "Close",
diff --git a/packages/shared/src/i18n/error-screens-en-US.ts b/packages/shared/src/i18n/error-screens-en-US.ts
new file mode 100644
index 00000000..88cc2449
--- /dev/null
+++ b/packages/shared/src/i18n/error-screens-en-US.ts
@@ -0,0 +1,22 @@
+export const errorScreensEnUS = {
+ noteTitle: "This note cannot be displayed",
+ noteBody: "The failure was isolated to this note. The note list and the rest of the app remain available. Choose another note or retry this one.",
+ backToNoteList: "Back to note list",
+ retryNote: "Retry this note",
+ safeModeTitle: "Safe startup mode is active",
+ safeModeBody: "EdgeEver did not reopen the note that failed last time. Choose another note from the list to continue; safe mode will then turn off automatically.",
+ pageTitle: "EdgeEver encountered a page error",
+ pageRecordedBody: "The problem was recorded on this device. Reloading will enter safe startup mode instead of reopening the previous note.",
+ pageReloadBody: "A safe reload will avoid reopening the previous note. If the problem persists, check the browser console.",
+ reloadSafely: "Reload safely",
+ opening: "Opening…",
+ reportToGithub: "Report to GitHub",
+ aiSidebarTitle: "The AI sidebar cannot open",
+ aiSidebarBody: "You can still view and edit your note. Retry the sidebar or close it to continue.",
+ retrySidebar: "Retry sidebar",
+ close: "Close",
+ editorTitle: "The editor encountered an error",
+ editorBody: "Your note is safe. Retry the editor or return to the note list.",
+ back: "Back",
+ retry: "Retry",
+} as const;
diff --git a/scripts/verify-web-performance.mjs b/scripts/verify-web-performance.mjs
index 90b3e27a..20fdff2a 100644
--- a/scripts/verify-web-performance.mjs
+++ b/scripts/verify-web-performance.mjs
@@ -30,7 +30,7 @@ assert.doesNotMatch(serviceWorker, /edgeever-offline-shell/, "PWA must not retai
const modulePreloads = indexHtml.match(/<link rel="modulepreload"[^>]+>/g)?.join("\n") ?? "";
const initialOptionalPattern = /vendor-code-highlight|vendor-D3|beautiful-mermaid|vendor-(?:mermaid|tiptap|prosemirror|floating|codemirror|x6|infographic|streamdown)|vendor~(?:wasm|emacs-lisp)-|ui-primitives|mermaid\.core|[^"']*Diagram(?:EditorPane)?-/;
assert.doesNotMatch(modulePreloads, initialOptionalPattern, "Optional editor and diagram chunks must remain out of the initial HTML modulepreload list");
-assert.doesNotMatch(modulePreloads, /mathlive-loader|i18n-ja-/, "MathLive and the Japanese catalog must remain deferred");
+assert.doesNotMatch(modulePreloads, /mathlive-loader|i18n-(?:en-US|ja)-/, "MathLive and optional locale catalogs must remain deferred");
assert.doesNotMatch(modulePreloads, /ui-button-tooltip/, "Button tooltips must load only when a titled button is rendered");
assert.doesNotMatch(modulePreloads, /vendor-radix(?!-slot)/, "Radix overlays must remain out of the initial HTML modulepreload list");
const initialModulePreloadBytes = [...indexHtml.matchAll(/<link rel="modulepreload"[^>]+href="([^"]+)"[^>]*>/g)]
@@ -43,7 +43,7 @@ assert.ok(initialModulePreloadBytes <= INITIAL_MODULE_PRELOAD_BUDGET, `Initial m
const startupGraph = readWebStartupGraph(distDirectory);
assert.ok(startupGraph.initialJavaScriptBytes <= 1024 * 1024, `Eager JavaScript exceeds 1 MiB: ${startupGraph.initialJavaScriptBytes}`);
-const eagerOptionalPattern = /(?:^|\/)(?:vendor-(?:code-highlight|beautiful-mermaid|mermaid|tiptap|prosemirror|codemirror|x6|infographic|streamdown)|i18n-(?:ja|pl|ru)-|(?:WorkspaceApp|EditorPane|DiagramEditorPane|PosterEditorPane|TableEditorPane|InfographicEditorPane)-)/;
+const eagerOptionalPattern = /(?:^|\/)(?:vendor-(?:code-highlight|beautiful-mermaid|mermaid|tiptap|prosemirror|codemirror|x6|infographic|streamdown)|i18n-(?:en-US|ja|pl|ru)-|(?:WorkspaceApp|EditorPane|DiagramEditorPane|PosterEditorPane|TableEditorPane|InfographicEditorPane)-)/;
assert.ok(!startupGraph.initialJavaScriptFiles.some(file => eagerOptionalPattern.test(file)), "Optional editors and locales must remain outside the actual startup module graph");
// Optional fonts must remain downloads, even when the desktop installer packages all Web files.