Compare commits
2
Commits
72c71bc789
...
95d1cb9630
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95d1cb9630 | ||
|
|
fabbbc40af |
@@ -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',
|
||||
});
|
||||
@@ -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<string>();
|
||||
|
||||
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<CachedChats>(() =>
|
||||
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 (
|
||||
<Avatar
|
||||
size="300"
|
||||
radii="400"
|
||||
className={css.SplashSpace}
|
||||
style={{ animationDelay: `${Math.min(index * 80, 640)}ms` }}
|
||||
>
|
||||
{src && !error ? (
|
||||
<AvatarImage
|
||||
className={css.SplashSpaceImage}
|
||||
src={src}
|
||||
alt={room.name}
|
||||
onError={() => setError(true)}
|
||||
draggable={false}
|
||||
/>
|
||||
) : (
|
||||
<AvatarFallback
|
||||
className={css.SplashSpaceFallback}
|
||||
style={{ backgroundColor: colorMXID(room.roomId), color: color.Surface.Container }}
|
||||
>
|
||||
<Text size="H6">{nameInitials(room.name, 2)}</Text>
|
||||
</AvatarFallback>
|
||||
)}
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<SplashScreen>
|
||||
<Box direction="Column" grow="Yes" alignItems="Center" justifyContent="Center" gap="400">
|
||||
<Spinner variant="Secondary" size="600" />
|
||||
<Text>Heating up</Text>
|
||||
{mx && (spaces.length > 0 || directs > 0) && (
|
||||
<>
|
||||
{spaces.length > 0 && (
|
||||
<Box className={css.SplashSpaces}>
|
||||
{spaces.map((space, index) => (
|
||||
<SplashSpaceAvatar key={space.roomId} mx={mx} room={space} index={index} />
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
<Text
|
||||
size="T300"
|
||||
align="Center"
|
||||
className={css.SplashStatus}
|
||||
style={{ animationDelay: `${Math.min(spaces.length * 80, 640) + 120}ms` }}
|
||||
>
|
||||
{foundLine(spaces.length, directs)}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
</SplashScreen>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<SplashScreen>
|
||||
<Box direction="Column" grow="Yes" alignItems="Center" justifyContent="Center" gap="400">
|
||||
<Spinner variant="Secondary" size="600" />
|
||||
<Text>Heating up</Text>
|
||||
</Box>
|
||||
</SplashScreen>
|
||||
);
|
||||
}
|
||||
|
||||
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<MatrixClient | undefined>(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<number | undefined>(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<number | undefined>(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<number | undefined>(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<void, Error, [MatrixClient]>(
|
||||
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 (
|
||||
<SpecVersions baseUrl={baseUrl!}>
|
||||
<TitleBar mx={mx} />
|
||||
{mx && <ClientAtomBinder mx={mx} />}
|
||||
{(loadState.status === AsyncStatus.Error || startState.status === AsyncStatus.Error) && (
|
||||
<SplashScreen>
|
||||
<Box direction="Column" grow="Yes" alignItems="Center" justifyContent="Center" gap="400">
|
||||
@@ -296,7 +443,7 @@ export function ClientRoot({ children }: ClientRootProps) {
|
||||
</SplashScreen>
|
||||
)}
|
||||
{loading || !mx ? (
|
||||
<ClientRootLoading />
|
||||
<ClientLoading mx={mx} />
|
||||
) : (
|
||||
<MatrixClientProvider value={mx}>
|
||||
<PluginLoader matrixClient={mx}>
|
||||
|
||||
+3
-1
@@ -361,7 +361,9 @@ export default defineConfig(() => ({
|
||||
build: {
|
||||
target: 'es2022',
|
||||
outDir: 'dist',
|
||||
sourcemap: true,
|
||||
// Maps are excluded from packaged builds anyway (electron-builder `!**/*.map`),
|
||||
// so skip generating them in CI to save build time.
|
||||
sourcemap: !process.env.CI,
|
||||
copyPublicDir: false,
|
||||
rollupOptions: {
|
||||
input: {
|
||||
|
||||
Reference in New Issue
Block a user