From b3748ccfe07964c0b7c45f6e29a8225883d1dfa4 Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 15 Sep 2024 23:23:33 +0800 Subject: [PATCH] feat: cache i18n resource to speed up loading time Signed-off-by: Innei --- src/renderer/src/i18n.ts | 40 +++++++++++++++++++- src/renderer/src/providers/i18n-provider.tsx | 29 ++++++++++---- 2 files changed, 59 insertions(+), 10 deletions(-) diff --git a/src/renderer/src/i18n.ts b/src/renderer/src/i18n.ts index 3c541f805..409345914 100644 --- a/src/renderer/src/i18n.ts +++ b/src/renderer/src/i18n.ts @@ -5,21 +5,57 @@ import { initReactI18next } from "react-i18next" import { defaultNS, ns } from "./@types/constants" import { defaultResources } from "./@types/default-resource" +import { getGeneralSettings } from "./atoms/settings/general" import { jotaiStore } from "./lib/jotai" +import { getStorageNS } from "./lib/ns" export const i18nAtom = atom(i18next) +export class LocaleCache { + static shared = new LocaleCache() + private getKey(lang: string) { + return getStorageNS(`locale-${lang}`) + } + get(lang: string) { + const key = this.getKey(lang) + const cache = localStorage.getItem(key) + if (!cache) return null + return JSON.parse(cache) + } + set(lang: string) { + const key = this.getKey(lang) + const mergedResources = {} as any + for (const nsKey of ns) { + const nsResources = i18next.getResourceBundle(lang, nsKey) + mergedResources[nsKey] = nsResources + } + localStorage.setItem(key, JSON.stringify(mergedResources)) + } +} + export const fallbackLanguage = "en" export const initI18n = async () => { const i18next = jotaiStore.get(i18nAtom) + + const lang = getGeneralSettings().language + const cache = LocaleCache.shared.get(lang) + + const mergedResources = { + ...defaultResources, + } + + if (cache) { + mergedResources[lang] = cache + } + await i18next.use(initReactI18next).init({ ns, - lng: "en", + lng: cache ? lang : fallbackLanguage, fallbackLng: fallbackLanguage, defaultNS, debug: import.meta.env.DEV, - resources: defaultResources, + resources: mergedResources, }) } diff --git a/src/renderer/src/providers/i18n-provider.tsx b/src/renderer/src/providers/i18n-provider.tsx index ea3418b9d..60abd0e73 100644 --- a/src/renderer/src/providers/i18n-provider.tsx +++ b/src/renderer/src/providers/i18n-provider.tsx @@ -1,16 +1,16 @@ import { currentSupportedLanguages, dayjsLocaleImportMap, - defaultNS, } from "@renderer/@types/constants" import { defaultResources } from "@renderer/@types/default-resource" -import { getGeneralSettings } from "@renderer/atoms/settings/general" -import { i18nAtom } from "@renderer/i18n" +import { getGeneralSettings, setGeneralSetting } from "@renderer/atoms/settings/general" +import { fallbackLanguage, i18nAtom, LocaleCache } from "@renderer/i18n" import { EventBus } from "@renderer/lib/event-bus" import { jotaiStore } from "@renderer/lib/jotai" import { isEmptyObject } from "@renderer/lib/utils" import dayjs from "dayjs" import i18next from "i18next" +import LanguageDetector from "i18next-browser-languagedetector" import { useAtom } from "jotai" import type { FC, PropsWithChildren } from "react" import { useEffect, useLayoutEffect, useRef } from "react" @@ -18,6 +18,7 @@ import { I18nextProvider } from "react-i18next" import { toast } from "sonner" const loadingLangLock = new Set() +const loadedLangs = new Set([fallbackLanguage]) const langChangedHandler = async (lang: string) => { const dayjsImport = dayjsLocaleImportMap[lang] @@ -35,7 +36,7 @@ const langChangedHandler = async (lang: string) => { if (!isSupport) { return } - const loaded = i18next.getResourceBundle(lang, defaultNS) + const loaded = loadedLangs.has(lang) if (loaded) { return @@ -68,8 +69,8 @@ const langChangedHandler = async (lang: string) => { } } } else { - const res = await import(`/locales/${lang}.js`) - .then((res) => res?.default || res) + const res = await eval(`import('/locales/${lang}.js')`) + .then((res: any) => res?.default || res) .catch(() => { toast.error(`${t("common:tips.load-lng-error")}: ${lang}`) loadingLangLock.delete(lang) @@ -86,10 +87,10 @@ const langChangedHandler = async (lang: string) => { await i18next.reloadResources() await i18next.changeLanguage(lang) + LocaleCache.shared.set(lang) + loadedLangs.add(lang) loadingLangLock.delete(lang) } - -langChangedHandler(getGeneralSettings().language) export const I18nProvider: FC = ({ children }) => { const [currentI18NInstance, update] = useAtom(i18nAtom) @@ -108,6 +109,18 @@ export const I18nProvider: FC = ({ children }) => { ) const callOnce = useRef(false) + const detectOnce = useRef(false) + useLayoutEffect(() => { + if (detectOnce.current) return + const languageDetector = new LanguageDetector() + const userLang = languageDetector.detect() + if (!userLang) return + const firstUserLang = Array.isArray(userLang) ? userLang[0] : userLang + if (currentSupportedLanguages.includes(firstUserLang)) { + setGeneralSetting("language", firstUserLang) + } + detectOnce.current = true + }, []) useLayoutEffect(() => { const i18next = currentI18NInstance