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