1 | import get from 'lodash/get';
|
2 |
|
3 | import { localeId } from '../';
|
4 | import locales from './locales';
|
5 |
|
6 | export let l = (() => {
|
7 | if (__SERVER__) {
|
8 | if (__DEV__ && typeof global.__KOOT_SSR__ === 'object') {
|
9 | if (typeof global.__KOOT_SSR__.locales === 'object')
|
10 | return global.__KOOT_SSR__.locales[localeId];
|
11 | return {};
|
12 | }
|
13 |
|
14 | if (typeof locales === 'object') return locales[localeId];
|
15 | return {};
|
16 | }
|
17 | if (JSON.parse(process.env.KOOT_I18N_TYPE) === 'store') return locales;
|
18 | return false;
|
19 | })();
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | const translate = (...args) => {
|
31 | let key = '';
|
32 | let str;
|
33 | let options = {};
|
34 | const keys = [];
|
35 |
|
36 | if (__SERVER__ && __DEV__) l = locales[global.__KOOT_LOCALEID__];
|
37 |
|
38 | args.forEach((value, index) => {
|
39 |
|
40 | if (
|
41 | index === args.length - 1 &&
|
42 | typeof value === 'object' &&
|
43 | !Array.isArray(value)
|
44 | ) {
|
45 | options = value;
|
46 | return;
|
47 | }
|
48 | if (typeof value === 'string' && value.includes('.')) {
|
49 | value.split('.').forEach(value => keys.push(value));
|
50 | return;
|
51 | }
|
52 | keys.push(value);
|
53 | });
|
54 |
|
55 | const length = keys.length;
|
56 |
|
57 | if (args.length === 1 && typeof args[0] === 'object') {
|
58 | |
59 |
|
60 |
|
61 | return args[0];
|
62 | }
|
63 |
|
64 | if (typeof keys[0] === 'object') {
|
65 | |
66 |
|
67 |
|
68 | key = keys[0];
|
69 | let hasUnmatched = false;
|
70 | for (let i = 1; i < length; i++) {
|
71 |
|
72 | const value = key[keys[i]];
|
73 |
|
74 | if (typeof value === 'undefined') {
|
75 | hasUnmatched = true;
|
76 | break;
|
77 | } else {
|
78 | key = value;
|
79 | }
|
80 |
|
81 | }
|
82 | if (hasUnmatched) key = keys[length - 1];
|
83 | } else if (length === 1) {
|
84 | key = keys[0];
|
85 | } else {
|
86 | for (let i = 0; i < length; i++) {
|
87 | if (typeof l === 'object') {
|
88 | if (keys[i] !== '') key += `[${JSON.stringify(keys[i])}]`;
|
89 | } else {
|
90 | key += (i ? '.' : '') + keys[i];
|
91 | }
|
92 | }
|
93 | }
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 | if (typeof l === 'undefined') {
|
102 | str = key;
|
103 | } else if (typeof l === 'object') {
|
104 |
|
105 | str = get(l, key);
|
106 | }
|
107 | // const localeId = _self.curLocaleId
|
108 |
|
109 | // if (typeof str === 'undefined' && typeof l === 'object') {
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 | if (typeof str === 'undefined') str = key;
|
117 |
|
118 | if (typeof str === 'string')
|
119 | return str.replace(/\$\{([^}]+)\}/g, (match, p) =>
|
120 | typeof options[p] === 'undefined' ? p : options[p]
|
121 | );
|
122 |
|
123 | return str;
|
124 | };
|
125 | export default translate;
|