55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import { useEffect, useState } from 'react'
|
|
import { setLocale, getLocale, loadTranslations, t, type Locale } from '@/lib/i18n'
|
|
|
|
export function useI18n(locale: Locale = 'fr'): {
|
|
loaded: boolean
|
|
locale: Locale
|
|
t: (key: string, params?: Record<string, string | number>) => string
|
|
} {
|
|
const [loaded, setLoaded] = useState(false)
|
|
const [currentLocale, setCurrentLocale] = useState<Locale>(getLocale())
|
|
|
|
useEffect(() => {
|
|
const load = async (): Promise<void> => {
|
|
try {
|
|
// Get saved locale from IndexedDB or use provided locale
|
|
let savedLocale: Locale | null = null
|
|
try {
|
|
// Migrate from localStorage if needed
|
|
const { localeStorage } = await import('@/lib/localeStorage')
|
|
await localeStorage.migrateFromLocalStorage()
|
|
// Load from IndexedDB
|
|
savedLocale = await localeStorage.getLocale()
|
|
} catch {
|
|
// Fallback to provided locale
|
|
}
|
|
const initialLocale = savedLocale && (savedLocale === 'fr' || savedLocale === 'en') ? savedLocale : locale
|
|
|
|
// Load translations from files in public directory
|
|
const frResponse = await globalThis.fetch('/locales/fr.txt')
|
|
const enResponse = await globalThis.fetch('/locales/en.txt')
|
|
|
|
if (frResponse.ok) {
|
|
const frText = await frResponse.text()
|
|
loadTranslations('fr', frText)
|
|
}
|
|
|
|
if (enResponse.ok) {
|
|
const enText = await enResponse.text()
|
|
loadTranslations('en', enText)
|
|
}
|
|
|
|
setLocale(initialLocale)
|
|
setCurrentLocale(initialLocale)
|
|
setLoaded(true)
|
|
} catch (e) {
|
|
console.error('Error loading translations:', e)
|
|
setLoaded(true) // Continue even if translations fail to load
|
|
}
|
|
}
|
|
void load()
|
|
}, [locale])
|
|
|
|
return { loaded, locale: currentLocale, t }
|
|
}
|