From a7595a4f1ed361d8d99b3cdfd698a84a537eb2d0 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 24 Feb 2026 23:21:00 -0600 Subject: [PATCH] lots of fixes and improvements to message and profile caching and general ux --- CHANGELOG.md | 3 + src/app/features/room/RoomTimeline.tsx | 126 +- src/app/features/room/message/Message.tsx | 1081 +++++++++-------- .../room/room-pin-menu/RoomPinMenu.tsx | 4 +- src/app/hooks/useBlobCache.ts | 54 +- src/app/hooks/useSableCosmetics.ts | 11 +- src/app/hooks/useUserProfile.ts | 124 +- 7 files changed, 667 insertions(+), 736 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 341721b8..76d8f0ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 40692cef..8abb94ee 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -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(); - const [profileCache, setProfileCache] = useState>({}); - 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>(new Set()); - - useEffect(() => { - const visibleIndices = getItems(); - const sendersToFetch = new Set(); - - 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 = 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 ( 0; const highlighted = focusItem?.index === item && focusItem.highlight; + const senderId = mEvent.getSender() ?? ''; return ( void; @@ -690,7 +693,7 @@ export type MessageProps = { memberPowerTag?: MemberPowerTag; hour24Clock: boolean; dateFormatString: string; - senderPronouns?: any[]; + senderId: string; }; function useMobileLongPress(callback: (e: React.PointerEvent) => void, delay = 700) { @@ -758,303 +761,324 @@ function PronounTag({ pronouns, tagColor }: { pronouns?: any[]; tagColor: string ); } -export const Message = as<'div', MessageProps>( - ( - { - className, - room, - mEvent, - collapse, - highlight, - edit, - canDelete, - canSendReaction, - canPinEvent, - imagePackRooms, - relations, - messageLayout, - messageSpacing, - onUserClick, - onUsernameClick, - onReplyClick, - onReactionToggle, - onEditId, - reply, - reactions, - hideReadReceipts, - showDeveloperTools, - memberPowerTag, - hour24Clock, - dateFormatString, - children, - senderPronouns, - ...props - }, - ref - ) => { - const mx = useMatrixClient(); - const useAuthentication = useMediaAuthentication(); - const senderId = mEvent.getSender() ?? ''; +function MessageInternal( + { + className, + room, + mEvent, + collapse, + highlight, + edit, + canDelete, + canSendReaction, + canPinEvent, + imagePackRooms, + relations, + messageLayout, + messageSpacing, + onUserClick, + onUsernameClick, + onReplyClick, + onReactionToggle, + onEditId, + reply, + reactions, + hideReadReceipts, + showDeveloperTools, + memberPowerTag, + hour24Clock, + dateFormatString, + children, + senderId, + ...props + }: MessageProps & { className?: string; children?: ReactNode }, + ref: any +) { + const mx = useMatrixClient(); + const useAuthentication = useMediaAuthentication(); - const [isDesktopHover, setIsDesktopHover] = useState(false); - const { hoverProps } = useHover({ - onHoverChange: (h) => { if (!mobileOrTablet()) setIsDesktopHover(h); } - }); - const { focusWithinProps } = useFocusWithin({ - onFocusWithinChange: (f) => { if (!mobileOrTablet()) setIsDesktopHover(f); } - }); + // Profiles and Colors + const profile = useUserProfile(senderId); + const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room); - const [menuAnchor, setMenuAnchor] = useState(); - const [emojiBoardAnchor, setEmojiBoardAnchor] = useState(); - const [nickEditOpen, setNickEditOpen] = useState(false); - const [nickDraft, setNickDraft] = useState(''); - const nicknames = useAtomValue(nicknamesAtom); - const setNickname = useSetAtom(setNicknameAtom); + // Avatars + const avatarUrl = useMemo(() => { + if (collapse) return undefined; + const mxc = profile.avatarUrl || getMemberAvatarMxc(room, senderId); + return mxc ? mxcUrlToHttp(mx, mxc, useAuthentication, 48, 48, 'crop') : undefined; + }, [collapse, profile.avatarUrl, senderId, mx, room, useAuthentication]); - const senderDisplayName = - getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId; - const senderAvatarMxc = getMemberAvatarMxc(room, senderId); + const cachedAvatar = useBlobCache(avatarUrl ?? undefined); - const tagIconSrc = memberPowerTag?.icon - ? getPowerTagIconSrc(mx, useAuthentication, memberPowerTag.icon) - : undefined; + // UI State + const [isDesktopHover, setIsDesktopHover] = useState(false); + const { hoverProps } = useHover({ + onHoverChange: (h) => { if (!mobileOrTablet()) setIsDesktopHover(h); } + }); + const { focusWithinProps } = useFocusWithin({ + onFocusWithinChange: (f) => { if (!mobileOrTablet()) setIsDesktopHover(f); } + }); - const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room); + const [menuAnchor, setMenuAnchor] = useState(); + const [emojiBoardAnchor, setEmojiBoardAnchor] = useState(); + const [nickEditOpen, setNickEditOpen] = useState(false); + const [nickDraft, setNickDraft] = useState(''); + const nicknames = useAtomValue(nicknamesAtom); + const setNickname = useSetAtom(setNicknameAtom); - const [mobileOptionsOpen, setMobileOptionsOpen] = useState(false); - const optionsRef = useRef(null); + const senderDisplayName = + nicknames[senderId] ?? + profile.displayName ?? + getMemberDisplayName(room, senderId) ?? + getMxIdLocalPart(senderId) ?? + senderId; - const [showPronouns] = useSetting(settingsAtom, 'showPronouns'); + const tagIconSrc = memberPowerTag?.icon + ? getPowerTagIconSrc(mx, useAuthentication, memberPowerTag.icon) + : undefined; - useEffect(() => { - if (!mobileOptionsOpen) return undefined; - const handleClickOutside = (e: globalThis.Event) => { - if (optionsRef.current && !optionsRef.current.contains(e.target as Node)) { - setMobileOptionsOpen(false); - } - }; - document.addEventListener('pointerdown', handleClickOutside, { capture: true }); - return () => document.removeEventListener('pointerdown', handleClickOutside, { capture: true }); - }, [mobileOptionsOpen]); + const [mobileOptionsOpen, setMobileOptionsOpen] = useState(false); + const optionsRef = useRef(null); + const [showPronouns] = useSetting(settingsAtom, 'showPronouns'); - const headerJSX = !collapse && ( - - - - - {senderDisplayName} - - - {showPronouns && ( - - )} - {tagIconSrc && } - - - {messageLayout === MessageLayout.Modern && isDesktopHover && ( - <> - - {senderId} - - - | - - - )} - - - ); - - const avatarJSX = !collapse && messageLayout !== MessageLayout.Compact && ( - - - } - /> - - - ); - - const msgContentJSX = ( - - {reply} - {edit && onEditId ? ( - onEditId()} - /> - ) : ( - children - )} - {reactions} - - ); - - const handleContextMenu: MouseEventHandler = (evt) => { - if (mobileOrTablet()) { - evt.preventDefault(); - return; + useEffect(() => { + if (!mobileOptionsOpen) return undefined; + const handleClickOutside = (e: globalThis.Event) => { + if (optionsRef.current && !optionsRef.current.contains(e.target as Node)) { + setMobileOptionsOpen(false); } - - if (evt.altKey || !window.getSelection()?.isCollapsed || edit) return; - const tag = (evt.target as any).tagName; - if (typeof tag === 'string' && tag.toLowerCase() === 'a') return; - evt.preventDefault(); - setMenuAnchor({ - x: evt.clientX, - y: evt.clientY, - width: 0, - height: 0, - }); }; + document.addEventListener('pointerdown', handleClickOutside, { capture: true }); + return () => document.removeEventListener('pointerdown', handleClickOutside, { capture: true }); + }, [mobileOptionsOpen]); - const handleOpenMenu: MouseEventHandler = (evt) => { - const target = evt.currentTarget.parentElement?.parentElement ?? evt.currentTarget; - setMenuAnchor(target.getBoundingClientRect()); - }; + const headerJSX = !collapse && ( + + + + + {senderDisplayName} + + + {showPronouns && ( + + )} + {tagIconSrc && } + + + {messageLayout === MessageLayout.Modern && isDesktopHover && ( + <> + + {senderId} + + + | + + + )} + + + ); - const closeMenu = () => { - setMenuAnchor(undefined); - setNickEditOpen(false); - setMobileOptionsOpen(false); - }; - - const handleOpenEmojiBoard: MouseEventHandler = (evt) => { - const target = evt.currentTarget.parentElement?.parentElement ?? evt.currentTarget; - setEmojiBoardAnchor(target.getBoundingClientRect()); - }; - - const handleAddReactions: MouseEventHandler = () => { - const rect = menuAnchor; - closeMenu(); - setTimeout(() => { - setEmojiBoardAnchor(rect); - }, 100); - }; - - const handleSwipeReply = () => { - const mockEvent = { - currentTarget: { - getAttribute: (attr: string) => (attr === 'data-event-id' ? mEvent.getId() : null), - }, - } as unknown as React.MouseEvent; - - onReplyClick(mockEvent); - }; - - const bindLongPress = useMobileLongPress(() => { - setMobileOptionsOpen(true); - }, 700); - - const isThreadedMessage = mEvent.threadRootId !== undefined; - - return ( - + - {!edit && (isDesktopHover || !!menuAnchor || !!emojiBoardAnchor || mobileOptionsOpen) && ( -
- - - {canSendReaction && ( - { - onReactionToggle(mEvent.getId()!, key); - setEmojiBoardAnchor(undefined); - setMobileOptionsOpen(false); - }} - onCustomEmojiSelect={(mxc, shortcode) => { - onReactionToggle(mEvent.getId()!, mxc, shortcode); - setEmojiBoardAnchor(undefined); - setMobileOptionsOpen(false); - }} - requestClose={() => { - setEmojiBoardAnchor(undefined); - }} - /> - } + } + /> + + + ); + + const msgContentJSX = ( + + {reply} + {edit && onEditId ? ( + onEditId()} + /> + ) : ( + children + )} + {reactions} + + ); + + const handleContextMenu: MouseEventHandler = (evt) => { + if (mobileOrTablet()) { + evt.preventDefault(); + return; + } + + if (evt.altKey || !window.getSelection()?.isCollapsed || edit) return; + const tag = (evt.target as any).tagName; + if (typeof tag === 'string' && tag.toLowerCase() === 'a') return; + evt.preventDefault(); + setMenuAnchor({ + x: evt.clientX, + y: evt.clientY, + width: 0, + height: 0, + }); + }; + + const handleOpenMenu: MouseEventHandler = (evt) => { + const target = evt.currentTarget.parentElement?.parentElement ?? evt.currentTarget; + setMenuAnchor(target.getBoundingClientRect()); + }; + + const closeMenu = () => { + setMenuAnchor(undefined); + setNickEditOpen(false); + setMobileOptionsOpen(false); + }; + + const handleOpenEmojiBoard: MouseEventHandler = (evt) => { + const target = evt.currentTarget.parentElement?.parentElement ?? evt.currentTarget; + setEmojiBoardAnchor(target.getBoundingClientRect()); + }; + + const handleAddReactions: MouseEventHandler = () => { + const rect = menuAnchor; + closeMenu(); + setTimeout(() => { + setEmojiBoardAnchor(rect); + }, 100); + }; + + const handleSwipeReply = () => { + const mockEvent = { + currentTarget: { + getAttribute: (attr: string) => (attr === 'data-event-id' ? mEvent.getId() : null), + }, + } as unknown as React.MouseEvent; + + onReplyClick(mockEvent); + }; + + const bindLongPress = useMobileLongPress(() => { + setMobileOptionsOpen(true); + }, 700); + + const isThreadedMessage = mEvent.threadRootId !== undefined; + + return ( + + {!edit && (isDesktopHover || !!menuAnchor || !!emojiBoardAnchor || mobileOptionsOpen) && ( +
+ + + {canSendReaction && ( + { + onReactionToggle(mEvent.getId()!, key); + setEmojiBoardAnchor(undefined); + setMobileOptionsOpen(false); + }} + onCustomEmojiSelect={(mxc, shortcode) => { + onReactionToggle(mEvent.getId()!, mxc, shortcode); + setEmojiBoardAnchor(undefined); + setMobileOptionsOpen(false); + }} + requestClose={() => { + setEmojiBoardAnchor(undefined); + }} + /> + } + > + - - - - - )} + + + + )} + { + onReplyClick(ev); + setMobileOptionsOpen(false); + }} + data-event-id={mEvent.getId()} + variant="SurfaceVariant" + size="300" + radii="300" + > + + + {!isThreadedMessage && ( { - onReplyClick(ev); + onReplyClick(ev, true); setMobileOptionsOpen(false); }} data-event-id={mEvent.getId()} @@ -1062,92 +1086,99 @@ export const Message = as<'div', MessageProps>( size="300" radii="300" > - + - {!isThreadedMessage && ( - { - onReplyClick(ev, true); - setMobileOptionsOpen(false); + )} + {canEditEvent(mx, mEvent) && onEditId && ( + { + onEditId(mEvent.getId()); + setMobileOptionsOpen(false); + }} + variant="SurfaceVariant" + size="300" + radii="300" + > + + + )} + setMenuAnchor(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', + isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', + escapeDeactivates: stopPropagation, }} - data-event-id={mEvent.getId()} - variant="SurfaceVariant" - size="300" - radii="300" > - - - )} - {canEditEvent(mx, mEvent) && onEditId && ( - { - onEditId(mEvent.getId()); - setMobileOptionsOpen(false); - }} - variant="SurfaceVariant" - size="300" - radii="300" - > - - - )} - setMenuAnchor(undefined), - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', - isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', - escapeDeactivates: stopPropagation, - }} - > - + + {canSendReaction && ( + { + onReactionToggle(mEvent.getId()!, key, shortcode); + closeMenu(); + }} + /> + )} + {canSendReaction && ( - { - onReactionToggle(mEvent.getId()!, key, shortcode); - closeMenu(); - }} - /> - )} - - {canSendReaction && ( - } - radii="300" - onClick={handleAddReactions} - > - - Add Reaction - - - )} - {relations && ( - - )} } + after={} + radii="300" + onClick={handleAddReactions} + > + + Add Reaction + + + )} + {relations && ( + + )} + } + radii="300" + data-event-id={mEvent.getId()} + onClick={(evt: any) => { + onReplyClick(evt); + closeMenu(); + }} + > + + Reply + + + {!isThreadedMessage && ( + } radii="300" data-event-id={mEvent.getId()} onClick={(evt: any) => { - onReplyClick(evt); + onReplyClick(evt, true); closeMenu(); }} > @@ -1157,202 +1188,184 @@ export const Message = as<'div', MessageProps>( size="T300" truncate > - Reply + Reply in Thread - {!isThreadedMessage && ( - } - radii="300" - data-event-id={mEvent.getId()} - onClick={(evt: any) => { - onReplyClick(evt, true); - closeMenu(); - }} + )} + {canEditEvent(mx, mEvent) && onEditId && ( + } + radii="300" + data-event-id={mEvent.getId()} + onClick={() => { + onEditId(mEvent.getId()); + closeMenu(); + }} + > + - - Reply in Thread - - - )} - {canEditEvent(mx, mEvent) && onEditId && ( + Edit Message + + + )} + {!hideReadReceipts && ( + + )} + {showDeveloperTools && ( + + )} + + {canPinEvent && ( + + )} + {senderId !== mx.getUserId() && ( + nickEditOpen ? ( + + Nickname + setNickDraft(e.target.value)} + placeholder={senderDisplayName} + onKeyDown={(e) => { + if (e.key === 'Enter') { + setNickname(senderId, nickDraft || undefined, mx); + closeMenu(); + } + if (e.key === 'Escape') closeMenu(); + }} + style={{ + background: 'var(--mx-c-surface)', + color: 'var(--mx-c-on-surface)', + border: '1px solid var(--mx-c-outline)', + borderRadius: '6px', + padding: '4px 8px', + fontSize: '14px', + width: '100%', + outline: 'none', + }} + /> + + { setNickname(senderId, nickDraft || undefined, mx); closeMenu(); }}> + Save + + {nicknames[senderId] && ( + { setNickname(senderId, undefined, mx); closeMenu(); }}> + Clear + + )} + + + ) : ( } radii="300" - data-event-id={mEvent.getId()} onClick={() => { - onEditId(mEvent.getId()); - closeMenu(); + setNickDraft(nicknames[senderId] ?? ''); + setNickEditOpen(true); }} > - - Edit Message + + {nicknames[senderId] ? 'Edit Nickname' : 'Set Nickname'} - )} - {!hideReadReceipts && ( - - )} - {showDeveloperTools && ( - - )} - - {canPinEvent && ( - - )} - {senderId !== mx.getUserId() && ( - nickEditOpen ? ( - - Nickname - setNickDraft(e.target.value)} - placeholder={senderDisplayName} - onKeyDown={(e) => { - if (e.key === 'Enter') { - setNickname(senderId, nickDraft || undefined, mx); - closeMenu(); - } - if (e.key === 'Escape') closeMenu(); - }} - style={{ - background: 'var(--mx-c-surface)', - color: 'var(--mx-c-on-surface)', - border: '1px solid var(--mx-c-outline)', - borderRadius: '6px', - padding: '4px 8px', - fontSize: '14px', - width: '100%', - outline: 'none', - }} + ) + )} + + {((!mEvent.isRedacted() && canDelete) || + mEvent.getSender() !== mx.getUserId()) && ( + <> + + + {!mEvent.isRedacted() && canDelete && ( + - - { setNickname(senderId, nickDraft || undefined, mx); closeMenu(); }}> - Save - - {nicknames[senderId] && ( - { setNickname(senderId, undefined, mx); closeMenu(); }}> - Clear - - )} - - - ) : ( - } - radii="300" - onClick={() => { - setNickDraft(nicknames[senderId] ?? ''); - setNickEditOpen(true); - }} - > - - {nicknames[senderId] ? 'Edit Nickname' : 'Set Nickname'} - - - ) - )} - - {((!mEvent.isRedacted() && canDelete) || - mEvent.getSender() !== mx.getUserId()) && ( - <> - - - {!mEvent.isRedacted() && canDelete && ( - - )} - {mEvent.getSender() !== mx.getUserId() && ( - - )} - - - )} - - - } + )} + {mEvent.getSender() !== mx.getUserId() && ( + + )} + + + )} + + + } + > + - - - - - - -
- )} - {messageLayout === MessageLayout.Compact && ( + + +
+
+
+
+ )} + {messageLayout === MessageLayout.Compact && ( + + +
+ {msgContentJSX} +
+
+
+ ) + } + {messageLayout === MessageLayout.Bubble && ( + + +
+ {msgContentJSX} +
+
+
+ )} + { + messageLayout !== MessageLayout.Compact && messageLayout !== MessageLayout.Bubble && ( - +
+ {headerJSX} {msgContentJSX}
-
+
) - } - {messageLayout === MessageLayout.Bubble && ( - - -
- {msgContentJSX} -
-
-
- )} - { - messageLayout !== MessageLayout.Compact && messageLayout !== MessageLayout.Bubble && ( - - -
- {headerJSX} - {msgContentJSX} -
-
-
- ) - } -
- ); - } -); + } + + ); +}; + +const MessageAs = as<'div', MessageProps>(MessageInternal); +export const Message = React.memo(MessageAs); export type EventProps = { room: Room; diff --git a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx index ebf84c1c..4f2ddad6 100644 --- a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx +++ b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx @@ -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 = () => ( - Open + Jump {canPinEvent && ( (); +const inflightRequests = new Map>(); 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; diff --git a/src/app/hooks/useSableCosmetics.ts b/src/app/hooks/useSableCosmetics.ts index 3878a814..2d132c8d 100644 --- a/src/app/hooks/useSableCosmetics.ts +++ b/src/app/hooks/useSableCosmetics.ts @@ -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]); } \ No newline at end of file diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts index b95ef440..9e61239a 100644 --- a/src/app/hooks/useUserProfile.ts +++ b/src/app/hooks/useUserProfile.ts @@ -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; + _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 => { const mx = useMatrixClient(); - const [globalProfiles, setGlobalProfiles] = useAtom(profilesCacheAtom); - const [profile, setProfile] = useState(() => { - 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]); }; \ No newline at end of file