UNPKG

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