Files
umed/web/composables/useSiteLocale.ts
T
2026-07-09 14:35:32 +08:00

80 lines
2.0 KiB
TypeScript

import type { SiteLocale } from '~/types/locale'
import { uiEn } from '~/locales/ui/en'
import { uiZh } from '~/locales/ui/zh'
const LOCALE_COOKIE = 'umedglobal_locale'
const uiMessages = {
en: uiEn,
zh: uiZh
} as const
function getNestedRaw(obj: Record<string, unknown>, path: string): unknown {
const keys = path.split('.')
let current: unknown = obj
for (const key of keys) {
if (!current || typeof current !== 'object' || !(key in current)) {
return undefined
}
current = (current as Record<string, unknown>)[key]
}
return current
}
function getNestedValue(obj: Record<string, unknown>, path: string): string | undefined {
const current = getNestedRaw(obj, path)
return typeof current === 'string' ? current : undefined
}
export function useSiteLocale() {
const locale = useState<SiteLocale>('site-locale', () => 'en')
const cookie = useCookie<SiteLocale>(LOCALE_COOKIE, {
default: () => 'en',
maxAge: 60 * 60 * 24 * 365,
sameSite: 'lax'
})
const htmlLang = computed(() => (locale.value === 'zh' ? 'zh-CN' : 'en'))
useHead(() => ({
htmlAttrs: {
lang: htmlLang.value
}
}))
function t(key: string, params?: Record<string, string>): string {
const messages = uiMessages[locale.value]
const value = getNestedValue(messages as Record<string, unknown>, key)
?? getNestedValue(uiMessages.en as Record<string, unknown>, key)
?? key
if (!params) return value
return Object.entries(params).reduce(
(text, [name, replacement]) => text.replaceAll(`{${name}}`, replacement),
value
)
}
function setLocale(next: SiteLocale) {
locale.value = next
cookie.value = next
}
function tr<T>(key: string): T {
const value = getNestedRaw(uiMessages[locale.value] as Record<string, unknown>, key)
?? getNestedRaw(uiMessages.en as Record<string, unknown>, key)
return value as T
}
return {
locale,
htmlLang,
setLocale,
t,
tr
}
}