lots of fixes and improvements to message and profile caching and general ux

This commit is contained in:
7w1 committed 2026-02-24 23:21:00 -06:00
1 parent b92ed1232b
commit a7595a4f1e
7 files changed
+667 -736

No files matched your search

+3
View File
@@ -4,6 +4,9 @@
- Profile banners. Support's Commet's format.
- Global name colors. Can be disabled in settings.
- Even more refractoring to improve timeline & user profile speeds and caches and fix that stupid bug.
- probably introduced more bugs tbh, but things should be faster and less intense on resources?
- Pinned messages actually jump to the damn pins instead of somewhere vaguely nearby half the time.
## Version 1.1.1
+10 -116
View File
@@ -23,7 +23,6 @@ import {
Room,
RoomEvent,
RoomEventHandlerMap,
RoomStateEvent,
} from 'matrix-js-sdk';
import { HTMLReactParserOptions } from 'html-react-parser';
import classNames from 'classnames';
@@ -109,7 +108,6 @@ import { useRoomCreators } from '../../hooks/useRoomCreators';
import { useRoomPermissions } from '../../hooks/useRoomPermissions';
import { useGetMemberPowerTag } from '../../hooks/useMemberPowerTag';
import { profilesCacheAtom } from '../../state/userRoomProfile';
import { UserProfile } from '../../hooks/useUserProfile';
const TimelineFloat = as<'div', css.TimelineFloatVariants>(
({ position, className, ...props }, ref) => (
@@ -240,7 +238,7 @@ type RoomTimelineProps = {
editor: Editor;
};
const PAGINATION_LIMIT = 80;
const PAGINATION_LIMIT = 40;
type Timeline = {
linkedTimelines: EventTimeline[];
@@ -473,8 +471,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const canPinEvent = permissions.stateEvent(StateEvent.RoomPinnedEvents, mx.getSafeUserId());
const [editId, setEditId] = useState<string>();
const [profileCache, setProfileCache] = useState<Record<string, any>>({});
const [globalProfiles, setGlobalProfiles] = useAtom(profilesCacheAtom);
const [globalProfiles] = useAtom(profilesCacheAtom);
const roomToParents = useAtomValue(roomToParentsAtom);
const unread = useRoomUnread(room.roomId, roomToUnreadAtom);
@@ -933,113 +930,6 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
}
}, [scrollToElement, editId]);
const fetchingProfilesRef = useRef<Set<string>>(new Set());
useEffect(() => {
const visibleIndices = getItems();
const sendersToFetch = new Set<string>();
const now = Date.now();
const PROFILE_TTL = 10 * 60 * 1000;
visibleIndices.forEach((index) => {
const [eventTimeline, baseIndex] = getTimelineAndBaseIndex(timeline.linkedTimelines, index);
if (!eventTimeline) return;
const mEvent = getTimelineEvent(eventTimeline, getTimelineRelativeIndex(index, baseIndex));
const senderId = mEvent?.getSender();
if (!senderId) return;
const cached = profileCache[senderId] || globalProfiles[senderId];
const isStale = !cached || (now - (cached._updatedAt || 0) > PROFILE_TTL);
if (!isStale) return;
if (!fetchingProfilesRef.current.has(senderId)) {
sendersToFetch.add(senderId);
}
});
if (sendersToFetch.size === 0) return;
sendersToFetch.forEach(async (userId) => {
fetchingProfilesRef.current.add(userId);
const [err, info] = await to(mx.getProfileInfo(userId));
if (err || !info) {
fetchingProfilesRef.current.delete(userId);
if ((err as any)?.errcode === 'M_NOT_FOUND') {
const nullProfile: any = { _notFound: true, _updatedAt: now };
setProfileCache((prev) => ({ ...prev, [userId]: nullProfile }));
setGlobalProfiles((prev) => ({ ...prev, [userId]: nullProfile }));
}
return;
}
const rawBanner = (info as any)['chat.commet.profile_banner'];
const parsedBanner = typeof rawBanner === 'string' ? rawBanner.replace(/^"|"$/g, '') : undefined;
const normalized: any = {
avatarUrl: info.avatar_url,
displayName: info.displayname,
pronouns: (info as any)['io.fsky.nyx.pronouns'],
timezone: (info as any)['us.cloke.msc4175.tz'] || (info as any)['m.tz'],
bio: (info as any)['moe.sable.app.bio'] || (info as any)['chat.commet.profile_bio'],
bannerUrl: parsedBanner,
extended: info,
_updatedAt: now,
};
setProfileCache((prev) => ({ ...prev, [userId]: normalized }));
setGlobalProfiles((prev) => ({ ...prev, [userId]: normalized }));
});
}, [timeline.range, timeline.linkedTimelines, mx, getItems, setGlobalProfiles, globalProfiles, profileCache]);
useEffect(() => {
const onMemberEvent = (event: MatrixEvent) => {
if (event.getType() !== StateEvent.RoomMember) return;
if (event.getRoomId() !== room.roomId) return;
const userId = event.getStateKey();
if (!userId) return;
const content = event.getContent();
setGlobalProfiles((prev) => {
const existing = prev[userId];
const newAvatar = content.avatar_url;
const newName = content.displayname;
if (
existing &&
existing.avatarUrl === newAvatar &&
existing.displayName === newName
) {
return prev;
}
const updatedProfile: any = {
...(existing || {}),
avatarUrl: newAvatar,
displayName: newName,
};
return {
...prev,
[userId]: updatedProfile,
};
});
};
mx.on(RoomStateEvent.Members, onMemberEvent);
return () => {
mx.removeListener(RoomStateEvent.Members, onMemberEvent);
};
}, [mx, room.roomId, setGlobalProfiles]);
const handleJumpToLatest = () => {
if (eventId) {
navigateRoom(room.roomId, undefined, { replace: true });
@@ -1076,9 +966,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const userId = evt.currentTarget.getAttribute('data-user-id');
if (!userId) return;
const cachedData = profileCache[userId] || globalProfiles[userId];
const cachedData = globalProfiles[userId];
const cleanExtended = cachedData?.extended ? { ...cachedData.extended } : undefined;
if (cleanExtended) {
delete cleanExtended['io.fsky.nyx.pronouns'];
delete cleanExtended['moe.sable.app.bio'];
@@ -1105,7 +996,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
}
);
},
[room, space, openUserRoomProfile, profileCache, globalProfiles]
[room, space, openUserRoomProfile, globalProfiles]
);
const handleUsernameClick: MouseEventHandler<HTMLButtonElement> = useCallback(
@@ -1238,7 +1129,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
onUsernameClick={handleUsernameClick}
onReplyClick={handleReplyClick}
onReactionToggle={handleReactionToggle}
senderPronouns={profileCache[senderId]?.pronouns || globalProfiles[senderId]?.pronouns}
senderId={senderId}
onEditId={handleEdit}
reply={
replyEventId && (
@@ -1294,6 +1185,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const hasReactions = reactions && reactions.length > 0;
const { replyEventId, threadRootId } = mEvent;
const highlighted = focusItem?.index === item && focusItem.highlight;
const senderId = mEvent.getSender() ?? '';
return (
<Message
@@ -1317,6 +1209,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
onReplyClick={handleReplyClick}
onReactionToggle={handleReactionToggle}
onEditId={handleEdit}
senderId={senderId}
reply={
replyEventId && (
<Reply
@@ -1369,7 +1262,6 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
editedEvent?.getContent()['m.new_content'] ??
mEvent.getContent()) as GetContentCallback;
const senderId = mEvent.getSender() ?? '';
const senderDisplayName =
getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId;
return (
@@ -1408,6 +1300,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const reactions = reactionRelations && reactionRelations.getSortedAnnotationsByKey();
const hasReactions = reactions && reactions.length > 0;
const highlighted = focusItem?.index === item && focusItem.highlight;
const senderId = mEvent.getSender() ?? '';
return (
<Message
@@ -1429,6 +1322,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
onUsernameClick={handleUsernameClick}
onReplyClick={handleReplyClick}
onReactionToggle={handleReactionToggle}
senderId={senderId}
reactions={
reactionRelations && (
<Reactions
File diff suppressed because it is too large. Load diff
@@ -20,6 +20,7 @@ import {
} from 'folds';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { HTMLReactParserOptions } from 'html-react-parser';
import { useAtomValue } from 'jotai';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useRoomPinnedEvents } from '../../../hooks/useRoomPinnedEvents';
import * as css from './RoomPinMenu.css';
@@ -86,7 +87,6 @@ import {
useGetMemberPowerTag,
} from '../../../hooks/useMemberPowerTag';
import { useRoomCreatorsTag } from '../../../hooks/useRoomCreatorsTag';
import { useAtomValue } from 'jotai';
import { nicknamesAtom } from '../../../state/nicknames';
type PinnedMessageProps = {
@@ -145,7 +145,7 @@ function PinnedMessage({
const renderOptions = () => (
<Box shrink="No" gap="200" alignItems="Center">
<Chip data-event-id={eventId} onClick={handleOpenClick} variant="Secondary" radii="Pill">
<Text size="T200">Open</Text>
<Text size="T200">Jump</Text>
</Chip>
{canPinEvent && (
<IconButton
+40 -14
View File
@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react';
const imageBlobCache = new Map<string, string>();
const inflightRequests = new Map<string, Promise<string>>();
export function useBlobCache(url?: string): string | undefined {
const [cacheState, setCacheState] = useState<{ sourceUrl?: string; blobUrl?: string }>({
@@ -16,22 +17,47 @@ export function useBlobCache(url?: string): string | undefined {
}
useEffect(() => {
if (!url || imageBlobCache.has(url)) return;
let isMounted = true;
if (url && !imageBlobCache.has(url)) {
fetch(url, { mode: 'cors' })
.then((res) => (res.ok ? res.blob() : Promise.reject()))
.then((blob) => {
if (isMounted) {
const objectUrl = URL.createObjectURL(blob);
imageBlobCache.set(url, objectUrl);
setCacheState({ sourceUrl: url, blobUrl: objectUrl });
}
})
.catch(() => {
// silently fail... mrow
});
}
const fetchBlob = async () => {
if (inflightRequests.has(url)) {
const existingBlobUrl = await inflightRequests.get(url);
if (isMounted) setCacheState({ sourceUrl: url, blobUrl: existingBlobUrl });
return;
}
const requestPromise = (async () => {
try {
const res = await fetch(url, { mode: 'cors' });
if (!res.ok) throw new Error();
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
imageBlobCache.set(url, objectUrl);
return objectUrl;
} catch (e) {
inflightRequests.delete(url);
throw e;
}
})();
inflightRequests.set(url, requestPromise);
try {
const finalBlobUrl = await requestPromise;
if (isMounted) {
setCacheState({ sourceUrl: url, blobUrl: finalBlobUrl });
}
} catch (err) {
// silency fail... mrow
} finally {
inflightRequests.delete(url);
}
};
fetchBlob();
return () => {
isMounted = false;
+5 -6
View File
@@ -12,7 +12,7 @@ import colorMXID from '../../util/colorMXID';
import { useRoomCreatorsTag } from './useRoomCreatorsTag';
import { usePowerLevelTags } from './usePowerLevelTags';
import { useTheme } from './useTheme';
import { profilesCacheAtom } from '../state/userRoomProfile';
import { useUserProfile } from './useUserProfile';
const isValidHex = (c: string) => /^#[0-9A-F]{6}$/i.test(c);
const sanitizeFont = (f: string) => f.replace(/[;{}<>]/g, '').slice(0, 32);
@@ -21,7 +21,7 @@ export function useSableCosmetics(userId: string, room: Room) {
const mx = useMatrixClient();
const theme = useTheme();
const globalProfiles = useAtomValue(profilesCacheAtom);
const profile = useUserProfile(userId);
const [legacyUsernameColor] = useSetting(settingsAtom, 'legacyUsernameColor');
const [renderGlobalColors] = useSetting(settingsAtom, 'renderGlobalNameColors');
@@ -79,12 +79,11 @@ export function useSableCosmetics(userId: string, room: Room) {
}
// global name color
const cachedProfile = globalProfiles[userId];
const hasGlobalColor = cachedProfile?.nameColor && isValidHex(cachedProfile.nameColor);
// show if its on, or the user is you
const hasGlobalColor = profile?.nameColor && isValidHex(profile.nameColor);
const isMe = userId === mx.getUserId();
const validGlobal = (renderGlobalColors || isMe) && hasGlobalColor
? cachedProfile.nameColor
? profile.nameColor
: undefined;
// resolve traditional fallbacks
@@ -108,5 +107,5 @@ export function useSableCosmetics(userId: string, room: Room) {
}
return { color: resolvedColor, font: resolvedFont };
}, [room, userId, mx, getPowerTag, accessibleTagColors, legacyUsernameColor, renderGlobalColors, globalProfiles]);
}, [room, userId, mx, getPowerTag, accessibleTagColors, legacyUsernameColor, renderGlobalColors, profile.nameColor]);
}
+60 -64
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { UserEvent, UserEventHandlerMap } from 'matrix-js-sdk';
import { useAtom } from 'jotai';
import { useEffect, useMemo } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { selectAtom } from 'jotai/utils';
import { useMatrixClient } from './useMatrixClient';
import { profilesCacheAtom } from '../state/userRoomProfile';
@@ -13,82 +13,78 @@ export type UserProfile = {
bannerUrl?: string;
nameColor?: string;
extended?: Record<string, any>;
_fetched?: boolean;
};
const normalizeInfo = (info: any): UserProfile => ({
avatarUrl: info.avatar_url,
displayName: info.displayname,
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
bio: info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
extended: {},
_fetched: true,
});
export const useUserProfile = (userId: string, initialProfile?: Partial<UserProfile>): UserProfile => {
const mx = useMatrixClient();
const [globalProfiles, setGlobalProfiles] = useAtom(profilesCacheAtom);
const [profile, setProfile] = useState<UserProfile>(() => {
const user = mx.getUser(userId);
const cached = globalProfiles[userId];
return {
avatarUrl: cached?.avatarUrl ?? initialProfile?.avatarUrl ?? user?.avatarUrl,
displayName: cached?.displayName ?? initialProfile?.displayName ?? user?.displayName,
pronouns: cached?.pronouns ?? initialProfile?.pronouns,
timezone: cached?.timezone ?? initialProfile?.timezone,
bio: cached?.bio ?? initialProfile?.bio,
bannerUrl: cached?.bannerUrl ?? initialProfile?.bannerUrl,
nameColor: cached?.nameColor ?? initialProfile?.nameColor,
extended: cached?.extended ?? initialProfile?.extended,
};
});
const userSelector = useMemo(
() => selectAtom(profilesCacheAtom, (db) => db[userId]),
[userId]
);
const normalizeInfo = useCallback((info: any): UserProfile => {
const normalized: UserProfile = {
avatarUrl: info.avatar_url,
displayName: info.displayname,
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
bio: info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
extended: { ...(profile?.extended || {}) },
};
const cached = useAtomValue(userSelector);
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
const knownKeys = [
'avatar_url',
'displayname',
'io.fsky.nyx.pronouns',
'us.cloke.msc4175.tz', 'm.tz',
'moe.sable.app.bio', 'chat.commet.profile_bio',
'moe.sable.app.name_color',
'chat.commet.profile_banner'
];
Object.keys(info).forEach((key) => {
if (!knownKeys.includes(key)) {
normalized.extended![key] = info[key];
}
});
return normalized;
}, [profile?.extended]);
const needsFetch = !!userId && userId !== 'undefined' && !cached?._fetched;
useEffect(() => {
const user = mx.getUser(userId);
if (!needsFetch) return;
let isMounted = true;
mx.getProfileInfo(userId).then((info: any) => {
if (!isMounted) return;
const normalized = normalizeInfo(info);
setProfile(normalized);
setGlobalProfiles((prev) => ({ ...prev, [userId]: normalized }));
setGlobalProfiles((prev) => {
const existing = prev[userId];
if (
existing?.nameColor === normalized.nameColor &&
existing?.displayName === normalized.displayName &&
existing?._fetched === true
) {
return prev;
}
return {
...prev,
[userId]: { ...existing, ...normalized }
};
});
}).catch(() => {
setGlobalProfiles((prev) => ({
...prev,
[userId]: { ...prev[userId], _fetched: true }
}));
});
const onAvatarChange: UserEventHandlerMap[UserEvent.AvatarUrl] = (event, myUser) => {
setProfile((cp) => ({ ...cp, avatarUrl: myUser.avatarUrl }));
};
const onDisplayNameChange: UserEventHandlerMap[UserEvent.DisplayName] = (event, myUser) => {
setProfile((cp) => ({ ...cp, displayName: myUser.displayName }));
};
return () => { isMounted = false; };
}, [userId, needsFetch, mx, setGlobalProfiles]);
user?.on(UserEvent.AvatarUrl, onAvatarChange);
user?.on(UserEvent.DisplayName, onDisplayNameChange);
return useMemo(() => {
if (cached) return cached;
return () => {
user?.removeListener(UserEvent.AvatarUrl, onAvatarChange);
user?.removeListener(UserEvent.DisplayName, onDisplayNameChange);
const user = mx.getUser(userId);
return {
displayName: initialProfile?.displayName ?? user?.displayName,
avatarUrl: initialProfile?.avatarUrl ?? user?.avatarUrl,
...initialProfile,
};
}, [mx, userId, normalizeInfo, setGlobalProfiles]);
return profile;
}, [cached, userId, initialProfile, mx]);
};