element-plus/packages/locale/index.ts

61 lines
1.3 KiB
TypeScript
Raw Normal View History

import dayjs from 'dayjs'
import defaultLang from './lang/en'
2020-07-28 20:18:11 +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, (_, key) => {
2020-09-16 14:46:41 +08:00
return option[key]
})
}
const defaultTranslator = (...args: any[]) => {
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
2020-07-28 20:18:11 +08:00
for (let i = 0, j = array.length; i < j; i++) {
const property = array[i]
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
}
}
export const t = (...args: any[]): string => {
if (i18nHandler) {
const translation = i18nHandler(...args)
if (!translation) {
return defaultTranslator(...args)
}
}
return defaultTranslator(...args)
}
export const use = (l: Language): void => {
2020-07-28 20:18:11 +08:00
lang = l || lang
if (lang.name) {
dayjs.locale(lang.name)
}
2020-07-28 20:18:11 +08:00
}
export const setLocale = use