From 6d60ff7f80f36fac70ee6d429b58795e1dbe5c2d Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 18 Mar 2026 16:13:22 -0500 Subject: [PATCH] initial big refractor, probably broke stuff and forgot stuff but oh well baby steps --- src/app/components/PaginationPlaceholders.tsx | 78 + src/app/features/room/RoomTimeline.tsx | 2686 ++--------------- .../hooks/timeline/useProcessedTimeline.ts | 143 + src/app/hooks/timeline/useTimelineActions.ts | 241 ++ .../timeline/useTimelineEventRenderer.tsx | 1067 +++++++ src/app/hooks/timeline/useTimelineSync.ts | 603 ++++ 6 files changed, 2452 insertions(+), 2366 deletions(-) create mode 100644 src/app/components/PaginationPlaceholders.tsx create mode 100644 src/app/hooks/timeline/useProcessedTimeline.ts create mode 100644 src/app/hooks/timeline/useTimelineActions.ts create mode 100644 src/app/hooks/timeline/useTimelineEventRenderer.tsx create mode 100644 src/app/hooks/timeline/useTimelineSync.ts diff --git a/src/app/components/PaginationPlaceholders.tsx b/src/app/components/PaginationPlaceholders.tsx new file mode 100644 index 00000000..c8221cfe --- /dev/null +++ b/src/app/components/PaginationPlaceholders.tsx @@ -0,0 +1,78 @@ +import { Box, Chip, Spinner, Text, color, config } from 'folds'; +import { MessageBase, CompactPlaceholder, DefaultPlaceholder } from '$components/message'; + +export type PaginationStatus = 'idle' | 'loading' | 'error'; + +export interface PaginationLoaderProps { + status: PaginationStatus; + direction: 'backward' | 'forward'; + isCompact: boolean; + isEmpty: boolean; + onRetry: () => void; + observerRef?: (node: HTMLElement | null) => void; +} + +export function PaginationLoader({ + status, + direction, + isCompact, + isEmpty, + onRetry, + observerRef, +}: PaginationLoaderProps) { + if (status === 'error') { + return ( + + + {direction === 'backward' ? 'Failed to load history.' : 'Failed to load messages.'} + + + Retry + + + ); + } + + if (isEmpty) { + const count = isCompact ? 5 : 3; + const anchorIndex = direction === 'backward' ? count - 1 : 0; + + return ( + <> + {[...Array(count)].map((_, i) => { + const attachRef = i === anchorIndex ? observerRef : undefined; + return ( + + {isCompact ? : } + + ); + })} + + ); + } + + return ( + +
+ + {status === 'loading' && ( + + + + )} + + ); +} diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 6b691fdb..d33b3d04 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -1,161 +1,74 @@ -/* eslint-disable react/destructuring-assignment */ -import { - Fragment, - Dispatch, - MouseEventHandler, - ReactNode, - RefObject, - SetStateAction, - useCallback, - useEffect, - useLayoutEffect, - useMemo, - useRef, - useState, -} from 'react'; -import { - Direction, - EventTimeline, - EventTimelineSet, - EventTimelineSetHandlerMap, - EventStatus, - IContent, - IRoomTimelineData, - MatrixClient, - MatrixEvent, - PushProcessor, - RelationType, - Room, - RoomEvent, - RoomEventHandlerMap, - ThreadEvent, -} from '$types/matrix-sdk'; -import { HTMLReactParserOptions } from 'html-react-parser'; -import classNames from 'classnames'; -import { ReactEditor } from 'slate-react'; +import { Fragment, RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Editor } from 'slate'; -import { SessionMembershipData } from 'matrix-js-sdk/lib/matrixrtc/CallMembership'; -import to from 'await-to-js'; -import * as Sentry from '@sentry/react'; import { useAtomValue, useSetAtom } from 'jotai'; +import { PushProcessor, Room, Direction } from '$types/matrix-sdk'; +import classNames from 'classnames'; import { as, - Avatar, - Badge, Box, Chip, - color, - config, - ContainerColor, Icon, Icons, Line, Scroll, - Spinner, Text, + Badge, + color, + config, toRem, + ContainerColor, } from 'folds'; -import { isKeyHotkey } from 'is-hotkey'; -import { Opts as LinkifyOpts } from 'linkifyjs'; -import { useTranslation } from 'react-i18next'; -import { getMxIdLocalPart, mxcUrlToHttp, toggleReaction } from '$utils/matrix'; +import { MessageBase } from '$components/message'; +import { RoomIntro } from '$components/room-intro'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { ItemRange, useVirtualPaginator } from '$hooks/useVirtualPaginator'; import { useAlive } from '$hooks/useAlive'; -import { editableActiveElement, scrollToBottom } from '$utils/dom'; +import { useVirtualPaginator } from '$hooks/useVirtualPaginator'; +import { useDocumentFocusChange } from '$hooks/useDocumentFocusChange'; +import { markAsRead } from '$utils/notifications'; import { - CompactPlaceholder, - DefaultPlaceholder, - EventContent, - ImageContent, - MessageBase, - MessageNotDecryptedContent, - MessageUnsupportedContent, - MSticker, - RedactedContent, - Reply, - Time, -} from '$components/message'; -import { - factoryRenderLinkifyWithMention, getReactCustomHtmlParser, LINKIFY_OPTS, makeMentionCustomProps, renderMatrixMention, + factoryRenderLinkifyWithMention, } from '$plugins/react-custom-html-parser'; -import { - canEditEvent, - decryptAllTimelineEvent, - getEditedEvent, - getEventReactions, - getLatestEditableEvt, - getMemberAvatarMxc, - getMemberDisplayName, - isMembershipChanged, - reactionOrEditEvent, -} from '$utils/room'; -import { - getLiveTimeline, - getEventTimeline, - getFirstLinkedTimeline, - getLinkedTimelines, - getTimelinesEventsCount, - getTimelineAndBaseIndex, - getTimelineRelativeIndex, - getTimelineEvent, - getEventIdAbsoluteIndex, - getInitialTimeline, - getEmptyTimeline, - getRoomUnreadInfo, - getThreadReplyCount, - PAGINATION_LIMIT, -} from '$utils/timeline'; -import { useSetting } from '$state/hooks/settings'; -import { MessageLayout, settingsAtom } from '$state/settings'; -import { nicknamesAtom } from '$state/nicknames'; -import { useMatrixEventRenderer } from '$hooks/useMatrixEventRenderer'; +import { today, yesterday, timeDayMonthYear } from '$utils/time'; import { useMemberEventParser } from '$hooks/useMemberEventParser'; -import * as customHtmlCss from '$styles/CustomHtml.css'; -import { RoomIntro } from '$components/room-intro'; -import { - getIntersectionObserverEntry, - useIntersectionObserver, -} from '$hooks/useIntersectionObserver'; -import { markAsRead } from '$utils/notifications'; -import { getResizeObserverEntry, useResizeObserver } from '$hooks/useResizeObserver'; -import { inSameDay, minuteDifference, timeDayMonthYear, today, yesterday } from '$utils/time'; -import { createMentionElement, isEmptyEditor, moveCursor } from '$components/editor'; -import { roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts'; -import { roomIdToOpenThreadAtomFamily } from '$state/room/roomToOpenThread'; import { usePowerLevelsContext } from '$hooks/usePowerLevels'; -import { GetContentCallback, MessageEvent, StateEvent } from '$types/matrix/room'; -import { useKeyDown } from '$hooks/useKeyDown'; -import { useDocumentFocusChange } from '$hooks/useDocumentFocusChange'; -import { RenderMessageContent } from '$components/RenderMessageContent'; -import { Image } from '$components/media'; -import { ImageViewer } from '$components/image-viewer'; -import { roomToParentsAtom } from '$state/room/roomToParents'; -import { useRoomUnread } from '$state/hooks/unread'; -import { roomToUnreadAtom } from '$state/room/roomToUnread'; -import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; -import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; -import { useRoomNavigate } from '$hooks/useRoomNavigate'; -import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; -import { UserAvatar } from '$components/user-avatar'; -import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; -import { useImagePackRooms } from '$hooks/useImagePackRooms'; -import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; -import { useSpaceOptionally } from '$hooks/useSpace'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; +import { useRoomNavigate } from '$hooks/useRoomNavigate'; +import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; +import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler'; +import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; +import { useSpaceOptionally } from '$hooks/useSpace'; +import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; +import { useImagePackRooms } from '$hooks/useImagePackRooms'; +import { settingsAtom, MessageLayout } from '$state/settings'; +import { useSetting } from '$state/hooks/settings'; +import { nicknamesAtom } from '$state/nicknames'; import { profilesCacheAtom } from '$state/userRoomProfile'; -import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; -import { createDebugLogger } from '$utils/debugLogger'; +import { roomToParentsAtom } from '$state/room/roomToParents'; +import { roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts'; +import { roomIdToOpenThreadAtomFamily } from '$state/room/roomToOpenThread'; +import { + getRoomUnreadInfo, + getEventTimeline, + getFirstLinkedTimeline, + getInitialTimeline, + PAGINATION_LIMIT, + getEventIdAbsoluteIndex, +} from '$utils/timeline'; +import { useScrollManager } from '$hooks/useScrollManager'; +import { getResizeObserverEntry, useResizeObserver } from '$hooks/useResizeObserver'; +import { useTimelineSync } from '$hooks/timeline/useTimelineSync'; +import { useTimelineActions } from '$hooks/timeline/useTimelineActions'; +import { useProcessedTimeline } from '$hooks/timeline/useProcessedTimeline'; +import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer'; +import { PaginationLoader } from '$components/PaginationPlaceholders'; import * as css from './RoomTimeline.css'; -import { EncryptedContent, Event, ForwardedMessageProps, Message, Reactions } from './message'; - -const debugLog = createDebugLogger('RoomTimeline'); const TimelineFloat = as<'div', css.TimelineFloatVariants>( ({ position, className, ...props }, ref) => ( @@ -180,430 +93,13 @@ const TimelineDivider = as<'div', { variant?: ContainerColor | 'Inherit' }>( ) ); -const EVENT_TIMELINE_LOAD_TIMEOUT_MS = 12000; - -type PaginationStatus = 'idle' | 'loading' | 'error'; - -type Timeline = { - linkedTimelines: EventTimeline[]; - range: ItemRange; +const getDayDividerText = (ts: number) => { + if (today(ts)) return 'Today'; + if (yesterday(ts)) return 'Yesterday'; + return timeDayMonthYear(ts); }; -const useEventTimelineLoader = ( - mx: MatrixClient, - room: Room, - onLoad: (eventId: string, linkedTimelines: EventTimeline[], evtAbsIndex: number) => void, - onError: (err: Error | null) => void -) => - useCallback( - async (eventId: string) => - Sentry.startSpan({ name: 'timeline.jump_load', op: 'matrix.timeline' }, async () => { - const jumpLoadStart = performance.now(); - const withTimeout = async (promise: Promise, timeoutMs: number): Promise => - new Promise((resolve, reject) => { - const timeoutId = globalThis.setTimeout(() => { - reject(new Error('Timed out loading event timeline')); - }, timeoutMs); - - promise - .then((value) => { - globalThis.clearTimeout(timeoutId); - resolve(value); - }) - .catch((error) => { - globalThis.clearTimeout(timeoutId); - reject(error); - }); - }); - - if (!room.getUnfilteredTimelineSet().getTimelineForEvent(eventId)) { - await withTimeout( - mx.roomInitialSync(room.roomId, PAGINATION_LIMIT), - EVENT_TIMELINE_LOAD_TIMEOUT_MS - ); - await withTimeout( - mx.getLatestTimeline(room.getUnfilteredTimelineSet()), - EVENT_TIMELINE_LOAD_TIMEOUT_MS - ); - } - const [err, replyEvtTimeline] = await to( - withTimeout( - mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId), - EVENT_TIMELINE_LOAD_TIMEOUT_MS - ) - ); - if (!replyEvtTimeline) { - onError(err ?? null); - return; - } - const linkedTimelines = getLinkedTimelines(replyEvtTimeline); - const absIndex = getEventIdAbsoluteIndex(linkedTimelines, replyEvtTimeline, eventId); - - if (absIndex === undefined) { - onError(err ?? null); - return; - } - - Sentry.metrics.distribution( - 'sable.timeline.jump_load_ms', - performance.now() - jumpLoadStart - ); - onLoad(eventId, linkedTimelines, absIndex); - }), // end startSpan - [mx, room, onLoad, onError] - ); - -const useTimelinePagination = ( - mx: MatrixClient, - timeline: Timeline, - setTimeline: Dispatch>, - limit: number -) => { - const timelineRef = useRef(timeline); - timelineRef.current = timeline; - const alive = useAlive(); - const [backwardStatus, setBackwardStatus] = useState('idle'); - const [forwardStatus, setForwardStatus] = useState('idle'); - - // Strict lock so timeline no do shift shift - const fetchingRef = useRef({ backward: false, forward: false }); - - const paginate = useMemo(() => { - const recalibratePagination = ( - linkedTimelines: EventTimeline[], - timelinesEventsCount: number[], - backwards: boolean - ) => { - const topTimeline = linkedTimelines[0]; - const timelineMatch = (mt: EventTimeline) => (t: EventTimeline) => t === mt; - - const newLTimelines = getLinkedTimelines(topTimeline); - const topTmIndex = newLTimelines.findIndex(timelineMatch(topTimeline)); - const topAddedTm = topTmIndex === -1 ? [] : newLTimelines.slice(0, topTmIndex); - - const topTmAddedEvt = - (newLTimelines[topTmIndex]?.getEvents()?.length ?? 0) - timelinesEventsCount[0]; - const offsetRange = getTimelinesEventsCount(topAddedTm) + (backwards ? topTmAddedEvt : 0); - - setTimeline((currentTimeline) => ({ - linkedTimelines: newLTimelines, - range: - offsetRange > 0 - ? { - start: currentTimeline.range.start + offsetRange, - end: currentTimeline.range.end + offsetRange, - } - : { ...currentTimeline.range }, - })); - }; - - return async (backwards: boolean) => { - const directionKey = backwards ? 'backward' : 'forward'; - - // Enforce the lock - if (fetchingRef.current[directionKey]) return; - - const { linkedTimelines: lTimelines } = timelineRef.current; - const timelinesEventsCount = lTimelines.map((t) => t.getEvents()?.length ?? 0); - - const timelineToPaginate = backwards ? lTimelines[0] : lTimelines.at(-1); - if (!timelineToPaginate) return; - - const paginationToken = timelineToPaginate.getPaginationToken( - backwards ? Direction.Backward : Direction.Forward - ); - if ( - !paginationToken && - getTimelinesEventsCount(lTimelines) !== - getTimelinesEventsCount(getLinkedTimelines(timelineToPaginate)) - ) { - recalibratePagination(lTimelines, timelinesEventsCount, backwards); - return; - } - - // Engage the lock - fetchingRef.current[directionKey] = true; - if (alive()) { - (backwards ? setBackwardStatus : setForwardStatus)('loading'); - debugLog.info('timeline', 'Timeline pagination started', { - direction: backwards ? 'backward' : 'forward', - eventsLoaded: getTimelinesEventsCount(lTimelines), - hasToken: !!paginationToken, - }); - } - try { - const paginateStart = performance.now(); - const [err] = await to( - mx.paginateEventTimeline(timelineToPaginate, { - backwards, - limit, - }) - ); - if (err) { - if (alive()) { - (backwards ? setBackwardStatus : setForwardStatus)('error'); - Sentry.metrics.count('sable.pagination.error', 1, { - attributes: { direction: backwards ? 'backward' : 'forward' }, - }); - debugLog.error('timeline', 'Timeline pagination failed', { - direction: backwards ? 'backward' : 'forward', - error: err instanceof Error ? err.message : String(err), - }); - } - return; - } - const fetchedTimeline = - timelineToPaginate.getNeighbouringTimeline( - backwards ? Direction.Backward : Direction.Forward - ) ?? timelineToPaginate; - // Decrypt all event ahead of render cycle - const roomId = fetchedTimeline.getRoomId(); - const room = roomId ? mx.getRoom(roomId) : null; - - if (room?.hasEncryptionStateEvent()) { - await to(decryptAllTimelineEvent(mx, fetchedTimeline)); - } - - if (alive()) { - recalibratePagination(lTimelines, timelinesEventsCount, backwards); - (backwards ? setBackwardStatus : setForwardStatus)('idle'); - Sentry.metrics.distribution( - 'sable.pagination.latency_ms', - performance.now() - paginateStart, - { - attributes: { - direction: backwards ? 'backward' : 'forward', - encrypted: String(!!room?.hasEncryptionStateEvent()), - }, - } - ); - debugLog.info('timeline', 'Timeline pagination completed', { - direction: backwards ? 'backward' : 'forward', - totalEventsNow: getTimelinesEventsCount(lTimelines), - }); - } - } finally { - // Release the lock - fetchingRef.current[directionKey] = false; - } - }; - }, [mx, alive, setTimeline, limit, setBackwardStatus, setForwardStatus]); - - return { paginate, backwardStatus, forwardStatus }; -}; - -const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) => { - const onArriveRef = useRef(onArrive); - onArriveRef.current = onArrive; - - useEffect(() => { - const liveTimeline = getLiveTimeline(room); - const registeredAt = Date.now(); - const handleTimelineEvent: EventTimelineSetHandlerMap[RoomEvent.Timeline] = ( - mEvent: MatrixEvent, - eventRoom: Room | undefined, - toStartOfTimeline: boolean | undefined, - removed: boolean, - data: IRoomTimelineData - ) => { - if (eventRoom?.roomId !== room.roomId) return; - const isLive = - data.liveEvent || - (!toStartOfTimeline && - !removed && - data.timeline === liveTimeline && - mEvent.getTs() >= registeredAt - 60_000); - if (!isLive) return; - onArriveRef.current(mEvent); - }; - const handleRedaction: RoomEventHandlerMap[RoomEvent.Redaction] = ( - mEvent: MatrixEvent, - eventRoom: Room | undefined - ) => { - if (eventRoom?.roomId !== room.roomId) return; - onArriveRef.current(mEvent); - }; - - room.on(RoomEvent.Timeline, handleTimelineEvent); - room.on(RoomEvent.Redaction, handleRedaction); - return () => { - room.removeListener(RoomEvent.Timeline, handleTimelineEvent); - room.removeListener(RoomEvent.Redaction, handleRedaction); - }; - }, [room]); -}; - -const useRelationUpdate = (room: Room, onRelation: () => void) => { - const onRelationRef = useRef(onRelation); - onRelationRef.current = onRelation; - - useEffect(() => { - const handleTimelineEvent: EventTimelineSetHandlerMap[RoomEvent.Timeline] = ( - mEvent: MatrixEvent, - eventRoom: Room | undefined, - _toStartOfTimeline: boolean | undefined, - _removed: boolean, - data: IRoomTimelineData - ) => { - if (eventRoom?.roomId !== room.roomId || data.liveEvent) return; - if (mEvent.getRelation()?.rel_type === RelationType.Replace) { - onRelationRef.current(); - } - }; - room.on(RoomEvent.Timeline, handleTimelineEvent); - return () => { - room.removeListener(RoomEvent.Timeline, handleTimelineEvent); - }; - }, [room]); -}; - -const useLiveTimelineRefresh = (room: Room, onRefresh: () => void) => { - const onRefreshRef = useRef(onRefresh); - onRefreshRef.current = onRefresh; - - useEffect(() => { - const handleTimelineRefresh: RoomEventHandlerMap[RoomEvent.TimelineRefresh] = (r: Room) => { - if (r.roomId !== room.roomId) return; - onRefreshRef.current(); - }; - const handleTimelineReset: EventTimelineSetHandlerMap[RoomEvent.TimelineReset] = () => { - Sentry.metrics.count('sable.timeline.limited_reset', 1); - onRefreshRef.current(); - }; - const unfilteredTimelineSet = room.getUnfilteredTimelineSet(); - - room.on(RoomEvent.TimelineRefresh, handleTimelineRefresh); - unfilteredTimelineSet.on(RoomEvent.TimelineReset, handleTimelineReset); - return () => { - room.removeListener(RoomEvent.TimelineRefresh, handleTimelineRefresh); - unfilteredTimelineSet.removeListener(RoomEvent.TimelineReset, handleTimelineReset); - }; - }, [room]); -}; - -const useThreadUpdate = (room: Room, onUpdate: () => void) => { - const onUpdateRef = useRef(onUpdate); - onUpdateRef.current = onUpdate; - - useEffect(() => { - const handler = () => onUpdateRef.current(); - room.on(ThreadEvent.New, handler); - room.on(ThreadEvent.Update, handler); - room.on(ThreadEvent.NewReply, handler); - return () => { - room.removeListener(ThreadEvent.New, handler); - room.removeListener(ThreadEvent.Update, handler); - room.removeListener(ThreadEvent.NewReply, handler); - }; - }, [room]); -}; - -type ThreadReplyChipProps = { - room: Room; - mEventId: string; - openThreadId: string | undefined; - onToggle: () => void; -}; - -function ThreadReplyChip({ - room, - mEventId, - openThreadId, - onToggle, -}: Readonly) { - const mx = useMatrixClient(); - const useAuthentication = useMediaAuthentication(); - const nicknames = useAtomValue(nicknamesAtom); - - const replyEvents = room - .getUnfilteredTimelineSet() - .getLiveTimeline() - .getEvents() - .filter( - (ev) => ev.threadRootId === mEventId && ev.getId() !== mEventId && !reactionOrEditEvent(ev) - ); - - const replyCount = replyEvents.length; - if (replyCount === 0) return null; - - const uniqueSenders: string[] = []; - const seen = new Set(); - replyEvents.forEach((ev) => { - const s = ev.getSender(); - if (s && !seen.has(s)) { - seen.add(s); - uniqueSenders.push(s); - } - }); - - const latestReply = replyEvents.at(-1); - const latestSenderId = latestReply?.getSender() ?? ''; - const latestSenderName = - getMemberDisplayName(room, latestSenderId, nicknames) ?? - getMxIdLocalPart(latestSenderId) ?? - latestSenderId; - const latestBody = (latestReply?.getContent()?.body as string | undefined) ?? ''; - - const isOpen = openThreadId === mEventId; - - return ( - - {uniqueSenders.slice(0, 3).map((senderId, index) => { - const avatarMxc = getMemberAvatarMxc(room, senderId); - const avatarUrl = avatarMxc - ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 20, 20, 'crop') ?? undefined) - : undefined; - const displayName = - getMemberDisplayName(room, senderId, nicknames) ?? - getMxIdLocalPart(senderId) ?? - senderId; - return ( - 0 ? '-4px' : 0 }}> - ( - - {displayName[0]?.toUpperCase() ?? '?'} - - )} - /> - - ); - })} - - } - onClick={onToggle} - style={{ marginTop: config.space.S200 }} - > - - {replyCount} {replyCount === 1 ? 'reply' : 'replies'} - - {latestBody && ( - -  · {latestSenderName}: {latestBody.slice(0, 60)} - - )} - - ); -} - -type RoomTimelineProps = { +export type RoomTimelineProps = { room: Room; eventId?: string; roomInputRef: RefObject; @@ -619,8 +115,9 @@ export function RoomTimeline({ onEditorReset, }: Readonly) { const mx = useMatrixClient(); - const useAuthentication = useMediaAuthentication(); - const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]); + const alive = useAlive(); + const { navigateRoom } = useRoomNavigate(); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const [messageLayout] = useSetting(settingsAtom, 'messageLayout'); const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing'); @@ -629,109 +126,153 @@ export function RoomTimeline({ const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); const [urlPreview] = useSetting(settingsAtom, 'urlPreview'); const [encUrlPreview] = useSetting(settingsAtom, 'encUrlPreview'); - const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; const [showHiddenEvents] = useSetting(settingsAtom, 'showHiddenEvents'); const [showTombstoneEvents] = useSetting(settingsAtom, 'showTombstoneEvents'); const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools'); const [reducedMotion] = useSetting(settingsAtom, 'reducedMotion'); - const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); - const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); + const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly'); + const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; + + const nicknames = useAtomValue(nicknamesAtom); + const globalProfiles = useAtomValue(profilesCacheAtom); const ignoredUsersList = useIgnoredUsers(); const ignoredUsersSet = useMemo(() => new Set(ignoredUsersList), [ignoredUsersList]); - const nicknames = useAtomValue(nicknamesAtom); - const setReplyDraft = useSetAtom(roomIdToReplyDraftAtomFamily(room.roomId)); - const replyDraft = useAtomValue(roomIdToReplyDraftAtomFamily(room.roomId)); - const activeReplyId = replyDraft?.eventId; - const openThreadId = useAtomValue(roomIdToOpenThreadAtomFamily(room.roomId)); - const setOpenThread = useSetAtom(roomIdToOpenThreadAtomFamily(room.roomId)); const powerLevels = usePowerLevelsContext(); const creators = useRoomCreators(room); - const getMemberPowerTag = useGetMemberPowerTag(room, creators, powerLevels); - const permissions = useRoomPermissions(creators, powerLevels); + const isReadOnly = useMemo(() => { + const myPowerLevel = powerLevels?.users?.[mx.getUserId()!] ?? powerLevels?.users_default ?? 0; + const sendLevel = powerLevels?.events?.['m.room.message'] ?? powerLevels?.events_default ?? 0; + return myPowerLevel < sendLevel; + }, [powerLevels, mx]); - const canRedact = permissions.action('redact', mx.getSafeUserId()); - const canDeleteOwn = permissions.event(MessageEvent.RoomRedaction, mx.getSafeUserId()); - const canSendReaction = permissions.event(MessageEvent.Reaction, mx.getSafeUserId()); - const canPinEvent = permissions.stateEvent(StateEvent.RoomPinnedEvents, mx.getSafeUserId()); const [editId, setEditId] = useState(); - - const globalProfiles = useAtomValue(profilesCacheAtom); - - const roomToParents = useAtomValue(roomToParentsAtom); - const unread = useRoomUnread(room.roomId, roomToUnreadAtom); - const { navigateRoom } = useRoomNavigate(); - const mentionClickHandler = useMentionClickHandler(room.roomId); - const spoilerClickHandler = useSpoilerClickHandler(); - const openUserRoomProfile = useOpenUserRoomProfile(); - const space = useSpaceOptionally(); - - const imagePackRooms: Room[] = useImagePackRooms(room.roomId, roomToParents); - const [unreadInfo, setUnreadInfo] = useState(() => getRoomUnreadInfo(room, true)); const unreadInfoRef = useRef(unreadInfo); unreadInfoRef.current = unreadInfo; - const readUptoEventIdRef = useRef(); - if (unreadInfo) { - readUptoEventIdRef.current = unreadInfo.readUptoEventId; - } + const readUptoEventIdRef = useRef(undefined); + if (unreadInfo) readUptoEventIdRef.current = unreadInfo.readUptoEventId; const hideReadsRef = useRef(hideReads); hideReadsRef.current = hideReads; - const atBottomAnchorRef = useRef(null); - const [atBottom, setAtBottomState] = useState(true); - const atBottomRef = useRef(atBottom); - const atBottomLastChangedRef = useRef(0); - const setAtBottom = useCallback( - (val: boolean) => { - setAtBottomState(val); - const now = Date.now(); - const msSincePrevious = now - atBottomLastChangedRef.current; - atBottomLastChangedRef.current = now; - Sentry.addBreadcrumb({ - category: 'ui.scroll', - message: val ? 'Timeline: scrolled to bottom' : 'Timeline: scrolled away from bottom', - level: 'info', - data: { roomId: room.roomId, msSincePrevious }, - }); - if (!val && msSincePrevious < 200) { - Sentry.captureMessage('Timeline: rapid atBottom flip (possible spurious scroll reset)', { - level: 'warning', - extra: { roomId: room.roomId, msSincePrevious }, - tags: { feature: 'timeline' }, - }); - } - atBottomRef.current = val; - }, - [room.roomId] - ); + const mediaAuthentication = useMediaAuthentication(); + const spoilerClickHandler = useSpoilerClickHandler(); + const mentionClickHandler = useMentionClickHandler(room.roomId); + const openUserRoomProfile = useOpenUserRoomProfile(); + const optionalSpace = useSpaceOptionally(); + const roomParents = useAtomValue(roomToParentsAtom); + const imagePackRooms = useImagePackRooms(room.roomId, roomParents); + const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]); + const parseMemberEvent = useMemberEventParser(); + + const replyDraftAtom = useMemo(() => roomIdToReplyDraftAtomFamily(room.roomId), [room.roomId]); + const activeReplyDraft = useAtomValue(replyDraftAtom); + const setReplyDraft = useSetAtom(replyDraftAtom); + const activeReplyId = activeReplyDraft?.eventId; + + const openThreadAtom = useMemo(() => roomIdToOpenThreadAtomFamily(room.roomId), [room.roomId]); + const openThreadId = useAtomValue(openThreadAtom); + const setOpenThread = useSetAtom(openThreadAtom); - const timelineJustResetRef = useRef(false); const scrollRef = useRef(null); - const scrollToBottomRef = useRef({ - count: 0, - smooth: true, + const { isAtBottom, onScroll, scrollToBottom } = useScrollManager(scrollRef); + + const timelineSync = useTimelineSync({ + room, + mx, + eventId, + isAtBottom, + scrollToBottom, + unreadInfo, + setUnreadInfo, + hideReadsRef, + readUptoEventIdRef, }); - const [focusItem, setFocusItem] = useState< - | { - index: number; - scrollTo: boolean; - highlight: boolean; - } - | undefined - >(); - const alive = useAlive(); + const getScrollElement = useCallback(() => scrollRef.current, []); - const linkifyOpts = useMemo( + const virtualPaginator = useVirtualPaginator({ + count: timelineSync.eventsLength, + limit: PAGINATION_LIMIT, + range: timelineSync.timeline.range, + onRangeChange: useCallback( + (newRange) => { + timelineSync.setTimeline((ct) => { + const deltaStart = Math.abs(ct.range.start - newRange.start); + const deltaEnd = Math.abs(ct.range.end - newRange.end); + if (deltaStart < 3 && deltaEnd < 3) return ct; + return { ...ct, range: newRange }; + }); + }, + [timelineSync] + ), + getScrollElement, + getItemElement: useCallback( + (index: number) => + (scrollRef.current?.querySelector(`[data-message-item="${index}"]`) as HTMLElement) ?? + undefined, + [] + ), + onEnd: timelineSync.handleTimelinePagination, + }); + + const actions = useTimelineActions({ + room, + mx, + editor, + alive, + nicknames, + globalProfiles, + spaceId: optionalSpace?.roomId, + openUserRoomProfile, + activeReplyId, + setReplyDraft, + openThreadId, + setOpenThread, + setEditId, + onEditorReset, + handleOpenEvent: (id) => { + const evtTimeline = getEventTimeline(room, id); + const absoluteIndex = evtTimeline + ? getEventIdAbsoluteIndex(timelineSync.timeline.linkedTimelines, evtTimeline, id) + : undefined; + + if (typeof absoluteIndex === 'number') { + const scrolled = virtualPaginator.scrollToItem(absoluteIndex, { + behavior: reducedMotion ? 'instant' : 'smooth', + align: 'center', + stopInView: true, + }); + timelineSync.setFocusItem({ + index: absoluteIndex, + scrollTo: !scrolled, + highlight: true, + }); + } else { + timelineSync.loadEventTimeline(id); + } + }, + }); + + const processedEvents = useProcessedTimeline({ + items: virtualPaginator.getItems(), + linkedTimelines: timelineSync.timeline.linkedTimelines, + ignoredUsersSet, + showHiddenEvents, + showTombstoneEvents, + mxUserId: mx.getUserId(), + readUptoEventId: readUptoEventIdRef.current, + }); + + const linkifyOpts = useMemo( () => ({ ...LINKIFY_OPTS, render: factoryRenderLinkifyWithMention((href) => @@ -744,13 +285,14 @@ export function RoomTimeline({ ) ), }), - [mx, room, mentionClickHandler, nicknames] + [mx, room.roomId, mentionClickHandler, nicknames] ); - const htmlReactParserOptions = useMemo( + + const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts, - useAuthentication, + useAuthentication: mediaAuthentication, handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, nicknames, @@ -758,1705 +300,117 @@ export function RoomTimeline({ }), [ mx, - room, + room.roomId, linkifyOpts, autoplayEmojis, - spoilerClickHandler, mentionClickHandler, - useAuthentication, nicknames, + mediaAuthentication, + spoilerClickHandler, ] ); - const parseMemberEvent = useMemberEventParser(); - const [timeline, setTimeline] = useState(() => - eventId ? getEmptyTimeline() : getInitialTimeline(room) - ); - const eventsLength = getTimelinesEventsCount(timeline.linkedTimelines); - const liveTimelineLinked = timeline.linkedTimelines.at(-1) === getLiveTimeline(room); - const prevEventsLengthRef = useRef(eventsLength); - - useEffect(() => { - const prev = prevEventsLengthRef.current; - const delta = eventsLength - prev; - prevEventsLengthRef.current = eventsLength; - - if (delta === 0) return; - - const isBatch = delta > 1; - let batchSize: string; - if (delta === 1) batchSize = 'single'; - else if (delta <= 20) batchSize = 'small'; - else if (delta <= 100) batchSize = 'medium'; - else batchSize = 'large'; - - Sentry.addBreadcrumb({ - category: 'timeline.events', - message: `Timeline: ${delta} event${delta === 1 ? '' : 's'} added (${batchSize})`, - level: isBatch ? 'info' : 'debug', - data: { - delta, - batchSize, - eventsLength, - prevEventsLength: prev, - liveTimelineLinked, - rangeEnd: timeline.range.end, - atBottom: atBottomRef.current, - rangeGap: eventsLength - timeline.range.end, - }, - }); - - if (delta > 50 && liveTimelineLinked) { - Sentry.captureMessage('Timeline: large event batch from sliding sync', { - level: 'warning', - extra: { delta, eventsLength, rangeEnd: timeline.range.end, atBottom: atBottomRef.current }, - tags: { feature: 'timeline', batchSize }, - }); - } - }, [eventsLength, liveTimelineLinked]); - - useEffect(() => { - const mode = eventId ? 'jump' : 'live'; - Sentry.metrics.count('sable.timeline.open', 1, { attributes: { mode } }); - const initialWindowSize = timeline.range.end - timeline.range.start; - if (initialWindowSize > 0) { - Sentry.metrics.distribution('sable.timeline.render_window', initialWindowSize, { - attributes: { encrypted: String(room.hasEncryptionStateEvent()), mode }, - }); - } - }, [room.roomId, eventId]); - - useEffect(() => { - debugLog.debug('timeline', 'Live timeline link state changed', { - roomId: room.roomId, - liveTimelineLinked, - eventsLength, - }); - }, [liveTimelineLinked, room.roomId, eventsLength]); - - const canPaginateBack = - typeof timeline.linkedTimelines[0]?.getPaginationToken(Direction.Backward) === 'string'; - const rangeAtStart = timeline.range.start === 0; - const rangeAtEnd = timeline.range.end === eventsLength; - const atLiveEndRef = useRef(liveTimelineLinked && rangeAtEnd); - atLiveEndRef.current = liveTimelineLinked && rangeAtEnd; - - const { - paginate: handleTimelinePagination, - backwardStatus, - forwardStatus, - } = useTimelinePagination(mx, timeline, setTimeline, PAGINATION_LIMIT); - - const getScrollElement = useCallback(() => scrollRef.current, []); - - const { getItems, scrollToItem, scrollToElement, observeBackAnchor, observeFrontAnchor } = - useVirtualPaginator({ - count: eventsLength, - limit: PAGINATION_LIMIT, - range: timeline.range, - onRangeChange: useCallback((newRange) => { - setTimeline((currentTimeline) => { - const deltaStart = Math.abs(currentTimeline.range.start - newRange.start); - const deltaEnd = Math.abs(currentTimeline.range.end - newRange.end); - - if (deltaStart < 3 && deltaEnd < 3) { - return currentTimeline; - } - - const scrollEl = scrollRef.current; - const ds = newRange.start - currentTimeline.range.start; - const de = newRange.end - currentTimeline.range.end; - debugLog.debug('timeline', 'Virtual paginator range changed', { - prevRange: { start: currentTimeline.range.start, end: currentTimeline.range.end }, - newRange, - deltaStart: ds, - deltaEnd: de, - scrollTop: scrollEl?.scrollTop, - scrollHeight: scrollEl?.scrollHeight, - clientHeight: scrollEl?.clientHeight, - }); - - return { ...currentTimeline, range: newRange }; - }); - }, []), - getScrollElement, - getItemElement: useCallback( - (index: number) => - (scrollRef.current?.querySelector(`[data-message-item="${index}"]`) as HTMLElement) ?? - undefined, - [] - ), - onEnd: handleTimelinePagination, - }); - - const loadEventTimeline = useEventTimelineLoader( + const renderMatrixEvent = useTimelineEventRenderer({ + room, mx, - room, - useCallback( - (evtId, lTimelines, evtAbsIndex) => { - if (!alive()) return; - const evLength = getTimelinesEventsCount(lTimelines); - - debugLog.info('timeline', 'Loading event timeline', { - roomId: room.roomId, - eventId: evtId, - totalEvents: evLength, - focusIndex: evtAbsIndex, - }); - - setAtBottom(false); - setFocusItem({ - index: evtAbsIndex, - scrollTo: true, - highlight: evtId !== readUptoEventIdRef.current, - }); - setTimeline({ - linkedTimelines: lTimelines, - range: { - start: Math.max(evtAbsIndex - PAGINATION_LIMIT, 0), - end: Math.min(evtAbsIndex + PAGINATION_LIMIT, evLength), - }, - }); - }, - [alive, setAtBottom, room.roomId] - ), - useCallback(() => { - if (!alive()) return; - debugLog.info('timeline', 'Resetting timeline to initial state', { roomId: room.roomId }); - setTimeline(getInitialTimeline(room)); - scrollToBottomRef.current.count += 1; - scrollToBottomRef.current.smooth = false; - }, [alive, room]) - ); - - useLiveEventArrive( - room, - useCallback( - (mEvt: MatrixEvent) => { - if (mEvt.threadRootId !== undefined) return; - - if (atBottomRef.current && atLiveEndRef.current) { - if ( - document.hasFocus() && - (!unreadInfoRef.current || mEvt.getSender() === mx.getUserId()) - ) { - requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideReadsRef.current)); - } - - if (!document.hasFocus() && !unreadInfoRef.current) { - setUnreadInfo(getRoomUnreadInfo(room)); - } - - scrollToBottomRef.current.count += 1; - scrollToBottomRef.current.smooth = mEvt.getSender() !== mx.getUserId(); - - setTimeline((ct) => ({ - ...ct, - range: { - start: ct.range.start + 1, - end: ct.range.end + 1, - }, - })); - return; - } - setTimeline((ct) => ({ ...ct })); - if (!unreadInfoRef.current) { - setUnreadInfo(getRoomUnreadInfo(room)); - } - }, - [mx, room, setUnreadInfo] - ) - ); - - useEffect(() => { - const handleLocalEchoUpdated: RoomEventHandlerMap[RoomEvent.LocalEchoUpdated] = ( - _mEvent: MatrixEvent, - eventRoom: Room | undefined - ) => { - if (eventRoom?.roomId !== room.roomId) return; - if (_mEvent.getAssociatedStatus() === EventStatus.NOT_SENT) { - Sentry.metrics.count('sable.message.send_failed', 1); - } - setTimeline((ct) => ({ ...ct })); - if (!unreadInfoRef.current) { - setUnreadInfo(getRoomUnreadInfo(room)); - } - }; - - room.on(RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); - return () => { - room.removeListener(RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); - }; - }, [room, setTimeline, setUnreadInfo]); - - const handleOpenEvent = useCallback( - async ( - evtId: string, - highlight = true, - onScroll: ((scrolled: boolean) => void) | undefined = undefined - ) => { - const evtTimeline = getEventTimeline(room, evtId); - const absoluteIndex = - evtTimeline && getEventIdAbsoluteIndex(timeline.linkedTimelines, evtTimeline, evtId); - - if (typeof absoluteIndex === 'number') { - setAtBottom(false); - - const scrolled = scrollToItem(absoluteIndex, { - behavior: reducedMotion ? 'instant' : 'smooth', - align: 'center', - stopInView: true, - }); - if (onScroll) onScroll(scrolled); - setFocusItem({ - index: absoluteIndex, - scrollTo: !scrolled, - highlight, - }); - } else { - loadEventTimeline(evtId); - } + pushProcessor, + nicknames, + imagePackRooms, + settings: { + messageLayout, + messageSpacing, + hideReads, + showDeveloperTools, + hour24Clock, + dateFormatString, + mediaAutoLoad, + showUrlPreview, + autoplayStickers, + hideMemberInReadOnly, + isReadOnly, + hideMembershipEvents, + hideNickAvatarEvents, + showHiddenEvents, }, - [room, timeline, scrollToItem, loadEventTimeline, reducedMotion, setAtBottom] - ); - - useLiveTimelineRefresh( - room, - useCallback(() => { - Sentry.metrics.count('sable.timeline.reinit', 1); - const wasAtBottom = atBottomRef.current; - timelineJustResetRef.current = true; - setTimeline(getInitialTimeline(room)); - if (wasAtBottom) { - setAtBottom(true); - scrollToBottomRef.current.count += 1; - scrollToBottomRef.current.smooth = false; - } - }, [room, setAtBottom]) - ); - - useRelationUpdate( - room, - useCallback(() => { - setTimeline((ct) => ({ ...ct })); - }, []) - ); - - useThreadUpdate( - room, - useCallback(() => { - setTimeline((ct) => ({ ...ct })); - }, []) - ); - - useEffect(() => { - const resetPending = timelineJustResetRef.current; - if ((atBottom || resetPending) && liveTimelineLinked && eventsLength > timeline.range.end) { - if (resetPending) timelineJustResetRef.current = false; - scrollToBottomRef.current.count += 1; - scrollToBottomRef.current.smooth = false; - setTimeline((ct) => ({ - ...ct, - range: { - start: Math.max(eventsLength - PAGINATION_LIMIT, 0), - end: eventsLength, - }, - })); - } - }, [atBottom, liveTimelineLinked, eventsLength, timeline.range.end]); - - useEffect(() => { - if (eventId) return; - if (timeline.linkedTimelines.length > 0) return; - if (getLiveTimeline(room).getEvents().length === 0) return; - setTimeline(getInitialTimeline(room)); - }, [eventId, room, timeline.linkedTimelines.length]); - - useResizeObserver( - useMemo(() => { - let mounted = false; - return (entries) => { - if (!mounted) { - mounted = true; - return; - } - if (!roomInputRef.current) return; - const editorBaseEntry = getResizeObserverEntry(roomInputRef.current, entries); - const scrollElement = getScrollElement(); - if (!editorBaseEntry || !scrollElement) return; - - if (atBottomRef.current) { - scrollToBottom(scrollElement); - } - }; - }, [getScrollElement, roomInputRef]), - useCallback(() => roomInputRef.current, [roomInputRef]) - ); + state: { focusItem: timelineSync.focusItem, editId, activeReplyId, openThreadId }, + permissions: { + canRedact: permissions.action('redact', mx.getSafeUserId()), + canDeleteOwn: permissions.event('m.room.redaction', mx.getSafeUserId()), + canSendReaction: permissions.event('m.reaction', mx.getSafeUserId()), + canPinEvent: permissions.stateEvent('m.room.pinned_events', mx.getSafeUserId()), + }, + callbacks: { + onUserClick: actions.handleUserClick, + onUsernameClick: actions.handleUsernameClick, + onReplyClick: actions.handleReplyClick, + onReactionToggle: actions.handleReactionToggle, + onEditId: actions.handleEdit, + onResend: actions.handleResend, + onDeleteFailedSend: actions.handleDeleteFailedSend, + setOpenThread: actions.setOpenThread, + handleOpenReply: actions.handleOpenReply, + }, + utils: { + htmlReactParserOptions, + linkifyOpts, + getMemberPowerTag, + parseMemberEvent, + }, + }); const tryAutoMarkAsRead = useCallback(() => { - const readUptoEventId = readUptoEventIdRef.current; - if (!readUptoEventId) { + if (!readUptoEventIdRef.current) { requestAnimationFrame(() => markAsRead(mx, room.roomId, hideReads)); return; } - const evtTimeline = getEventTimeline(room, readUptoEventId); + const evtTimeline = getEventTimeline(room, readUptoEventIdRef.current); const latestTimeline = evtTimeline && getFirstLinkedTimeline(evtTimeline, Direction.Forward); if (latestTimeline === room.getLiveTimeline()) { requestAnimationFrame(() => markAsRead(mx, room.roomId, hideReads)); } }, [mx, room, hideReads]); - useIntersectionObserver( - useCallback( - (entries) => { - const target = atBottomAnchorRef.current; - if (!target) return; - const targetEntry = getIntersectionObserverEntry(target, entries); - if (!targetEntry) return; - - if (targetEntry.isIntersecting) { - setAtBottom(true); - if (atLiveEndRef.current && document.hasFocus()) { - tryAutoMarkAsRead(); - } - } else { - setAtBottom(false); - } - }, - [tryAutoMarkAsRead, setAtBottom, room.roomId] - ), - useCallback( - () => ({ - root: getScrollElement(), - rootMargin: '150px 0px 150px 0px', - }), - [getScrollElement] - ), - useCallback(() => atBottomAnchorRef.current, []) - ); - useDocumentFocusChange( useCallback( (inFocus) => { - if (inFocus && atBottomRef.current) { - tryAutoMarkAsRead(); - } + if (inFocus && isAtBottom) tryAutoMarkAsRead(); }, - [tryAutoMarkAsRead] + [tryAutoMarkAsRead, isAtBottom] ) ); - useKeyDown( - window, - useCallback( - (evt) => { - if ( - isKeyHotkey('arrowup', evt) && - editableActiveElement() && - document.activeElement?.getAttribute('data-editable-name') === 'RoomInput' && - isEmptyEditor(editor) - ) { - const editableEvt = getLatestEditableEvt(room.getLiveTimeline(), (mEvt) => - canEditEvent(mx, mEvt) - ); - const editableEvtId = editableEvt?.getId(); - if (!editableEvtId) return; - setEditId(editableEvtId); - evt.preventDefault(); - } - }, - [mx, room, editor] - ) - ); - - const handleOpenEventRef = useRef(handleOpenEvent); - handleOpenEventRef.current = handleOpenEvent; - useEffect(() => { - if (eventId) { - handleOpenEventRef.current(eventId); + if ( + isAtBottom && + document.hasFocus() && + timelineSync.liveTimelineLinked && + timelineSync.rangeAtEnd + ) { + tryAutoMarkAsRead(); } - }, [eventId]); + }, [isAtBottom, timelineSync.liveTimelineLinked, timelineSync.rangeAtEnd, tryAutoMarkAsRead]); - useLayoutEffect(() => { - const scrollEl = scrollRef.current; - if (scrollEl) { - scrollToBottom(scrollEl); - } - }, []); - - useEffect(() => { - const scrollEl = scrollRef.current; - const contentEl = scrollEl?.firstElementChild as HTMLElement; - if (!scrollEl || !contentEl) return () => {}; - - const forceScroll = () => { - const wasAtBottom = atBottomRef.current; - if (!wasAtBottom) return; - scrollToBottom(scrollEl, 'instant'); - }; - - const resizeObserver = new ResizeObserver(() => { - requestAnimationFrame(forceScroll); - }); - - resizeObserver.observe(contentEl); - - return () => { - resizeObserver.disconnect(); - }; - }, [room]); - - useLayoutEffect(() => { - const { readUptoEventId, inLiveTimeline, scrollTo } = unreadInfo ?? {}; - if (readUptoEventId && inLiveTimeline && scrollTo) { - const linkedTimelines = getLinkedTimelines(getLiveTimeline(room)); - const evtTimeline = getEventTimeline(room, readUptoEventId); - const absoluteIndex = - evtTimeline && getEventIdAbsoluteIndex(linkedTimelines, evtTimeline, readUptoEventId); - if (absoluteIndex) { - scrollToItem(absoluteIndex, { - behavior: 'instant', - align: 'start', - stopInView: true, - }); - } - } - }, [room, unreadInfo, scrollToItem]); - - useLayoutEffect(() => { - if (focusItem?.scrollTo) { - scrollToItem(focusItem.index, { - behavior: 'instant', - align: 'center', - stopInView: true, - }); - } - - const timeoutId = setTimeout(() => { - if (!alive()) return; - setFocusItem((currentItem) => { - if (currentItem === focusItem) return undefined; - return currentItem; - }); - }, 2000); - - return () => clearTimeout(timeoutId); - }, [alive, focusItem, scrollToItem]); - - const scrollToBottomCount = scrollToBottomRef.current.count; - useLayoutEffect(() => { - if (scrollToBottomCount > 0) { - const scrollEl = scrollRef.current; - if (scrollEl) { - const behavior = scrollToBottomRef.current.smooth && !reducedMotion ? 'smooth' : 'instant'; - requestAnimationFrame(() => { - scrollToBottom(scrollEl, behavior); - if (behavior === 'instant') { - setTimeout(() => { - scrollToBottom(scrollEl, 'instant'); - }, 80); - } - }); - } - } - }, [scrollToBottomCount, reducedMotion, room.roomId]); - - useEffect(() => { - if (!unread) { - setUnreadInfo(undefined); - } - }, [unread]); - - useEffect(() => { - if (editId) { - const editMsgElement = - (scrollRef.current?.querySelector(`[data-message-id="${editId}"]`) as HTMLElement) ?? - undefined; - if (editMsgElement) { - scrollToElement(editMsgElement, { - align: 'center', - behavior: 'smooth', - stopInView: true, - }); - } - } - }, [scrollToElement, editId]); - - const handleJumpToLatest = () => { - if (eventId) { - navigateRoom(room.roomId, undefined, { replace: true }); - } - setTimeline(getInitialTimeline(room)); - scrollToBottomRef.current.count += 1; - scrollToBottomRef.current.smooth = false; - }; - - const handleJumpToUnread = () => { - if (unreadInfo?.readUptoEventId) { - loadEventTimeline(unreadInfo.readUptoEventId); - } - }; - - const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideReads); - }; - - const handleOpenReply: MouseEventHandler = useCallback( - async (evt) => { - const targetId = evt.currentTarget.getAttribute('data-event-id'); - if (!targetId) return; - handleOpenEvent(targetId); - }, - [handleOpenEvent] - ); - - const handleUserClick: MouseEventHandler = useCallback( - (evt) => { - evt.preventDefault(); - evt.stopPropagation(); - const userId = evt.currentTarget.getAttribute('data-user-id'); - if (!userId) return; - - 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']; - delete cleanExtended['chat.commet.profile_bio']; - delete cleanExtended['chat.commet.profile_status']; - delete cleanExtended['us.cloke.msc4175.tz']; - delete cleanExtended['m.tz']; - delete cleanExtended['chat.commet.profile_banner']; - delete cleanExtended['moe.sable.app.name_color']; - delete cleanExtended.avatar_url; - delete cleanExtended.displayname; - delete cleanExtended['kitty.meow.has_cats']; - delete cleanExtended['kitty.meow.is_cat']; - } - - openUserRoomProfile( - room.roomId, - space?.roomId, - userId, - evt.currentTarget.getBoundingClientRect(), - undefined, - { - pronouns: cachedData?.pronouns, - bio: cachedData?.bio, - timezone: cachedData?.timezone, - extended: cleanExtended, + useResizeObserver( + useMemo(() => { + let mounted = false; + return (entries: ResizeObserverEntry[]) => { + if (!mounted) { + mounted = true; + return; } - ); - }, - [room, space, openUserRoomProfile, globalProfiles] - ); + if (!roomInputRef.current) return; - const handleUsernameClick: MouseEventHandler = useCallback( - (evt) => { - evt.preventDefault(); - const userId = evt.currentTarget.getAttribute('data-user-id'); - if (!userId) { - throw new Error('Button should have "data-user-id" attribute!'); - } - const name = - getMemberDisplayName(room, userId, nicknames) ?? getMxIdLocalPart(userId) ?? userId; - editor.insertNode( - createMentionElement( - userId, - name.startsWith('@') ? name : `@${name}`, - userId === mx.getUserId() - ) - ); - ReactEditor.focus(editor); - moveCursor(editor); - }, - [mx, room, editor, nicknames] - ); + const editorBaseEntry = getResizeObserverEntry(roomInputRef.current, entries); + if (!editorBaseEntry || !scrollRef.current) return; - const triggerReply = useCallback( - (replyId: string, startThread = false) => { - if (activeReplyId === replyId) { - setReplyDraft(undefined); - return; - } - - const replyEvt = room.findEventById(replyId); - if (!replyEvt) return; - const editedReply = getEditedEvent(replyId, replyEvt, room.getUnfilteredTimelineSet()); - const content: IContent = editedReply?.getContent()['m.new_content'] ?? replyEvt.getContent(); - const { body, formatted_body: formattedBody } = content; - const { 'm.relates_to': relation } = startThread - ? { 'm.relates_to': { rel_type: 'm.thread', event_id: replyId } } - : replyEvt.getWireContent(); - const senderId = replyEvt.getSender(); - if (senderId) { - setReplyDraft({ - userId: senderId, - eventId: replyId, - body: typeof body === 'string' ? body : '', - formattedBody: typeof formattedBody === 'string' ? formattedBody : '', - relation, - }); - } - }, - [room, setReplyDraft, activeReplyId] - ); - - const handleReplyClick: MouseEventHandler = useCallback( - (evt, startThread = false) => { - const replyId = evt.currentTarget.getAttribute('data-event-id'); - if (!replyId) { - setReplyDraft(undefined); - return; - } - if (startThread) { - const rootEvent = room.findEventById(replyId); - if (rootEvent && !room.getThread(replyId)) { - room.createThread(replyId, rootEvent, [], false); + if (isAtBottom) { + scrollToBottom('instant'); } - setOpenThread(openThreadId === replyId ? undefined : replyId); - return; - } - triggerReply(replyId, false); - }, - [triggerReply, setReplyDraft, setOpenThread, openThreadId, room] + }; + }, [isAtBottom, scrollToBottom, roomInputRef]), + useCallback(() => roomInputRef.current, [roomInputRef]) ); - const handleReactionToggle = useCallback( - (targetEventId: string, key: string, shortcode?: string) => { - toggleReaction(mx, room, targetEventId, key, shortcode); - }, - [mx, room] - ); - - const handleResend = useCallback( - (mEvent: MatrixEvent) => { - if (mEvent.getAssociatedStatus() !== EventStatus.NOT_SENT) return; - mx.resendEvent(mEvent, room).catch(() => undefined); - }, - [mx, room] - ); - - const handleDeleteFailedSend = useCallback( - (mEvent: MatrixEvent) => { - if (mEvent.getAssociatedStatus() !== EventStatus.NOT_SENT) return; - mx.cancelPendingEvent(mEvent); - }, - [mx] - ); - - const handleEdit = useCallback( - (editEvtId?: string) => { - if (editEvtId) { - setEditId(editEvtId); - return; - } - setEditId(undefined); - onEditorReset?.(); - - requestAnimationFrame(() => { - if (!alive()) return; - ReactEditor.focus(editor); - moveCursor(editor); - }); - }, - [editor, alive, onEditorReset] - ); - const { t } = useTranslation(); - - const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly'); - - const isReadOnly = useMemo(() => { - const myPowerLevel = powerLevels?.users?.[mx.getUserId()!] ?? powerLevels?.users_default ?? 0; - const sendLevel = - powerLevels?.events?.[MessageEvent.RoomMessage] ?? powerLevels?.events_default ?? 0; - return myPowerLevel < sendLevel; - }, [powerLevels, mx]); - - const renderMatrixEvent = useMatrixEventRenderer< - [string, MatrixEvent, number, EventTimelineSet, boolean] - >( - { - [MessageEvent.RoomMessage]: (mEventId, mEvent, item, timelineSet, collapse) => { - const reactionRelations = getEventReactions(timelineSet, mEventId); - const reactions = reactionRelations?.getSortedAnnotationsByKey(); - const hasReactions = reactions && reactions.length > 0; - const { replyEventId, threadRootId } = mEvent; - const highlighted = focusItem?.index === item && focusItem.highlight; - - const pushActions = pushProcessor.actionsForEvent(mEvent); - let notifyHighlight: 'silent' | 'loud' | undefined; - if (pushActions?.notify && pushActions.tweaks?.highlight) { - notifyHighlight = pushActions.tweaks?.sound ? 'loud' : 'silent'; - } - - const editedEvent = getEditedEvent(mEventId, mEvent, timelineSet); - const editedNewContent = editedEvent?.getContent()['m.new_content']; - const baseContent = mEvent.getContent(); - const safeContent = - Object.keys(baseContent).length > 0 ? baseContent : mEvent.getOriginalContent(); - const getContent = (() => editedNewContent ?? safeContent) as GetContentCallback; - - const senderId = mEvent.getSender() ?? ''; - const senderDisplayName = - getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId; - - const forwardContent = safeContent['moe.sable.message.forward'] as - | { - original_timestamp?: unknown; - original_room_id?: string; - original_event_id?: string; - original_event_private?: boolean; - } - | undefined; - - const messageForwardedProps: ForwardedMessageProps | undefined = forwardContent - ? { - isForwarded: true, - originalTimestamp: - typeof forwardContent.original_timestamp === 'number' - ? forwardContent.original_timestamp - : mEvent.getTs(), - originalRoomId: forwardContent.original_room_id ?? room.roomId, - originalEventId: forwardContent.original_event_id ?? '', - originalEventPrivate: forwardContent.original_event_private ?? false, - } - : undefined; - - return ( - - ) - } - reactions={(() => { - const threadReplyCount = getThreadReplyCount(room, mEventId); - const threadChip = - threadReplyCount > 0 ? ( - setOpenThread(openThreadId === mEventId ? undefined : mEventId)} - /> - ) : null; - if (!reactionRelations && !threadChip) return undefined; - return ( - <> - {reactionRelations && ( - - )} - {threadChip} - - ); - })()} - hideReadReceipts={hideReads} - showDeveloperTools={showDeveloperTools} - memberPowerTag={getMemberPowerTag(senderId)} - hour24Clock={hour24Clock} - dateFormatString={dateFormatString} - > - {mEvent.isRedacted() ? ( - - ) : ( - - )} - - ); - }, - [MessageEvent.RoomMessageEncrypted]: (mEventId, mEvent, item, timelineSet, collapse) => { - const reactionRelations = getEventReactions(timelineSet, mEventId); - const reactions = reactionRelations?.getSortedAnnotationsByKey(); - const hasReactions = reactions && reactions.length > 0; - const { replyEventId, threadRootId } = mEvent; - const highlighted = focusItem?.index === item && focusItem.highlight; - const senderId = mEvent.getSender() ?? ''; - const senderDisplayName = - getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId; - - const pushActions = pushProcessor.actionsForEvent(mEvent); - let notifyHighlight: 'silent' | 'loud' | undefined; - if (pushActions?.notify && pushActions.tweaks?.highlight) { - notifyHighlight = pushActions.tweaks?.sound ? 'loud' : 'silent'; - } - - return ( - - ) - } - reactions={(() => { - const threadReplyCount = getThreadReplyCount(room, mEventId); - const threadChip = - threadReplyCount > 0 ? ( - setOpenThread(openThreadId === mEventId ? undefined : mEventId)} - /> - ) : null; - if (!reactionRelations && !threadChip) return undefined; - return ( - <> - {reactionRelations && ( - - )} - {threadChip} - - ); - })()} - hideReadReceipts={hideReads} - showDeveloperTools={showDeveloperTools} - memberPowerTag={getMemberPowerTag(mEvent.getSender() ?? '')} - hour24Clock={hour24Clock} - dateFormatString={dateFormatString} - > - - {() => { - if (mEvent.isRedacted()) return ; - if (mEvent.getType() === MessageEvent.Sticker) - return ( - ( - { - if (!autoplayStickers && p.src) { - return ( - - - - ); - } - return ; - }} - renderViewer={(p) => } - /> - )} - /> - ); - if (mEvent.getType() === MessageEvent.RoomMessage) { - const editedEvent = getEditedEvent(mEventId, mEvent, timelineSet); - const editedNewContent = editedEvent?.getContent()['m.new_content']; - const baseContent = mEvent.getContent(); - const safeContent = - Object.keys(baseContent).length > 0 ? baseContent : mEvent.getOriginalContent(); - const getContent = (() => editedNewContent ?? safeContent) as GetContentCallback; - - return ( - - ); - } - if (mEvent.getType() === MessageEvent.RoomMessageEncrypted) - return ( - - - - ); - return ( - - - - ); - }} - - - ); - }, - [MessageEvent.Sticker]: (mEventId, mEvent, item, timelineSet, collapse) => { - const reactionRelations = getEventReactions(timelineSet, mEventId); - const reactions = reactionRelations?.getSortedAnnotationsByKey(); - const hasReactions = reactions && reactions.length > 0; - const { replyEventId, threadRootId } = mEvent; - const highlighted = focusItem?.index === item && focusItem.highlight; - const senderId = mEvent.getSender() ?? ''; - const senderDisplayName = - getMemberDisplayName(room, senderId, nicknames) ?? getMxIdLocalPart(senderId) ?? senderId; - - return ( - - ) - } - reactions={(() => { - const threadReplyCount = getThreadReplyCount(room, mEventId); - const threadChip = - threadReplyCount > 0 ? ( - setOpenThread(openThreadId === mEventId ? undefined : mEventId)} - /> - ) : null; - if (!reactionRelations && !threadChip) return undefined; - return ( - <> - {reactionRelations && ( - - )} - {threadChip} - - ); - })()} - hideReadReceipts={hideReads} - showDeveloperTools={showDeveloperTools} - memberPowerTag={getMemberPowerTag(mEvent.getSender() ?? '')} - hour24Clock={hour24Clock} - dateFormatString={dateFormatString} - > - {mEvent.isRedacted() ? ( - - ) : ( - ( - { - if (!autoplayStickers && p.src) { - return ( - - - - ); - } - return ; - }} - renderViewer={(p) => } - /> - )} - /> - )} - - ); - }, - [StateEvent.RoomMember]: (mEventId, mEvent, item) => { - const membershipChanged = isMembershipChanged(mEvent); - if (hideMemberInReadOnly && isReadOnly) return null; - if (membershipChanged && hideMembershipEvents) return null; - if (!membershipChanged && hideNickAvatarEvents) return null; - - const highlighted = focusItem?.index === item && focusItem.highlight; - const parsed = parseMemberEvent(mEvent); - - const timeJSX = ( -