1 |
|
2 |
|
3 | export const I18N_INIT = 'I18N_INIT'
|
4 | export const I18N_LOCALES = 'I18N_LOCALES'
|
5 |
|
6 |
|
7 |
|
8 | export let availableLocales = []
|
9 | export const setAvailableLocales = arr => availableLocales = arr
|
10 |
|
11 |
|
12 | export let localeId = null
|
13 | export const setLocaleId = newLlocalId => {
|
14 | if (typeof newLlocalId === 'undefined' || newLlocalId === null)
|
15 | return
|
16 | if (__DEV__ && __SERVER__)
|
17 | console.log(`\n \x1b[93m[super/i18n]\x1b[0m setLocaleId -> \x1b[32m${newLlocalId}\x1b[0m\n`)
|
18 | localeId = newLlocalId
|
19 | return localeId
|
20 | }
|
21 |
|
22 |
|
23 | export let locales = {}
|
24 | export const setLocales = (locale = localeId, obj) => {
|
25 | locales[locale] = obj
|
26 | }
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | export const checkLocalesReady = (theLocaleId = localeId) => {
|
39 | return (typeof locales[theLocaleId] !== 'undefined')
|
40 | }
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | const translate = (...args) => {
|
54 | let key = ''
|
55 | let str
|
56 | let options = {}
|
57 | const keys = []
|
58 | const l = JSON.parse(process.env.SUPER_I18N_TYPE) === 'redux' || __SERVER__
|
59 | ? locales[localeId]
|
60 | : undefined
|
61 |
|
62 | args.forEach((value, index) => {
|
63 | if (index == args.length - 1 && typeof value === 'object') {
|
64 | options = value
|
65 | return
|
66 | }
|
67 | if (typeof value === 'string' && value.includes('.')) {
|
68 | value.split('.').forEach(value => keys.push(value))
|
69 | return
|
70 | }
|
71 | keys.push(value)
|
72 | })
|
73 |
|
74 | const length = keys.length
|
75 |
|
76 | if (typeof keys[0] === 'object') {
|
77 | key = keys[0]
|
78 | for (let i = 1; i < length; i++) {
|
79 | if (typeof key[keys[i]] !== 'undefined')
|
80 | key = key[keys[i]]
|
81 | }
|
82 | if (typeof key === 'object') key = keys[length - 1]
|
83 | } else {
|
84 | for (let i = 0; i < length; i++) {
|
85 | key += (i ? '.' : '') + keys[i]
|
86 | }
|
87 | }
|
88 |
|
89 |
|
90 |
|
91 | if (typeof l === 'undefined') {
|
92 | str = key
|
93 | } else {
|
94 | str = (l && typeof l[key] !== 'undefined') ? l[key] : undefined
|
95 | }
|
96 |
|
97 |
|
98 | if (typeof str === 'undefined') {
|
99 | try {
|
100 | str = eval('l.' + key)
|
101 | } catch (e) { }
|
102 | }
|
103 |
|
104 | if (typeof str === 'undefined') str = key
|
105 |
|
106 | if (typeof str === 'string')
|
107 | return str.replace(
|
108 | /\$\{([^}]+)\}/g,
|
109 | (match, p) => typeof options[p] === 'undefined' ? p : options[p]
|
110 | )
|
111 | else
|
112 | return str
|
113 | }
|
114 |
|
115 | export default translate
|