Skip to content

🤯 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.

🐛 fix: prevent blank screen when switching language (#15977)

AmAzing-85e2d3c1ebc7
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsx
new file mode 100644
index 00000000000..469bbbfea44
--- /dev/null
+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx
@@ -0,0 +1,70 @@
+'use client';
+
+import type { PropsWithChildren } from 'react';
+import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from 'react';
+
+import { cacheHydration, isCacheHydrationBlocked } from '@/libs/swr/cacheHydration';
+import { useCacheScope } from '@/libs/swr/useCacheScope';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+const HYDRATION_TIMEOUT = 1500;
+
+const CacheHydrationGate = ({ children }: PropsWithChildren) => {
+ const scope = useCacheScope();
+
+ return (
+ <CacheHydrationGateInner key={scope} scope={scope}>
+ {children}
+ </CacheHydrationGateInner>
+ );
+};
+
+interface CacheHydrationGateInnerProps extends PropsWithChildren {
+ scope: string;
+}
+
+const CacheHydrationGateInner = ({ children, scope }: CacheHydrationGateInnerProps) => {
+ const isAuthLoaded = Boolean(useUserStore(authSelectors.isLoaded));
+
+ const ready = useSyncExternalStore(
+ cacheHydration.subscribe,
+ () => cacheHydration.isReady(scope),
+ () => true,
+ );
+
+ const [released, setReleased] = useState(false);
+ const [timedOutScope, setTimedOutScope] = useState<string | null>(null);
+
+ useEffect(() => {
+ const timer = setTimeout(() => setTimedOutScope(scope), HYDRATION_TIMEOUT);
+ return () => clearTimeout(timer);
+ }, [scope]);
+
+ useEffect(() => {
+ if (!isAuthLoaded) return;
+ if (!cacheHydration.isReady(scope) && timedOutScope !== scope) return;
+
+ setReleased(true);
+ }, [isAuthLoaded, ready, scope, timedOutScope]);
+
+ const booting = isCacheHydrationBlocked({
+ isAuthLoaded,
+ ready,
+ released,
+ scope,
+ timedOutScope,
+ });
+
+ useLayoutEffect(() => {
+ if (booting) return;
+
+ document.getElementById('loading-screen')?.remove();
+ }, [booting]);
+
+ if (booting) return null;
+
+ return <>{children}</>;
+};
+
+export default CacheHydrationGate;
diff --git a/src/layout/GlobalProvider/Query.tsx b/src/layout/GlobalProvider/Query.tsx
index ca5a527ae85..0ac033d4539 100644
--- a/src/layout/GlobalProvider/Query.tsx
+++ b/src/layout/GlobalProvider/Query.tsx
@@ -1,11 +1,13 @@
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { type PropsWithChildren } from 'react';
-import React, { useState } from 'react';
+import type { PropsWithChildren } from 'react';
+import React, { useLayoutEffect, useRef, useState } from 'react';
import { type Cache, SWRConfig } from 'swr';
-import { appSWRCacheProvider } from '@/libs/swr/appCacheProvider';
+import { cacheHydration } from '@/libs/swr/cacheHydration';
+import { swrCacheProvider } from '@/libs/swr/localStorageProvider';
+import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';
import { lambdaQuery, lambdaQueryClient } from '@/libs/trpc/client';
import SWRMutateInitializer from './SWRMutateInitializer';
@@ -17,9 +19,26 @@ const QueryProvider = ({ children }: PropsWithChildren) => {
typeof lambdaQuery.Provider
>['queryClient'];
- // Reuse the app-level SWR provider initialized by the SPA bootstrap, so React
- // consumes the same cache map that the bootstrap hydrates.
- const [provider] = useState(() => appSWRCacheProvider);
+ // Keep the SWR cache provider inside SWRConfig's lifecycle. SWR registers
+ // global state for the returned Map during Provider render, so creating and
+ // hydrating that same Map from SPA bootstrap can leave hooks with an
+ // unregistered cache after remounts.
+ const [provider] = useState(() => swrCacheProvider(getCacheScope, cacheHydration.markReady));
+
+ const scope = useCacheScope();
+ const lastScope = useRef(scope);
+ useLayoutEffect(() => {
+ if (lastScope.current === scope) return;
+
+ lastScope.current = scope;
+ cacheHydration.markPending(scope);
+ const reloadScope = provider.reloadScope;
+ if (!reloadScope) return;
+
+ void reloadScope().catch((error) => {
+ console.error('[SWR Cache] failed to reload scope', error);
+ });
+ }, [scope, provider]);
return (
<SWRConfig value={{ provider: provider as unknown as (cache: Readonly<Cache>) => Cache }}>
diff --git a/src/layout/SPAGlobalProvider/Locale.tsx b/src/layout/SPAGlobalProvider/Locale.tsx
index ee875254867..a53bd26c9f5 100644
--- a/src/layout/SPAGlobalProvider/Locale.tsx
+++ b/src/layout/SPAGlobalProvider/Locale.tsx
@@ -10,14 +10,30 @@ import type { DayjsLocaleGlobEntry } from '@/utils/dayjsLocale';
import { loadDayjsLocaleModule, normalizeDayjsLocale } from '@/utils/dayjsLocale';
import { getAntdLocale } from '@/utils/locale';
-const dayjsLocaleLoaders = import.meta.glob<{ default: ILocale }>(
- '/node_modules/dayjs/locale/{ar,bg,de,en,es,fa,fr,it,ja,ko,nl,pl,pt-br,ru,tr,vi,zh-cn,zh-tw}.js',
-) as Record<string, DayjsLocaleGlobEntry>;
+const dayjsLocaleLoaders: Record<string, DayjsLocaleGlobEntry> = {
+ 'ar': () => import('dayjs/locale/ar'),
+ 'bg': () => import('dayjs/locale/bg'),
+ 'de': () => import('dayjs/locale/de'),
+ 'en': () => import('dayjs/locale/en'),
+ 'es': () => import('dayjs/locale/es'),
+ 'fa': () => import('dayjs/locale/fa'),
+ 'fr': () => import('dayjs/locale/fr'),
+ 'it': () => import('dayjs/locale/it'),
+ 'ja': () => import('dayjs/locale/ja'),
+ 'ko': () => import('dayjs/locale/ko'),
+ 'nl': () => import('dayjs/locale/nl'),
+ 'pl': () => import('dayjs/locale/pl'),
+ 'pt-br': () => import('dayjs/locale/pt-br'),
+ 'ru': () => import('dayjs/locale/ru'),
+ 'tr': () => import('dayjs/locale/tr'),
+ 'vi': () => import('dayjs/locale/vi'),
+ 'zh-cn': () => import('dayjs/locale/zh-cn'),
+ 'zh-tw': () => import('dayjs/locale/zh-tw'),
+};
const updateDayjs = async (lang: string) => {
const locale = normalizeDayjsLocale(lang);
- const key = `/node_modules/dayjs/locale/${locale}.js`;
- const loader = dayjsLocaleLoaders[key] ?? dayjsLocaleLoaders['/node_modules/dayjs/locale/en.js'];
+ const loader = dayjsLocaleLoaders[locale] ?? dayjsLocaleLoaders.en;
try {
const mod = await loadDayjsLocaleModule(loader);
@@ -26,9 +42,7 @@ const updateDayjs = async (lang: string) => {
} catch (error) {
console.error('error', error);
console.error(`dayjs locale for ${lang} not found, fallback to en`);
- const fallback = await loadDayjsLocaleModule(
- dayjsLocaleLoaders['/node_modules/dayjs/locale/en.js']!,
- );
+ const fallback = await loadDayjsLocaleModule(dayjsLocaleLoaders.en!);
dayjs.locale(fallback.default);
}
};
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index a82465f37c2..8fc1d0312c8 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -12,6 +12,7 @@ import AgentMockDevtools from '@/features/AgentMockDevtools';
import DevFeatureFlagPanel from '@/features/DevFeatureFlagPanel';
import AuthProvider from '@/layout/AuthProvider';
import AppTheme from '@/layout/GlobalProvider/AppTheme';
+import CacheHydrationGate from '@/layout/GlobalProvider/CacheHydrationGate';
import DynamicFavicon from '@/layout/GlobalProvider/DynamicFavicon';
import { FaviconProvider } from '@/layout/GlobalProvider/FaviconProvider';
import { GroupWizardProvider } from '@/layout/GlobalProvider/GroupWizardProvider';
@@ -59,7 +60,9 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
<LazyMotion features={domMax}>
<TooltipGroup layoutAnimation={false}>
<StyleProvider speedy={import.meta.env.PROD}>
- <LobeAnalyticsProviderWrapper>{children}</LobeAnalyticsProviderWrapper>
+ <LobeAnalyticsProviderWrapper>
+ <CacheHydrationGate>{children}</CacheHydrationGate>
+ </LobeAnalyticsProviderWrapper>
</StyleProvider>
</TooltipGroup>
<Suspense>
diff --git a/src/libs/swr/appCacheProvider.ts b/src/libs/swr/appCacheProvider.ts
deleted file mode 100644
index 06314dae7bc..00000000000
--- a/src/libs/swr/appCacheProvider.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { swrCacheProvider } from './localStorageProvider';
-import { getCacheScope } from './useCacheScope';
-
-export const appSWRCacheProvider = swrCacheProvider(getCacheScope);
-
-export const hydrateAppSWRCache = async (): Promise<void> => {
- await appSWRCacheProvider.hydrateScope?.();
-};
diff --git a/src/libs/swr/cacheHydration.test.ts b/src/libs/swr/cacheHydration.test.ts
new file mode 100644
index 00000000000..44ff971b2f1
--- /dev/null
+++ b/src/libs/swr/cacheHydration.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheHydration, isCacheHydrationBlocked } from './cacheHydration';
+
+describe('cacheHydration', () => {
+ const scopes = ['anon:personal', 'u1:personal'];
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ scopes.forEach((scope) => cacheHydration.markPending(scope));
+ });
+
+ it('marks a ready scope as pending before reload completes', () => {
+ const listener = vi.fn();
+ const unsubscribe = cacheHydration.subscribe(listener);
+
+ cacheHydration.markReady('anon:personal');
+ expect(cacheHydration.isReady('anon:personal')).toBe(true);
+
+ cacheHydration.markPending('anon:personal');
+
+ expect(cacheHydration.isReady('anon:personal')).toBe(false);
+ expect(listener).toHaveBeenCalledTimes(2);
+
+ unsubscribe();
+ });
+
+ it('blocks a returned scope until it is released after the latest hydration', () => {
+ cacheHydration.markReady('anon:personal');
+ cacheHydration.markReady('u1:personal');
+
+ cacheHydration.markPending('anon:personal');
+
+ expect(
+ isCacheHydrationBlocked({
+ isAuthLoaded: true,
+ ready: cacheHydration.isReady('anon:personal'),
+ released: false,
+ scope: 'anon:personal',
+ timedOutScope: null,
+ }),
+ ).toBe(true);
+
+ cacheHydration.markReady('anon:personal');
+
+ expect(
+ isCacheHydrationBlocked({
+ isAuthLoaded: true,
+ ready: cacheHydration.isReady('anon:personal'),
+ released: true,
+ scope: 'anon:personal',
+ timedOutScope: null,
+ }),
+ ).toBe(false);
+ });
+
+ it('does not let a timeout from another scope release the current scope', () => {
+ expect(
+ isCacheHydrationBlocked({
+ isAuthLoaded: true,
+ ready: false,
+ released: true,
+ scope: 'u1:personal',
+ timedOutScope: 'anon:personal',
+ }),
+ ).toBe(true);
+
+ expect(
+ isCacheHydrationBlocked({
+ isAuthLoaded: true,
+ ready: false,
+ released: true,
+ scope: 'u1:personal',
+ timedOutScope: 'u1:personal',
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/libs/swr/cacheHydration.ts b/src/libs/swr/cacheHydration.ts
new file mode 100644
index 00000000000..0eb26a20722
--- /dev/null
+++ b/src/libs/swr/cacheHydration.ts
@@ -0,0 +1,55 @@
+/**
+ * Tracks which identity scopes have finished hydrating the IndexedDB SWR tier.
+ */
+interface CacheHydrationBlockState {
+ isAuthLoaded: boolean;
+ ready: boolean;
+ released: boolean;
+ scope: string;
+ timedOutScope: string | null;
+}
+
+const readyScopes = new Set<string>();
+const listeners = new Set<() => void>();
+
+const emit = () => {
+ for (const listener of listeners) listener();
+};
+
+const markPending = (scope: string): void => {
+ if (!readyScopes.delete(scope)) return;
+
+ emit();
+};
+
+export const isCacheHydrationBlocked = ({
+ isAuthLoaded,
+ ready,
+ released,
+ scope,
+ timedOutScope,
+}: CacheHydrationBlockState) => {
+ if (!released) return true;
+
+ return !(isAuthLoaded && ready) && timedOutScope !== scope;
+};
+
+export const cacheHydration = {
+ isReady: (scope: string): boolean => readyScopes.has(scope),
+
+ markReady: (scope: string): void => {
+ if (readyScopes.has(scope)) return;
+
+ readyScopes.add(scope);
+ emit();
+ },
+
+ markPending,
+
+ reset: markPending,
+
+ subscribe: (listener: () => void): (() => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+};
diff --git a/src/libs/swr/cacheProvider.integration.test.tsx b/src/libs/swr/cacheProvider.integration.test.tsx
index 683073c5069..7bea0b09782 100644
--- a/src/libs/swr/cacheProvider.integration.test.tsx
+++ b/src/libs/swr/cacheProvider.integration.test.tsx
@@ -6,7 +6,8 @@
* synchronous local-first read before the network resolves.
*/
import { renderHook, waitFor } from '@testing-library/react';
-import { createElement, type PropsWithChildren } from 'react';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
import useSWR, { type Cache, SWRConfig } from 'swr';
import { afterEach, describe, expect, it } from 'vitest';
diff --git a/src/spa/AppLayer.tsx b/src/spa/AppLayer.tsx
index b7ffb5660c7..891085ec9d3 100644
--- a/src/spa/AppLayer.tsx
+++ b/src/spa/AppLayer.tsx
@@ -1,23 +1,12 @@
'use client';
-import { memo, type PropsWithChildren, useLayoutEffect, useRef } from 'react';
+import type { PropsWithChildren } from 'react';
+import { memo } from 'react';
import { useAppReady } from './atoms/app';
-const removeLoadingScreen = () => {
- document.querySelector('#loading-screen')?.remove();
-};
-
const AppLayer = memo<PropsWithChildren>(({ children }) => {
const appReady = useAppReady();
- const onceReady = useRef(false);
-
- useLayoutEffect(() => {
- if (!appReady || onceReady.current) return;
-
- onceReady.current = true;
- removeLoadingScreen();
- }, [appReady]);
return appReady ? <>{children}</> : null;
});
diff --git a/src/spa/initialize/bootstrap.ts b/src/spa/initialize/bootstrap.ts
index 76d4f394ae8..b3bfc7d81d6 100644
--- a/src/spa/initialize/bootstrap.ts
+++ b/src/spa/initialize/bootstrap.ts
@@ -2,7 +2,6 @@ import { flushSync } from 'react-dom';
import { setAppReady } from '../atoms/app';
import { initializeApp } from '.';
-import { startSWRCacheScopeSync } from './cacheScope';
import { startImportSettingsFromUrl } from './importSettings';
import { startPostRenderInitialization } from './postRender';
import { registerBuiltinToolSurfaces } from './toolSurfaces';
@@ -13,7 +12,6 @@ export const startAppInitialization = () => {
if (started) return;
started = true;
- startSWRCacheScopeSync();
startImportSettingsFromUrl();
registerBuiltinToolSurfaces();
diff --git a/src/spa/initialize/cacheScope.ts b/src/spa/initialize/cacheScope.ts
deleted file mode 100644
index e43bf0f9742..00000000000
--- a/src/spa/initialize/cacheScope.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { appSWRCacheProvider } from '@/libs/swr/appCacheProvider';
-import { getCacheScope } from '@/libs/swr/useCacheScope';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-
-let lastScope: string | undefined;
-let unsubscribeUserScope: (() => void) | undefined;
-
-const syncSWRCacheScope = () => {
- const scope = getCacheScope();
- if (lastScope === scope) return;
-
- lastScope = scope;
- void appSWRCacheProvider.reloadScope?.();
-};
-
-export const startSWRCacheScopeSync = () => {
- if (unsubscribeUserScope) return;
-
- lastScope = getCacheScope();
- unsubscribeUserScope = useUserStore.subscribe(userProfileSelectors.userId, syncSWRCacheScope);
-};
diff --git a/src/spa/initialize/index.ts b/src/spa/initialize/index.ts
index a115ff539ee..59163841d3f 100644
--- a/src/spa/initialize/index.ts
+++ b/src/spa/initialize/index.ts
@@ -1,20 +1,9 @@
-import { hydrateAppSWRCache } from '@/libs/swr/appCacheProvider';
-
const appLog = (...args: unknown[]) => {
if (__DEV__) console.info('[SPA Initialize]', ...args);
};
-const apm = async <T>(label: string, task: () => Promise<T> | T): Promise<T> => {
- const start = Date.now();
- const result = await task();
- appLog(`${label} took ${Date.now() - start}ms`);
- return result;
-};
-
export const initializeApp = async (): Promise<void> => {
const start = Date.now();
- await apm('hydrateSWRCache', hydrateAppSWRCache);
-
appLog('done', `${Date.now() - start}ms`);
};
diff --git a/src/utils/dayjsLocale.test.ts b/src/utils/dayjsLocale.test.ts
index 1b7984fa308..d9973022bee 100644
--- a/src/utils/dayjsLocale.test.ts
+++ b/src/utils/dayjsLocale.test.ts
@@ -12,6 +12,12 @@ const localeModule = {
};
describe('normalizeDayjsLocale', () => {
+ it('should normalize full app locales to dayjs locale ids', () => {
+ expect(normalizeDayjsLocale('en-US')).toBe('en');
+ expect(normalizeDayjsLocale('zh-CN')).toBe('zh-cn');
+ expect(normalizeDayjsLocale('pt-BR')).toBe('pt-br');
+ });
+
it('should normalize simplified Chinese script locales to zh-cn', () => {
expect(normalizeDayjsLocale('zh-Hans')).toBe('zh-cn');
expect(normalizeDayjsLocale('zh-Hans-CN')).toBe('zh-cn');
diff --git a/src/utils/dayjsLocale.ts b/src/utils/dayjsLocale.ts
index d2126839793..a9f029956f9 100644
--- a/src/utils/dayjsLocale.ts
+++ b/src/utils/dayjsLocale.ts
@@ -4,6 +4,8 @@
const DAYJS_LOCALE_ALIASES: Record<string, string> = {
'en-us': 'en',
'zh': 'zh-cn',
+ 'zh-cn': 'zh-cn',
+ 'zh-tw': 'zh-tw',
};
interface DayjsLocaleModule {
diff --git a/src/utils/router.tsx b/src/utils/router.tsx
index 8f47837801a..e10d1d5de40 100644
--- a/src/utils/router.tsx
+++ b/src/utils/router.tsx
@@ -1,6 +1,7 @@
'use client';
-import { ThemeProvider } from '@lobehub/ui';
+import { ConfigProvider, ThemeProvider } from '@lobehub/ui';
+import * as m from 'motion/react-m';
import { type ComponentType, type ReactElement } from 'react';
import { lazy, memo, Suspense, useLayoutEffect } from 'react';
import type { RouteObject } from 'react-router-dom';
@@ -114,7 +115,9 @@ export const ErrorBoundary = ({ resetPath }: ErrorBoundaryProps) => {
defaultThemeMode={appearance}
theme={{ cssVar: { key: 'lobe-vars' } }}
>
- <ErrorCapture error={error} resetPath={resetPath} />
+ <ConfigProvider motion={m}>
+ <ErrorCapture error={error} resetPath={resetPath} />
+ </ConfigProvider>
</ThemeProvider>
);
};