-
-
Notifications
You must be signed in to change notification settings - Fork 860
/
index.js
684 lines (595 loc) · 20.6 KB
/
index.js
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
/* @flow */
import { install, Vue } from './install'
import {
warn,
isNull,
parseArgs,
isPlainObject,
isObject,
looseClone,
remove,
canUseDateTimeFormat,
canUseNumberFormat
} from './util'
import BaseFormatter from './format'
import I18nPath from './path'
import type { PathValue } from './path'
const numberFormatKeys = [
'style',
'currency',
'currencyDisplay',
'useGrouping',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
'localeMatcher',
'formatMatcher'
]
const linkKeyMatcher = /(@:([\w\-_|.]+|\([\w\-_|.]+\)))/g
const bracketsMatcher = /[()]/g
export default class VueI18n {
static install: () => void
static version: string
static availabilities: IntlAvailability
_vm: any
_formatter: Formatter
_root: any
_sync: boolean
_fallbackRoot: boolean
_missing: ?MissingHandler
_exist: Function
_watcher: any
_i18nWatcher: Function
_silentTranslationWarn: boolean
_dateTimeFormatters: Object
_numberFormatters: Object
_path: I18nPath
_dataListeners: Array<any>
constructor (options: I18nOptions = {}) {
// Auto install if it is not done yet and `window` has `Vue`.
// To allow users to avoid auto-installation in some cases,
// this code should be placed here. See #290
/* istanbul ignore if */
if (!Vue && typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
const locale: Locale = options.locale || 'en-US'
const fallbackLocale: Locale = options.fallbackLocale || 'en-US'
const messages: LocaleMessages = options.messages || {}
const dateTimeFormats = options.dateTimeFormats || {}
const numberFormats = options.numberFormats || {}
this._vm = null
this._formatter = options.formatter || new BaseFormatter()
this._missing = options.missing || null
this._root = options.root || null
this._sync = options.sync === undefined ? true : !!options.sync
this._fallbackRoot = options.fallbackRoot === undefined
? true
: !!options.fallbackRoot
this._silentTranslationWarn = options.silentTranslationWarn === undefined
? false
: !!options.silentTranslationWarn
this._dateTimeFormatters = {}
this._numberFormatters = {}
this._path = new I18nPath()
this._dataListeners = []
this._exist = (message: Object, key: Path): boolean => {
if (!message || !key) { return false }
return !isNull(this._path.getPathValue(message, key))
}
this._initVM({
locale,
fallbackLocale,
messages,
dateTimeFormats,
numberFormats
})
}
_initVM (data: {
locale: Locale,
fallbackLocale: Locale,
messages: LocaleMessages,
dateTimeFormats: DateTimeFormats,
numberFormats: NumberFormats
}): void {
const silent = Vue.config.silent
Vue.config.silent = true
this._vm = new Vue({ data })
Vue.config.silent = silent
}
subscribeDataChanging (vm: any): void {
this._dataListeners.push(vm)
}
unsubscribeDataChanging (vm: any): void {
remove(this._dataListeners, vm)
}
watchI18nData (): Function {
const self = this
return this._vm.$watch('$data', () => {
let i = self._dataListeners.length
while (i--) {
Vue.nextTick(() => {
self._dataListeners[i] && self._dataListeners[i].$forceUpdate()
})
}
}, { deep: true })
}
watchLocale (): ?Function {
/* istanbul ignore if */
if (!this._sync || !this._root) { return null }
const target: any = this._vm
return this._root.$i18n.vm.$watch('locale', (val) => {
target.$set(target, 'locale', val)
target.$forceUpdate()
}, { immediate: true })
}
get vm (): any { return this._vm }
get messages (): LocaleMessages { return looseClone(this._getMessages()) }
get dateTimeFormats (): DateTimeFormats { return looseClone(this._getDateTimeFormats()) }
get numberFormats (): NumberFormats { return looseClone(this._getNumberFormats()) }
get locale (): Locale { return this._vm.locale }
set locale (locale: Locale): void {
this._vm.$set(this._vm, 'locale', locale)
}
get fallbackLocale (): Locale { return this._vm.fallbackLocale }
set fallbackLocale (locale: Locale): void {
this._vm.$set(this._vm, 'fallbackLocale', locale)
}
get missing (): ?MissingHandler { return this._missing }
set missing (handler: MissingHandler): void { this._missing = handler }
get formatter (): Formatter { return this._formatter }
set formatter (formatter: Formatter): void { this._formatter = formatter }
get silentTranslationWarn (): boolean { return this._silentTranslationWarn }
set silentTranslationWarn (silent: boolean): void { this._silentTranslationWarn = silent }
_getMessages (): LocaleMessages { return this._vm.messages }
_getDateTimeFormats (): DateTimeFormats { return this._vm.dateTimeFormats }
_getNumberFormats (): NumberFormats { return this._vm.numberFormats }
_warnDefault (locale: Locale, key: Path, result: ?any, vm: ?any, values: any): ?string {
if (!isNull(result)) { return result }
if (this._missing) {
const missingRet = this._missing.apply(null, [locale, key, vm, values])
if (typeof missingRet === 'string') {
return missingRet
}
} else {
if (process.env.NODE_ENV !== 'production' && !this._silentTranslationWarn) {
warn(
`Cannot translate the value of keypath '${key}'. ` +
'Use the value of keypath as default.'
)
}
}
return key
}
_isFallbackRoot (val: any): boolean {
return !val && !isNull(this._root) && this._fallbackRoot
}
_interpolate (
locale: Locale,
message: LocaleMessageObject,
key: Path,
host: any,
interpolateMode: string,
values: any,
visitedLinkStack: Array<string>
): any {
if (!message) { return null }
const pathRet: PathValue = this._path.getPathValue(message, key)
if (Array.isArray(pathRet) || isPlainObject(pathRet)) { return pathRet }
let ret: mixed
if (isNull(pathRet)) {
/* istanbul ignore else */
if (isPlainObject(message)) {
ret = message[key]
if (typeof ret !== 'string') {
if (process.env.NODE_ENV !== 'production' && !this._silentTranslationWarn) {
warn(`Value of key '${key}' is not a string!`)
}
return null
}
} else {
return null
}
} else {
/* istanbul ignore else */
if (typeof pathRet === 'string') {
ret = pathRet
} else {
if (process.env.NODE_ENV !== 'production' && !this._silentTranslationWarn) {
warn(`Value of key '${key}' is not a string!`)
}
return null
}
}
// Check for the existance of links within the translated string
if (ret.indexOf('@:') >= 0) {
ret = this._link(locale, message, ret, host, interpolateMode, values, visitedLinkStack)
}
return this._render(ret, interpolateMode, values)
}
_link (
locale: Locale,
message: LocaleMessageObject,
str: string,
host: any,
interpolateMode: string,
values: any,
visitedLinkStack: Array<string>
): any {
let ret: string = str
// Match all the links within the local
// We are going to replace each of
// them with its translation
const matches: any = ret.match(linkKeyMatcher)
for (const idx in matches) {
// ie compatible: filter custom array
// prototype method
if (!matches.hasOwnProperty(idx)) {
continue
}
const link: string = matches[idx]
// Remove the leading @: and the brackets
const linkPlaceholder: string = link.substr(2).replace(bracketsMatcher, '')
if (visitedLinkStack.includes(linkPlaceholder)) {
if (process.env.NODE_ENV !== 'production') {
warn(`Circular reference found. "${link}" is already visited in the chain of ${visitedLinkStack.reverse().join(' <- ')}`)
}
return ret
}
visitedLinkStack.push(linkPlaceholder)
// Translate the link
let translated: any = this._interpolate(
locale, message, linkPlaceholder, host,
interpolateMode === 'raw' ? 'string' : interpolateMode,
interpolateMode === 'raw' ? undefined : values,
visitedLinkStack
)
if (this._isFallbackRoot(translated)) {
if (process.env.NODE_ENV !== 'production' && !this._silentTranslationWarn) {
warn(`Fall back to translate the link placeholder '${linkPlaceholder}' with root locale.`)
}
/* istanbul ignore if */
if (!this._root) { throw Error('unexpected error') }
const root: any = this._root.$i18n
translated = root._translate(
root._getMessages(), root.locale, root.fallbackLocale,
linkPlaceholder, host, interpolateMode, values
)
}
translated = this._warnDefault(
locale, linkPlaceholder, translated, host,
Array.isArray(values) ? values : [values]
)
visitedLinkStack.pop()
// Replace the link with the translated
ret = !translated ? ret : ret.replace(link, translated)
}
return ret
}
_render (message: string, interpolateMode: string, values: any): any {
const ret = this._formatter.interpolate(message, values)
// if interpolateMode is **not** 'string' ('row'),
// return the compiled data (e.g. ['foo', VNode, 'bar']) with formatter
return interpolateMode === 'string' ? ret.join('') : ret
}
_translate (
messages: LocaleMessages,
locale: Locale,
fallback: Locale,
key: Path,
host: any,
interpolateMode: string,
args: any
): any {
let res: any =
this._interpolate(locale, messages[locale], key, host, interpolateMode, args, [key])
if (!isNull(res)) { return res }
res = this._interpolate(fallback, messages[fallback], key, host, interpolateMode, args, [key])
if (!isNull(res)) {
if (process.env.NODE_ENV !== 'production' && !this._silentTranslationWarn) {
warn(`Fall back to translate the keypath '${key}' with '${fallback}' locale.`)
}
return res
} else {
return null
}
}
_t (key: Path, _locale: Locale, messages: LocaleMessages, host: any, ...values: any): any {
if (!key) { return '' }
const parsedArgs = parseArgs(...values)
const locale: Locale = parsedArgs.locale || _locale
const ret: any = this._translate(
messages, locale, this.fallbackLocale, key,
host, 'string', parsedArgs.params
)
if (this._isFallbackRoot(ret)) {
if (process.env.NODE_ENV !== 'production' && !this._silentTranslationWarn) {
warn(`Fall back to translate the keypath '${key}' with root locale.`)
}
/* istanbul ignore if */
if (!this._root) { throw Error('unexpected error') }
return this._root.$t(key, ...values)
} else {
return this._warnDefault(locale, key, ret, host, values)
}
}
t (key: Path, ...values: any): TranslateResult {
return this._t(key, this.locale, this._getMessages(), null, ...values)
}
_i (key: Path, locale: Locale, messages: LocaleMessages, host: any, values: Object): any {
const ret: any =
this._translate(messages, locale, this.fallbackLocale, key, host, 'raw', values)
if (this._isFallbackRoot(ret)) {
if (process.env.NODE_ENV !== 'production' && !this._silentTranslationWarn) {
warn(`Fall back to interpolate the keypath '${key}' with root locale.`)
}
if (!this._root) { throw Error('unexpected error') }
return this._root.$i18n.i(key, locale, values)
} else {
return this._warnDefault(locale, key, ret, host, [values])
}
}
i (key: Path, locale: Locale, values: Object): TranslateResult {
/* istanbul ignore if */
if (!key) { return '' }
if (typeof locale !== 'string') {
locale = this.locale
}
return this._i(key, locale, this._getMessages(), null, values)
}
_tc (
key: Path,
_locale: Locale,
messages: LocaleMessages,
host: any,
choice?: number,
...values: any
): any {
if (!key) { return '' }
if (choice === undefined) {
choice = 1
}
const predefined = { 'count': choice, 'n': choice }
const parsedArgs = parseArgs(...values)
parsedArgs.params = Object.assign(predefined, parsedArgs.params)
values = parsedArgs.locale === null ? [parsedArgs.params] : [parsedArgs.locale, parsedArgs.params]
return this.fetchChoice(this._t(key, _locale, messages, host, ...values), choice)
}
fetchChoice (message: string, choice: number): ?string {
/* istanbul ignore if */
if (!message && typeof message !== 'string') { return null }
const choices: Array<string> = message.split('|')
choice = this.getChoiceIndex(choice, choices.length)
if (!choices[choice]) { return message }
return choices[choice].trim()
}
/**
* @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)`
* @param choiceLength {number} an overall amount of available choices
* @returns a final choice index
*/
getChoiceIndex (choice: number, choicesLength: number): number {
choice = Math.abs(choice)
if (choicesLength === 2) {
return choice
? choice > 1
? 1
: 0
: 1
}
return choice ? Math.min(choice, 2) : 0
}
tc (key: Path, choice?: number, ...values: any): TranslateResult {
return this._tc(key, this.locale, this._getMessages(), null, choice, ...values)
}
_te (key: Path, locale: Locale, messages: LocaleMessages, ...args: any): boolean {
const _locale: Locale = parseArgs(...args).locale || locale
return this._exist(messages[_locale], key)
}
te (key: Path, locale?: Locale): boolean {
return this._te(key, this.locale, this._getMessages(), locale)
}
getLocaleMessage (locale: Locale): LocaleMessageObject {
return looseClone(this._vm.messages[locale] || {})
}
setLocaleMessage (locale: Locale, message: LocaleMessageObject): void {
this._vm.$set(this._vm.messages, locale, message)
}
mergeLocaleMessage (locale: Locale, message: LocaleMessageObject): void {
this._vm.$set(this._vm.messages, locale, Vue.util.extend(this._vm.messages[locale] || {}, message))
}
getDateTimeFormat (locale: Locale): DateTimeFormat {
return looseClone(this._vm.dateTimeFormats[locale] || {})
}
setDateTimeFormat (locale: Locale, format: DateTimeFormat): void {
this._vm.$set(this._vm.dateTimeFormats, locale, format)
}
mergeDateTimeFormat (locale: Locale, format: DateTimeFormat): void {
this._vm.$set(this._vm.dateTimeFormats, locale, Vue.util.extend(this._vm.dateTimeFormats[locale] || {}, format))
}
_localizeDateTime (
value: number | Date,
locale: Locale,
fallback: Locale,
dateTimeFormats: DateTimeFormats,
key: string
): ?DateTimeFormatResult {
let _locale: Locale = locale
let formats: DateTimeFormat = dateTimeFormats[_locale]
// fallback locale
if (isNull(formats) || isNull(formats[key])) {
if (process.env.NODE_ENV !== 'production') {
warn(`Fall back to '${fallback}' datetime formats from '${locale} datetime formats.`)
}
_locale = fallback
formats = dateTimeFormats[_locale]
}
if (isNull(formats) || isNull(formats[key])) {
return null
} else {
const format: ?DateTimeFormatOptions = formats[key]
const id = `${_locale}__${key}`
let formatter = this._dateTimeFormatters[id]
if (!formatter) {
formatter = this._dateTimeFormatters[id] = new Intl.DateTimeFormat(_locale, format)
}
return formatter.format(value)
}
}
_d (value: number | Date, locale: Locale, key: ?string): DateTimeFormatResult {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !VueI18n.availabilities.dateTimeFormat) {
warn('Cannot format a Date value due to not supported Intl.DateTimeFormat.')
return ''
}
if (!key) {
return new Intl.DateTimeFormat(locale).format(value)
}
const ret: ?DateTimeFormatResult =
this._localizeDateTime(value, locale, this.fallbackLocale, this._getDateTimeFormats(), key)
if (this._isFallbackRoot(ret)) {
if (process.env.NODE_ENV !== 'production') {
warn(`Fall back to datetime localization of root: key '${key}' .`)
}
/* istanbul ignore if */
if (!this._root) { throw Error('unexpected error') }
return this._root.$i18n.d(value, key, locale)
} else {
return ret || ''
}
}
d (value: number | Date, ...args: any): DateTimeFormatResult {
let locale: Locale = this.locale
let key: ?string = null
if (args.length === 1) {
if (typeof args[0] === 'string') {
key = args[0]
} else if (isObject(args[0])) {
if (args[0].locale) {
locale = args[0].locale
}
if (args[0].key) {
key = args[0].key
}
}
} else if (args.length === 2) {
if (typeof args[0] === 'string') {
key = args[0]
}
if (typeof args[1] === 'string') {
locale = args[1]
}
}
return this._d(value, locale, key)
}
getNumberFormat (locale: Locale): NumberFormat {
return looseClone(this._vm.numberFormats[locale] || {})
}
setNumberFormat (locale: Locale, format: NumberFormat): void {
this._vm.$set(this._vm.numberFormats, locale, format)
}
mergeNumberFormat (locale: Locale, format: NumberFormat): void {
this._vm.$set(this._vm.numberFormats, locale, Vue.util.extend(this._vm.numberFormats[locale] || {}, format))
}
_localizeNumber (
value: number,
locale: Locale,
fallback: Locale,
numberFormats: NumberFormats,
key: string,
options: ?NumberFormatOptions
): ?NumberFormatResult {
let _locale: Locale = locale
let formats: NumberFormat = numberFormats[_locale]
// fallback locale
if (isNull(formats) || isNull(formats[key])) {
if (process.env.NODE_ENV !== 'production') {
warn(`Fall back to '${fallback}' number formats from '${locale} number formats.`)
}
_locale = fallback
formats = numberFormats[_locale]
}
if (isNull(formats) || isNull(formats[key])) {
return null
} else {
const format: ?NumberFormatOptions = formats[key]
let formatter
if (options) {
// If options specified - create one time number formatter
formatter = new Intl.NumberFormat(_locale, Object.assign({}, format, options))
} else {
const id = `${_locale}__${key}`
formatter = this._numberFormatters[id]
if (!formatter) {
formatter = this._numberFormatters[id] = new Intl.NumberFormat(_locale, format)
}
}
return formatter.format(value)
}
}
_n (value: number, locale: Locale, key: ?string, options: ?NumberFormatOptions): NumberFormatResult {
/* istanbul ignore if */
if (!VueI18n.availabilities.numberFormat) {
if (process.env.NODE_ENV !== 'production') {
warn('Cannot format a Number value due to not supported Intl.NumberFormat.')
}
return ''
}
if (!key) {
const nf = !options ? new Intl.NumberFormat(locale) : new Intl.NumberFormat(locale, options)
return nf.format(value)
}
const ret: ?NumberFormatResult =
this._localizeNumber(value, locale, this.fallbackLocale, this._getNumberFormats(), key, options)
if (this._isFallbackRoot(ret)) {
if (process.env.NODE_ENV !== 'production') {
warn(`Fall back to number localization of root: key '${key}' .`)
}
/* istanbul ignore if */
if (!this._root) { throw Error('unexpected error') }
return this._root.$i18n.n(value, Object.assign({}, { key, locale }, options))
} else {
return ret || ''
}
}
n (value: number, ...args: any): NumberFormatResult {
let locale: Locale = this.locale
let key: ?string = null
let options: ?NumberFormatOptions = null
if (args.length === 1) {
if (typeof args[0] === 'string') {
key = args[0]
} else if (isObject(args[0])) {
if (args[0].locale) {
locale = args[0].locale
}
if (args[0].key) {
key = args[0].key
}
// Filter out number format options only
options = Object.keys(args[0]).reduce((acc, key) => {
if (numberFormatKeys.includes(key)) {
return Object.assign({}, acc, { [key]: args[0][key] })
}
return acc
}, null)
}
} else if (args.length === 2) {
if (typeof args[0] === 'string') {
key = args[0]
}
if (typeof args[1] === 'string') {
locale = args[1]
}
}
return this._n(value, locale, key, options)
}
}
VueI18n.availabilities = {
dateTimeFormat: canUseDateTimeFormat,
numberFormat: canUseNumberFormat
}
VueI18n.install = install
VueI18n.version = '__VERSION__'