|
import "@/client/libs/dayjs"; |
|
|
|
import { i18n } from "@lingui/core"; |
|
import { detect, fromStorage, fromUrl } from "@lingui/detect-locale"; |
|
import { I18nProvider } from "@lingui/react"; |
|
import { languages } from "@reactive-resume/utils"; |
|
import { useEffect } from "react"; |
|
|
|
import { defaultLocale, dynamicActivate } from "../libs/lingui"; |
|
import { updateUser } from "../services/user"; |
|
import { useAuthStore } from "../stores/auth"; |
|
|
|
type Props = { |
|
children: React.ReactNode; |
|
}; |
|
|
|
export const LocaleProvider = ({ children }: Props) => { |
|
const userLocale = useAuthStore((state) => state.user?.locale ?? defaultLocale); |
|
|
|
useEffect(() => { |
|
const detectedLocale = |
|
detect(fromUrl("locale"), fromStorage("locale"), userLocale, defaultLocale) ?? defaultLocale; |
|
|
|
|
|
if (languages.some((lang) => lang.locale === detectedLocale)) { |
|
void dynamicActivate(detectedLocale); |
|
} else { |
|
void dynamicActivate(defaultLocale); |
|
} |
|
}, [userLocale]); |
|
|
|
return <I18nProvider i18n={i18n}>{children}</I18nProvider>; |
|
}; |
|
|
|
export const changeLanguage = async (locale: string) => { |
|
|
|
window.localStorage.setItem("locale", locale); |
|
|
|
|
|
const state = useAuthStore.getState(); |
|
if (state.user) await updateUser({ locale }).catch(() => null); |
|
|
|
|
|
window.location.reload(); |
|
}; |
|
|