diff --git a/apps/website/README.md b/apps/website/README.md
index f69967340a2..20d91ac7aa2 100644
--- a/apps/website/README.md
+++ b/apps/website/README.md
@@ -56,6 +56,21 @@ composer because the site renders locales concurrently. Missing messages fall
back to English. The catalog test compiles every message and checks that each
eligible English message has Chinese copy.
+The build renders every locale, but in production a browser loads only English and
+the page's own `` catalog. `LocaleCatalogPreloads.astro` declares
+those catalogs in the layout `
` so they download in parallel with the
+page, and a client-side navigation into another locale loads that catalog
+before the page swaps. A component in the browser can render English or its
+page's locale; calling `translationsFor` with any other locale throws. A new
+layout that hosts islands should include `LocaleCatalogPreloads`. `BaseLayout`
+registers catalog preparation before `ClientRouter`, so navigation also waits
+when it starts before the island modules load. If an initial catalog request
+fails or exceeds ten seconds, the browser retries with its bundled catalog
+chunk. Failed navigation loads use a full-page retry; a superseded navigation
+cancels its catalog fetch. Catalog links persist only when their locale and
+build URL match, and navigation consumes each catalog without repeating its
+preload request.
+
`main.json` is the catalog for each locale. Keep feature copy grouped under a
nested feature key.
diff --git a/apps/website/e2e/locale-catalogs.spec.ts b/apps/website/e2e/locale-catalogs.spec.ts
new file mode 100644
index 00000000000..f53275af3c5
--- /dev/null
+++ b/apps/website/e2e/locale-catalogs.spec.ts
@@ -0,0 +1,497 @@
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+import { expect } from '@playwright/test'
+
+import { websiteRoot } from '@website/paths'
+
+import en from '@/locales/en/main.json' with { type: 'json' }
+import ja from '@/locales/ja/main.json' with { type: 'json' }
+import zhCN from '@/locales/zh-CN/main.json' with { type: 'json' }
+import { test } from './fixtures/blockExternalMedia'
+import { expectIslandHydrated, waitForIsland } from './fixtures/islands'
+
+const copyOnlyIn = {
+ en: en.footer.location,
+ 'zh-CN': zhCN.footer.location,
+ ja: ja.auth.confirmPassword.label
+}
+
+test.describe('Locale catalogs', () => {
+ for (const { path, loaded } of [
+ { path: '/', loaded: ['en'] },
+ { path: '/zh-CN/', loaded: ['en', 'zh-CN'] },
+ { path: '/ja/', loaded: ['en', 'ja'] },
+ { path: '/enterprise-msa/', loaded: ['en'] },
+ { path: '/affiliates/terms/', loaded: ['en'] }
+ ]) {
+ test(`${path} downloads only the ${loaded.join(' and ')} catalogs`, async ({
+ page
+ }) => {
+ const assetRequests: string[] = []
+ page.on('request', (request) => assetRequests.push(request.url()))
+ await page.goto(path)
+ await expectIslandHydrated(
+ page,
+ page.getByRole('navigation', { name: 'Main navigation' })
+ )
+
+ const downloaded = await page.evaluate(
+ async ({ copies, requests }) => {
+ const assets = requests
+ .map((name) => new URL(name))
+ .filter(
+ (url) =>
+ url.origin === location.origin &&
+ /^\/_website\/.*\.(js|json)$/.test(url.pathname)
+ )
+ const sources = await Promise.all(
+ [...new Set(assets.map((url) => url.href))].map(async (href) => ({
+ href,
+ source: await (await fetch(href)).text()
+ }))
+ )
+ return Object.entries(copies).flatMap(([locale, copy]) =>
+ assets
+ .filter((url) =>
+ sources.some(
+ ({ href, source }) =>
+ href === url.href && source.includes(copy)
+ )
+ )
+ .map((url) => ({ locale, path: url.pathname }))
+ )
+ },
+ { copies: copyOnlyIn, requests: [...assetRequests] }
+ )
+ expect(
+ downloaded.map(({ locale }) => locale),
+ JSON.stringify(downloaded)
+ ).toEqual(loaded)
+ })
+ }
+
+ test('reuses the catalog preload when navigating within a language', async ({
+ page
+ }) => {
+ const catalogRequests: string[] = []
+ page.on('request', (request) => {
+ if (/\/_website\/main\.[^/]+\.json$/.test(request.url()))
+ catalogRequests.push(request.url())
+ })
+ await page.goto('/')
+ const cliLink = page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: 'Comfy CLI', exact: true })
+ await waitForIsland(page, cliLink)
+ const initialRequests = [...catalogRequests]
+
+ await cliLink.click()
+ await expect(page).toHaveURL(/\/cli\/$/)
+ await waitForIsland(page, cliLink)
+
+ expect(catalogRequests).toEqual(initialRequests)
+ })
+
+ test('retains only the incoming language catalog links', async ({ page }) => {
+ const catalogRequests: string[] = []
+ page.on('request', (request) => {
+ if (/\/_website\/main\.[^/]+\.json$/.test(request.url()))
+ catalogRequests.push(request.url())
+ })
+ await page.goto('/zh-CN/')
+ const japaneseLink = page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: '日本語', exact: true })
+ await waitForIsland(page, japaneseLink)
+ const initialRequestCount = catalogRequests.length
+ await japaneseLink.click()
+ await expect(page).toHaveURL(/\/ja\/$/)
+ await waitForIsland(page, japaneseLink)
+
+ await expect(page.locator('link[data-locale-catalog="en"]')).toHaveCount(1)
+ await expect(page.locator('link[data-locale-catalog="ja"]')).toHaveCount(1)
+ await expect(page.locator('link[data-locale-catalog="zh-CN"]')).toHaveCount(
+ 0
+ )
+ expect(catalogRequests.slice(initialRequestCount)).toHaveLength(1)
+ })
+
+ test('replaces a persisted catalog link when the incoming build changes its URL', async ({
+ page,
+ context
+ }) => {
+ await page.goto('/')
+ const englishCatalog = page.locator('link[data-locale-catalog="en"]')
+ const previousHref = await englishCatalog.getAttribute('href')
+ if (!previousHref) throw new Error('Expected an English catalog URL')
+ const nextHref = `${previousHref}?revision=next`
+ const html = readFileSync(
+ join(websiteRoot, 'dist/cli/index.html'),
+ 'utf8'
+ ).replaceAll(previousHref, nextHref)
+ await context.route('**/cli/', (route) =>
+ route.fulfill({ contentType: 'text/html', body: html })
+ )
+ const cliLink = page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: 'Comfy CLI', exact: true })
+ await waitForIsland(page, cliLink)
+ await cliLink.click()
+ await expect(page).toHaveURL(/\/cli\/$/)
+ await waitForIsland(page, cliLink)
+ await expect(englishCatalog).toHaveAttribute('href', nextHref)
+ await expect(englishCatalog).toHaveCount(1)
+ })
+
+ test('a stalled earlier catalog does not block a later language switch', async ({
+ page,
+ context
+ }) => {
+ const catalogRequested = Promise.withResolvers()
+ const releaseCatalog = Promise.withResolvers()
+ const fullNavigations: string[] = []
+ page.on('request', (request) => {
+ if (request.isNavigationRequest())
+ fullNavigations.push(new URL(request.url()).pathname)
+ })
+ await page.goto('/')
+ const footer = page.getByRole('contentinfo')
+ const chineseLink = footer.getByRole('link', {
+ name: '简体中文',
+ exact: true
+ })
+ const japaneseLink = footer.getByRole('link', {
+ name: '日本語',
+ exact: true
+ })
+ await waitForIsland(page, chineseLink)
+ await context.route(
+ /\/_website\/main\.[^/]+\.json$/,
+ async (route) => {
+ catalogRequested.resolve()
+ await releaseCatalog.promise
+ await route.continue()
+ },
+ { times: 1 }
+ )
+ try {
+ await chineseLink.click()
+ await catalogRequested.promise
+ await japaneseLink.click()
+ await expect(page).toHaveURL(/\/ja\/$/)
+ await waitForIsland(page, chineseLink)
+ await chineseLink.click()
+ await expect(page).toHaveURL(/\/zh-CN\/$/)
+ await waitForIsland(page, chineseLink)
+ expect(fullNavigations).toEqual(['/'])
+ } finally {
+ releaseCatalog.resolve()
+ }
+ })
+
+ test('switching language before the locale module starts keeps the new page interactive', async ({
+ page,
+ context
+ }) => {
+ const moduleRequested = Promise.withResolvers()
+ const releaseModule = Promise.withResolvers()
+ const releaseDocument = Promise.withResolvers()
+ const fullNavigations: string[] = []
+ const errors: string[] = []
+ page.on('request', (request) => {
+ if (request.isNavigationRequest()) fullNavigations.push(request.url())
+ })
+ page.on('console', (message) => {
+ if (
+ /catalog|setup function|hydration|t is not a function/i.test(
+ message.text()
+ )
+ )
+ errors.push(message.text())
+ })
+ page.on('pageerror', (error) => errors.push(error.message))
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.addInitScript(() => {
+ document.addEventListener('astro:before-preparation', () => {
+ document.documentElement.dataset.preparationStarted = 'true'
+ })
+ })
+ await context.route(
+ /\/_website\/translations\.[^/]+\.js$/,
+ async (route) => {
+ moduleRequested.resolve()
+ await releaseModule.promise
+ await route.continue()
+ }
+ )
+ await context.route(/\/zh-CN\/cli\/$/, async (route) => {
+ await releaseDocument.promise
+ await route.continue()
+ })
+
+ try {
+ await page.goto('/cli/', { waitUntil: 'commit' })
+ await moduleRequested.promise
+ await page.waitForFunction(() => typeof history.state?.index === 'number')
+ await page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: '简体中文' })
+ .click()
+ await expect(page.locator('html')).toHaveAttribute(
+ 'data-preparation-started',
+ 'true'
+ )
+ releaseModule.resolve()
+ await waitForIsland(
+ page,
+ page.getByRole('button', { name: 'Toggle menu' })
+ )
+ releaseDocument.resolve()
+
+ await expect(page).toHaveURL(/\/zh-CN\/cli\/$/)
+ await expectIslandHydrated(
+ page,
+ page.getByRole('navigation', { name: 'Main navigation' })
+ )
+ expect(errors).toEqual([])
+ const menuButton = page.getByRole('button', { name: '切换菜单' })
+ await waitForIsland(page, menuButton)
+ await menuButton.click()
+ await expect(page.getByRole('dialog', { name: '菜单' })).toBeVisible()
+ expect(errors).toEqual([])
+ expect(fullNavigations.map((url) => new URL(url).pathname)).toEqual([
+ '/cli/'
+ ])
+ } finally {
+ releaseModule.resolve()
+ releaseDocument.resolve()
+ }
+ })
+
+ test('switching language before the first catalog loads keeps the new page interactive', async ({
+ page,
+ context
+ }) => {
+ const releaseCatalogs = Promise.withResolvers()
+ const errors: string[] = []
+ page.on('console', (message) => {
+ if (
+ /catalog|setup function|hydration|t is not a function/i.test(
+ message.text()
+ )
+ )
+ errors.push(message.text())
+ })
+ page.on('pageerror', (error) => errors.push(error.message))
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.addInitScript(() => {
+ document.addEventListener('astro:before-preparation', (event) => {
+ const loadDocument = event.loader
+ event.loader = async () => {
+ await loadDocument()
+ document.documentElement.dataset.documentPrepared = 'true'
+ }
+ })
+ const fetch = window.fetch.bind(window)
+ window.fetch = (...args) => {
+ const [resource] = args
+ if (
+ typeof resource === 'string' &&
+ /\/main\.[^/]+\.json$/.test(resource)
+ )
+ document.documentElement.dataset.catalogRequested = 'true'
+ return fetch(...args)
+ }
+ })
+ await context.route(/\/_website\/main\.[^/]+\.json$/, async (route) => {
+ await releaseCatalogs.promise
+ await route.continue()
+ })
+
+ try {
+ await page.goto('/cli/', { waitUntil: 'commit' })
+ await expect(page.locator('html')).toHaveAttribute(
+ 'data-catalog-requested',
+ 'true'
+ )
+ const switchLanguage = page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: '简体中文' })
+ .click()
+ await expect(page.locator('html')).toHaveAttribute(
+ 'data-document-prepared',
+ 'true'
+ )
+ releaseCatalogs.resolve()
+ await switchLanguage
+
+ await expect(page).toHaveURL(/\/zh-CN\/cli\/$/)
+ const menuButton = page.getByRole('button', { name: '切换菜单' })
+ await expect(menuButton).toBeVisible()
+ await waitForIsland(page, menuButton)
+ await menuButton.click()
+ await expect(page.getByRole('dialog', { name: '菜单' })).toBeVisible()
+ expect(errors).toEqual([])
+ } finally {
+ releaseCatalogs.resolve()
+ }
+ })
+
+ for (const { failure, path, status, button, dialog } of [
+ {
+ failure: 'an HTTP error',
+ path: '/zh-CN/cli/',
+ status: 503,
+ button: '切换菜单',
+ dialog: '菜单'
+ },
+ {
+ failure: 'empty English',
+ path: '/cli/',
+ status: 200,
+ button: 'Toggle menu',
+ dialog: 'Menu'
+ },
+ {
+ failure: 'empty active',
+ path: '/zh-CN/cli/',
+ status: 200,
+ button: '切换菜单',
+ dialog: '菜单'
+ }
+ ]) {
+ test(`${failure} initial catalog recovers through the bundled catalog`, async ({
+ page,
+ context
+ }) => {
+ await page.setViewportSize({ width: 390, height: 844 })
+ await context.route(/\/_website\/main\.[^/]+\.json$/, (route) =>
+ route.fulfill({
+ status,
+ contentType: 'application/json',
+ body: '{}'
+ })
+ )
+
+ await page.goto(path)
+ const menuButton = page.getByRole('button', { name: button })
+ await waitForIsland(page, menuButton)
+ await menuButton.click()
+ await expect(
+ page.getByRole('dialog', { name: dialog, exact: true })
+ ).toBeVisible()
+ })
+ }
+
+ test('a stalled initial catalog recovers through the bundled catalog', async ({
+ page,
+ context
+ }) => {
+ const releaseCatalogs = Promise.withResolvers()
+ await page.setViewportSize({ width: 390, height: 844 })
+ await context.route(/\/_website\/main\.[^/]+\.json$/, async (route) => {
+ await releaseCatalogs.promise
+ await route.continue()
+ })
+ try {
+ await page.goto('/zh-CN/cli/', { waitUntil: 'commit' })
+ const menuButton = page.getByRole('button', { name: '切换菜单' })
+ await expect(async () => {
+ await expectIslandHydrated(page, menuButton)
+ }).toPass({ timeout: 15_000 })
+ await menuButton.click()
+ await expect(
+ page.getByRole('dialog', { name: '菜单', exact: true })
+ ).toBeVisible()
+ } finally {
+ releaseCatalogs.resolve()
+ }
+ })
+
+ test('a timed-out navigation catalog recovers through a full-page retry', async ({
+ page,
+ context
+ }) => {
+ const releaseCatalog = Promise.withResolvers()
+ const fullNavigations: string[] = []
+ page.on('request', (request) => {
+ if (request.isNavigationRequest())
+ fullNavigations.push(new URL(request.url()).pathname)
+ })
+ await page.goto('/cli/')
+ const chineseLink = page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: '简体中文', exact: true })
+ await waitForIsland(page, chineseLink)
+ await context.route(
+ /\/_website\/main\.[^/]+\.json$/,
+ async (route) => {
+ await releaseCatalog.promise
+ await route.continue()
+ },
+ { times: 1 }
+ )
+ try {
+ await chineseLink.click()
+ await expect(page).toHaveURL(/\/zh-CN\/cli\/$/, { timeout: 15_000 })
+ await waitForIsland(page, chineseLink)
+ expect(fullNavigations).toEqual(['/cli/', '/zh-CN/cli/'])
+ await expect(
+ page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: '工作流', exact: true })
+ .first()
+ ).toBeVisible()
+ } finally {
+ releaseCatalog.resolve()
+ }
+ })
+
+ for (const { failure, status, body } of [
+ { failure: 'an HTTP error', status: 503, body: '{}' },
+ { failure: 'an empty catalog', status: 200, body: '{}' },
+ { failure: 'an invalid catalog', status: 200, body: '{"invalid":42}' }
+ ]) {
+ test(`recovers from ${failure} during a language switch`, async ({
+ page,
+ context
+ }) => {
+ const fullNavigations: string[] = []
+ const pageErrors: string[] = []
+ page.on('request', (request) => {
+ if (request.isNavigationRequest()) fullNavigations.push(request.url())
+ })
+ page.on('pageerror', (error) => pageErrors.push(error.message))
+
+ await page.goto('/cli/')
+ const chineseLink = page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: '简体中文' })
+ await waitForIsland(page, chineseLink)
+ await context.route(
+ /\/_website\/main\.[^/]+\.json$/,
+ (route) =>
+ route.fulfill({ status, contentType: 'application/json', body }),
+ { times: 1 }
+ )
+
+ await chineseLink.click()
+
+ await expect(page).toHaveURL(/\/zh-CN\/cli\/$/)
+ await waitForIsland(page, chineseLink)
+ await expect(chineseLink).toHaveAttribute('aria-current', 'page')
+ await expect(
+ page
+ .getByRole('contentinfo')
+ .getByRole('link', { name: '工作流' })
+ .first()
+ ).toBeVisible()
+ expect(fullNavigations.map((url) => new URL(url).pathname)).toEqual([
+ '/cli/',
+ '/zh-CN/cli/'
+ ])
+ expect(pageErrors).toEqual([])
+ })
+ }
+})
diff --git a/apps/website/src/components/common/LocaleCatalogPreloads.astro b/apps/website/src/components/common/LocaleCatalogPreloads.astro
new file mode 100644
index 00000000000..c0e92531c41
--- /dev/null
+++ b/apps/website/src/components/common/LocaleCatalogPreloads.astro
@@ -0,0 +1,26 @@
+---
+import { DEFAULT_LOCALE } from '@/config/locales'
+import type { Locale } from '@/config/locales'
+import en from '@/locales/en/main.json?url'
+import ja from '@/locales/ja/main.json?url'
+import zhCN from '@/locales/zh-CN/main.json?url'
+
+interface Props {
+ locale: Locale
+}
+
+const catalogUrls = { en, 'zh-CN': zhCN, ja } satisfies Record
+const { locale } = Astro.props
+const locales = [...new Set([DEFAULT_LOCALE, locale])]
+---
+
+{locales.map((code) => (
+
+))}
diff --git a/apps/website/src/components/legal/LegalContentSection.vue b/apps/website/src/components/legal/LegalContentSection.vue
index a9df5a09ecb..ebf24465fe5 100644
--- a/apps/website/src/components/legal/LegalContentSection.vue
+++ b/apps/website/src/components/legal/LegalContentSection.vue
@@ -6,8 +6,8 @@ import { computed, ref } from 'vue'
import type { Locale, TranslationKey } from '@/i18n/translations'
import { prefersReducedMotion } from '@/composables/useReducedMotion'
+import { DEFAULT_LOCALE } from '@/config/locales'
import { translationsFor } from '@/i18n/translations'
-import en from '@/locales/en/main.json' with { type: 'json' }
import { scrollTo } from '@/scripts/smoothScroll'
import SafeRichText from '@/components/common/SafeRichTextContent'
@@ -42,7 +42,8 @@ function isMessageGroup(value: unknown): value is MessageGroup {
}
function buildSections(): LegalSection[] {
- const catalog: unknown = en
+ const catalog: unknown =
+ translationsFor(DEFAULT_LOCALE).getLocaleMessage(DEFAULT_LOCALE)
if (!isMessageGroup(catalog) || !isMessageGroup(catalog[prefix])) return []
return Object.entries(catalog[prefix]).flatMap(([id, section]) => {
diff --git a/apps/website/src/config/auth-sign-in-state.ts b/apps/website/src/config/auth-sign-in-state.ts
index d58cc6e2bb1..aa09e590803 100644
--- a/apps/website/src/config/auth-sign-in-state.ts
+++ b/apps/website/src/config/auth-sign-in-state.ts
@@ -13,9 +13,9 @@ import type {
AuthErrorCopy
} from '@comfyorg/account-core/firebaseAuthError'
+import { DEFAULT_LOCALE } from '@/config/locales'
import type { Locale, TranslationKey } from '@/i18n/translations'
import { translationsFor } from '@/i18n/translations'
-import en from '@/locales/en/main.json' with { type: 'json' }
export type AuthSignInProvider = 'google' | 'github' | 'email'
@@ -55,9 +55,9 @@ export type AuthSignInEvent =
const SUPPORT_EMAIL = 'support@comfy.org'
-const authErrorCodes = Object.keys(en.auth.errors).filter(
- (code) => code !== 'generic' && code !== 'signupBlocked'
-)
+const authErrorCodes = Object.keys(
+ translationsFor(DEFAULT_LOCALE).tm('auth.errors')
+).filter((code) => code !== 'generic' && code !== 'signupBlocked')
/** This host's own auth-error table, keyed the way the package resolver reads it. */
function localizedAuthErrorCopy(locale: Locale): AuthErrorCopy {
diff --git a/apps/website/src/config/contentSections.ts b/apps/website/src/config/contentSections.ts
index 0c5faaec523..ebed5b8137a 100644
--- a/apps/website/src/config/contentSections.ts
+++ b/apps/website/src/config/contentSections.ts
@@ -1,4 +1,5 @@
-import en from '@/locales/en/main.json' with { type: 'json' }
+import { DEFAULT_LOCALE } from '@/config/locales'
+import { translationsFor } from '@/i18n/translations'
type BlockType =
| 'paragraph'
@@ -40,7 +41,8 @@ function inferBlockType(block: string | MessageGroup): BlockType {
}
export function deriveSections(prefix: string): SectionConfig[] {
- const catalog: unknown = en
+ const catalog: unknown =
+ translationsFor(DEFAULT_LOCALE).getLocaleMessage(DEFAULT_LOCALE)
if (!isMessageGroup(catalog) || !isMessageGroup(catalog[prefix])) return []
return Object.entries(catalog[prefix]).flatMap(([id, section]) => {
diff --git a/apps/website/src/i18n/translations.test.ts b/apps/website/src/i18n/translations.test.ts
index 449c4928413..e87d011b16d 100644
--- a/apps/website/src/i18n/translations.test.ts
+++ b/apps/website/src/i18n/translations.test.ts
@@ -85,6 +85,10 @@ describe('site translations', () => {
expect(t('tags.partnerNodes')).toBe('Partner Nodes')
})
+ it('preserves intentional empty messages', () => {
+ expect(translationsFor('en').t('gallery.heroTitleAfter')).toBe('')
+ })
+
it.for([
['en', '42 models'],
['zh-CN', '42 个模型'],
diff --git a/apps/website/src/i18n/translations.ts b/apps/website/src/i18n/translations.ts
index c4727c4bb07..0e779490db7 100644
--- a/apps/website/src/i18n/translations.ts
+++ b/apps/website/src/i18n/translations.ts
@@ -1,41 +1,152 @@
import { createI18n } from 'vue-i18n'
-import { DEFAULT_LOCALE } from '@/config/locales'
+import { DEFAULT_LOCALE, LOCALE_CODES, resolveLocale } from '@/config/locales'
import type { Locale } from '@/config/locales'
-import en from '@/locales/en/main.json' with { type: 'json' }
-import ja from '@/locales/ja/main.json' with { type: 'json' }
-import zhCN from '@/locales/zh-CN/main.json' with { type: 'json' }
+import { combineAbortSignals, createTimeoutSignal } from '@/utils/abortSignal'
+
+const catalogLoaders = {
+ en: () => import('@/locales/en/main.json', { with: { type: 'json' } }),
+ 'zh-CN': () =>
+ import('@/locales/zh-CN/main.json', { with: { type: 'json' } }),
+ ja: () => import('@/locales/ja/main.json', { with: { type: 'json' } })
+} satisfies Record Promise<{ default: object }>>
+
+type EnglishCatalog = Awaited>['default']
type MessageKey = {
[K in keyof T & string]: T[K] extends string ? K : `${K}.${MessageKey}`
}[keyof T & string]
-export type TranslationKey = MessageKey
+export type TranslationKey = MessageKey
export type LocalizedText = { en: string; 'zh-CN': string } & Partial<
Record
>
-function createSiteI18n(locale: Locale) {
+function createSiteComposer(locale: Locale) {
return createI18n({
legacy: false,
locale,
fallbackLocale: DEFAULT_LOCALE,
- messages: { en, 'zh-CN': zhCN, ja },
missingWarn: false,
fallbackWarn: false,
warnHtmlMessage: false
+ }).global
+}
+
+const composers = {
+ en: createSiteComposer('en'),
+ 'zh-CN': createSiteComposer('zh-CN'),
+ ja: createSiteComposer('ja')
+} satisfies Record>
+
+type MessageTree = { [key: string]: string | MessageTree }
+
+function isMessageTree(value: unknown): value is MessageTree {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ !Array.isArray(value) &&
+ Object.values(value).every(
+ (entry: unknown) => typeof entry === 'string' || isMessageTree(entry)
+ )
+ )
+}
+
+async function fetchDeclaredCatalog(
+ page: Document,
+ locale: Locale,
+ signal?: AbortSignal
+): Promise {
+ const href = page
+ .querySelector(`link[data-locale-catalog="${locale}"]`)
+ ?.getAttribute('href')
+ if (!href) return undefined
+ const timeout = createTimeoutSignal(10_000)
+ const response = await fetch(href, {
+ signal: signal ? combineAbortSignals([signal, timeout]) : timeout
})
+ if (!response.ok) {
+ throw new Error(
+ `The ${locale} catalog at ${href} returned ${response.status}`
+ )
+ }
+ const catalog: unknown = await response.json()
+ if (!isMessageTree(catalog) || Object.keys(catalog).length === 0) {
+ throw new Error(`The ${locale} catalog at ${href} is not a message catalog`)
+ }
+ return catalog
}
-const siteI18nByLocale = {
- en: createSiteI18n('en'),
- 'zh-CN': createSiteI18n('zh-CN'),
- ja: createSiteI18n('ja')
-} satisfies Record>
+const loadedLocales = new Set()
+const localeLoads = new Map>()
+
+async function addCatalog(
+ locale: Locale,
+ page?: Document,
+ signal?: AbortSignal
+): Promise {
+ const declared = page
+ ? await fetchDeclaredCatalog(page, locale, signal)
+ : undefined
+ const catalog = declared ?? (await catalogLoaders[locale]()).default
+ for (const composer of Object.values(composers)) {
+ composer.setLocaleMessage(locale, catalog)
+ }
+ loadedLocales.add(locale)
+}
+
+function loadLocale(
+ locale: Locale,
+ page?: Document,
+ signal?: AbortSignal
+): Promise {
+ const load =
+ localeLoads.get(locale) ??
+ addCatalog(locale, page, signal).catch((error: unknown) => {
+ localeLoads.delete(locale)
+ throw error
+ })
+ localeLoads.set(locale, load)
+ return load
+}
+
+const pageDocument =
+ typeof window !== 'undefined' && import.meta.env.PROD ? document : undefined
+
+const initialLocales = new Set(
+ pageDocument
+ ? [DEFAULT_LOCALE, resolveLocale(pageDocument.documentElement.lang)]
+ : LOCALE_CODES
+)
+
+await Promise.all(
+ [...initialLocales].map((locale) =>
+ loadLocale(locale, pageDocument).catch(() => loadLocale(locale))
+ )
+)
+
+if (pageDocument) {
+ const locale = resolveLocale(pageDocument.documentElement.lang)
+ await loadLocale(locale, pageDocument).catch(() => loadLocale(locale))
+}
+
+export async function loadPageLocale(
+ page: Document,
+ signal?: AbortSignal
+): Promise {
+ const locale = resolveLocale(page.documentElement.lang)
+ await loadLocale(locale, page, signal)
+ page
+ .querySelector(`link[data-locale-catalog="${locale}"]`)
+ ?.removeAttribute('rel')
+}
export function translationsFor(locale: Locale) {
- return siteI18nByLocale[locale].global
+ if (!loadedLocales.has(locale)) {
+ throw new Error(`The ${locale} catalog is not loaded on this page`)
+ }
+ return composers[locale]
}
export const { t, te } = translationsFor(DEFAULT_LOCALE)
diff --git a/apps/website/src/layouts/AuthLayout.astro b/apps/website/src/layouts/AuthLayout.astro
index 57f77e85a0c..fc5a1e989e3 100644
--- a/apps/website/src/layouts/AuthLayout.astro
+++ b/apps/website/src/layouts/AuthLayout.astro
@@ -4,6 +4,7 @@ import '@/styles/global.css'
import AuthHeroCarousel from '@/components/auth/AuthHeroCarousel.vue'
import AuthToast from '@/components/auth/AuthToast.vue'
import GoogleTagManager from '@/components/common/GoogleTagManager.astro'
+import LocaleCatalogPreloads from '@/components/common/LocaleCatalogPreloads.astro'
import type { Locale } from '@/i18n/translations'
/**
@@ -29,6 +30,7 @@ const { t } = Astro.locals
+
{title}
diff --git a/apps/website/src/layouts/BaseLayout.astro b/apps/website/src/layouts/BaseLayout.astro
index 06ed103c77c..36fc4af2523 100644
--- a/apps/website/src/layouts/BaseLayout.astro
+++ b/apps/website/src/layouts/BaseLayout.astro
@@ -37,6 +37,7 @@ import {
} from '@/utils/jsonLd'
import type { Crumb, JsonLdNode, WebPageType } from '@/utils/jsonLd'
import JsonLdGraph from '@/components/common/JsonLdGraph.astro'
+import LocaleCatalogPreloads from '@/components/common/LocaleCatalogPreloads.astro'
type PPFormulaFace =
'Light' | 'Regular' | 'Medium' | 'Semibold' | 'Bold' | 'NarrowSemibold'
@@ -148,6 +149,7 @@ const structuredData = head.emitStructuredData
+
{keywordsContent && }
{head.robotsNoindex && }
@@ -263,6 +265,9 @@ const structuredData = head.emitStructuredData
+