perf: make useLocale hook to use server-fetched i18n if in App router context (#20597)
* write I18nProvider * rename * update useLocale * fix * use a singleton * safer * better * fix e2e test 1 * fix e2e test 2 * fix e2e test 3 * fix e2e test 4 * fix * refactor * address comments * fix * fix * fix * fix * fix * fix * fix * fix * fix * fix * fix flaky test * add more caching * revert changes to e2e tests * add jsdoc * memoize * update window object with new translations in /settings/my-account/general * remove dead code * only use locale and ns as deps * fix
This commit is contained in:
1 parent
9eb1fe06e3
commit
b17b5a169f
7 files changed
+182
-101
No files matched your search
@@ -1,18 +1,24 @@
|
||||
import { createInstance } from "i18next";
|
||||
import type { TFunction, i18n } from "i18next";
|
||||
import { useContext } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useAtomsContext } from "@calcom/atoms/hooks/useAtomsContext";
|
||||
import { AppRouterI18nContext } from "@calcom/web/app/AppRouterI18nProvider";
|
||||
|
||||
export const useLocale = (namespace: Parameters<typeof useTranslation>[0] = "common") => {
|
||||
type useLocaleReturnType = {
|
||||
i18n: i18n;
|
||||
t: TFunction;
|
||||
isLocaleReady: boolean;
|
||||
};
|
||||
|
||||
// @internal
|
||||
const useClientLocale = (namespace: Parameters<typeof useTranslation>[0] = "common"): useLocaleReturnType => {
|
||||
const context = useAtomsContext();
|
||||
const { i18n, t } = useTranslation(namespace);
|
||||
const isLocaleReady = Object.keys(i18n).length > 0;
|
||||
|
||||
if (context?.clientId) {
|
||||
return { i18n: context.i18n, t: context.t, isLocaleReady: true } as unknown as {
|
||||
i18n: ReturnType<typeof useTranslation>["i18n"];
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
isLocaleReady: boolean;
|
||||
};
|
||||
return { i18n: context.i18n, t: context.t, isLocaleReady: true } as unknown as useLocaleReturnType;
|
||||
}
|
||||
return {
|
||||
i18n,
|
||||
@@ -20,3 +26,46 @@ export const useLocale = (namespace: Parameters<typeof useTranslation>[0] = "com
|
||||
isLocaleReady,
|
||||
};
|
||||
};
|
||||
|
||||
// @internal
|
||||
const serverI18nInstances = new Map();
|
||||
|
||||
export const useLocale = (): useLocaleReturnType => {
|
||||
const appRouterContext = useContext(AppRouterI18nContext);
|
||||
const clientI18n = useClientLocale();
|
||||
|
||||
if (appRouterContext) {
|
||||
const { translations, locale, ns } = appRouterContext;
|
||||
const instanceKey = `${locale}-${ns}`;
|
||||
|
||||
// Check if we already have an instance for this locale and namespace
|
||||
if (!serverI18nInstances.has(instanceKey)) {
|
||||
const i18n = createInstance();
|
||||
i18n.init({
|
||||
lng: locale,
|
||||
resources: {
|
||||
[locale]: {
|
||||
[ns]: translations,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
serverI18nInstances.set(instanceKey, {
|
||||
t: i18n.getFixedT(locale, ns),
|
||||
isLocaleReady: true,
|
||||
i18n,
|
||||
});
|
||||
}
|
||||
|
||||
return serverI18nInstances.get(instanceKey);
|
||||
}
|
||||
|
||||
console.warn(
|
||||
"useLocale hook is being used outside of App Router - hence this hook will use a global, client-side i18n which can cause a small flicker"
|
||||
);
|
||||
return {
|
||||
t: clientI18n.t,
|
||||
isLocaleReady: clientI18n.isLocaleReady,
|
||||
i18n: clientI18n.i18n,
|
||||
};
|
||||
};
|
||||
+59
-10
@@ -2,31 +2,79 @@ import { createInstance } from "i18next";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
const translationCache = new Map<string, Record<string, string>>();
|
||||
const i18nInstanceCache = new Map<string, any>();
|
||||
|
||||
/**
|
||||
* Loads English fallback translations for when requested locale translations fail
|
||||
* Implements caching to avoid redundant network requests
|
||||
* @returns {Promise<Record<string, string>>} English translations object or empty object on failure
|
||||
*/
|
||||
async function loadFallbackTranslations() {
|
||||
const cacheKey = "en-common";
|
||||
|
||||
if (translationCache.has(cacheKey)) {
|
||||
return translationCache.get(cacheKey);
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${WEBAPP_URL}/static/locales/en/common.json`);
|
||||
if (res) {
|
||||
return await res.json();
|
||||
const res = await fetch(`${WEBAPP_URL}/static/locales/en/common.json`, {
|
||||
cache: process.env.NODE_ENV === "production" ? "force-cache" : "no-store",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch fallback translations: ${res.status}`);
|
||||
}
|
||||
} catch {
|
||||
console.error("Could not fetch fallback translations.");
|
||||
|
||||
const translations = await res.json();
|
||||
translationCache.set(cacheKey, translations);
|
||||
return translations;
|
||||
} catch (error) {
|
||||
console.error("Could not fetch fallback translations:", error);
|
||||
return {};
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
async function loadTranslations(locale: string, ns: string) {
|
||||
/**
|
||||
* Loads translations for a specific locale and namespace with optimized caching
|
||||
* @param {string} _locale - The locale code (e.g., 'en', 'fr', 'zh')
|
||||
* @param {string} ns - The namespace for the translations
|
||||
* @returns {Promise<Record<string, string>>} Translations object or fallback translations on failure
|
||||
*/
|
||||
export async function loadTranslations(_locale: string, ns: string) {
|
||||
const locale = _locale === "zh" ? "zh-CN" : _locale;
|
||||
const cacheKey = `${locale}-${ns}`;
|
||||
|
||||
if (translationCache.has(cacheKey)) {
|
||||
return translationCache.get(cacheKey);
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${WEBAPP_URL}/static/locales/${locale}/${ns}.json`;
|
||||
const response = await fetch(url);
|
||||
return await response.json();
|
||||
const response = await fetch(url, {
|
||||
cache: process.env.NODE_ENV === "production" ? "force-cache" : "no-store",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch translations: ${response.status}`);
|
||||
}
|
||||
|
||||
const translations = await response.json();
|
||||
translationCache.set(cacheKey, translations);
|
||||
return translations;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to load translations for ${locale}/${ns}, falling back to English:`, error);
|
||||
const fallbackTranslations = await loadFallbackTranslations();
|
||||
return fallbackTranslations ?? {};
|
||||
return fallbackTranslations;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or retrieves a cached i18next translation function for the specified locale and namespace
|
||||
* @param {string} locale - The locale code (e.g., 'en', 'fr')
|
||||
* @param {string} ns - The namespace for the translations
|
||||
* @returns {Promise<Function>} A translation function bound to the specified locale and namespace
|
||||
*/
|
||||
export const getTranslation = async (locale: string, ns: string) => {
|
||||
const cacheKey = `${locale}-${ns}`;
|
||||
if (i18nInstanceCache.has(cacheKey)) {
|
||||
@@ -46,6 +94,7 @@ export const getTranslation = async (locale: string, ns: string) => {
|
||||
fallbackLng: "en",
|
||||
});
|
||||
|
||||
// Cache the i18n instance
|
||||
i18nInstanceCache.set(cacheKey, _i18n);
|
||||
return _i18n.getFixedT(locale, ns);
|
||||
};
|
||||
@@ -32,6 +32,11 @@ export function UnpublishedEntity(props: UnpublishedEntityProps) {
|
||||
avatar={<Avatar alt={slug ?? ""} imageSrc={getPlaceholderAvatar(props.logoUrl, slug)} size="lg" />}
|
||||
headline={t("team_is_unpublished", {
|
||||
team: props.name,
|
||||
interpolation: {
|
||||
// This is needed because React automatically escapes special characters like apostrophes
|
||||
// for security (XSS prevention), but we want to display the actual apostrophe in the UI
|
||||
escapeValue: false,
|
||||
},
|
||||
})}
|
||||
description={t(`${props.orgSlug ? "org" : "team"}_is_unpublished_description`)}
|
||||
/>
|
||||
|
||||
Reference in new issue
Block a user