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, 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)[key]
}
return current
}
function getNestedValue(obj: Record, path: string): string | undefined {
const current = getNestedRaw(obj, path)
return typeof current === 'string' ? current : undefined
}
export function useSiteLocale() {
const locale = useState('site-locale', () => 'en')
const cookie = useCookie(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 {
const messages = uiMessages[locale.value]
const value = getNestedValue(messages as Record, key)
?? getNestedValue(uiMessages.en as Record, 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(key: string): T {
const value = getNestedRaw(uiMessages[locale.value] as Record, key)
?? getNestedRaw(uiMessages.en as Record, key)
return value as T
}
return {
locale,
htmlLang,
htmlDir,
setLocale,
t,
tr
}
}