-
-
Notifications
You must be signed in to change notification settings - Fork 337
/
i18n.ts
1760 lines (1638 loc) · 49.2 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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
inject,
onBeforeMount,
onMounted,
onUnmounted,
InjectionKey,
getCurrentInstance,
shallowRef,
isRef,
ref,
computed,
effectScope
} from 'vue'
import {
inBrowser,
isEmptyObject,
isBoolean,
isString,
isArray,
isPlainObject,
isRegExp,
isFunction,
warn,
makeSymbol,
createEmitter,
assign
} from '@intlify/shared'
import { createComposer, DEFAULT_LOCALE } from './composer'
import { createVueI18n } from './legacy'
import { I18nWarnCodes, getWarnMessage } from './warnings'
import { I18nErrorCodes, createI18nError } from './errors'
import {
EnableEmitter,
DisableEmitter,
DisposeSymbol,
InejctWithOptionSymbol,
LegacyInstanceSymbol,
__VUE_I18N_BRIDGE__
} from './symbols'
import { apply as applyNext } from './plugin/next'
import { apply as applyBridge } from './plugin/bridge'
import { defineMixin as defineMixinNext } from './mixins/next'
import { defineMixin as defineMixinBridge } from './mixins/bridge'
import { enableDevTools, addTimelineEvent } from './devtools'
import {
isLegacyVueI18n,
getComponentOptions,
getLocaleMessages,
adjustI18nResources
} from './utils'
import type { ComponentInternalInstance, App, EffectScope } from 'vue'
import type {
Locale,
Path,
FallbackLocale,
SchemaParams,
LocaleMessages,
LocaleMessage,
LocaleMessageValue,
LocaleMessageDictionary,
PostTranslationHandler,
DateTimeFormats as DateTimeFormatsType,
NumberFormats as NumberFormatsType,
DateTimeFormat,
NumberFormat,
LocaleParams,
LinkedModifiers,
PluralizationRules
} from '@intlify/core-base'
import type {
VueDevToolsEmitter,
VueDevToolsEmitterEvents
} from '@intlify/vue-devtools'
import type {
VueMessageType,
MissingHandler,
DefaultLocaleMessageSchema,
DefaultDateTimeFormatSchema,
DefaultNumberFormatSchema,
Composer,
ComposerOptions,
ComposerInternalOptions
} from './composer'
import type {
VueI18n,
VueI18nOptions,
VueI18nInternal,
VueI18nExtender
} from './legacy'
import type { Disposer } from './types'
declare module 'vue' {
// eslint-disable-next-line
interface App<HostElement = any> {
__VUE_I18N__?: I18n & I18nInternal
__VUE_I18N_SYMBOL__?: InjectionKey<I18n> | string
}
}
// internal Component Instance API isCE
declare module '@vue/runtime-core' {
export interface ComponentInternalInstance {
/**
* @internal
* is custom element?
*/
isCE?: boolean
}
}
// for bridge
let _legacyVueI18n: any = /* #__PURE__*/ null // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* I18n Options for `createI18n`
*
* @remarks
* `I18nOptions` is inherited {@link I18nAdditionalOptions}, {@link ComposerOptions} and {@link VueI18nOptions},
* so you can specify these options.
*
* @VueI18nGeneral
*/
export type I18nOptions<
Schema extends {
message?: unknown
datetime?: unknown
number?: unknown
} = {
message: DefaultLocaleMessageSchema
datetime: DefaultDateTimeFormatSchema
number: DefaultNumberFormatSchema
},
Locales extends
| {
messages: unknown
datetimeFormats: unknown
numberFormats: unknown
}
| string = Locale,
Options extends
| ComposerOptions<Schema, Locales>
| VueI18nOptions<Schema, Locales> =
| ComposerOptions<Schema, Locales>
| VueI18nOptions<Schema, Locales>
> = I18nAdditionalOptions & Options
/**
* I18n Additional Options
*
* @remarks
* Specific options for {@link createI18n}
*
* @VueI18nGeneral
*/
export interface I18nAdditionalOptions {
/**
* Whether vue-i18n Legacy API mode use on your Vue App
*
* @remarks
* The default is to use the Legacy API mode. If you want to use the Composition API mode, you need to set it to `false`.
*
* @VueI18nSee [Composition API](../guide/advanced/composition)
*
* @defaultValue `true`
*/
legacy?: boolean
/**
* Whether to inject global properties & functions into for each component.
*
* @remarks
* If set to `true`, then properties and methods prefixed with `$` are injected into Vue Component.
*
* @VueI18nSee [Implicit with injected properties and functions](../guide/advanced/composition#implicit-with-injected-properties-and-functions)
* @VueI18nSee [ComponentCustomProperties](injection#componentcustomproperties)
*
* @defaultValue `true`
*/
globalInjection?: boolean
/**
* Whether to allow the Composition API to be used in Legacy API mode.
*
* @remarks
* If this option is enabled, you can use {@link useI18n} in Legacy API mode. This option is supported to support the migration from Legacy API mode to Composition API mode.
*
* @VueI18nWarning Note that the Composition API made available with this option doesn't work on SSR.
* @VueI18nSee [Composition API](../guide/advanced/composition)
*
* @defaultValue `false`
*/
allowComposition?: boolean
}
/**
* Vue I18n API mode
*
* @VueI18nSee [I18n#mode](general#mode)
*
* @VueI18nGeneral
*/
export type I18nMode = 'legacy' | 'composition'
/**
* I18n instance
*
* @remarks
* The instance required for installation as the Vue plugin
*
* @VueI18nGeneral
*/
export interface I18n<
Messages extends Record<string, unknown> = {},
DateTimeFormats extends Record<string, unknown> = {},
NumberFormats extends Record<string, unknown> = {},
OptionLocale = Locale,
Legacy = boolean
> {
/**
* Vue I18n API mode
*
* @remarks
* If you specified `legacy: true` option in `createI18n`, return `legacy`, else `composition`
*
* @defaultValue `'legacy'`
*/
readonly mode: I18nMode
// prettier-ignore
/**
* The property accessible to the global Composer instance or VueI18n instance
*
* @remarks
* If the [I18n#mode](general#mode) is `'legacy'`, then you can access to a global {@link VueI18n} instance, else then [I18n#mode](general#mode) is `'composition' `, you can access to the global {@link Composer} instance.
*
* An instance of this property is **global scope***.
*/
readonly global: Legacy extends true
? VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
: Legacy extends false
? Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
: unknown
/**
* The property whether or not the Composition API is available
*
* @remarks
* If you specified `allowComposition: true` option in Legacy API mode, return `true`, else `false`. else you use the Composition API mode, this property will always return `true`.
*/
readonly allowComposition: boolean
/**
* Install entry point
*
* @param app - A target Vue app instance
* @param options - An install options
*/
install(app: App, ...options: unknown[]): void
/**
* Release global scope resource
*/
dispose(): void
}
export type ComposerExtender = (composer: Composer) => Disposer | undefined
/**
* The hooks that give to extend Composer (Composition API) and VueI18n instance (Options API).
* This hook is mainly for vue-i18n-routing and nuxt i18n.
*
* @internal
*/
type ExtendHooks = {
__composerExtend?: ComposerExtender
__vueI18nExtend?: VueI18nExtender
}
/**
* I18n interface for internal usage
*
* @internal
*/
export interface I18nInternal<
Messages extends Record<string, unknown> = {},
DateTimeFormats extends Record<string, unknown> = {},
NumberFormats extends Record<string, unknown> = {},
OptionLocale = Locale
> {
__instances: Map<
ComponentInternalInstance,
| VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
| Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
>
__getInstance<
Instance extends
| VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
| Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
>(
component: ComponentInternalInstance
): Instance | null
__setInstance<
Instance extends
| VueI18n<Messages, DateTimeFormats, NumberFormats, OptionLocale>
| Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale>
>(
component: ComponentInternalInstance,
instance: Instance
): void
__deleteInstance(component: ComponentInternalInstance): void
__composerExtend?: ComposerExtender
__vueI18nExtend?: VueI18nExtender
}
/**
* I18n Scope
*
* @VueI18nSee [ComposerAdditionalOptions#useScope](composition#usescope)
* @VueI18nSee [useI18n](composition#usei18n)
*
* @VueI18nGeneral
*/
export type I18nScope = 'local' | 'parent' | 'global'
/**
* I18n Options for `useI18n`
*
* @remarks
* `UseI18nOptions` is inherited {@link ComposerAdditionalOptions} and {@link ComposerOptions}, so you can specify these options.
*
* @VueI18nSee [useI18n](composition#usei18n)
*
* @VueI18nComposition
*/
export type UseI18nOptions<
Schema extends {
message?: unknown
datetime?: unknown
number?: unknown
} = {
message: DefaultLocaleMessageSchema
datetime: DefaultDateTimeFormatSchema
number: DefaultNumberFormatSchema
},
Locales extends
| {
messages: unknown
datetimeFormats: unknown
numberFormats: unknown
}
| string = Locale,
Options extends ComposerOptions<Schema, Locales> = ComposerOptions<
Schema,
Locales
>
> = ComposerAdditionalOptions & Options
/**
* Composer additional options for `useI18n`
*
* @remarks
* `ComposerAdditionalOptions` is extend for {@link ComposerOptions}, so you can specify these options.
*
* @VueI18nSee [useI18n](composition#usei18n)
*
* @VueI18nComposition
*/
export interface ComposerAdditionalOptions {
useScope?: I18nScope
}
/**
* Injection key for {@link useI18n}
*
* @remarks
* The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
* Specify the i18n instance created by {@link createI18n} together with `provide` function.
*
* @VueI18nGeneral
*/
export const I18nInjectionKey: InjectionKey<I18n> | string =
/* #__PURE__*/ makeSymbol('global-vue-i18n')
export function createI18n<
Legacy extends boolean = true,
Options extends I18nOptions = I18nOptions,
Messages extends Record<string, unknown> = Options['messages'] extends Record<
string,
unknown
>
? Options['messages']
: {},
DateTimeFormats extends Record<
string,
unknown
> = Options['datetimeFormats'] extends Record<string, unknown>
? Options['datetimeFormats']
: {},
NumberFormats extends Record<
string,
unknown
> = Options['numberFormats'] extends Record<string, unknown>
? Options['numberFormats']
: {},
OptionLocale = Options['locale'] extends string ? Options['locale'] : Locale
>(
options: Options,
LegacyVueI18n?: any // eslint-disable-line @typescript-eslint/no-explicit-any
): (typeof options)['legacy'] extends true
? I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, true>
: (typeof options)['legacy'] extends false
? I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, false>
: I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, Legacy>
/**
* Vue I18n factory
*
* @param options - An options, see the {@link I18nOptions}
*
* @typeParam Schema - The i18n resources (messages, datetimeFormats, numberFormats) schema, default {@link LocaleMessage}
* @typeParam Locales - The locales of i18n resource schema, default `en-US`
* @typeParam Legacy - Whether legacy mode is enabled or disabled, default `true`
*
* @returns {@link I18n} instance
*
* @remarks
* If you use Legacy API mode, you need to specify {@link VueI18nOptions} and `legacy: true` option.
*
* If you use composition API mode, you need to specify {@link ComposerOptions}.
*
* @VueI18nSee [Getting Started](../guide/)
* @VueI18nSee [Composition API](../guide/advanced/composition)
*
* @example
* case: for Legacy API
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* // ...
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @example
* case: for composition API
* ```js
* import { createApp } from 'vue'
* import { createI18n, useI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* legacy: false, // you must specify 'legacy: false' option
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* setup() {
* // ...
* const { t } = useI18n({ ... })
* return { ... , t }
* }
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @VueI18nGeneral
*/
export function createI18n<
Schema extends object = DefaultLocaleMessageSchema,
Locales extends string | object = 'en-US',
Legacy extends boolean = true,
Options extends I18nOptions<
SchemaParams<Schema, VueMessageType>,
LocaleParams<Locales>
> = I18nOptions<SchemaParams<Schema, VueMessageType>, LocaleParams<Locales>>,
Messages extends Record<string, unknown> = NonNullable<
Options['messages']
> extends Record<string, unknown>
? NonNullable<Options['messages']>
: {},
DateTimeFormats extends Record<string, unknown> = NonNullable<
Options['datetimeFormats']
> extends Record<string, unknown>
? NonNullable<Options['datetimeFormats']>
: {},
NumberFormats extends Record<string, unknown> = NonNullable<
Options['numberFormats']
> extends Record<string, unknown>
? NonNullable<Options['numberFormats']>
: {},
OptionLocale = Options['locale'] extends string ? Options['locale'] : Locale
>(
options: Options,
LegacyVueI18n?: any // eslint-disable-line @typescript-eslint/no-explicit-any
): (typeof options)['legacy'] extends true
? I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, true>
: (typeof options)['legacy'] extends false
? I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, false>
: I18n<Messages, DateTimeFormats, NumberFormats, OptionLocale, Legacy>
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
export function createI18n(options: any = {}, VueI18nLegacy?: any): any {
type _I18n = I18n & I18nInternal
if (__BRIDGE__) {
_legacyVueI18n = VueI18nLegacy
}
// prettier-ignore
const __legacyMode = __LITE__
? false
: __FEATURE_LEGACY_API__ && isBoolean(options.legacy)
? options.legacy
: __FEATURE_LEGACY_API__
// prettier-ignore
const __globalInjection = isBoolean(options.globalInjection)
? options.globalInjection
: true
// prettier-ignore
const __allowComposition = __LITE__
? true
: __FEATURE_LEGACY_API__ && __legacyMode
? !!options.allowComposition
: true
const __instances = new Map<ComponentInternalInstance, VueI18n | Composer>()
const [globalScope, __global] = createGlobal(
options,
__legacyMode,
VueI18nLegacy
)
const symbol: InjectionKey<I18n> | string = /* #__PURE__*/ makeSymbol(
__DEV__ ? 'vue-i18n' : ''
)
if (__DEV__) {
if (__legacyMode && __allowComposition && !__TEST__) {
warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION))
}
}
function __getInstance<Instance extends VueI18n | Composer>(
component: ComponentInternalInstance
): Instance | null {
return (__instances.get(component) as unknown as Instance) || null
}
function __setInstance<Instance extends VueI18n | Composer>(
component: ComponentInternalInstance,
instance: Instance
): void {
__instances.set(component, instance)
}
function __deleteInstance(component: ComponentInternalInstance): void {
__instances.delete(component)
}
if (!__BRIDGE__) {
const i18n = {
// mode
get mode(): I18nMode {
return !__LITE__ && __FEATURE_LEGACY_API__ && __legacyMode
? 'legacy'
: 'composition'
},
// allowComposition
get allowComposition(): boolean {
return __allowComposition
},
// install plugin
async install(app: App, ...options: unknown[]): Promise<void> {
if (
!__BRIDGE__ &&
(__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
!__NODE_JS__
) {
app.__VUE_I18N__ = i18n as unknown as _I18n
}
// setup global provider
app.__VUE_I18N_SYMBOL__ = symbol
app.provide(app.__VUE_I18N_SYMBOL__, i18n as unknown as I18n)
// set composer & vuei18n extend hook options from plugin options
if (isPlainObject(options[0])) {
const opts = options[0] as ExtendHooks
// Plugin options cannot be passed directly to the function that creates Composer & VueI18n,
// so we keep it temporary
;(i18n as unknown as I18nInternal).__composerExtend =
opts.__composerExtend
;(i18n as unknown as I18nInternal).__vueI18nExtend =
opts.__vueI18nExtend
}
// global method and properties injection for Composition API
let globalReleaseHandler: ReturnType<typeof injectGlobalFields> | null =
null
if (!__legacyMode && __globalInjection) {
globalReleaseHandler = injectGlobalFields(
app,
i18n.global as Composer
)
}
// install built-in components and directive
if (!__LITE__ && __FEATURE_FULL_INSTALL__) {
applyNext(app, i18n as I18n, ...options)
}
// setup mixin for Legacy API
if (!__LITE__ && __FEATURE_LEGACY_API__ && __legacyMode) {
app.mixin(
defineMixinNext(
__global as unknown as VueI18n,
(__global as unknown as VueI18nInternal).__composer as Composer,
i18n as unknown as I18nInternal
)
)
}
// release global scope
const unmountApp = app.unmount
app.unmount = () => {
globalReleaseHandler && globalReleaseHandler()
i18n.dispose()
unmountApp()
}
// setup vue-devtools plugin
if ((__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) && !__NODE_JS__) {
const ret = await enableDevTools(app, i18n as _I18n)
if (!ret) {
throw createI18nError(
I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN
)
}
const emitter: VueDevToolsEmitter =
createEmitter<VueDevToolsEmitterEvents>()
if (__legacyMode) {
const _vueI18n = __global as unknown as VueI18nInternal
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter)
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global as any
_composer[EnableEmitter] && _composer[EnableEmitter](emitter)
}
emitter.on('*', addTimelineEvent)
}
},
// global accessor
get global() {
return __global
},
dispose(): void {
globalScope.stop()
},
// @internal
__instances,
// @internal
__getInstance,
// @internal
__setInstance,
// @internal
__deleteInstance
}
return i18n
} else {
// extend legacy VueI18n instance
const i18n = (__global as any)[LegacyInstanceSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
let _localeWatcher: Function | null = null
Object.defineProperty(i18n, 'global', {
get() {
return __global
}
})
Object.defineProperty(i18n, 'mode', {
get() {
return __legacyMode ? 'legacy' : 'composition'
}
})
Object.defineProperty(i18n, 'allowComposition', {
get() {
return __allowComposition
}
})
Object.defineProperty(i18n, '__instances', {
get() {
return __instances
}
})
Object.defineProperty(i18n, 'install', {
writable: true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: (Vue: any, ...options: unknown[]) => {
const version =
(Vue && Vue.version && Number(Vue.version.split('.')[0])) || -1
if (version !== 2) {
throw createI18nError(I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY)
}
__FEATURE_FULL_INSTALL__ && applyBridge(Vue, ...options)
if (!__legacyMode && __globalInjection) {
_localeWatcher = injectGlobalFieldsForBridge(
Vue,
i18n,
__global as Composer
)
}
Vue.mixin(defineMixinBridge(i18n, _legacyVueI18n))
}
})
Object.defineProperty(i18n, 'dispose', {
value: (): void => {
_localeWatcher && _localeWatcher()
globalScope.stop()
}
})
const methodMap = {
__getInstance,
__setInstance,
__deleteInstance
}
Object.keys(methodMap).forEach(
key =>
Object.defineProperty(i18n, key, { value: (methodMap as any)[key] }) // eslint-disable-line @typescript-eslint/no-explicit-any
)
return i18n
}
}
export function useI18n<Options extends UseI18nOptions = UseI18nOptions>(
options?: Options
): Composer<
NonNullable<Options['messages']>,
NonNullable<Options['datetimeFormats']>,
NonNullable<Options['numberFormats']>,
Options['locale'] extends unknown ? string : Options['locale']
>
/**
* Use Composition API for Vue I18n
*
* @param options - An options, see {@link UseI18nOptions}
*
* @typeParam Schema - The i18n resources (messages, datetimeFormats, numberFormats) schema, default {@link LocaleMessage}
* @typeParam Locales - The locales of i18n resource schema, default `en-US`
*
* @returns {@link Composer} instance
*
* @remarks
* This function is mainly used by `setup`.
*
* If options are specified, Composer instance is created for each component and you can be localized on the component.
*
* If options are not specified, you can be localized using the global Composer.
*
* @example
* case: Component resource base localization
* ```html
* <template>
* <form>
* <label>{{ t('language') }}</label>
* <select v-model="locale">
* <option value="en">en</option>
* <option value="ja">ja</option>
* </select>
* </form>
* <p>message: {{ t('hello') }}</p>
* </template>
*
* <script>
* import { useI18n } from 'vue-i18n'
*
* export default {
* setup() {
* const { t, locale } = useI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
* // Something to do ...
*
* return { ..., t, locale }
* }
* }
* </script>
* ```
*
* @VueI18nComposition
*/
export function useI18n<
Schema = DefaultLocaleMessageSchema,
Locales = 'en-US',
Options extends UseI18nOptions<
SchemaParams<Schema, VueMessageType>,
LocaleParams<Locales>
> = UseI18nOptions<
SchemaParams<Schema, VueMessageType>,
LocaleParams<Locales>
>
>(
options?: Options
): Composer<
NonNullable<Options['messages']>,
NonNullable<Options['datetimeFormats']>,
NonNullable<Options['numberFormats']>,
Options['locale'] extends unknown ? string : Options['locale']
>
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function useI18n<
Options extends UseI18nOptions = UseI18nOptions,
Messages extends Record<string, unknown> = NonNullable<Options['messages']>,
DateTimeFormats extends Record<string, unknown> = NonNullable<
Options['datetimeFormats']
>,
NumberFormats extends Record<string, unknown> = NonNullable<
Options['numberFormats']
>,
OptionLocale = NonNullable<Options['locale']>
>(options: Options = {} as Options) {
const instance = getCurrentInstance()
if (instance == null) {
throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP)
}
if (
!__BRIDGE__ &&
!instance.isCE &&
instance.appContext.app != null &&
!instance.appContext.app.__VUE_I18N_SYMBOL__
) {
throw createI18nError(I18nErrorCodes.NOT_INSTALLED)
}
if (__BRIDGE__) {
if (_legacyVueI18n == null) {
throw createI18nError(I18nErrorCodes.NOT_INSTALLED)
}
}
const i18n = getI18nInstance(instance)
const gl = getGlobalComposer(i18n)
const componentOptions = getComponentOptions(instance)
const scope = getScope(options, componentOptions)
if (!__LITE__ && __FEATURE_LEGACY_API__) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (i18n.mode === 'legacy' && !(options as any).__useComponent) {
if (!i18n.allowComposition) {
throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE)
}
return useI18nForLegacy(instance, scope, gl, options)
}
}
if (scope === 'global') {
adjustI18nResources(gl, options, componentOptions)
return gl as unknown as Composer<
Messages,
DateTimeFormats,
NumberFormats,
OptionLocale
>
}
if (scope === 'parent') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let composer = getComposer(i18n, instance, (options as any).__useComponent)
if (composer == null) {
if (__DEV__) {
warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE))
}
composer = gl as unknown as Composer
}
return composer as unknown as Composer<
Messages,
DateTimeFormats,
NumberFormats,
OptionLocale
>
}
const i18nInternal = i18n as unknown as I18nInternal
let composer = i18nInternal.__getInstance(instance)
if (composer == null) {
const composerOptions = assign({}, options) as ComposerOptions &
ComposerInternalOptions
if ('__i18n' in componentOptions) {
composerOptions.__i18n = componentOptions.__i18n
}
if (gl) {
composerOptions.__root = gl
}
composer = createComposer(composerOptions, _legacyVueI18n) as Composer
if (i18nInternal.__composerExtend) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(composer as any)[DisposeSymbol] =
i18nInternal.__composerExtend(composer)
}
setupLifeCycle(i18nInternal, instance, composer)
i18nInternal.__setInstance(instance, composer)
}
return composer as unknown as Composer<
Messages,
DateTimeFormats,
NumberFormats,
OptionLocale
>
}
/**
* Cast to VueI18n legacy compatible type
*
* @remarks
* This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).
*
* The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `[email protected]` compatible instance of `new VueI18n` in a TypeScript environment.
*
* @param i18n - An instance of {@link I18n}
* @returns A i18n instance which is casted to {@link VueI18n} type
*
* @VueI18nTip
* :new: provided by **vue-i18n-bridge only**
*
* @VueI18nGeneral
*/
/* #__NO_SIDE_EFFECTS__ */
export const castToVueI18n = (
i18n: I18n
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): VueI18n & { install: (Vue: any, options?: any) => void } => {
if (!(__VUE_I18N_BRIDGE__ in i18n)) {
throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N)
}
return i18n as unknown as VueI18n & {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
install: (Vue: any, options?: any) => void
}
}
function createGlobal(
options: I18nOptions,
legacyMode: boolean,
VueI18nLegacy: any // eslint-disable-line @typescript-eslint/no-explicit-any
): [EffectScope, VueI18n | Composer] {
const scope = effectScope()
if (!__BRIDGE__) {
const obj =
!__LITE__ && __FEATURE_LEGACY_API__ && legacyMode
? scope.run(() => createVueI18n(options, VueI18nLegacy))
: scope.run(() => createComposer(options, VueI18nLegacy))
if (obj == null) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
return [scope, obj]
} else {
if (!isLegacyVueI18n(VueI18nLegacy)) {
throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N)
}
const obj = scope.run(() => createComposer(options, VueI18nLegacy))
if (obj == null) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
return [scope, obj]
}
}
function getI18nInstance(instance: ComponentInternalInstance): I18n {
if (!__BRIDGE__) {
const i18n = inject(
!instance.isCE
? instance.appContext.app.__VUE_I18N_SYMBOL__!
: I18nInjectionKey
)