github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/static_source/admin/src/hooks/web/useI18n.ts (about) 1 import { i18n } from '@/plugins/vueI18n' 2 3 type I18nGlobalTranslation = { 4 (key: string): string 5 (key: string, locale: string): string 6 (key: string, locale: string, list: unknown[]): string 7 (key: string, locale: string, named: Record<string, unknown>): string 8 (key: string, list: unknown[]): string 9 (key: string, named: Record<string, unknown>): string 10 } 11 12 type I18nTranslationRestParameters = [string, any] 13 14 const getKey = (namespace: string | undefined, key: string) => { 15 if (!namespace) { 16 return key 17 } 18 if (key.startsWith(namespace)) { 19 return key 20 } 21 return `${namespace}.${key}` 22 } 23 24 export const useI18n = ( 25 namespace?: string 26 ): { 27 t: I18nGlobalTranslation 28 } => { 29 const normalFn = { 30 t: (key: string) => { 31 return getKey(namespace, key) 32 } 33 } 34 35 if (!i18n) { 36 return normalFn 37 } 38 39 const { t, ...methods } = i18n.global 40 41 const tFn: I18nGlobalTranslation = (key: string, ...arg: any[]) => { 42 if (!key) return '' 43 if (!key.includes('.') && !namespace) return key 44 return (t as any)(getKey(namespace, key), ...(arg as I18nTranslationRestParameters)) 45 } 46 return { 47 ...methods, 48 t: tFn 49 } 50 } 51 52 export const t = (key: string) => key