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