element-plus/packages/locale/index.ts

71 lines
1.6 KiB
TypeScript
Raw Normal View History

import dayjs from 'dayjs'
import { debugWarn } from '@element-plus/utils/error'
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
export const restoreHandler = () => (i18nHandler = defaultTranslator)
2020-09-16 14:46:41 +08:00
function template(str: string, option) {
if (!str || !option) return str
2020-09-16 14:46:41 +08:00
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)
return translation || defaultTranslator(...args)
}
return defaultTranslator(...args)
}
export const use = (l: Language): void => {
debugWarn(
'deprecation',
`:
2021-07-26 00:24:30 +08:00
The previous i18n usage is deprecated please update to
the new one to get reactive i18n translations, refer to:
https://element-plus.org/#/en-US/component/i18n
`
)
2021-07-26 00:24:30 +08:00
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