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;
|
2025-08-04 17:45:44 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const I18nContext = createContext<I18nContextType>({
|
2025-08-28 18:27:07 +02:00
|
|
|
locale: "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 }) => {
|
2025-08-28 18:27:07 +02:00
|
|
|
return (
|
|
|
|
|
<I18nContext.Provider value={{ locale: validateLocale(locale) }}>
|
|
|
|
|
{children}
|
|
|
|
|
</I18nContext.Provider>
|
|
|
|
|
);
|
2025-08-04 17:45:44 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useTranslation = () => {
|
2025-08-28 18:27:07 +02:00
|
|
|
const { locale } = useContext(I18nContext);
|
|
|
|
|
return useMemo(() => {
|
|
|
|
|
return (
|
|
|
|
|
locale === "en" ? { locale: "en", t: en } : { locale: "it", t: it }
|
|
|
|
|
) as {
|
|
|
|
|
locale: Locales;
|
|
|
|
|
t: LangDict;
|
|
|
|
|
};
|
|
|
|
|
}, [locale]);
|
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
|
|
|
};
|