From 95d1cb9630c8d6b925769594583a497f80ba2203 Mon Sep 17 00:00:00 2001 From: litruv Date: Tue, 6 Oct 2026 11:11:27 +1100 Subject: [PATCH] Show cached spaces on the loading splash until the chats are ready The splash hid as soon as sync reported Prepared, so the first paint after it disappeared showed the empty state. Hide only once the room-list atoms actually contain chats, and bind those atoms while the splash is still up so the first paint is already populated. Also fixes the ClientEvent.Sync handler signature: data is the third argument, so reading it as the second made fromCache always undefined. --- src/app/pages/client/ClientLoading.css.ts | 49 ++++++ src/app/pages/client/ClientLoading.tsx | 128 +++++++++++++++ src/app/pages/client/ClientRoot.tsx | 187 +++++++++++++++++++--- 3 files changed, 344 insertions(+), 20 deletions(-) create mode 100644 src/app/pages/client/ClientLoading.css.ts create mode 100644 src/app/pages/client/ClientLoading.tsx diff --git a/src/app/pages/client/ClientLoading.css.ts b/src/app/pages/client/ClientLoading.css.ts new file mode 100644 index 00000000..55af087f --- /dev/null +++ b/src/app/pages/client/ClientLoading.css.ts @@ -0,0 +1,49 @@ +import { keyframes, style } from '@vanilla-extract/css'; +import { config, DefaultReset, toRem } from 'folds'; + +const particleRise = keyframes({ + '0%': { + opacity: 0, + transform: 'translateY(24px) scale(0.85)', + }, + '100%': { + opacity: 1, + transform: 'translateY(0) scale(1)', + }, +}); + +export const SplashSpaces = style([ + DefaultReset, + { + display: 'flex', + flexWrap: 'wrap', + justifyContent: 'center', + alignItems: 'center', + gap: config.space.S300, + maxWidth: toRem(420), + }, +]); + +export const SplashSpace = style({ + animation: `${particleRise} 450ms cubic-bezier(0.16, 1, 0.3, 1) both`, +}); + +export const SplashSpaceImage = style({ + width: '100%', + height: '100%', + borderRadius: 'inherit', +}); + +export const SplashStatus = style({ + animation: `${particleRise} 450ms cubic-bezier(0.16, 1, 0.3, 1) both`, +}); + +export const SplashSpaceFallback = style({ + width: '100%', + height: '100%', + borderRadius: 'inherit', + textTransform: 'capitalize', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', +}); diff --git a/src/app/pages/client/ClientLoading.tsx b/src/app/pages/client/ClientLoading.tsx new file mode 100644 index 00000000..0ee9c122 --- /dev/null +++ b/src/app/pages/client/ClientLoading.tsx @@ -0,0 +1,128 @@ +import { Avatar, AvatarFallback, AvatarImage, Box, Spinner, Text, color } from 'folds'; +import React, { useEffect, useState } from 'react'; +import { ClientEvent, MatrixClient, Room } from 'matrix-js-sdk'; +import { SplashScreen } from '../../components/splash-screen'; +import { getAccountData, getMDirects, getRoomAvatarUrl, isSpace } from '../../utils/room'; +import { AccountDataEvent } from '../../../types/matrix/accountData'; +import { nameInitials } from '../../utils/common'; +import colorMXID from '../../../util/colorMXID'; +import * as css from './ClientLoading.css'; + +type CachedChats = { + spaces: Room[]; + directs: number; +}; + +const getSnapshot = (mx: MatrixClient): CachedChats => { + const rooms = mx.getRooms(); + const mDirectEvent = getAccountData(mx, AccountDataEvent.Direct); + const directs = mDirectEvent ? getMDirects(mDirectEvent) : new Set(); + + return { + spaces: rooms + .filter((room) => isSpace(room) && room.getMyMembership() === 'join') + .sort((a, b) => (a.name ?? '').localeCompare(b.name ?? '')), + directs: rooms.filter((room) => directs.has(room.roomId)).length, + }; +}; + +/** + * Cached rooms are restored asynchronously from the IndexedDB store, so poll + * while connecting to show the user's spaces as soon as they become available. + */ +function useCachedChats(mx?: MatrixClient): CachedChats { + const [snapshot, setSnapshot] = useState(() => + mx ? getSnapshot(mx) : { spaces: [], directs: 0 }, + ); + + useEffect(() => { + if (!mx) return undefined; + + const update = () => setSnapshot(getSnapshot(mx)); + update(); + + const timer = setInterval(update, 400); + mx.on(ClientEvent.Room, update); + mx.on(ClientEvent.AccountData, update); + + return () => { + clearInterval(timer); + mx.removeListener(ClientEvent.Room, update); + mx.removeListener(ClientEvent.AccountData, update); + }; + }, [mx]); + + return snapshot; +} + +function SplashSpaceAvatar({ mx, room, index }: { mx: MatrixClient; room: Room; index: number }) { + // Authenticated media needs the full client context, which is not available + // while loading; fall back to initials when the plain URL fails. + const src = getRoomAvatarUrl(mx, room, 96); + const [error, setError] = useState(false); + + return ( + + {src && !error ? ( + setError(true)} + draggable={false} + /> + ) : ( + + {nameInitials(room.name, 2)} + + )} + + ); +} + +const foundLine = (spaces: number, directs: number): string => { + const parts = []; + if (spaces > 0) parts.push(`Found ${spaces} ${spaces === 1 ? 'space' : 'spaces'}`); + if (directs > 0) parts.push(`${directs} ${directs === 1 ? 'chat' : 'chats'}`); + return parts.join(' · '); +}; + +export function ClientLoading({ mx }: { mx?: MatrixClient }) { + const { spaces, directs } = useCachedChats(mx); + + return ( + + + + Heating up + {mx && (spaces.length > 0 || directs > 0) && ( + <> + {spaces.length > 0 && ( + + {spaces.map((space, index) => ( + + ))} + + )} + + {foundLine(spaces.length, directs)} + + + )} + + + ); +} diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index dfa50d29..dfbea08b 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -1,6 +1,12 @@ -import { Box, Button, config, Dialog, IconButton, Menu, MenuItem, PopOut, RectCords, Spinner, Text } from 'folds'; +import { Box, Button, config, Dialog, IconButton, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; import { Icon, Icons } from '../../components/icons'; -import { HttpApiEvent, HttpApiEventHandlerMap, MatrixClient, SyncState } from 'matrix-js-sdk'; +import { + ClientEvent, + HttpApiEvent, + HttpApiEventHandlerMap, + MatrixClient, + SyncState, +} from 'matrix-js-sdk'; import FocusTrap from 'focus-trap-react'; import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; import { @@ -11,6 +17,7 @@ import { startClient, } from '../../../client/initMatrix'; import { SplashScreen } from '../../components/splash-screen'; +import { ClientLoading } from './ClientLoading'; import { ServerConfigsLoader } from '../../components/ServerConfigsLoader'; import { CapabilitiesProvider } from '../../hooks/useCapabilities'; import { MediaConfigProvider } from '../../hooks/useMediaConfig'; @@ -20,6 +27,10 @@ import { SpecVersions } from './SpecVersions'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { useSyncState } from '../../hooks/useSyncState'; import { stopPropagation } from '../../utils/keyboard'; +import { useAtomValue } from 'jotai'; +import { allRoomsAtom, useBindAllRoomsAtom } from '../../state/room-list/roomList'; +import { mDirectAtom, useBindMDirectAtom } from '../../state/mDirectList'; +import { roomToParentsAtom, useBindRoomToParentsAtom } from '../../state/room/roomToParents'; import { AuthMetadataProvider } from '../../hooks/useAuthMetadata'; import { getCurrentSession } from '../../state/sessions'; import { CallProviderWrapper } from '../../features/call/CallProviderWrapper'; @@ -29,17 +40,6 @@ import { AccountSwitcher } from '../../components/account-switcher'; import { getLoginPath, withSearchParam } from '../pathUtils'; import { useViewTransitions } from '../../hooks/useViewTransitions'; -function ClientRootLoading() { - return ( - - - - Heating up - - - ); -} - const useLogoutListener = (mx?: MatrixClient) => { useEffect(() => { const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => { @@ -140,6 +140,21 @@ const useBackgroundSync = (mx?: MatrixClient) => { }, [mx]); }; +/** + * Binds the atoms the chat UI reads while the splash is still up. Without this, + * they are only bound after the splash hides, so the first paint shows the empty + * state ("No Direct Messages") for a moment. + * + * Only the context-free bindings go here: the rest (unread, typing, auto-join) + * needs the RoomsNotificationPreferences provider, which lives inside children. + */ +function ClientAtomBinder({ mx }: { mx: MatrixClient }) { + useBindMDirectAtom(mx, mDirectAtom); + useBindAllRoomsAtom(mx, allRoomsAtom); + useBindRoomToParentsAtom(mx, roomToParentsAtom); + return null; +} + type ClientRootProps = { children: ReactNode; }; @@ -148,6 +163,49 @@ export function ClientRoot({ children }: ClientRootProps) { const [loading, setLoading] = useState(true); const mxRef = useRef(undefined); const recoverInFlight = useRef(false); + // Hold the splash briefly after chats are loaded so the space particles + // finish animating before the UI swaps in. + const splashHoldTimer = useRef(undefined); + // Grace window for the first network sync to land after the cache is ready; + // hide anyway if we are offline so the UI is never blocked. + const firstNetworkSyncGrace = useRef(undefined); + // Hard deadline so a sync that never lands (offline, empty store, errored + // first sync) can not leave the splash up forever. + const splashDeadline = useRef(undefined); + + const scheduleHide = useCallback((reason?: string) => { + if (splashHoldTimer.current !== undefined) return; + + if (reason) console.log(`[ClientRoot] Hiding splash: ${reason}`); + splashHoldTimer.current = window.setTimeout(() => { + splashHoldTimer.current = undefined; + setLoading(false); + }, 1500); + }, []); + + // The UI renders chats from the room-list atoms, which are filled by + // ClientAtomBinder while the splash is still up. Gate the hide on those atoms + // so the first paint after the splash already contains the chats. + const roomsAtom = useAtomValue(allRoomsAtom); + const directsAtom = useAtomValue(mDirectAtom); + const chatsReady = + roomsAtom.length > 0 && directsAtom.size > 0 && roomsAtom.some((roomId) => directsAtom.has(roomId)); + + const tryHide = useCallback( + (reason: string): boolean => { + if (chatsReady) { + scheduleHide(reason); + return true; + } + return false; + }, + [chatsReady, scheduleHide] + ); + + // The atoms fill in as the store restores the cache; hide as soon as they do. + useEffect(() => { + if (loading && chatsReady) scheduleHide('chats populated'); + }, [loading, chatsReady, scheduleHide]); const { baseUrl } = getCurrentSession() ?? {}; // Enable view transitions for smooth navigation @@ -168,6 +226,20 @@ export function ClientRoot({ children }: ClientRootProps) { mxRef.current = mx; }, [mx]); + useEffect(() => { + return () => { + if (splashHoldTimer.current !== undefined) { + window.clearTimeout(splashHoldTimer.current); + } + if (firstNetworkSyncGrace.current !== undefined) { + window.clearTimeout(firstNetworkSyncGrace.current); + } + if (splashDeadline.current !== undefined) { + window.clearTimeout(splashDeadline.current); + } + }; + }, []); + const [startState, startMatrix] = useAsyncCallback( useCallback((m) => startClient(m), []) ); @@ -188,6 +260,45 @@ export function ClientRoot({ children }: ClientRootProps) { } }, [mx, startMatrix]); + // Cached rooms and m.direct land asynchronously from the IndexedDB store, so + // watch for them while loading and hide as soon as the chats are populated. + useEffect(() => { + if (!mx || !loading) return undefined; + + const check = () => tryHide('chats populated'); + + check(); + + console.log( + '[ClientRoot] Splash gate:', + mx.getSyncState(), + `${roomsAtom.length} rooms in atom`, + `${directsAtom.size} m.direct` + ); + + // Prepared can fire before this listener attaches, so look at the current + // state too, and never let the splash outlive the deadline. + const syncState = mx.getSyncState(); + if (syncState === SyncState.Prepared || syncState === SyncState.Syncing) check(); + + if (splashDeadline.current === undefined) { + splashDeadline.current = window.setTimeout(() => { + splashDeadline.current = undefined; + scheduleHide('deadline reached, showing whatever the cache has'); + }, 10000); + } + + const poll = window.setInterval(check, 400); + mx.on(ClientEvent.Room, check); + mx.on(ClientEvent.AccountData, check); + + return () => { + window.clearInterval(poll); + mx.removeListener(ClientEvent.Room, check); + mx.removeListener(ClientEvent.AccountData, check); + }; + }, [mx, loading, chatsReady, tryHide, scheduleHide, roomsAtom, directsAtom]); + // Timeout if sync takes too long - nudge the client rather than immediately erroring useEffect(() => { if (!mx || !loading) return; @@ -200,19 +311,54 @@ export function ClientRoot({ children }: ClientRootProps) { return () => clearTimeout(timeout); }, [mx, loading]); - // Soft-recover from sync ERROR (e.g. sleep/wake with no network). - // Never block the UI — SyncStatus / title bar already show "Connection Lost". + // Hold the splash until the chats are actually populated, then keep it a + // moment longer so the space particles finish animating. + // Soft-recover from sync ERROR (e.g. sleep/wake with no network); the grace + // window ensures we never block the UI when offline. useSyncState( mx, - useCallback((state) => { + useCallback((state, prevState, data) => { const client = mxRef.current; if (state === SyncState.Prepared || state === SyncState.Syncing) { - setLoading(false); + if (state === SyncState.Prepared) { + console.log( + '[ClientRoot] Prepared from', + prevState ?? 'nothing', + data?.fromCache ? '(cache)' : '(network)' + ); + } + + if (tryHide(data?.fromCache ? 'cache populated' : 'first network sync')) { + return; + } + + if (data?.fromCache) { + // Cache-only prepared: the room list is still being restored, so wait + // for it, but hide anyway once the grace expires so we never block the + // UI when offline. + if (firstNetworkSyncGrace.current === undefined) { + firstNetworkSyncGrace.current = window.setTimeout(() => { + firstNetworkSyncGrace.current = undefined; + scheduleHide('cache grace expired'); + }, 5000); + } + } else { + // First network sync completed: whatever we have is what the UI shows. + scheduleHide('first network sync completed'); + } recoverInFlight.current = false; return; } - if (state !== SyncState.Error || !client || recoverInFlight.current) { + if (state !== SyncState.Error || !client) { + return; + } + + // Sync failed (no network, first sync never landed). Show whatever the + // cache restored instead of leaving the splash up. + if (client.getRooms().length > 0) scheduleHide('sync error with cached chats'); + + if (recoverInFlight.current) { return; } @@ -243,7 +389,7 @@ export function ClientRoot({ children }: ClientRootProps) { // Give Wi‑Fi a moment to come back after lid open / resume window.setTimeout(recover, 1500); - }, []) + }, [tryHide, scheduleHide]) ); // Also nudge sync when the laptop wakes / network returns @@ -274,6 +420,7 @@ export function ClientRoot({ children }: ClientRootProps) { return ( + {mx && } {(loadState.status === AsyncStatus.Error || startState.status === AsyncStatus.Error) && ( @@ -296,7 +443,7 @@ export function ClientRoot({ children }: ClientRootProps) { )} {loading || !mx ? ( - + ) : (