2020-08-03 19:16:13 +08:00
|
|
|
import defaultLang from './lang/en'
|
2020-11-19 15:58:25 +08:00
|
|
|
import dayjs from 'dayjs'
|
2020-07-28 20:18:11 +08:00
|
|
|
|
2021-01-19 23:49:07 +08:00
|
|
|
|
|
|
|
export type TranslatePair = {
|
|
|
|
[key: string]: string | string[] | TranslatePair
|
|
|
|
}
|
|
|
|
|
|
|
|
export type Language = {
|
|
|
|
name: string
|
|
|
|
el: TranslatePair
|
|
|
|
}
|
|
|
|
|
|
|
|
let lang: Language = defaultLang as Language
|
|
|
|
|
|
|
|
let i18nHandler: null | ((...args: any[]) => string) = null
|
|
|
|
|
|
|
|
export const i18n = (fn: (...args: any[]) => string) => {
|
|
|
|
i18nHandler = fn
|
|
|
|
}
|
2020-07-28 20:18:11 +08:00
|
|
|
|
2020-09-16 14:46:41 +08:00
|
|
|
function template(str: string, option) {
|
|
|
|
if(!str || !option) return str
|
|
|
|
|
|
|
|
return str.replace(/\{(\w+)\}/g, (match, key) => {
|
|
|
|
return option[key]
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-01-19 23:49:07 +08:00
|
|
|
export const t = (...args: any[]): string => {
|
|
|
|
if (i18nHandler) return i18nHandler(...args)
|
|
|
|
|
|
|
|
const [path, option] = args
|
2020-08-03 19:16:13 +08:00
|
|
|
let value
|
2020-07-28 20:18:11 +08:00
|
|
|
const array = path.split('.')
|
|
|
|
let current = lang
|
|
|
|
for (let i = 0, j = array.length; i < j; i++) {
|
|
|
|
const property = array[i]
|
2020-09-16 14:49:21 +08:00
|
|
|
value = current[property]
|
2020-09-16 14:46:41 +08:00
|
|
|
if (i === j - 1) return template(value, option)
|
2020-07-28 20:18:11 +08:00
|
|
|
if (!value) return ''
|
|
|
|
current = value
|
|
|
|
}
|
|
|
|
return ''
|
|
|
|
}
|
|
|
|
|
2021-01-19 23:49:07 +08:00
|
|
|
export const use = (l: Language): void => {
|
2020-07-28 20:18:11 +08:00
|
|
|
lang = l || lang
|
2020-11-19 15:58:25 +08:00
|
|
|
if (lang.name) {
|
|
|
|
dayjs.locale(lang.name)
|
|
|
|
}
|
2020-07-28 20:18:11 +08:00
|
|
|
}
|
|
|
|
|
2021-01-19 23:49:07 +08:00
|
|
|
export default { use, t, i18n }
|