🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⚡️ perf(i18n): preload locale bundles on language picker hover (#18135)
Inneif4aeeca53cb4
diff --git a/src/features/Settings/common/features/Common/Common.tsx b/src/features/Settings/common/features/Common/Common.tsxindex e28bd3af047..fbd826c243a 100644--- a/src/features/Settings/common/features/Common/Common.tsx+++ b/src/features/Settings/common/features/Common/Common.tsx@@ -21,6 +21,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/selectors';import { type LocaleMode } from '@/types/locale';+import { preloadLang } from '@/utils/client/preloadLang';const Common = memo(() => {const { t } = useTranslation('setting');@@ -86,6 +87,19 @@ const Common = memo(() => {<Flexbox horizontal justify={'flex-end'}><SelectdefaultValue={language}+ optionRender={(option) => (+ <span+ style={{+ flex: 1,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ onMouseEnter={() => preloadLang(option.value as LocaleMode)}+ >+ {option.label}+ </span>+ )}options={[{ label: t('settingCommon.lang.autoMode'), value: 'auto' },...localeOptions,diff --git a/src/features/User/UserPanel/LangButton.tsx b/src/features/User/UserPanel/LangButton.tsxindex 6b301a2958f..a855f795078 100644--- a/src/features/User/UserPanel/LangButton.tsx+++ b/src/features/User/UserPanel/LangButton.tsx@@ -9,6 +9,7 @@ import { localeOptions } from '@/locales/resources';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';import { electronStylish } from '@/styles/electron';+import { preloadLang } from '@/utils/client/preloadLang';const LangButton = memo<{ placement?: DropdownMenuProps['placement']; size?: number }>(({ placement, size }) => {@@ -25,7 +26,7 @@ const LangButton = memo<{ placement?: DropdownMenuProps['placement']; size?: numcloseOnClick: true,key: 'auto',label: (- <Flexbox gap={4}>+ <Flexbox gap={4} onMouseEnter={() => preloadLang('auto')}><Text style={{ lineHeight: 1.2 }}>{t('settingCommon.lang.autoMode')}</Text><Text fontSize={12} style={{ lineHeight: 1.2 }} type={'secondary'}>{t(`lang.auto` as any, { ns: 'common' })}@@ -45,7 +46,7 @@ const LangButton = memo<{ placement?: DropdownMenuProps['placement']; size?: numcloseOnClick: true,key: item.value,label: (- <Flexbox gap={4} key={item.value}>+ <Flexbox gap={4} key={item.value} onMouseEnter={() => preloadLang(item.value)}><Text style={{ lineHeight: 1.2 }}>{item.label}</Text><Text fontSize={12} style={{ lineHeight: 1.2 }} type={'secondary'}>{t(`lang.${item.value}` as any, { ns: 'common' })}diff --git a/src/utils/client/preloadLang.test.ts b/src/utils/client/preloadLang.test.tsnew file mode 100644index 00000000000..5d3c55f0c12--- /dev/null+++ b/src/utils/client/preloadLang.test.ts@@ -0,0 +1,64 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { preloadLang } from './preloadLang';++const { getAntdLocale, load } = vi.hoisted(() => ({+ getAntdLocale: vi.fn(() => Promise.resolve({})),+ load: vi.fn(),+}));++vi.mock('i18next', () => ({+ changeLanguage: vi.fn(),+ default: {+ getDataByLanguage: () => ({ chat: {}, setting: {} }),+ language: 'en-US',+ options: { ns: ['common', 'chat'] },+ services: { backendConnector: { load } },+ },+}));++vi.mock('@/utils/locale', () => ({ getAntdLocale }));++describe('preloadLang', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ it('should load the currently used namespaces after the hover intent delay', () => {+ preloadLang('zh-CN');++ expect(load).not.toHaveBeenCalled();++ vi.runAllTimers();++ expect(load).toHaveBeenCalledWith('zh-CN', ['common', 'chat', 'setting'], expect.any(Function));+ expect(getAntdLocale).toHaveBeenCalledWith('zh-CN');+ });++ it('should resolve "auto" to the system language so the preloaded bundle matches switchLang', () => {+ vi.stubGlobal('lobeEnv', { systemLanguage: 'ja-JP' });++ preloadLang('auto');+ vi.runAllTimers();++ expect(load).toHaveBeenCalledWith('ja-JP', ['common', 'chat', 'setting'], expect.any(Function));++ vi.unstubAllGlobals();+ });++ it('should only preload the last hovered locale when moving across items', () => {+ preloadLang('de-DE');+ preloadLang('fr-FR');+ preloadLang('ko-KR');++ vi.runAllTimers();++ expect(load).toHaveBeenCalledTimes(1);+ expect(load).toHaveBeenCalledWith('ko-KR', ['common', 'chat', 'setting'], expect.any(Function));+ });+});diff --git a/src/utils/client/preloadLang.ts b/src/utils/client/preloadLang.tsnew file mode 100644index 00000000000..6afb4ec6554--- /dev/null+++ b/src/utils/client/preloadLang.ts@@ -0,0 +1,42 @@+import i18n from 'i18next';++import { type LocaleMode } from '@/types/locale';+import { getAntdLocale } from '@/utils/locale';++import { resolveLang } from './switchLang';++const HOVER_INTENT_DELAY = 120;++let intentTimer: ReturnType<typeof setTimeout> | undefined;++// `options.ns` misses the namespaces bundled at init (react-i18next only registers a namespace+// when it had to be fetched), so the store keys are unioned in to cover them as well.+const resolveNamespaces = () => {+ const { ns } = i18n.options;+ const registered = typeof ns === 'string' ? [ns] : (ns ?? []);+ const inStore = Object.keys(i18n.getDataByLanguage(i18n.resolvedLanguage || i18n.language) ?? {});++ return [...new Set([...registered, ...inStore])];+};++const loadNamespaces = (lang: string) => {+ const backendConnector = i18n.services?.backendConnector;+ if (!backendConnector) return;++ const namespaces = resolveNamespaces();+ if (namespaces.length === 0) return;++ // i18next skips (lng, ns) pairs that are already loaded or in flight, so no dedupe cache is needed here+ backendConnector.load(lang, namespaces, () => {});+};++export const preloadLang = (locale: LocaleMode) => {+ clearTimeout(intentTimer);++ intentTimer = setTimeout(() => {+ const lang = resolveLang(locale);++ loadNamespaces(lang);+ getAntdLocale(lang).catch(() => {});+ }, HOVER_INTENT_DELAY);+};diff --git a/src/utils/client/switchLang.ts b/src/utils/client/switchLang.tsindex 0b656aa2d64..2079fed2b97 100644--- a/src/utils/client/switchLang.ts+++ b/src/utils/client/switchLang.ts@@ -5,8 +5,11 @@ import { LOBE_LOCALE_COOKIE } from '@/const/locale';import { type LocaleMode } from '@/types/locale';import { getSystemLanguage } from '@/utils/client/systemLanguage';+export const resolveLang = (locale: LocaleMode) =>+ locale === 'auto' ? getSystemLanguage() : locale;+export const switchLang = (locale: LocaleMode) => {- const lang = locale === 'auto' ? getSystemLanguage() : locale;+ const lang = resolveLang(locale);changeLanguage(lang);document.documentElement.lang = lang;