UNPKG

3.22 kBJavaScriptView Raw
1// import React from 'react'
2
3export const I18N_INIT = 'I18N_INIT'
4export const I18N_LOCALES = 'I18N_LOCALES'
5
6// 当前项目可用的语言包代码,与语言包文件名精确匹配
7// 注:无论何种环境,在使用任何函数前,需要使用 register() 函数定义/初始化该 Array
8export let availableLocales = []
9export const setAvailableLocales = arr => availableLocales = arr
10
11// 当前语言包名代码,与语言包文件名精确匹配
12export let localeId = null
13export const setLocaleId = newLlocalId => {
14 if (typeof newLlocalId === 'undefined' || newLlocalId === null)
15 return
16 if (__DEV__ && __SERVER__)
17 console.log(`\n\x1b[93m[super/i18n]\x1b[0m setLocaleId -> \x1b[32m${newLlocalId}\x1b[0m\n`)
18 localeId = newLlocalId
19 return localeId
20}
21
22// 存储文本,按语言包名,如 locales.en、locales['zh-cn']
23export let locales = {}
24export const setLocales = (locale = localeId, obj) => {
25 locales[locale] = obj
26}
27
28
29
30
31/**
32 * 检查目标语言包ID的语言包内容是否已初始化
33 *
34 * @param {*string} theLocaleId 目标语言包ID
35 *
36 * @returns {boolean}
37 */
38export const checkLocalesReady = (theLocaleId = localeId) => {
39 return (typeof locales[theLocaleId] !== 'undefined')
40}
41
42
43
44/**
45 * 翻译文本
46 * 语言包中源文本中的 ${replaceKey} 表示此处需要替换,replaceKey 就是传入的 obj 中对应的值
47 *
48 * @param {string} key 要翻译的文本 Key
49 * @param {*object} obj 文本内对应的替换内容
50 *
51 * @returns {string} 翻译的文本;如果语言包中没有对应的项,返回 key
52 */
53const translate = (...args) => {
54 let key = ''
55 let str
56 let options = {}
57 const keys = []
58 const l = JSON.parse(process.env.SUPER_I18N_TYPE) === 'redux' || __SERVER__
59 ? locales[localeId]
60 : undefined
61
62 args.forEach((value, index) => {
63 if (index == args.length - 1 && typeof value === 'object') {
64 options = value
65 return
66 }
67 if (typeof value === 'string' && value.includes('.')) {
68 value.split('.').forEach(value => keys.push(value))
69 return
70 }
71 keys.push(value)
72 })
73
74 const length = keys.length
75
76 if (typeof keys[0] === 'object') {
77 key = keys[0]
78 for (let i = 1; i < length; i++) {
79 if (typeof key[keys[i]] !== 'undefined')
80 key = key[keys[i]]
81 }
82 if (typeof key === 'object') key = keys[length - 1]
83 } else {
84 for (let i = 0; i < length; i++) {
85 key += (i ? '.' : '') + keys[i]
86 }
87 }
88
89 // console.log(keys, length, key)
90
91 if (typeof l === 'undefined') {
92 str = key
93 } else {
94 str = (l && typeof l[key] !== 'undefined') ? l[key] : undefined
95 }
96 // const localeId = _self.curLocaleId
97
98 if (typeof str === 'undefined') {
99 try {
100 str = eval('l.' + key)
101 } catch (e) { }
102 }
103
104 if (typeof str === 'undefined') str = key
105
106 if (typeof str === 'string')
107 return str.replace(
108 /\$\{([^}]+)\}/g,
109 (match, p) => typeof options[p] === 'undefined' ? p : options[p]
110 )
111 else
112 return str
113}
114
115export default translate