-
-
Notifications
You must be signed in to change notification settings - Fork 490
/
Copy pathi18n.ts
569 lines (534 loc) · 18.4 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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import { computed } from 'vue'
import { createI18n } from 'vue-i18n'
import {
createLocaleFromRouteGetter,
extendI18n,
registerGlobalOptions,
getRouteBaseName,
localePath,
localeRoute,
switchLocalePath,
localeHead,
setLocale,
getLocale,
getComposer
} from 'vue-i18n-routing'
import {
defineNuxtPlugin,
useRouter,
useRoute,
addRouteMiddleware,
defineNuxtRouteMiddleware,
useNuxtApp
} from '#imports'
import {
localeCodes,
vueI18nConfigs,
nuxtI18nOptions,
nuxtI18nInternalOptions,
isSSG,
localeMessages,
parallelPlugin
} from '#build/i18n.options.mjs'
import { loadVueI18nOptions, loadInitialMessages } from '../messages'
import {
loadAndSetLocale,
detectLocale,
detectRedirect,
navigate,
injectNuxtHelpers,
extendBaseUrl,
extendPrefixable,
extendSwitchLocalePathIntercepter,
_setLocale
} from '../utils'
import {
getBrowserLocale as _getBrowserLocale,
getLocaleCookie as _getLocaleCookie,
setLocaleCookie as _setLocaleCookie,
detectBrowserLanguage,
DefaultDetectBrowserLanguageFromResult
} from '../internal'
import type { Composer, Locale, I18nOptions, LocaleMessages, DefineLocaleMessage } from 'vue-i18n'
import type { LocaleObject, ExtendProperyDescripters, VueI18nRoutingPluginOptions } from 'vue-i18n-routing'
import type { NuxtApp } from '#app'
type GetRouteBaseName = typeof getRouteBaseName
type LocalePath = typeof localePath
type LocaleRoute = typeof localeRoute
type LocaleHead = typeof localeHead
type SwitchLocalePath = typeof switchLocalePath
// cache for locale messages
const cacheMessages = new Map<string, LocaleMessages<DefineLocaleMessage>>()
export default defineNuxtPlugin({
name: 'i18n:plugin',
parallel: parallelPlugin,
async setup(nuxt) {
const router = useRouter()
const route = useRoute()
const { vueApp: app } = nuxt
const nuxtContext = nuxt as unknown as NuxtApp
const vueI18nOptions: I18nOptions = await loadVueI18nOptions(vueI18nConfigs, useNuxtApp())
const useCookie = nuxtI18nOptions.detectBrowserLanguage && nuxtI18nOptions.detectBrowserLanguage.useCookie
const { __normalizedLocales: normalizedLocales } = nuxtI18nInternalOptions
const {
defaultLocale,
differentDomains,
skipSettingLocaleOnNavigate,
lazy,
routesNameSeparator,
defaultLocaleRouteNameSuffix,
strategy,
rootRedirect
} = nuxtI18nOptions
__DEBUG__ && console.log('isSSG', isSSG)
__DEBUG__ && console.log('useCookie on setup', useCookie)
__DEBUG__ && console.log('defaultLocale on setup', defaultLocale)
nuxtI18nOptions.baseUrl = extendBaseUrl(nuxtI18nOptions.baseUrl, {
differentDomains,
localeCodeLoader: defaultLocale,
normalizedLocales
})
const getLocaleFromRoute = createLocaleFromRouteGetter(
localeCodes,
routesNameSeparator,
defaultLocaleRouteNameSuffix
)
vueI18nOptions.messages = vueI18nOptions.messages || {}
vueI18nOptions.fallbackLocale = vueI18nOptions.fallbackLocale ?? false
// register nuxt/i18n options as global
// so global options is reffered by `vue-i18n-routing`
registerGlobalOptions(router, {
...nuxtI18nOptions,
dynamicRouteParamsKey: 'nuxtI18n',
switchLocalePathIntercepter: extendSwitchLocalePathIntercepter(differentDomains, normalizedLocales),
prefixable: extendPrefixable(differentDomains)
})
const getDefaultLocale = (defaultLocale: string) => defaultLocale || vueI18nOptions.locale || 'en-US'
// detect initial locale
let initialLocale = detectLocale(
route,
getLocaleFromRoute,
nuxtI18nOptions,
vueI18nOptions,
getDefaultLocale(defaultLocale),
{ ssg: isSSG && strategy === 'no_prefix' ? 'ssg_ignore' : 'normal', callType: 'setup', firstAccess: true },
normalizedLocales,
localeCodes
)
__DEBUG__ && console.log('first detect initial locale', initialLocale)
// load initial vue-i18n locale messages
vueI18nOptions.messages = await loadInitialMessages(vueI18nOptions.messages, localeMessages, {
...nuxtI18nOptions,
initialLocale,
fallbackLocale: vueI18nOptions.fallbackLocale,
localeCodes,
cacheMessages
})
/**
* 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() && strategy === 'no_prefix' && process.client) {
nuxt.hook('app:mounted', async () => {
__DEBUG__ && console.log('hook app:mounted')
const {
locale: browserLocale,
stat,
reason,
from
} = nuxtI18nOptions.detectBrowserLanguage
? detectBrowserLanguage(
route,
nuxtI18nOptions,
nuxtI18nInternalOptions,
vueI18nOptions,
{ ssg: 'ssg_setup', callType: 'setup', firstAccess: true },
localeCodes,
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: nuxtI18nOptions.locales,
localeCodes,
baseUrl: nuxtI18nOptions.baseUrl,
context: nuxtContext,
hooks: {
onExtendComposer(composer: Composer) {
composer.strategy = strategy
composer.localeProperties = computed(() => {
return (
normalizedLocales.find((l: LocaleObject) => l.code === composer.locale.value) || {
code: composer.locale.value
}
)
})
composer.setLocale = async (locale: string) => {
const localeSetup = isInitialLocaleSetup(locale)
const [modified] = await loadAndSetLocale(locale, localeMessages, i18n, {
useCookie,
differentDomains,
initial: localeSetup,
cacheMessages,
skipSettingLocaleOnNavigate,
lazy
})
if (modified && localeSetup) {
notInitialSetup = false
}
const redirectPath = detectRedirect({
route: { to: route },
targetLocale: locale,
routeLocaleGetter: getLocaleFromRoute,
nuxtI18nOptions
})
__DEBUG__ && console.log('redirectPath on setLocale', redirectPath)
await navigate(
{
i18n,
redirectPath,
locale,
route
},
{
differentDomains,
skipSettingLocaleOnNavigate,
rootRedirect,
enableNavigate: true
}
)
}
composer.differentDomains = differentDomains
composer.defaultLocale = defaultLocale
composer.getBrowserLocale = () => _getBrowserLocale(nuxtI18nInternalOptions)
composer.getLocaleCookie = () => _getLocaleCookie({ ...nuxtI18nOptions.detectBrowserLanguage, localeCodes })
composer.setLocaleCookie = (locale: string) =>
_setLocaleCookie(locale, nuxtI18nOptions.detectBrowserLanguage || undefined)
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): ExtendProperyDescripters {
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): ExtendProperyDescripters {
return {
strategy: {
get() {
return composer.strategy
}
},
localeProperties: {
get() {
return composer.localeProperties.value
}
},
setLocale: {
get() {
return async (locale: string) => Reflect.apply(composer.setLocale, 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 () => {}
}
}
app.use(i18n, pluginOptions) // TODO: should implement `{ inject: false } via `nuxtjs/i18n` configuration
// inject for nuxt helpers
injectNuxtHelpers(nuxtContext, i18n)
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,
nuxtI18nOptions,
vueI18nOptions,
() => {
return getLocale(i18n) || getDefaultLocale(defaultLocale)
},
{
ssg: isSSGModeInitialSetup() && strategy === 'no_prefix' ? 'ssg_ignore' : 'normal',
callType: 'routing',
firstAccess: routeChangeCount === 0
},
normalizedLocales,
localeCodes
)
__DEBUG__ && console.log('detect locale', locale)
const localeSetup = isInitialLocaleSetup(locale)
__DEBUG__ && console.log('localeSetup', localeSetup)
const [modified] = await loadAndSetLocale(locale, localeMessages, i18n, {
useCookie,
differentDomains,
initial: localeSetup,
cacheMessages,
skipSettingLocaleOnNavigate,
lazy
})
if (modified && localeSetup) {
notInitialSetup = false
}
const redirectPath = detectRedirect({
route: { to, from },
targetLocale: locale,
routeLocaleGetter: nuxtI18nOptions.strategy === 'no_prefix' ? () => locale : getLocaleFromRoute,
nuxtI18nOptions,
calledWithRouting: true
})
__DEBUG__ && console.log('redirectPath on locale-changing middleware', redirectPath)
routeChangeCount++
return navigate(
{
i18n,
redirectPath,
locale,
route: to
},
{
differentDomains,
skipSettingLocaleOnNavigate,
rootRedirect
}
)
}),
{ 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<GetRouteBaseName>) => ReturnType<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<LocalePath>) => ReturnType<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<LocaleRoute>) => ReturnType<LocaleRoute>
/**
* Returns localized head properties for locale-related aspects.
*
* @param options - An options, see about details [I18nHeadOptions](https://github.com/intlify/routing/blob/main/packages/vue-i18n-routing/api.md#i18nheadoptions).
*
* @returns The localized [head properties](https://github.com/intlify/routing/blob/main/packages/vue-i18n-routing/api.md#i18nheadmetainfo).
*/
$localeHead: (...args: Parameters<LocaleHead>) => ReturnType<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<SwitchLocalePath>) => ReturnType<SwitchLocalePath>
}
}