1 | import { localeId } from '../'
|
2 | import locales from './locales'
|
3 |
|
4 | export let l = (() => {
|
5 | if (__SERVER__) {
|
6 | if (__DEV__ && typeof global.__KOOT_SSR__ === 'object') {
|
7 | if (typeof global.__KOOT_SSR__.locales === 'object')
|
8 | return global.__KOOT_SSR__.locales[localeId]
|
9 | return {}
|
10 | }
|
11 |
|
12 | if (typeof locales === 'object')
|
13 | return locales[localeId]
|
14 | return {}
|
15 | }
|
16 | if (JSON.parse(process.env.KOOT_I18N_TYPE) === 'redux')
|
17 | return locales
|
18 | return false
|
19 | })()
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | const translate = (...args) => {
|
31 |
|
32 | let key = ''
|
33 | let str
|
34 | let options = {}
|
35 | const keys = []
|
36 |
|
37 | if (__SERVER__ && __DEV__) l = locales[global.__KOOT_LOCALEID__]
|
38 |
|
39 | args.forEach((value, index) => {
|
40 | if (index == args.length - 1 && typeof value === 'object' && !Array.isArray(value)) {
|
41 | options = value
|
42 | return
|
43 | }
|
44 | if (typeof value === 'string' && value.includes('.')) {
|
45 | value.split('.').forEach(value => keys.push(value))
|
46 | return
|
47 | }
|
48 | keys.push(value)
|
49 | })
|
50 |
|
51 | const length = keys.length
|
52 |
|
53 | if (typeof keys[0] === 'object') {
|
54 | key = keys[0]
|
55 | for (let i = 1; i < length; i++) {
|
56 | if (typeof key[keys[i]] !== 'undefined')
|
57 | key = key[keys[i]]
|
58 | }
|
59 | if (typeof key === 'object') key = keys[length - 1]
|
60 | } else {
|
61 | for (let i = 0; i < length; i++) {
|
62 | key += (i ? '.' : '') + keys[i]
|
63 | }
|
64 | }
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | if (typeof l === 'undefined') {
|
72 | str = key
|
73 | } else {
|
74 | str = (l && typeof l[key] !== 'undefined') ? l[key] : undefined
|
75 | }
|
76 |
|
77 |
|
78 | if (typeof str === 'undefined') {
|
79 | try {
|
80 | str = eval('l.' + key)
|
81 | } catch (e) { }
|
82 | }
|
83 |
|
84 | if (typeof str === 'undefined') str = key
|
85 |
|
86 | if (typeof str === 'string')
|
87 | return str.replace(
|
88 | /\$\{([^}]+)\}/g,
|
89 | (match, p) => typeof options[p] === 'undefined' ? p : options[p]
|
90 | )
|
91 | else
|
92 | return str
|
93 | }
|
94 | export default translate
|