From c2c5bcac08739f85e644c3327c24cafaab892dce Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Tue, 6 Oct 2026 16:50:48 -0700 Subject: [PATCH 1/7] fix(website): never load subresources while building markdown twins happy-dom fetches targets when it parses a page. With no page URL that throws an unhandled Invalid URL rejection and kills the build; with one it would fetch over the network. Give the parser the page's URL and answer every request locally. --- apps/website/src/lib/markdown-twin.test.ts | 9 +++++++++ apps/website/src/lib/markdown-twin.ts | 9 ++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/apps/website/src/lib/markdown-twin.test.ts b/apps/website/src/lib/markdown-twin.test.ts index a8ca446e541..574dfef2084 100644 --- a/apps/website/src/lib/markdown-twin.test.ts +++ b/apps/website/src/lib/markdown-twin.test.ts @@ -161,6 +161,15 @@ describe('htmlToTwin', () => { expect(noMain.body).toBe('# Pack\n\nNodes.') }) + it('reads a page that preloads a fetched resource without loading it', async () => { + const page = htmlToTwin( + '

x

', + 'https://comfy.org/x/' + ) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(page.body).toBe('x') + }) + it('falls back to the route when the page has no canonical link', () => { const bare = htmlToTwin( '

x

', diff --git a/apps/website/src/lib/markdown-twin.ts b/apps/website/src/lib/markdown-twin.ts index c74dc8e7fd0..c151c7e9d46 100644 --- a/apps/website/src/lib/markdown-twin.ts +++ b/apps/website/src/lib/markdown-twin.ts @@ -285,10 +285,17 @@ function meta(document: Document, name: string): string { /** Extract the page's main content as markdown, with absolute links. */ export function htmlToTwin(html: string, fallbackCanonical: string): TwinPage { const window = new Window({ + url: fallbackCanonical, settings: { disableJavaScriptEvaluation: true, disableJavaScriptFileLoading: true, - disableCSSFileLoading: true + disableCSSFileLoading: true, + fetch: { + interceptor: { + beforeAsyncRequest: ({ window }) => + Promise.resolve(new window.Response(null, { status: 204 })) + } + } } }) try { From 1b47371a3ea7881344e871cce5b7d61ed82fafea Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Tue, 6 Oct 2026 16:51:31 -0700 Subject: [PATCH 2/7] perf(website): load only English and the page's locale catalog Catalogs become per-locale files. The layout declares English plus the page's catalog as preloads, and the browser fetches only those; a client-side navigation into another locale loads its catalog before the swap. Build, tests and Playwright still load every locale through the bundled imports. English pages stop downloading Chinese and Japanese, and Japanese pages stop downloading Chinese. --- apps/website/README.md | 8 ++ apps/website/e2e/locale-catalogs.spec.ts | 52 ++++++++ .../common/LocaleCatalogPreloads.astro | 25 ++++ apps/website/src/config/auth-sign-in-state.ts | 8 +- apps/website/src/config/contentSections.ts | 6 +- apps/website/src/i18n/translations.ts | 125 ++++++++++++++++-- apps/website/src/layouts/AuthLayout.astro | 2 + apps/website/src/layouts/BaseLayout.astro | 2 + 8 files changed, 208 insertions(+), 20 deletions(-) create mode 100644 apps/website/e2e/locale-catalogs.spec.ts create mode 100644 apps/website/src/components/common/LocaleCatalogPreloads.astro diff --git a/apps/website/README.md b/apps/website/README.md index f69967340a2..b14359be2f4 100644 --- a/apps/website/README.md +++ b/apps/website/README.md @@ -56,6 +56,14 @@ 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 a visitor's 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`. + `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..11fadf1ad32 --- /dev/null +++ b/apps/website/e2e/locale-catalogs.spec.ts @@ -0,0 +1,52 @@ +import { expect } from '@playwright/test' + +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 } 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'] } + ]) { + test(`${path} downloads only the ${loaded.join(' and ')} catalogs`, async ({ + page + }) => { + await page.addInitScript(() => + performance.setResourceTimingBufferSize(10_000) + ) + await page.goto(path) + await expectIslandHydrated( + page, + page.getByRole('navigation', { name: 'Main navigation' }) + ) + + const downloaded = await page.evaluate(async (copies) => { + const sources = await Promise.all( + performance + .getEntriesByType('resource') + .map((entry) => new URL(entry.name)) + .filter( + (url) => + url.origin === location.origin && + /\.(js|json)$/.test(url.pathname) + ) + .map(async (url) => (await fetch(url)).text()) + ) + return Object.entries(copies) + .filter(([, copy]) => sources.some((source) => source.includes(copy))) + .map(([locale]) => locale) + }, copyOnlyIn) + expect(downloaded).toEqual(loaded) + }) + } +}) diff --git a/apps/website/src/components/common/LocaleCatalogPreloads.astro b/apps/website/src/components/common/LocaleCatalogPreloads.astro new file mode 100644 index 00000000000..6037fb17955 --- /dev/null +++ b/apps/website/src/components/common/LocaleCatalogPreloads.astro @@ -0,0 +1,25 @@ +--- +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/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.ts b/apps/website/src/i18n/translations.ts index c4727c4bb07..fbdc0a27fe6 100644 --- a/apps/website/src/i18n/translations.ts +++ b/apps/website/src/i18n/translations.ts @@ -1,41 +1,138 @@ 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' } + +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) + ) + ) } -const siteI18nByLocale = { - en: createSiteI18n('en'), - 'zh-CN': createSiteI18n('zh-CN'), - ja: createSiteI18n('ja') -} satisfies Record> +async function fetchDeclaredCatalog( + page: Document, + locale: Locale +): Promise { + const href = page + .querySelector(`link[data-locale-catalog="${locale}"]`) + ?.getAttribute('href') + if (!href) return undefined + const response = await fetch(href) + if (!response.ok) { + throw new Error( + `The ${locale} catalog at ${href} returned ${response.status}` + ) + } + const catalog: unknown = await response.json() + if (!isMessageTree(catalog)) { + throw new Error(`The ${locale} catalog at ${href} is not a message catalog`) + } + return catalog +} + +const loadedLocales = new Set() +const localeLoads = new Map>() + +async function addCatalog(locale: Locale, page?: Document): Promise { + const declared = page ? await fetchDeclaredCatalog(page, locale) : 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): Promise { + const load = + localeLoads.get(locale) ?? + addCatalog(locale, page).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)) +) + +if (pageDocument) { + pageDocument.addEventListener('astro:before-preparation', (event) => { + const loadDocument = event.loader + event.loader = async () => { + await loadDocument() + if (event.defaultPrevented) return + const { newDocument } = event + try { + await loadLocale( + resolveLocale(newDocument.documentElement.lang), + newDocument + ) + } catch { + event.preventDefault() + } + } + }) +} 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..bcd876371b4 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 && } From c5c3a1a8ddc122fc482f8b394e7b037756a162ae Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Thu, 8 Oct 2026 14:27:31 -0700 Subject: [PATCH 3/7] test(website): verify locale load failure recovery --- apps/website/e2e/locale-catalogs.spec.ts | 48 +++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/apps/website/e2e/locale-catalogs.spec.ts b/apps/website/e2e/locale-catalogs.spec.ts index 11fadf1ad32..a1a22667841 100644 --- a/apps/website/e2e/locale-catalogs.spec.ts +++ b/apps/website/e2e/locale-catalogs.spec.ts @@ -4,7 +4,7 @@ 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 } from './fixtures/islands' +import { expectIslandHydrated, waitForIsland } from './fixtures/islands' const copyOnlyIn = { en: en.footer.location, @@ -49,4 +49,50 @@ test.describe('Locale catalogs', () => { expect(downloaded).toEqual(loaded) }) } + + for (const { failure, status, body } of [ + { failure: 'an HTTP error', status: 503, 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([]) + }) + } }) From 4a4f3ec680e7667eb42b82efe3bad4575b1a52ed Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Thu, 8 Oct 2026 14:43:08 -0700 Subject: [PATCH 4/7] fix(website): prepare locale changes before hydration --- apps/website/README.md | 3 +- apps/website/e2e/locale-catalogs.spec.ts | 80 ++++++++++++++++++++++ apps/website/src/i18n/translations.ts | 27 +++++--- apps/website/src/lib/markdown-twin.test.ts | 3 +- 4 files changed, 100 insertions(+), 13 deletions(-) diff --git a/apps/website/README.md b/apps/website/README.md index b14359be2f4..d30beb114e0 100644 --- a/apps/website/README.md +++ b/apps/website/README.md @@ -62,7 +62,8 @@ 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`. +layout that hosts islands should include `LocaleCatalogPreloads`. If an initial +catalog request fails, the browser retries with its bundled catalog chunk. `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 index a1a22667841..0449fa6f75c 100644 --- a/apps/website/e2e/locale-catalogs.spec.ts +++ b/apps/website/e2e/locale-catalogs.spec.ts @@ -50,6 +50,86 @@ test.describe('Locale catalogs', () => { }) } + 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(() => { + 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 targetPage = page.waitForResponse(/\/zh-CN\/cli\/$/) + const switchLanguage = page + .getByRole('contentinfo') + .getByRole('link', { name: '简体中文' }) + .click() + await targetPage + 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() + } + }) + + test('a failed initial catalog request 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: 503, + contentType: 'application/json', + body: '{}' + }) + ) + + await page.goto('/zh-CN/cli/') + const menuButton = page.getByRole('button', { name: '切换菜单' }) + await waitForIsland(page, menuButton) + await menuButton.click() + await expect(page.getByRole('dialog', { name: '菜单' })).toBeVisible() + }) + for (const { failure, status, body } of [ { failure: 'an HTTP error', status: 503, body: '{}' }, { failure: 'an invalid catalog', status: 200, body: '{"invalid":42}' } diff --git a/apps/website/src/i18n/translations.ts b/apps/website/src/i18n/translations.ts index fbdc0a27fe6..44651918be8 100644 --- a/apps/website/src/i18n/translations.ts +++ b/apps/website/src/i18n/translations.ts @@ -99,16 +99,6 @@ function loadLocale(locale: Locale, page?: Document): Promise { 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)) -) - if (pageDocument) { pageDocument.addEventListener('astro:before-preparation', (event) => { const loadDocument = event.loader @@ -128,6 +118,23 @@ if (pageDocument) { }) } +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 function translationsFor(locale: Locale) { if (!loadedLocales.has(locale)) { throw new Error(`The ${locale} catalog is not loaded on this page`) diff --git a/apps/website/src/lib/markdown-twin.test.ts b/apps/website/src/lib/markdown-twin.test.ts index 574dfef2084..d892c2afe0a 100644 --- a/apps/website/src/lib/markdown-twin.test.ts +++ b/apps/website/src/lib/markdown-twin.test.ts @@ -161,12 +161,11 @@ describe('htmlToTwin', () => { expect(noMain.body).toBe('# Pack\n\nNodes.') }) - it('reads a page that preloads a fetched resource without loading it', async () => { + it('reads a page that preloads a fetched resource without loading it', () => { const page = htmlToTwin( '

x

', 'https://comfy.org/x/' ) - await new Promise((resolve) => setTimeout(resolve, 0)) expect(page.body).toBe('x') }) From cad60f2977c8ee38ba800b50cfb345b24c8d8fea Mon Sep 17 00:00:00 2001 From: Benjamin Lu Date: Thu, 8 Oct 2026 15:06:57 -0700 Subject: [PATCH 5/7] fix(website): prepare locales before router startup --- apps/website/README.md | 8 +- apps/website/e2e/locale-catalogs.spec.ts | 127 ++++++++++++++++-- .../components/legal/LegalContentSection.vue | 5 +- apps/website/src/i18n/translations.ts | 23 +--- apps/website/src/layouts/BaseLayout.astro | 3 + apps/website/src/lib/markdown-twin.test.ts | 22 ++- apps/website/src/lib/markdown-twin.ts | 8 +- apps/website/src/scripts/localeNavigation.ts | 13 ++ 8 files changed, 160 insertions(+), 49 deletions(-) create mode 100644 apps/website/src/scripts/localeNavigation.ts diff --git a/apps/website/README.md b/apps/website/README.md index d30beb114e0..01ef96324c3 100644 --- a/apps/website/README.md +++ b/apps/website/README.md @@ -56,14 +56,16 @@ 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 a visitor's browser loads only English and +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`. If an initial -catalog request fails, the browser retries with its bundled catalog chunk. +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, the browser retries with its bundled catalog chunk. `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 index 0449fa6f75c..4b08953edb0 100644 --- a/apps/website/e2e/locale-catalogs.spec.ts +++ b/apps/website/e2e/locale-catalogs.spec.ts @@ -16,7 +16,9 @@ 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: '/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 @@ -32,24 +34,116 @@ test.describe('Locale catalogs', () => { const downloaded = await page.evaluate(async (copies) => { const sources = await Promise.all( - performance - .getEntriesByType('resource') - .map((entry) => new URL(entry.name)) + [ + ...new Set( + performance + .getEntriesByType('resource') + .map((entry) => entry.name) + ) + ] + .map((name) => new URL(name)) .filter( (url) => url.origin === location.origin && - /\.(js|json)$/.test(url.pathname) + /^\/_website\/.*\.(js|json)$/.test(url.pathname) ) - .map(async (url) => (await fetch(url)).text()) + .map(async (url) => ({ + path: url.pathname, + source: await (await fetch(url)).text() + })) + ) + return Object.entries(copies).flatMap(([locale, copy]) => + sources + .filter(({ source }) => source.includes(copy)) + .map(({ path }) => ({ locale, path })) ) - return Object.entries(copies) - .filter(([, copy]) => sources.some((source) => source.includes(copy))) - .map(([locale]) => locale) }, copyOnlyIn) - expect(downloaded).toEqual(loaded) + expect( + downloaded.map(({ locale }) => locale), + JSON.stringify(downloaded) + ).toEqual(loaded) }) } + 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 @@ -67,6 +161,13 @@ test.describe('Locale catalogs', () => { 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 @@ -89,12 +190,14 @@ test.describe('Locale catalogs', () => { 'data-catalog-requested', 'true' ) - const targetPage = page.waitForResponse(/\/zh-CN\/cli\/$/) const switchLanguage = page .getByRole('contentinfo') .getByRole('link', { name: '简体中文' }) .click() - await targetPage + await expect(page.locator('html')).toHaveAttribute( + 'data-document-prepared', + 'true' + ) releaseCatalogs.resolve() await switchLanguage 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/i18n/translations.ts b/apps/website/src/i18n/translations.ts index 44651918be8..9a60c35955b 100644 --- a/apps/website/src/i18n/translations.ts +++ b/apps/website/src/i18n/translations.ts @@ -99,25 +99,6 @@ function loadLocale(locale: Locale, page?: Document): Promise { const pageDocument = typeof window !== 'undefined' && import.meta.env.PROD ? document : undefined -if (pageDocument) { - pageDocument.addEventListener('astro:before-preparation', (event) => { - const loadDocument = event.loader - event.loader = async () => { - await loadDocument() - if (event.defaultPrevented) return - const { newDocument } = event - try { - await loadLocale( - resolveLocale(newDocument.documentElement.lang), - newDocument - ) - } catch { - event.preventDefault() - } - } - }) -} - const initialLocales = new Set( pageDocument ? [DEFAULT_LOCALE, resolveLocale(pageDocument.documentElement.lang)] @@ -135,6 +116,10 @@ if (pageDocument) { await loadLocale(locale, pageDocument).catch(() => loadLocale(locale)) } +export function loadPageLocale(page: Document): Promise { + return loadLocale(resolveLocale(page.documentElement.lang), page) +} + export function translationsFor(locale: Locale) { if (!loadedLocales.has(locale)) { throw new Error(`The ${locale} catalog is not loaded on this page`) diff --git a/apps/website/src/layouts/BaseLayout.astro b/apps/website/src/layouts/BaseLayout.astro index bcd876371b4..36fc4af2523 100644 --- a/apps/website/src/layouts/BaseLayout.astro +++ b/apps/website/src/layouts/BaseLayout.astro @@ -265,6 +265,9 @@ const structuredData = head.emitStructuredData +