48 lines
1 KiB
TypeScript
48 lines
1 KiB
TypeScript
import {
|
|
createContext,
|
|
type FC,
|
|
type ReactNode,
|
|
useContext,
|
|
useMemo,
|
|
} from "react";
|
|
import { en } from "~/i18n/en";
|
|
import { it } from "~/i18n/it";
|
|
import type { LangDict, Locales } from "~/i18n/locales";
|
|
|
|
type I18nContextType = {
|
|
locale: Locales;
|
|
t: LangDict;
|
|
};
|
|
|
|
const I18nContext = createContext<I18nContextType>({
|
|
locale: "it",
|
|
t: it,
|
|
});
|
|
|
|
export const I18nProvider: FC<{
|
|
children: ReactNode;
|
|
locale: string | undefined;
|
|
}> = ({ children, locale }) => {
|
|
const contextValue = useMemo(() => {
|
|
const validatedLocale = validateLocale(locale);
|
|
return {
|
|
locale: validatedLocale,
|
|
t: validatedLocale === "en" ? en : it,
|
|
};
|
|
}, [locale]);
|
|
return (
|
|
<I18nContext.Provider value={contextValue}>{children}</I18nContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useTranslation = () => {
|
|
const value = useContext(I18nContext);
|
|
if (!value) {
|
|
throw new Error("useTranslation must be used within a I18nProvider");
|
|
}
|
|
return value;
|
|
};
|
|
const validateLocale = (locale: string | undefined): Locales => {
|
|
if (locale === "en") return "en";
|
|
return "it";
|
|
};
|