mirror of
https://github.com/ArthurDanjou/ui.git
synced 2026-01-23 16:30:45 +01:00
feat(module): support i18n in components (#2553)
Co-authored-by: Benjamin Canac <canacb1@gmail.com>
This commit is contained in:
37
src/runtime/utils/locale.ts
Normal file
37
src/runtime/utils/locale.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { Ref } from 'vue'
|
||||
import type { Locale } from '../types/locale'
|
||||
import type { MaybeRef } from '@vueuse/core'
|
||||
import { computed, isRef, ref, unref } from 'vue'
|
||||
import { get } from './index'
|
||||
|
||||
export type TranslatorOption = Record<string, string | number>
|
||||
export type Translator = (path: string, option?: TranslatorOption) => string
|
||||
export type LocaleContext = {
|
||||
locale: Ref<Locale>
|
||||
lang: Ref<string>
|
||||
t: Translator
|
||||
}
|
||||
|
||||
export function buildTranslator(locale: MaybeRef<Locale>): Translator {
|
||||
return (path, option) => translate(path, option, unref(locale))
|
||||
}
|
||||
|
||||
export function translate(path: string, option: undefined | TranslatorOption, locale: Locale): string {
|
||||
const prop: string = get(locale, path, path)
|
||||
|
||||
return prop.replace(
|
||||
/\{(\w+)\}/g,
|
||||
(_, key) => `${option?.[key] ?? `{${key}}`}`
|
||||
)
|
||||
}
|
||||
|
||||
export function buildLocaleContext(locale: MaybeRef<Locale>): LocaleContext {
|
||||
const lang = computed(() => unref(locale).name)
|
||||
const localeRef = isRef(locale) ? locale : ref(locale)
|
||||
|
||||
return {
|
||||
lang,
|
||||
locale: localeRef,
|
||||
t: buildTranslator(locale)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user