-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathi18n.wxs
More file actions
334 lines (297 loc) · 7.96 KB
/
i18n.wxs
File metadata and controls
334 lines (297 loc) · 7.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
function genRegExp (str, flags) {
if (!__mpx_wxs__) {
return new RegExp(str, flags)
} else {
return getRegExp(str, flags)
}
}
function isArray (arr) {
if (!__mpx_wxs__) {
return Array.isArray(arr)
} else {
return isDef(arr) && arr.constructor === 'Array'
}
}
function isString (str) {
return typeof str === 'string'
}
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
function isDef (v) {
return v !== undefined && v !== null
}
var RE_TOKEN_LIST_VALUE = genRegExp('^[0-9]+')
var RE_TOKEN_NAMED_VALUE = genRegExp('^[A-Za-z0-9_]+')
var _tokenCaches = {}
var _pathCaches = {}
function parseMessage (format) {
var tokens = []
var position = 0
var text = ''
while (position < format.length) {
var char = format[position++]
if (char === '{') {
if (text) {
tokens.push({
type: 'text',
value: text
})
}
text = ''
var sub = ''
char = format[position++]
while (char !== undefined && char !== '}') {
sub += char
char = format[position++]
}
var isClosed = char === '}'
var type = RE_TOKEN_LIST_VALUE.test(sub)
? 'list'
: isClosed && RE_TOKEN_NAMED_VALUE.test(sub)
? 'named'
: 'unknown'
tokens.push({
value: sub,
type: type
})
} else if (char === '%') {
// when found rails i18n syntax, skip text capture
if (format[(position)] !== '{') {
text += char
}
} else {
text += char
}
}
text && tokens.push({
type: 'text',
value: text
})
return tokens
}
function compile (tokens, values) {
var compiled = []
var index = 0
var mode = isArray(values)
? 'list'
: isObject(values)
? 'named'
: 'unknown'
if (mode === 'unknown') {
return compiled
}
while (index < tokens.length) {
var token = tokens[index]
switch (token.type) {
case 'text':
compiled.push(token.value)
break
case 'list':
compiled.push(values[parseInt(token.value, 10)])
break
case 'named':
if (mode === 'named') {
compiled.push(values[token.value])
} else {
console.log('Type of token ' + token.type + ' and format of value ' + mode + ' do not match!')
}
break
case 'unknown':
console.log('Detect unknown type of token!')
break
}
index++
}
return compiled
}
function interpolate (message, values) {
if (!values) {
return [message]
}
var tokens = _tokenCaches[message]
if (!tokens) {
tokens = parseMessage(message)
_tokenCaches[message] = tokens
}
return compile(tokens, values)
}
function render (message, values) {
return interpolate(message, values).join('')
}
function getPathValue (message, path) {
if (!isObject(message)) return
var parsedPath = _pathCaches[path]
if (!parsedPath) {
parsedPath = parsePath(path)
_pathCaches[path] = parsedPath
}
return outPutByPath(message, parsedPath)
}
function outPutByPath (context, path) {
var result = context
var len = path.length
for (var index = 0; index < len; index++) {
var key
var item = path[index]
if (result) {
if (isArray(item)) {
// 获取子数组的输出结果作为当前key
key = outPutByPath(context, item)
} else if (genRegExp('^__mpx_str_').test(item)) {
// 字符串一定会被[]包裹,一定在子数组中
result = item.replace('__mpx_str_', '')
} else if (genRegExp('^[0-9]+$').test(item)) {
// 数字一定会被[]包裹,一定在子数组中
result = +item
} else if (item === '+') {
// 获取加号后面所有path最终的结果
result += outPutByPath(context, path.slice(index + 1))
break
} else {
key = item
}
if (key !== undefined) {
result = result[key]
}
} else {
break
}
}
return result
}
function genStack (mark) {
var value = []
return {
mark: mark,
type: genRegExp('[\'"]').test(mark) ? 'string' : 'normal',
value: value,
push: function (data) {
value.push(data)
}
}
}
function parsePath (pathStr) {
function startStack (mark) {
// 开启栈或关闭栈都意味着前面的字符拼接截止
propertyJoinOver()
curStack && targetStacks.push(curStack)
curStack = genStack(mark)
}
function endStack () {
// 开启栈或关闭栈都意味着前面的字符拼接截止
propertyJoinOver()
// 字符串栈直接拼接
var result = curStack.type === 'string' ? '__mpx_str_' + curStack.value.join('') : curStack.value
curStack = targetStacks.pop()
// 将当前stack结果保存到父级stack里
curStack.push(result)
}
function propertyJoinOver () {
property = property.trim()
if (property) curStack.push(property)
property = ''
}
var curStack = genStack()
var targetStacks = []
var property = ''
var index = 0
if (genRegExp('^[^[]]+$').test(pathStr)) {
// 对于简单数据路径,直接分割,避免无意义的解析
return pathStr.split('.')
}
while (index < pathStr.length) {
var char = pathStr[index]
// 当前遍历引号内的字符串时
if (curStack.type === 'string') {
// 若为对应的结束flag,则出栈,反之直接push
curStack.mark === char ? endStack() : curStack.push(char)
} else if (genRegExp('[\'"[]').test(char)) {
startStack(char)
} else if (char === ']') {
endStack()
} else if (char === '.' || char === '+') {
propertyJoinOver()
if (char === '+') curStack.push(char)
} else {
property += char
}
index++
}
// 字符解析收尾
propertyJoinOver()
return curStack.value
}
function translate (messages, locale, fallbackLocale, key, values) {
var message = getMessage(messages, locale, fallbackLocale, key)
if (isString(message)) {
return render(message, values)
}
return key
}
function exist (messages, locale, key) {
return isDef(resolve(messages, locale, key))
}
function getMessage (messages, locale, fallbackLocale, key) {
var locales = [locale, fallbackLocale]
for (var i = 0; i < locales.length; i++) {
var message = resolve(messages, locales[i], key)
if (isDef(message)) return message
}
}
function resolve (messages, locale, key) {
if (messages && messages[locale] && key) {
var format = getPathValue(messages[locale], key)
if (format == null) {
format = messages[locale][key]
}
return format
}
}
function getLocale () {
return __mpx_locale__ || 'zh-CN'
}
function getFallbackLocale () {
return __mpx_fallback_locale__ || 'zh-CN'
}
function getMessages (messages) {
// __mpx_messages__会在编译时通过lib/wxs/i18n-loader注入
return messages || __mpx_messages__ || {}
}
function fetchChoice (message, choice) {
var choices = message.split('|')
choice = getChoiceIndex(choice, choices.length)
if (!choices[choice]) return message
return choices[choice].trim()
}
function getChoiceIndex (choice, choicesLength) {
choice = Math.abs(choice)
if (choicesLength === 2) {
return choice ? choice > 1 ? 1 : 0 : 1
}
return choice ? Math.min(choice, 2) : 0
}
module.exports = {
t: function (messages, locale, fallbackLocale, key, values) {
return translate(getMessages(messages), locale, fallbackLocale, key, values)
},
tc: function (messages, locale, fallbackLocale, key, choice, values) {
return fetchChoice(translate(getMessages(messages), locale, fallbackLocale, key, values), choice)
},
te: function (messages, locale, fallbackLocale, key) {
return exist(getMessages(messages), locale, key)
},
tm: function (messages, locale, fallbackLocale, key) {
return getMessage(getMessages(messages), locale, fallbackLocale, key)
}
}
if (!__mpx_wxs__) {
if (!global.i18n) {
global.i18n = {
locale: getLocale(),
fallbackLocale: getFallbackLocale(),
messages: getMessages(),
methods: module.exports
}
}
}