2022-03-25 15:35:56 +08:00
|
|
|
import { computed, isRef, ref, unref } from 'vue'
|
2022-02-08 10:37:21 +08:00
|
|
|
import { get } from 'lodash-unified'
|
2021-07-25 15:26:00 +08:00
|
|
|
import English from '@element-plus/locale/lang/en'
|
2022-01-08 19:36:13 +08:00
|
|
|
import { useGlobalConfig } from '../use-global-config'
|
2021-11-29 15:58:44 +08:00
|
|
|
import type { MaybeRef } from '@vueuse/core'
|
2022-01-08 19:36:13 +08:00
|
|
|
import type { Ref } from 'vue'
|
2021-07-25 15:26:00 +08:00
|
|
|
import type { Language } from '@element-plus/locale'
|
|
|
|
|
2021-12-04 11:15:49 +08:00
|
|
|
export type TranslatorOption = Record<string, string | number>
|
|
|
|
export type Translator = (path: string, option?: TranslatorOption) => string
|
2021-07-25 15:26:00 +08:00
|
|
|
export type LocaleContext = {
|
2021-07-26 00:24:30 +08:00
|
|
|
locale: Ref<Language>
|
|
|
|
lang: Ref<string>
|
2021-07-25 15:26:00 +08:00
|
|
|
t: Translator
|
|
|
|
}
|
|
|
|
|
2021-11-29 15:58:44 +08:00
|
|
|
export const buildTranslator =
|
|
|
|
(locale: MaybeRef<Language>): Translator =>
|
2021-12-04 11:15:49 +08:00
|
|
|
(path, option) =>
|
|
|
|
translate(path, option, unref(locale))
|
2021-11-29 15:58:44 +08:00
|
|
|
|
2021-12-04 11:15:49 +08:00
|
|
|
export const translate = (
|
|
|
|
path: string,
|
|
|
|
option: undefined | TranslatorOption,
|
|
|
|
locale: Language
|
|
|
|
): string =>
|
2021-12-04 23:40:06 +08:00
|
|
|
(get(locale, path, path) as string).replace(
|
2021-12-04 11:15:49 +08:00
|
|
|
/\{(\w+)\}/g,
|
|
|
|
(_, key) => `${option?.[key] ?? `{${key}}`}`
|
|
|
|
)
|
2021-07-25 15:26:00 +08:00
|
|
|
|
2022-01-08 19:36:13 +08:00
|
|
|
export const buildLocaleContext = (
|
|
|
|
locale: MaybeRef<Language>
|
|
|
|
): LocaleContext => {
|
|
|
|
const lang = computed(() => unref(locale).name)
|
|
|
|
const localeRef = isRef(locale) ? locale : ref(locale)
|
2021-08-24 13:36:48 +08:00
|
|
|
return {
|
|
|
|
lang,
|
|
|
|
locale: localeRef,
|
2022-01-08 19:36:13 +08:00
|
|
|
t: buildTranslator(locale),
|
2021-08-24 13:36:48 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-29 15:58:44 +08:00
|
|
|
export const useLocale = () => {
|
2022-01-08 19:36:13 +08:00
|
|
|
const locale = useGlobalConfig('locale')
|
|
|
|
return buildLocaleContext(computed(() => locale.value || English))
|
2021-07-25 15:26:00 +08:00
|
|
|
}
|