infoalloggi-monorepo/apps/infoalloggi/src/providers/I18nProvider.tsx

49 lines
1 KiB
TypeScript
Raw Normal View History

2025-08-04 17:45:44 +02:00
import {
2025-08-28 18:27:07 +02:00
createContext,
type FC,
type ReactNode,
useContext,
useMemo,
2025-08-04 17:45:44 +02:00
} from "react";
2025-08-28 18:27:07 +02:00
import { en } from "~/i18n/en";
import { it } from "~/i18n/it";
import type { LangDict, Locales } from "~/i18n/locales";
2025-08-04 17:45:44 +02:00
type I18nContextType = {
2025-08-28 18:27:07 +02:00
locale: Locales;
t: LangDict;
2025-08-04 17:45:44 +02:00
};
const I18nContext = createContext<I18nContextType>({
2025-08-28 18:27:07 +02:00
locale: "it",
t: it,
2025-08-04 17:45:44 +02:00
});
export const I18nProvider: FC<{
2025-08-28 18:27:07 +02:00
children: ReactNode;
locale: string | undefined;
2025-08-04 17:45:44 +02:00
}> = ({ children, locale }) => {
const contextValue = useMemo(() => {
const validatedLocale = validateLocale(locale);
return {
locale: validatedLocale,
t: validatedLocale === "en" ? en : it,
};
}, [locale]);
2025-08-28 18:27:07 +02:00
return (
<I18nContext.Provider value={contextValue}>{children}</I18nContext.Provider>
2025-08-28 18:27:07 +02:00
);
2025-08-04 17:45:44 +02:00
};
export const useTranslation = () => {
const value = useContext(I18nContext);
if (!value) {
throw new Error("useTranslation must be used within a I18nProvider");
}
return value;
2025-08-04 17:45:44 +02:00
};
const validateLocale = (locale: string | undefined): Locales => {
2025-08-28 18:27:07 +02:00
if (locale === "en") return "en";
return "it";
2025-08-04 17:45:44 +02:00
};