47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
|
|
import { LOCALES, translate, type Locale, type MessageKey } from "./messages";
|
|
|
|
const STORAGE_KEY = "ui_locale";
|
|
|
|
function detectInitialLocale(): Locale {
|
|
const stored = localStorage.getItem(STORAGE_KEY);
|
|
if (stored && (LOCALES as string[]).includes(stored)) return stored as Locale;
|
|
|
|
const browser = navigator.language?.slice(0, 2);
|
|
if (browser && (LOCALES as string[]).includes(browser)) return browser as Locale;
|
|
|
|
return "en";
|
|
}
|
|
|
|
interface LanguageContextValue {
|
|
locale: Locale;
|
|
setLocale: (locale: Locale) => void;
|
|
t: (key: MessageKey, vars?: Record<string, string | number>) => string;
|
|
}
|
|
|
|
const LanguageContext = createContext<LanguageContextValue | undefined>(undefined);
|
|
|
|
export function LanguageProvider({ children }: { children: ReactNode }) {
|
|
const [locale, setLocaleState] = useState<Locale>(detectInitialLocale);
|
|
|
|
const setLocale = useCallback((next: Locale) => {
|
|
setLocaleState(next);
|
|
localStorage.setItem(STORAGE_KEY, next);
|
|
}, []);
|
|
|
|
const t = useCallback(
|
|
(key: MessageKey, vars?: Record<string, string | number>) => translate(locale, key, vars),
|
|
[locale],
|
|
);
|
|
|
|
const value = useMemo(() => ({ locale, setLocale, t }), [locale, setLocale, t]);
|
|
|
|
return <LanguageContext.Provider value={value}>{children}</LanguageContext.Provider>;
|
|
}
|
|
|
|
export function useI18n(): LanguageContextValue {
|
|
const ctx = useContext(LanguageContext);
|
|
if (!ctx) throw new Error("useI18n must be used within a LanguageProvider");
|
|
return ctx;
|
|
}
|