2023-08-19 00:46:17 +00:00
|
|
|
import { useSession } from "next-auth/react";
|
2021-10-12 13:11:33 +00:00
|
|
|
import { useTranslation } from "next-i18next";
|
2021-10-14 19:10:44 +00:00
|
|
|
import { useEffect } from "react";
|
2021-10-12 13:11:33 +00:00
|
|
|
|
2022-07-22 17:27:06 +00:00
|
|
|
import { trpc } from "@calcom/trpc/react";
|
2021-10-12 13:11:33 +00:00
|
|
|
|
2023-08-19 00:46:17 +00:00
|
|
|
// eslint-disable-next-line turbo/no-undeclared-env-vars
|
|
|
|
const vercelCommitHash = process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA || "NA";
|
|
|
|
|
|
|
|
export function useViewerI18n(locale: string) {
|
|
|
|
return trpc.viewer.public.i18n.useQuery(
|
|
|
|
{ locale, CalComVersion: vercelCommitHash },
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* i18n should never be clubbed with other queries, so that it's caching can be managed independently.
|
|
|
|
**/
|
|
|
|
trpc: {
|
|
|
|
context: { skipBatch: true },
|
|
|
|
},
|
|
|
|
}
|
|
|
|
);
|
2021-10-14 19:10:44 +00:00
|
|
|
}
|
|
|
|
|
2021-10-14 10:57:49 +00:00
|
|
|
/**
|
|
|
|
* Auto-switches locale client-side to the logged in user's preference
|
|
|
|
*/
|
2023-07-19 12:30:25 +00:00
|
|
|
const I18nLanguageHandler = () => {
|
2023-08-19 00:46:17 +00:00
|
|
|
const session = useSession();
|
2021-10-12 13:11:33 +00:00
|
|
|
const { i18n } = useTranslation("common");
|
2023-08-19 00:46:17 +00:00
|
|
|
const locale = useViewerI18n(session.data?.user.locale || "en").data?.locale || i18n.language;
|
2021-10-14 10:57:49 +00:00
|
|
|
|
2021-10-14 19:10:44 +00:00
|
|
|
useEffect(() => {
|
2023-04-21 00:45:22 +00:00
|
|
|
// bail early when i18n = {}
|
2023-07-19 09:19:53 +00:00
|
|
|
if (Object.keys(i18n).length === 0) return;
|
2023-04-21 00:45:22 +00:00
|
|
|
// if locale is ready and the i18n.language does != locale - changeLanguage
|
|
|
|
if (locale && i18n.language !== locale) {
|
|
|
|
i18n.changeLanguage(locale);
|
2021-10-14 19:10:44 +00:00
|
|
|
}
|
2023-04-21 00:45:22 +00:00
|
|
|
// set dir="rtl|ltr"
|
|
|
|
document.dir = i18n.dir();
|
2023-01-03 10:09:05 +00:00
|
|
|
document.documentElement.setAttribute("lang", locale);
|
2021-10-14 19:10:44 +00:00
|
|
|
}, [locale, i18n]);
|
2023-07-19 12:30:25 +00:00
|
|
|
return null;
|
2021-10-12 13:11:33 +00:00
|
|
|
};
|
|
|
|
|
2023-07-19 12:30:25 +00:00
|
|
|
export default I18nLanguageHandler;
|