fix: client locale inference (#10850)

This commit is contained in:
Omar López authored and GitHub committed 2023-08-22 14:34:55 +02:00
1 parent bbad0fbc18
commit 6743aa4609
16 files changed
+102 -127

No files matched your search

+26 -8
View File
@@ -1,15 +1,14 @@
import parser from "accept-language-parser";
import { useSession } from "next-auth/react";
import { useTranslation } from "next-i18next";
import { useEffect } from "react";
import { CALCOM_VERSION } from "@calcom/lib/constants";
import { trpc } from "@calcom/trpc/react";
// 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) {
function useViewerI18n(locale: string) {
return trpc.viewer.public.i18n.useQuery(
{ locale, CalComVersion: vercelCommitHash },
{ locale, CalComVersion: CALCOM_VERSION },
{
/**
* i18n should never be clubbed with other queries, so that it's caching can be managed independently.
@@ -21,13 +20,32 @@ export function useViewerI18n(locale: string) {
);
}
function useClientLocale(locales: string[]) {
const session = useSession();
// If the user is logged in, use their locale
if (session.data?.user.locale) return session.data.user.locale;
// If the user is not logged in, use the browser locale
if (typeof window !== "undefined") {
// This is the only way I found to ensure the prefetched locale is used on first render
// FIXME: Find a better way to pick the best matching locale from the browser
return parser.pick(locales, window.navigator.language, { loose: true }) || window.navigator.language;
}
// If the browser is not available, use English
return "en";
}
export function useClientViewerI18n(locales: string[]) {
const clientLocale = useClientLocale(locales);
return useViewerI18n(clientLocale);
}
/**
* Auto-switches locale client-side to the logged in user's preference
*/
const I18nLanguageHandler = () => {
const session = useSession();
const I18nLanguageHandler = (props: { locales: string[] }) => {
const { locales } = props;
const { i18n } = useTranslation("common");
const locale = useViewerI18n(session.data?.user.locale || "en").data?.locale || i18n.language;
const locale = useClientViewerI18n(locales).data?.locale || i18n.language;
useEffect(() => {
// bail early when i18n = {}
+2 -2
View File
@@ -6,7 +6,7 @@ import Script from "next/script";
import "@calcom/embed-core/src/embed-iframe";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import { WEBAPP_URL, IS_CALCOM } from "@calcom/lib/constants";
import { IS_CALCOM, WEBAPP_URL } from "@calcom/lib/constants";
import { buildCanonical } from "@calcom/lib/next-seo.config";
import type { AppProps } from "@lib/app-providers";
@@ -72,7 +72,7 @@ function PageWrapper(props: AppProps) {
}
{...seoConfig.defaultNextSeo}
/>
<I18nLanguageHandler />
<I18nLanguageHandler locales={props.router.locales || []} />
<Script
nonce={nonce}
id="page-status"
+3 -6
View File
@@ -20,7 +20,7 @@ import { MetaProvider } from "@calcom/ui";
import useIsBookingPage from "@lib/hooks/useIsBookingPage";
import type { WithNonceProps } from "@lib/withNonce";
import { useViewerI18n } from "@components/I18nLanguageHandler";
import { useClientViewerI18n } from "@components/I18nLanguageHandler";
const I18nextAdapter = appWithTranslation<
NextJsAppProps<SSRConfig> & {
@@ -69,11 +69,8 @@ const CustomI18nextProvider = (props: AppPropsWithoutNonce) => {
/**
* i18n should never be clubbed with other queries, so that it's caching can be managed independently.
**/
const session = useSession();
const localeToUse = session.data?.user.locale ?? "en";
const { i18n, locale } = useViewerI18n(localeToUse).data ?? {
locale: "en",
};
const clientViewerI18n = useClientViewerI18n(props.router.locales || []);
const { i18n, locale } = clientViewerI18n.data || {};
const passedProps = {
...props,
-53
View File
@@ -1,53 +0,0 @@
import parser from "accept-language-parser";
import type { IncomingMessage } from "http";
import type { GetServerSidePropsContext } from "next";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import type { Maybe } from "@calcom/trpc/server";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { i18n } = require("@calcom/config/next-i18next.config");
export function getLocaleFromHeaders(req: IncomingMessage): string {
let preferredLocale: string | null | undefined;
if (req.headers["accept-language"]) {
preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]) as Maybe<string>;
}
return preferredLocale ?? i18n.defaultLocale;
}
export const getOrSetUserLocaleFromHeaders = async (
req: GetServerSidePropsContext["req"],
res: GetServerSidePropsContext["res"]
): Promise<string> => {
const { default: prisma } = await import("@calcom/prisma");
const session = await getServerSession({ req, res });
const preferredLocale = getLocaleFromHeaders(req);
if (session?.user?.id) {
const user = await prisma.user.findUnique({
where: {
id: session.user.id,
},
select: {
locale: true,
},
});
if (user?.locale) {
return user.locale;
}
await prisma.user.update({
where: {
id: session.user.id,
},
data: {
locale: preferredLocale,
},
});
}
return preferredLocale;
};
+4
View File
@@ -3,6 +3,7 @@ const CopyWebpackPlugin = require("copy-webpack-plugin");
const os = require("os");
const englishTranslation = require("./public/static/locales/en/common.json");
const { withAxiom } = require("next-axiom");
const { version } = require("./package.json");
const { i18n } = require("./next-i18next.config");
const {
orgHostPath,
@@ -14,6 +15,9 @@ const {
if (!process.env.NEXTAUTH_SECRET) throw new Error("Please set NEXTAUTH_SECRET");
if (!process.env.CALENDSO_ENCRYPTION_KEY) throw new Error("Please set CALENDSO_ENCRYPTION_KEY");
// To be able to use the version in the app without having to import package.json
process.env.NEXT_PUBLIC_CALCOM_VERSION = version;
// So we can test deploy previews preview
if (process.env.VERCEL_URL && !process.env.NEXT_PUBLIC_WEBAPP_URL) {
process.env.NEXT_PUBLIC_WEBAPP_URL = "https://" + process.env.VERCEL_URL;
+2 -5
View File
@@ -2,6 +2,7 @@ import type { GetStaticPropsContext } from "next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import superjson from "superjson";
import { CALCOM_VERSION } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import { createProxySSGHelpers } from "@calcom/trpc/react/ssg";
import { appRouter } from "@calcom/trpc/server/routers/_app";
@@ -9,10 +10,6 @@ import { appRouter } from "@calcom/trpc/server/routers/_app";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { i18n } = require("@calcom/config/next-i18next.config");
// TODO: Consolidate this constant
// eslint-disable-next-line turbo/no-undeclared-env-vars
const CalComVersion = process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA || "NA";
/**
* Initialize static site rendering tRPC helpers.
* Provides a method to prefetch tRPC-queries in a `getStaticProps`-function.
@@ -41,7 +38,7 @@ export async function ssgInit<TParams extends { locale?: string }>(opts: GetStat
});
// always preload i18n
await ssg.viewer.public.i18n.fetch({ locale, CalComVersion });
await ssg.viewer.public.i18n.fetch({ locale, CalComVersion: CALCOM_VERSION });
return ssg;
}
+13 -15
View File
@@ -2,15 +2,12 @@ import type { GetServerSidePropsContext } from "next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import superjson from "superjson";
import { getLocaleFromHeaders } from "@calcom/lib/i18n";
import { CALCOM_VERSION } from "@calcom/lib/constants";
import { getLocaleFromRequest } from "@calcom/lib/i18n";
import { createProxySSGHelpers } from "@calcom/trpc/react/ssg";
import { createContext } from "@calcom/trpc/server/createContext";
import { appRouter } from "@calcom/trpc/server/routers/_app";
// TODO: Consolidate this constant
// eslint-disable-next-line turbo/no-undeclared-env-vars
const CalComVersion = process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA || "NA";
/**
* Initialize server-side rendering tRPC helpers.
* Provides a method to prefetch tRPC-queries in a `getServerSideProps`-function.
@@ -19,8 +16,8 @@ const CalComVersion = process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA || "NA";
*/
export async function ssrInit(context: GetServerSidePropsContext) {
const ctx = await createContext(context);
const locale = getLocaleFromHeaders(context.req);
const i18n = await serverSideTranslations(getLocaleFromHeaders(context.req), ["common", "vital"]);
const locale = await getLocaleFromRequest(context.req);
const i18n = await serverSideTranslations(locale, ["common", "vital"]);
const ssr = createProxySSGHelpers({
router: appRouter,
@@ -28,14 +25,15 @@ export async function ssrInit(context: GetServerSidePropsContext) {
ctx: { ...ctx, locale, i18n },
});
// always preload "viewer.public.i18n"
await ssr.viewer.public.i18n.fetch({ locale, CalComVersion });
// So feature flags are available on first render
await ssr.viewer.features.map.prefetch();
// Provides a better UX to the users who have already upgraded.
await ssr.viewer.teams.hasTeamPlan.prefetch();
await ssr.viewer.public.session.prefetch();
await Promise.allSettled([
// always preload "viewer.public.i18n"
ssr.viewer.public.i18n.prefetch({ locale, CalComVersion: CALCOM_VERSION }),
// So feature flags are available on first render
ssr.viewer.features.map.prefetch(),
// Provides a better UX to the users who have already upgraded.
ssr.viewer.teams.hasTeamPlan.prefetch(),
ssr.viewer.public.session.prefetch(),
]);
return ssr;
}