91 lines
2.2 KiB
TypeScript
91 lines
2.2 KiB
TypeScript
import {
|
|
isRtlLocale,
|
|
LOCALE_HTML_LANG,
|
|
type SiteLocale
|
|
} from '~/types/locale'
|
|
import { uiAr } from '~/locales/ui/ar'
|
|
import { uiEn } from '~/locales/ui/en'
|
|
import { uiRu } from '~/locales/ui/ru'
|
|
import { uiZh } from '~/locales/ui/zh'
|
|
|
|
const LOCALE_COOKIE = 'umedglobal_locale'
|
|
|
|
const uiMessages = {
|
|
en: uiEn,
|
|
zh: uiZh,
|
|
ar: uiAr,
|
|
ru: uiRu
|
|
} 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_HTML_LANG[locale.value])
|
|
const htmlDir = computed(() => (isRtlLocale(locale.value) ? 'rtl' : 'ltr'))
|
|
|
|
useHead(() => ({
|
|
htmlAttrs: {
|
|
lang: htmlLang.value,
|
|
dir: htmlDir.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,
|
|
htmlDir,
|
|
setLocale,
|
|
t,
|
|
tr
|
|
}
|
|
}
|