index.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { computed, inject, isRef, ref, unref } from 'vue'
  2. import { get } from 'lodash-unified'
  3. import ZhCn from '@element-plus/locale/lang/zh-cn'
  4. import type { MaybeRef } from '@vueuse/core'
  5. import type { InjectionKey, Ref } from 'vue'
  6. import type { Language } from '@element-plus/locale'
  7. export type TranslatorOption = Record<string, string | number>
  8. export type Translator = (path: string, option?: TranslatorOption) => string
  9. export type LocaleContext = {
  10. locale: Ref<Language>
  11. lang: Ref<string>
  12. t: Translator
  13. }
  14. export const buildTranslator =
  15. (locale: MaybeRef<Language>): Translator =>
  16. (path, option) =>
  17. translate(path, option, unref(locale))
  18. export const translate = (
  19. path: string,
  20. option: undefined | TranslatorOption,
  21. locale: Language
  22. ): string =>
  23. (get(locale, path, path) as string).replace(
  24. /\{(\w+)\}/g,
  25. (_, key) => `${option?.[key] ?? `{${key}}`}`
  26. )
  27. export const buildLocaleContext = (
  28. locale: MaybeRef<Language>
  29. ): LocaleContext => {
  30. const lang = computed(() => unref(locale).name)
  31. const localeRef = isRef(locale) ? locale : ref(locale)
  32. return {
  33. lang,
  34. locale: localeRef,
  35. t: buildTranslator(locale),
  36. }
  37. }
  38. export const localeContextKey: InjectionKey<Ref<Language | undefined>> =
  39. Symbol('localeContextKey')
  40. export const useLocale = (localeOverrides?: Ref<Language | undefined>) => {
  41. const locale = localeOverrides || inject(localeContextKey, ref())!
  42. return buildLocaleContext(computed(() => locale.value || ZhCn))
  43. }