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)} )} ); }