V0 : initial import
This commit is contained in:
38
PS_Report/src/i18n/context.tsx
Normal file
38
PS_Report/src/i18n/context.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { createContext, useContext, useState, useCallback, type ReactNode } from 'react';
|
||||
import { translations, type Lang, type TranslationKey } from './translations';
|
||||
|
||||
interface I18nContextType {
|
||||
lang: Lang;
|
||||
setLang: (lang: Lang) => void;
|
||||
t: (key: TranslationKey) => string;
|
||||
}
|
||||
|
||||
const I18nContext = createContext<I18nContextType | null>(null);
|
||||
|
||||
export function I18nProvider({ children }: { children: ReactNode }) {
|
||||
const [lang, setLang] = useState<Lang>(() => {
|
||||
const saved = localStorage.getItem('proserve-lang');
|
||||
return (saved === 'en' || saved === 'fr') ? saved : 'fr';
|
||||
});
|
||||
|
||||
const changeLang = useCallback((newLang: Lang) => {
|
||||
setLang(newLang);
|
||||
localStorage.setItem('proserve-lang', newLang);
|
||||
}, []);
|
||||
|
||||
const t = useCallback((key: TranslationKey): string => {
|
||||
return translations[key]?.[lang] || key;
|
||||
}, [lang]);
|
||||
|
||||
return (
|
||||
<I18nContext.Provider value={{ lang, setLang: changeLang, t }}>
|
||||
{children}
|
||||
</I18nContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useI18n() {
|
||||
const context = useContext(I18nContext);
|
||||
if (!context) throw new Error('useI18n must be used within I18nProvider');
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user