import { useEffect, useState } from 'react'; import { UserEvent, UserEventHandlerMap } from 'matrix-js-sdk'; import { useMatrixClient } from './useMatrixClient'; import { getCachedProfileFields, getProfileFields, registerProfileCacheListener } from '../utils/profileCache'; export type UserProfile = { avatarUrl?: string; displayName?: string; }; export const useUserProfile = (userId: string): UserProfile => { const mx = useMatrixClient(); const [profile, setProfile] = useState(() => { const user = mx.getUser(userId); return { avatarUrl: user?.avatarUrl, displayName: user?.displayName, }; }); useEffect(() => { if (!userId) return undefined; const user = mx.getUser(userId); let disposed = false; const applyFields = (fields: Record) => { const avatarUrl = typeof fields.avatar_url === 'string' ? fields.avatar_url : undefined; const displayName = typeof fields.displayname === 'string' ? fields.displayname : undefined; if (!avatarUrl && !displayName) return; setProfile((cp) => ({ avatarUrl: avatarUrl ?? cp.avatarUrl, displayName: displayName ?? cp.displayName, })); }; // The SDK already holds profile data from sync, so only hit the network when // both the SDK and the shared profile cache are cold. const cached = getCachedProfileFields(userId); if (cached) { applyFields(cached); } else if (!user?.displayName && !user?.avatarUrl) { getProfileFields(mx, userId).then((fields) => { if (!disposed) applyFields(fields); }); } const onProfileChange: UserEventHandlerMap[UserEvent.AvatarUrl] = (event, myUser) => { setProfile((cp) => ({ ...cp, avatarUrl: myUser.avatarUrl, })); }; const onDisplayNameChange: UserEventHandlerMap[UserEvent.DisplayName] = (event, myUser) => { setProfile((cp) => ({ ...cp, displayName: myUser.displayName, })); }; const unsubscribeCache = registerProfileCacheListener((changedUserId) => { if (changedUserId !== userId) return; const fields = getCachedProfileFields(userId); if (fields) applyFields(fields); }); user?.on(UserEvent.AvatarUrl, onProfileChange); user?.on(UserEvent.DisplayName, onDisplayNameChange); return () => { disposed = true; unsubscribeCache(); user?.removeListener(UserEvent.AvatarUrl, onProfileChange); user?.removeListener(UserEvent.DisplayName, onDisplayNameChange); }; }, [mx, userId]); return profile; };