-
Notifications
You must be signed in to change notification settings - Fork 462
/
i18n.ts
535 lines (499 loc) · 18.7 KB
/
i18n.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import { computed } from 'vue'
import { createI18n } from 'vue-i18n'
import { defineNuxtPlugin, useRoute, addRouteMiddleware, defineNuxtRouteMiddleware, useNuxtApp } from '#imports'
import {
localeCodes,
vueI18nConfigs,
isSSG,
localeLoaders,
parallelPlugin,
normalizedLocales,
SWITCH_LOCALE_PATH_LINK_IDENTIFIER
} from '#build/i18n.options.mjs'
import { loadVueI18nOptions, loadInitialMessages, loadLocale } from '../messages'
import { useSwitchLocalePath } from '../composables'
import {
loadAndSetLocale,
detectLocale,
detectRedirect,
navigate,
injectNuxtHelpers,
extendBaseUrl,
_setLocale,
mergeLocaleMessage
} from '../utils'
import {
getBrowserLocale as _getBrowserLocale,
getLocaleCookie as _getLocaleCookie,
setLocaleCookie as _setLocaleCookie,
detectBrowserLanguage,
DefaultDetectBrowserLanguageFromResult,
getI18nCookie,
runtimeDetectBrowserLanguage
} from '../internal'
import { getComposer, getLocale, setLocale } from '../routing/utils'
import { extendI18n, createLocaleFromRouteGetter } from '../routing/extends'
import type { Composer, Locale, I18nOptions } from 'vue-i18n'
import type { NuxtApp } from '#app'
import type { ExtendPropertyDescriptors, VueI18nRoutingPluginOptions } from '../routing/extends'
import type { getRouteBaseName, localePath, localeRoute, switchLocalePath, localeHead } from '../routing/compatibles'
import type {
LocaleHeadFunction,
LocalePathFunction,
LocaleRouteFunction,
RouteBaseNameFunction,
SwitchLocalePathFunction
} from '../composables'
export default defineNuxtPlugin({
name: 'i18n:plugin',
parallel: parallelPlugin,
async setup(nuxt) {
const route = useRoute()
const { vueApp: app } = nuxt
const nuxtContext = nuxt as unknown as NuxtApp
// Fresh copy per request to prevent reusing mutated options
const runtimeI18n = { ...nuxtContext.$config.public.i18n }
// @ts-expect-error type incompatible
runtimeI18n.baseUrl = extendBaseUrl()
const _detectBrowserLanguage = runtimeDetectBrowserLanguage()
__DEBUG__ && console.log('isSSG', isSSG)
__DEBUG__ && console.log('useCookie on setup', _detectBrowserLanguage && _detectBrowserLanguage.useCookie)
__DEBUG__ && console.log('defaultLocale on setup', runtimeI18n.defaultLocale)
const vueI18nOptions: I18nOptions = await loadVueI18nOptions(vueI18nConfigs, useNuxtApp())
vueI18nOptions.messages = vueI18nOptions.messages || {}
vueI18nOptions.fallbackLocale = vueI18nOptions.fallbackLocale ?? false
const getLocaleFromRoute = createLocaleFromRouteGetter()
const getDefaultLocale = (defaultLocale: string) => defaultLocale || vueI18nOptions.locale || 'en-US'
const localeCookie = getI18nCookie()
// detect initial locale
let initialLocale = detectLocale(
route,
getLocaleFromRoute,
vueI18nOptions.locale,
getDefaultLocale(runtimeI18n.defaultLocale),
{
ssg: isSSG && runtimeI18n.strategy === 'no_prefix' ? 'ssg_ignore' : 'normal',
callType: 'setup',
firstAccess: true,
localeCookie: _getLocaleCookie(localeCookie, _detectBrowserLanguage, runtimeI18n.defaultLocale)
},
runtimeI18n
)
__DEBUG__ && console.log('first detect initial locale', initialLocale)
// load initial vue-i18n locale messages
vueI18nOptions.messages = await loadInitialMessages(vueI18nOptions.messages, localeLoaders, {
localeCodes,
initialLocale,
lazy: runtimeI18n.lazy,
defaultLocale: runtimeI18n.defaultLocale,
fallbackLocale: vueI18nOptions.fallbackLocale
})
/**
* NOTE:
* If `initialLocale` is not set, then the `vueI18n` option `locale` is respect!
* It means a mode that works only with simple vue-i18n, without nuxtjs/i18n routing, browser detection, SEO, and other features.
*/
initialLocale = getDefaultLocale(initialLocale)
__DEBUG__ && console.log('final initial locale:', initialLocale)
// create i18n instance
const i18n = createI18n({ ...vueI18nOptions, locale: initialLocale })
let notInitialSetup = true
const isInitialLocaleSetup = (locale: Locale) => initialLocale !== locale && notInitialSetup
let ssgModeInitialSetup = true
const isSSGModeInitialSetup = () => isSSG && ssgModeInitialSetup
/**
* NOTE:
* avoid hydration mismatch for SSG mode
*/
if (isSSGModeInitialSetup() && runtimeI18n.strategy === 'no_prefix' && import.meta.client) {
nuxt.hook('app:mounted', async () => {
__DEBUG__ && console.log('hook app:mounted')
const {
locale: browserLocale,
stat,
reason,
from
} = _detectBrowserLanguage
? detectBrowserLanguage(
route,
vueI18nOptions.locale,
{
ssg: 'ssg_setup',
callType: 'setup',
firstAccess: true,
localeCookie: _getLocaleCookie(localeCookie, _detectBrowserLanguage, runtimeI18n.defaultLocale)
},
initialLocale
)
: DefaultDetectBrowserLanguageFromResult
__DEBUG__ &&
console.log(
'app:mounted: detectBrowserLanguage (browserLocale, stat, reason, from) -',
browserLocale,
stat,
reason,
from
)
_setLocale(i18n, browserLocale)
ssgModeInitialSetup = false
})
}
// extend i18n instance
extendI18n(i18n, {
locales: runtimeI18n.configLocales,
localeCodes,
baseUrl: runtimeI18n.baseUrl,
context: nuxtContext,
hooks: {
onExtendComposer(composer: Composer) {
composer.strategy = runtimeI18n.strategy
composer.localeProperties = computed(
() => normalizedLocales.find(l => l.code === composer.locale.value) || { code: composer.locale.value }
)
composer.setLocale = async (locale: string) => {
const localeSetup = isInitialLocaleSetup(locale)
const modified = await loadAndSetLocale(locale, i18n, runtimeI18n, localeSetup)
if (modified && localeSetup) {
notInitialSetup = false
}
const redirectPath = await nuxtContext.runWithContext(() =>
detectRedirect({
route: { to: route },
targetLocale: locale,
routeLocaleGetter: getLocaleFromRoute
})
)
__DEBUG__ && console.log('redirectPath on setLocale', redirectPath)
await nuxtContext.runWithContext(
async () =>
await navigate(
{
nuxtApp: nuxtContext,
i18n,
redirectPath,
locale,
route
},
{ enableNavigate: true }
)
)
}
composer.loadLocaleMessages = async (locale: string) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const setter = (locale: Locale, message: Record<string, any>) => mergeLocaleMessage(i18n, locale, message)
await loadLocale(locale, localeLoaders, setter)
}
composer.differentDomains = runtimeI18n.differentDomains
composer.defaultLocale = runtimeI18n.defaultLocale
composer.getBrowserLocale = () => _getBrowserLocale()
composer.getLocaleCookie = () =>
_getLocaleCookie(localeCookie, _detectBrowserLanguage, runtimeI18n.defaultLocale)
composer.setLocaleCookie = (locale: string) => _setLocaleCookie(localeCookie, locale, _detectBrowserLanguage)
composer.onBeforeLanguageSwitch = (oldLocale, newLocale, initialSetup, context) =>
nuxt.callHook('i18n:beforeLocaleSwitch', { oldLocale, newLocale, initialSetup, context })
composer.onLanguageSwitched = (oldLocale, newLocale) =>
nuxt.callHook('i18n:localeSwitched', { oldLocale, newLocale })
composer.finalizePendingLocaleChange = async () => {
if (!i18n.__pendingLocale) {
return
}
setLocale(i18n, i18n.__pendingLocale)
if (i18n.__resolvePendingLocalePromise) {
await i18n.__resolvePendingLocalePromise()
}
i18n.__pendingLocale = undefined
}
composer.waitForPendingLocaleChange = async () => {
if (i18n.__pendingLocale && i18n.__pendingLocalePromise) {
await i18n.__pendingLocalePromise
}
}
},
onExtendExportedGlobal(g: Composer): ExtendPropertyDescriptors {
return {
strategy: {
get() {
return g.strategy
}
},
localeProperties: {
get() {
return g.localeProperties.value
}
},
setLocale: {
get() {
return async (locale: string) => Reflect.apply(g.setLocale, g, [locale])
}
},
differentDomains: {
get() {
return g.differentDomains
}
},
defaultLocale: {
get() {
return g.defaultLocale
}
},
getBrowserLocale: {
get() {
return () => Reflect.apply(g.getBrowserLocale, g, [])
}
},
getLocaleCookie: {
get() {
return () => Reflect.apply(g.getLocaleCookie, g, [])
}
},
setLocaleCookie: {
get() {
return (locale: string) => Reflect.apply(g.setLocaleCookie, g, [locale])
}
},
onBeforeLanguageSwitch: {
get() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (oldLocale: string, newLocale: string, initialSetup: boolean, context: NuxtApp) =>
Reflect.apply(g.onBeforeLanguageSwitch, g, [oldLocale, newLocale, initialSetup, context])
}
},
onLanguageSwitched: {
get() {
return (oldLocale: string, newLocale: string) =>
Reflect.apply(g.onLanguageSwitched, g, [oldLocale, newLocale])
}
},
finalizePendingLocaleChange: {
get() {
return () => Reflect.apply(g.finalizePendingLocaleChange, g, [])
}
},
waitForPendingLocaleChange: {
get() {
return () => Reflect.apply(g.waitForPendingLocaleChange, g, [])
}
}
}
},
onExtendVueI18n(composer: Composer): ExtendPropertyDescriptors {
return {
strategy: {
get() {
return composer.strategy
}
},
localeProperties: {
get() {
return composer.localeProperties.value
}
},
setLocale: {
get() {
return async (locale: string) => Reflect.apply(composer.setLocale, composer, [locale])
}
},
loadLocaleMessages: {
get() {
return async (locale: string) => Reflect.apply(composer.loadLocaleMessages, composer, [locale])
}
},
differentDomains: {
get() {
return composer.differentDomains
}
},
defaultLocale: {
get() {
return composer.defaultLocale
}
},
getBrowserLocale: {
get() {
return () => Reflect.apply(composer.getBrowserLocale, composer, [])
}
},
getLocaleCookie: {
get() {
return () => Reflect.apply(composer.getLocaleCookie, composer, [])
}
},
setLocaleCookie: {
get() {
return (locale: string) => Reflect.apply(composer.setLocaleCookie, composer, [locale])
}
},
onBeforeLanguageSwitch: {
get() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (oldLocale: string, newLocale: string, initialSetup: boolean, context: NuxtApp) =>
Reflect.apply(composer.onBeforeLanguageSwitch, composer, [
oldLocale,
newLocale,
initialSetup,
context
])
}
},
onLanguageSwitched: {
get() {
return (oldLocale: string, newLocale: string) =>
Reflect.apply(composer.onLanguageSwitched, composer, [oldLocale, newLocale])
}
},
finalizePendingLocaleChange: {
get() {
return () => Reflect.apply(composer.finalizePendingLocaleChange, composer, [])
}
},
waitForPendingLocaleChange: {
get() {
return () => Reflect.apply(composer.waitForPendingLocaleChange, composer, [])
}
}
}
}
}
})
// vue-i18n installation
const pluginOptions: VueI18nRoutingPluginOptions = {
__composerExtend: (c: Composer) => {
const g = getComposer(i18n)
c.strategy = g.strategy
c.localeProperties = computed(() => g.localeProperties.value)
c.setLocale = g.setLocale
c.differentDomains = g.differentDomains
c.getBrowserLocale = g.getBrowserLocale
c.getLocaleCookie = g.getLocaleCookie
c.setLocaleCookie = g.setLocaleCookie
c.onBeforeLanguageSwitch = g.onBeforeLanguageSwitch
c.onLanguageSwitched = g.onLanguageSwitched
c.finalizePendingLocaleChange = g.finalizePendingLocaleChange
c.waitForPendingLocaleChange = g.waitForPendingLocaleChange
return () => {}
}
}
// @ts-ignore
app.use(i18n, pluginOptions) // TODO: should implement `{ inject: false } via `nuxtjs/i18n` configuration
// inject for nuxt helpers
injectNuxtHelpers(nuxtContext, i18n)
// Replace `SwitchLocalePathLink` href in rendered html for SSR support
if (runtimeI18n.experimental.switchLocalePathLinkSSR === true) {
const switchLocalePath = useSwitchLocalePath()
const switchLocalePathLinkWrapperExpr = new RegExp(
[
`<!--${SWITCH_LOCALE_PATH_LINK_IDENTIFIER}-\\[(\\w+)\\]-->`,
`.+?`,
`<!--\/${SWITCH_LOCALE_PATH_LINK_IDENTIFIER}-->`
].join(''),
'g'
)
nuxt.hook('app:rendered', ctx => {
if (ctx.renderResult?.html == null) return
ctx.renderResult.html = ctx.renderResult.html.replaceAll(
switchLocalePathLinkWrapperExpr,
(match: string, p1: string) => match.replace(/href="([^"]+)"/, `href="${switchLocalePath(p1 ?? '')}"`)
)
})
}
let routeChangeCount = 0
addRouteMiddleware(
'locale-changing',
// eslint-disable-next-line @typescript-eslint/no-unused-vars
defineNuxtRouteMiddleware(async (to, from) => {
__DEBUG__ && console.log('locale-changing middleware', to, from)
const locale = detectLocale(
to,
getLocaleFromRoute,
vueI18nOptions.locale,
() => {
return getLocale(i18n) || getDefaultLocale(runtimeI18n.defaultLocale)
},
{
ssg: isSSGModeInitialSetup() && runtimeI18n.strategy === 'no_prefix' ? 'ssg_ignore' : 'normal',
callType: 'routing',
firstAccess: routeChangeCount === 0,
localeCookie: _getLocaleCookie(localeCookie, _detectBrowserLanguage, runtimeI18n.defaultLocale)
},
runtimeI18n
)
__DEBUG__ && console.log('detect locale', locale)
const localeSetup = isInitialLocaleSetup(locale)
__DEBUG__ && console.log('localeSetup', localeSetup)
const modified = await loadAndSetLocale(locale, i18n, runtimeI18n, localeSetup)
if (modified && localeSetup) {
notInitialSetup = false
}
const redirectPath = await nuxtContext.runWithContext(() =>
detectRedirect({
route: { to, from },
targetLocale: locale,
routeLocaleGetter: runtimeI18n.strategy === 'no_prefix' ? () => locale : getLocaleFromRoute,
calledWithRouting: true
})
)
__DEBUG__ && console.log('redirectPath on locale-changing middleware', redirectPath)
routeChangeCount++
return await nuxtContext.runWithContext(async () =>
navigate({ nuxtApp: nuxtContext, i18n, redirectPath, locale, route: to })
)
}),
{ global: true }
)
}
})
declare module '#app' {
interface NuxtApp {
/**
* Returns base name of current (if argument not provided) or passed in route.
*
* @remarks
* Base name is name of the route without locale suffix and other metadata added by nuxt i18n module
*
* @param givenRoute - A route.
*
* @returns The route base name. if cannot get, `undefined` is returned.
*/
$getRouteBaseName: (...args: Parameters<RouteBaseNameFunction>) => ReturnType<typeof getRouteBaseName>
/**
* Returns localized path for passed in route.
*
* @remarks
* If locale is not specified, uses current locale.
*
* @param route - A route.
* @param locale - A locale, optional.
*
* @returns A path of the current route.
*/
$localePath: (...args: Parameters<LocalePathFunction>) => ReturnType<typeof localePath>
/**
* Returns localized route for passed in `route` parameters.
*
* @remarks
* If `locale` is not specified, uses current locale.
*
* @param route - A route.
* @param locale - A {@link Locale | locale}, optional.
*
* @returns A route. if cannot resolve, `undefined` is returned.
*/
$localeRoute: (...args: Parameters<LocaleRouteFunction>) => ReturnType<typeof localeRoute>
/**
* Returns localized head properties for locale-related aspects.
*
* @param options - An options object, see `I18nHeadOptions`.
*
* @returns The localized head properties.
*/
$localeHead: (...args: Parameters<LocaleHeadFunction>) => ReturnType<typeof localeHead>
/**
* Returns path of the current route for specified locale
*
* @param locale - A {@link Locale}
*
* @returns A path of the current route
*/
$switchLocalePath: (...args: Parameters<SwitchLocalePathFunction>) => ReturnType<typeof switchLocalePath>
}
}