镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit b872eae

Browse files
committed
feat(i18n): preload switching languages without loading another page
1 parent d318e63 commit b872eae

3 files changed

Lines changed: 49 additions & 4 deletions

File tree

‎docs/guide/i18n.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,3 +582,26 @@ async function setLocale(locale: string) {
582582
@endif
583583
</section>
584584
```
585+
586+
587+
## Switch without fetching another page
588+
589+
Production pages normally include the current language and fallback only. For
590+
instant client-side switching, preload the supported alternatives in the native
591+
STX message configuration:
592+
593+
```ts
594+
messages: {
595+
dir: 'resources/lang/messages',
596+
languages: ['en', 'de'],
597+
fallback: 'en',
598+
preload: 'all',
599+
}
600+
```
601+
602+
Use `preload: ['de']` for a selected subset. This adds the selected languages'
603+
JSON for only the areas a page imports. The ordinary module registry stays split;
604+
no replacement HTML request is required to change words. The tradeoff is more
605+
translation data in the initial page. Unconfigured preload languages fail the
606+
build. Bind translated labels reactively, and preserve forms and completed
607+
actions while updating the translator's locale.

‎packages/stx/src/message-catalogs.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ export interface PageMessagesOptions extends MessageCatalogsOptions {
4949
* first of `languages`.
5050
*/
5151
fallback?: string
52+
/** Additional languages available for in-place switching, without fetching a page. */
53+
preload?: 'all' | string[]
5254
}
5355

5456
export interface CollectedMessages {
@@ -107,6 +109,7 @@ export interface PageMessages extends CollectedMessages {
107109
stubs: Map<string, string>
108110
languages: string[]
109111
fallback: string
112+
preload?: string[]
110113
}
111114

112115
const collected = new Map<string, { signature: string, messages: PageMessages }>()
@@ -146,7 +149,7 @@ export async function loadPageMessages(root: string, options: PageMessagesOption
146149
try { return `${language}:${statSync(path.join(dir, language)).mtimeMs}` }
147150
catch { return `${language}:-` }
148151
}).join('|')
149-
const cacheKey = `${dir}\0${options.languages.join(',')}\0${options.fallback ?? ''}`
152+
const cacheKey = `${dir}\0${options.languages.join(',')}\0${options.fallback ?? ''}\0${JSON.stringify(options.preload ?? [])}`
150153
const cached = collected.get(cacheKey)
151154
if (cached && cached.signature === signature) return cached.messages
152155
const catalogs = await collectMessageCatalogs(root, options)
@@ -157,7 +160,11 @@ export async function loadPageMessages(root: string, options: PageMessagesOption
157160
}
158161
const fallback = options.fallback ?? options.languages[0]!
159162
if (!options.languages.includes(fallback)) throw new Error(`messages.fallback "${fallback}" is not one of messages.languages`)
160-
const messages = { ...catalogs, stubs, languages: [...options.languages], fallback }
163+
const preload = options.preload === 'all' ? [...options.languages] : [...(options.preload ?? [])]
164+
for (const language of preload) {
165+
if (!options.languages.includes(language)) throw new Error(`messages.preload "${language}" is not one of messages.languages`)
166+
}
167+
const messages = { ...catalogs, stubs, languages: [...options.languages], fallback, preload }
161168
collected.set(cacheKey, { signature, messages })
162169
return messages
163170
}
@@ -178,14 +185,14 @@ export function messageAreasIn(...codes: Array<string | null | undefined>): Set<
178185
* Every language when the page names none of them, since nothing then says
179186
* which one its scripts will read.
180187
*/
181-
export function pageLanguages(html: string, messages: Pick<PageMessages, 'languages' | 'fallback'>): string[] {
188+
export function pageLanguages(html: string, messages: Pick<PageMessages, 'languages' | 'fallback' | 'preload'>): string[] {
182189
const htmlTag = /<html\b[^>]*>/i.exec(html)?.[0] ?? ''
183190
const lang = /\slang\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(htmlTag)
184191
const value = (lang ? (lang[1] ?? lang[2] ?? lang[3] ?? '') : '').trim().toLowerCase()
185192
const known = new Map(messages.languages.map(language => [language.toLowerCase(), language]))
186193
const language = known.get(value) ?? known.get(value.split(/[-_]/)[0] ?? '')
187194
if (!language) return [...messages.languages]
188-
return [...new Set([language, messages.fallback])]
195+
return [...new Set([language, messages.fallback, ...(messages.preload ?? [])])]
189196
}
190197

191198
/**

‎packages/stx/test/page-messages.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,21 @@ describe('message catalogs, a language at a time', () => {
8989
expect(pageLanguages('<html lang="fr">', known)).toEqual(['en', 'de'])
9090
})
9191

92+
it('preloads configured switching languages while retaining area splitting', async () => {
93+
process.env.STX_PAGE_MESSAGES = '1'
94+
const html = await render('en', { messages: { ...messages, preload: 'all' } })
95+
const filled = tagged(html, 'data-stx-messages')
96+
expect(filled).toContain('EN_AUTH_TITLE')
97+
expect(filled).toContain('DE_AUTH_TITLE')
98+
expect(filled).not.toContain('BILLING')
99+
expect(tagged(html, 'data-stx-modules')).not.toContain('DE_AUTH_TITLE')
100+
const specific = await loadPageMessages(APP, { ...messages, preload: ['de'] })
101+
expect(pageLanguages('<html lang="en">', specific)).toEqual(['en', 'de'])
102+
const ordinary = await loadPageMessages(APP, messages)
103+
expect(pageLanguages('<html lang="en">', ordinary)).toEqual(['en'])
104+
await expect(loadPageMessages(APP, { ...messages, preload: ['fr'] })).rejects.toThrow('messages.preload')
105+
})
106+
92107
it('fills each area once, into the object its importers already hold', async () => {
93108
const collected = await loadPageMessages(APP, messages)
94109
expect(messageAreasIn('x"stx-messages:de:auth"y', 'z "stx-messages:en:server/errors"')).toEqual(new Set(['auth', 'server/errors']))

0 commit comments

Comments
 (0)