import { useCallback, useEffect, useState } from 'react'; import { useMatrixClient } from './useMatrixClient'; import { useMediaAuthentication } from './useMediaAuthentication'; import { extractBannerUrlFromProfile, deleteBannerUrl, saveBannerUrl, } from '../utils/profileFields'; import { getProfileFields, registerProfileCacheListener } from '../utils/profileCache'; import { getProfileAssetUrl } from '../utils/profileAssetCache'; /** * Hook to manage the user's profile banner (MSC4427 via MSC4133). */ export function useUserBanner(): [ string | undefined, (banner: string | undefined) => Promise, boolean ] { const mx = useMatrixClient(); const [banner, setBanner] = useState(); const [loading, setLoading] = useState(true); useEffect(() => { const userId = mx.getUserId(); if (!userId) { setLoading(false); return undefined; } let cancelled = false; const load = async () => { setLoading(true); try { const bannerMxc = extractBannerUrlFromProfile(await getProfileFields(mx, userId)); if (!cancelled) setBanner(bannerMxc); } catch { if (!cancelled) setBanner(undefined); } if (!cancelled) setLoading(false); }; load(); return () => { cancelled = true; }; }, [mx]); const updateBanner = useCallback( async (newBanner: string | undefined) => { if (!newBanner) { await deleteBannerUrl(mx); setBanner(undefined); return; } await saveBannerUrl(mx, newBanner); setBanner(newBanner); }, [mx] ); return [banner, updateBanner, loading]; } /** * Hook to get another user's profile banner as a blob URL. * Profile fields come from the shared profile cache, and the media itself is * cached so reopening the same profile does not re-download the banner. */ export function useOtherUserBanner(userId: string): string | undefined { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const [bannerBlobUrl, setBannerBlobUrl] = useState(); useEffect(() => { if (!userId) { setBannerBlobUrl(undefined); return undefined; } let cancelled = false; const load = async () => { const fields = await getProfileFields(mx, userId); if (cancelled) return; const bannerMxc = extractBannerUrlFromProfile(fields); if (!bannerMxc) { setBannerBlobUrl(undefined); return; } const blobUrl = await getProfileAssetUrl(mx, bannerMxc, useAuthentication); if (!cancelled) setBannerBlobUrl(blobUrl); }; const unsubscribe = registerProfileCacheListener((changedUserId) => { if (changedUserId === userId) load(); }); load(); return () => { cancelled = true; unsubscribe(); }; }, [mx, useAuthentication, userId]); return bannerBlobUrl; }