(
);
const replyEvent = replyDraft ? room.findEventById(replyDraft.eventId) : undefined;
- const {
- body: replyBody,
- formatted_body: replyFormattedBody,
- format: replyFormat,
- } = replyEvent?.getContent() ?? {};
-
- // Prefer the live event content; fall back to what was snapshotted in the
- // draft when the user hit Reply (the event may not be in SDK state if it
- // was redacted or evicted, but the draft always carries the original body).
- const htmlBody =
- replyFormat === 'org.matrix.custom.html' ? replyFormattedBody : replyDraft?.formattedBody;
- const plainBody = replyBody ?? replyDraft?.body;
-
- let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null;
-
- if (htmlBody) {
- /**
- * message with linebreaks, etc stripped
- */
- const strippedHtml = trimReplyFromFormattedBody(htmlBody)
- .replaceAll(/
/gi, ' ')
- .replaceAll(/<\/p>\s*]*>/gi, ' ')
- .replaceAll(/<\/?p[^>]*>/gi, '')
- .replaceAll(/(?:\r\n|\r|\n)/g, ' ')
- .trim();
- const parserOpts = getReactCustomHtmlParser(mx, roomId, {
- linkifyOpts: LINKIFY_OPTS,
- useAuthentication,
- nicknames,
- });
- replyBodyJSX = parse(strippedHtml, parserOpts);
- } else if (plainBody) {
- const strippedBody = trimReplyFromBody(plainBody).replaceAll(/(?:\r\n|\r|\n)/g, ' ');
- replyBodyJSX = scaleSystemEmoji(strippedBody);
- }
// Seed the reply draft with the thread relation whenever we're in thread
// mode (e.g. on first render or when the thread root changes). We use the
@@ -449,9 +398,9 @@ export const RoomInput = forwardRef(
useEffect(() => {
if (replyDraft !== undefined) {
- setSilentReply(replyDraft.userId === mx.getUserId());
+ setSilentReply(replyDraft.userId === mx.getUserId() || !mentionInReplies);
}
- }, [mx, replyDraft]);
+ }, [mentionInReplies, mx, replyDraft]);
const handleFileMetadata = useCallback(
(fileItem: TUploadItem, metadata: TUploadMetadata) => {
@@ -485,6 +434,35 @@ export const RoomInput = forwardRef(
[setSelectedFiles, selectedFiles]
);
+ const handleAudioRecordingComplete = useCallback(
+ (payload: AudioRecordingCompletePayload) => {
+ const extension = getSupportedAudioExtension(payload.audioCodec);
+ const file = new File(
+ [payload.audioBlob],
+ `sable-audio-message-${Date.now()}.${extension}`,
+ {
+ type: payload.audioCodec,
+ }
+ );
+ handleFiles([file], {
+ waveform: payload.waveform,
+ audioDuration: payload.audioLength,
+ });
+ setShowAudioRecorder(false);
+ },
+ [handleFiles]
+ );
+
+ const audioRecorder = showAudioRecorder ? (
+ setShowAudioRecorder(false)}
+ onRecordingComplete={handleAudioRecordingComplete}
+ onAudioLengthUpdate={() => {}}
+ onWaveformUpdate={() => {}}
+ />
+ ) : undefined;
+
const handleCancelUpload = (uploads: Upload[]) => {
uploads.forEach((upload) => {
if (upload.status === UploadStatus.Loading) {
@@ -768,30 +746,34 @@ export const RoomInput = forwardRef(
const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
if (perMessageProfile) {
- content['com.beeper.per_message_profile'] =
- convertPerMessageProfileToBeeperFormat(perMessageProfile);
+ content['com.beeper.per_message_profile'] = convertPerMessageProfileToBeeperFormat(
+ perMessageProfile,
+ perMessageProfile.name.trim() !== ''
+ );
- // if a per-message profile is used, it must per spec include a fallback
- const prefix = `${perMessageProfile.name}: `;
+ if (perMessageProfile.name.trim() !== '') {
+ // if a per-message profile is used, it must per spec include a fallback
+ const prefix = `${perMessageProfile.name}: `;
- if (!content.body.startsWith(prefix)) {
- // to prevent double-prefixing when the fallback is already present
- content.body = prefix + content.body;
- }
+ if (!content.body.startsWith(prefix)) {
+ // to prevent double-prefixing when the fallback is already present
+ content.body = prefix + content.body;
+ }
- /**
- * html escaped version of the display name
- */
- const escapedName = sanitizeCustomHtml(perMessageProfile.name);
+ /**
+ * html escaped version of the display name
+ */
+ const escapedName = sanitizeCustomHtml(perMessageProfile.name);
- const htmlPrefix = `${escapedName}: `;
+ const htmlPrefix = `${escapedName}: `;
- if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) {
- content.formatted_body = htmlPrefix + content.formatted_body;
- } else {
- // we don't have a formatted body, but we need one
- content.format = 'org.matrix.custom.html';
- content.formatted_body = `${htmlPrefix}${plainText}`;
+ if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) {
+ content.formatted_body = htmlPrefix + content.formatted_body;
+ } else {
+ // we don't have a formatted body, but we need one
+ content.format = 'org.matrix.custom.html';
+ content.formatted_body = `${htmlPrefix}${plainText}`;
+ }
}
}
@@ -947,6 +929,15 @@ export const RoomInput = forwardRef(
}
}
+ if (isKeyHotkey('arrowup', evt) && isEmptyEditor(editor)) {
+ const { selection } = editor;
+ if (selection && Editor.isStart(editor, selection.anchor, [])) {
+ evt.preventDefault();
+ onEditLastMessage?.();
+ return;
+ }
+ }
+
if (
(isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) &&
!isComposing(evt)
@@ -978,6 +969,8 @@ export const RoomInput = forwardRef(
autocompleteQuery,
isComposing,
showAudioRecorder,
+ editor,
+ onEditLastMessage,
]
);
@@ -1180,10 +1173,12 @@ export const RoomInput = forwardRef(
editableName="RoomInput"
editor={editor}
key={inputKey}
- placeholder={showAudioRecorder && mobileOrTablet() ? '' : 'Send a message...'}
+ placeholder="Send a message..."
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onPaste={handlePaste}
+ responsiveAfter={audioRecorder}
+ forceMultilineLayout={showAudioRecorder}
top={
<>
{scheduledTime && (
@@ -1260,22 +1255,7 @@ export const RoomInput = forwardRef(
{replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && (
)}
-
-
- {getMemberDisplayName(room, replyDraft.userId, nicknames) ??
- getMxIdLocalPart(replyDraft.userId) ??
- replyDraft.userId}
-
-
- }
- >
-
- {replyBodyJSX}
-
-
+
(
>
}
before={
- !(showAudioRecorder && mobileOrTablet()) && (
- pickFile('*')}
- variant="SurfaceVariant"
- size="300"
- radii="300"
- title="Upload File"
- aria-label="Upload and attach a File"
- >
-
-
- )
+ pickFile('*')}
+ variant="SurfaceVariant"
+ size="300"
+ radii="300"
+ title="Upload File"
+ aria-label="Upload and attach a File"
+ >
+
+
}
after={
<>
- {showAudioRecorder && (
- setShowAudioRecorder(false)}
- onRecordingComplete={(payload) => {
- const extension = getSupportedAudioExtension(payload.audioCodec);
- const file = new File(
- [payload.audioBlob],
- `sable-audio-message-${Date.now()}.${extension}`,
- {
- type: payload.audioCodec,
- }
- );
- handleFiles([file], {
- waveform: payload.waveform,
- audioDuration: payload.audioLength,
- });
- setShowAudioRecorder(false);
- }}
- onAudioLengthUpdate={() => {}}
- onWaveformUpdate={() => {}}
- />
- )}
-
{/* ── Mic button — always present; icon swaps to Stop while recording ── */}
(
aria-label={showAudioRecorder ? 'Stop recording' : 'Record audio message'}
aria-pressed={showAudioRecorder}
onClick={() => {
- if (mobileOrTablet()) return;
+ if (mobileOrTablet() && !showAudioRecorder) return;
if (showAudioRecorder) {
audioRecorderRef.current?.stop();
} else {
diff --git a/src/app/features/room/RoomTimeline.css.ts b/src/app/features/room/RoomTimeline.css.ts
index 29f18f3a..7b355fe1 100644
--- a/src/app/features/room/RoomTimeline.css.ts
+++ b/src/app/features/room/RoomTimeline.css.ts
@@ -1,6 +1,6 @@
import { globalStyle, style } from '@vanilla-extract/css';
import { RecipeVariants, recipe } from '@vanilla-extract/recipes';
-import { DefaultReset, config } from 'folds';
+import { DefaultReset, color, config, toRem } from 'folds';
export const TimelineFloat = recipe({
base: [
@@ -29,17 +29,71 @@ export const TimelineFloat = recipe({
});
export type TimelineFloatVariants = RecipeVariants;
-
export const messageList = style({
- display: 'flex',
- flexDirection: 'column',
- width: '100%',
+ overflowY: 'scroll',
+ scrollbarGutter: 'stable',
+
+ '@supports': {
+ 'not selector(::-webkit-scrollbar)': {
+ scrollbarWidth: 'auto',
+ selectors: {
+ '&:hover, &:has(*:hover)': {
+ scrollbarColor: `${color.SurfaceVariant.ContainerLine} ${color.SurfaceVariant.ContainerActive}`,
+ },
+ },
+ },
+ },
+
+ selectors: {
+ '&::-webkit-scrollbar': {
+ width: toRem(16),
+ height: toRem(16),
+ },
+ '&::-webkit-scrollbar-corner': {
+ backgroundColor: 'transparent',
+ },
+ '&::-webkit-scrollbar-thumb': {
+ backgroundColor: 'transparent',
+ borderRadius: config.radii.Pill,
+ minHeight: toRem(35),
+ border: `${toRem(4)} solid transparent`,
+ backgroundClip: 'padding-box',
+ },
+ '&::-webkit-scrollbar-track': {
+ backgroundColor: 'transparent',
+ borderRadius: config.radii.Pill,
+ border: `${toRem(4)} solid transparent`,
+ backgroundClip: 'padding-box',
+ },
+ '&:hover::-webkit-scrollbar-thumb, &:has(*:hover)::-webkit-scrollbar-thumb': {
+ backgroundColor: color.SurfaceVariant.ContainerLine,
+ },
+ '&:hover::-webkit-scrollbar-track, &:has(*:hover)::-webkit-scrollbar-track': {
+ backgroundColor: color.SurfaceVariant.ContainerActive,
+ },
+ },
+});
+globalStyle(`${messageList} > *`, {
+ scrollbarWidth: 'auto',
+ scrollbarColor: 'auto',
+});
+
+globalStyle(`body ${messageList} > *`, {
+ overflowAnchor: 'none',
});
globalStyle(`body ${messageList} [data-message-id]`, {
+ overflowAnchor: 'auto',
transition: 'background-color 0.1s ease-in-out !important',
+ position: 'relative',
+ zIndex: 1,
});
globalStyle(`body ${messageList} [data-message-id]:hover`, {
backgroundColor: 'var(--sable-surface-container-hover) !important',
+ zIndex: 2,
+});
+
+globalStyle(`body ${messageList} [data-message-id]:focus-within`, {
+ zIndex: 10,
});
diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx
index 292023fa..dd655dee 100644
--- a/src/app/features/room/RoomTimeline.tsx
+++ b/src/app/features/room/RoomTimeline.tsx
@@ -1,11 +1,6 @@
-/* eslint-disable react/destructuring-assignment */
import {
Fragment,
- Dispatch,
- MouseEventHandler,
ReactNode,
- RefObject,
- SetStateAction,
useCallback,
useEffect,
useLayoutEffect,
@@ -13,135 +8,72 @@ import {
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 { 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 { VList, VListHandle } from 'virtua';
import {
as,
- Avatar,
- Badge,
Box,
Chip,
- color,
- config,
- ContainerColor,
Icon,
Icons,
Line,
- Scroll,
- Spinner,
Text,
+ Badge,
+ color,
+ config,
toRem,
+ ContainerColor,
+ Spinner,
} 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, CompactPlaceholder, DefaultPlaceholder } 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 { 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 {
- roomHaveNotification,
- roomHaveUnread,
- canEditEvent,
- decryptAllTimelineEvent,
- getEditedEvent,
- getEventReactions,
- getLatestEditableEvt,
- getMemberAvatarMxc,
- getMemberDisplayName,
- isMembershipChanged,
- reactionOrEditEvent,
-} from '$utils/room';
-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,
+ getEventIdAbsoluteIndex,
+} from '$utils/timeline';
+import { useTimelineSync } from '$hooks/timeline/useTimelineSync';
+import { useTimelineActions } from '$hooks/timeline/useTimelineActions';
+import { ProcessedEvent, useProcessedTimeline } from '$hooks/timeline/useProcessedTimeline';
+import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer';
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) => (
@@ -166,623 +98,31 @@ const TimelineDivider = as<'div', { variant?: ContainerColor | 'Inherit' }>(
)
);
-export const getLiveTimeline = (room: Room): EventTimeline =>
- room.getUnfilteredTimelineSet().getLiveTimeline();
-
-export const getEventTimeline = (room: Room, eventId: string): EventTimeline | undefined => {
- const timelineSet = room.getUnfilteredTimelineSet();
- return timelineSet.getTimelineForEvent(eventId) ?? undefined;
+const getDayDividerText = (ts: number) => {
+ if (today(ts)) return 'Today';
+ if (yesterday(ts)) return 'Yesterday';
+ return timeDayMonthYear(ts);
};
-export const getFirstLinkedTimeline = (
- timeline: EventTimeline,
- direction: Direction
-): EventTimeline => {
- const linkedTm = timeline.getNeighbouringTimeline(direction);
- if (!linkedTm) return timeline;
- return getFirstLinkedTimeline(linkedTm, direction);
-};
-
-export const getLinkedTimelines = (timeline: EventTimeline): EventTimeline[] => {
- const firstTimeline = getFirstLinkedTimeline(timeline, Direction.Backward);
- const timelines: EventTimeline[] = [];
-
- for (
- let nextTimeline: EventTimeline | null = firstTimeline;
- nextTimeline;
- nextTimeline = nextTimeline.getNeighbouringTimeline(Direction.Forward)
- ) {
- timelines.push(nextTimeline);
- }
- return timelines;
-};
-
-export const timelineToEventsCount = (t: EventTimeline) => {
- if (!t) return 0;
- const events = t.getEvents();
- return events ? events.length : 0;
-};
-
-export const getTimelinesEventsCount = (timelines: EventTimeline[]): number => {
- const timelineEventCountReducer = (count: number, tm: EventTimeline) =>
- count + timelineToEventsCount(tm);
- return (timelines || [])
- .filter(Boolean)
- .reduce((accumulator, element) => timelineEventCountReducer(accumulator, element), 0);
-};
-
-export const getTimelineAndBaseIndex = (
- timelines: EventTimeline[],
- index: number
-): [EventTimeline | undefined, number] => {
- let uptoTimelineLen = 0;
- const validTimelines = (timelines || []).filter(Boolean);
-
- const timeline = validTimelines.find((t) => {
- const events = t.getEvents();
- if (!events) return false;
-
- uptoTimelineLen += events.length;
- return index < uptoTimelineLen;
- });
-
- if (!timeline) return [undefined, 0];
-
- const events = timeline.getEvents();
- const timelineLen = events ? events.length : 0;
-
- return [timeline, Math.max(0, uptoTimelineLen - timelineLen)];
-};
-
-export const getTimelineRelativeIndex = (absoluteIndex: number, timelineBaseIndex: number) =>
- absoluteIndex - timelineBaseIndex;
-
-export const getTimelineEvent = (
- timeline: EventTimeline,
- index: number
-): MatrixEvent | undefined => {
- if (!timeline) return undefined;
- const events = timeline.getEvents();
- return events ? events[index] : undefined;
-};
-
-export const getEventIdAbsoluteIndex = (
- timelines: EventTimeline[],
- eventTimeline: EventTimeline,
- eventId: string
-): number | undefined => {
- const timelineIndex = timelines.indexOf(eventTimeline);
- if (timelineIndex === -1) return undefined;
-
- const currentEvents = eventTimeline.getEvents();
- if (!currentEvents) return undefined;
-
- const eventIndex = currentEvents.findIndex((evt: MatrixEvent) => evt.getId() === eventId);
- if (eventIndex === -1) return undefined;
-
- const baseIndex = timelines.slice(0, timelineIndex).reduce((accValue, timeline) => {
- const evs = timeline.getEvents();
- return (evs ? evs.length : 0) + accValue;
- }, 0);
-
- return baseIndex + eventIndex;
-};
-
-type RoomTimelineProps = {
+export type RoomTimelineProps = {
room: Room;
eventId?: string;
- roomInputRef: RefObject;
editor: Editor;
onEditorReset?: () => void;
-};
-
-const PAGINATION_LIMIT = 60;
-const EVENT_TIMELINE_LOAD_TIMEOUT_MS = 12000;
-
-type PaginationStatus = 'idle' | 'loading' | 'error';
-
-type Timeline = {
- linkedTimelines: EventTimeline[];
- range: ItemRange;
-};
-
-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');
-
- const paginate = useMemo(() => {
- let fetching = false;
-
- 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 =
- timelineToEventsCount(newLTimelines[topTmIndex]) - 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) => {
- if (fetching) return;
- const { linkedTimelines: lTimelines } = timelineRef.current;
- const timelinesEventsCount = lTimelines.map(timelineToEventsCount);
-
- 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;
- }
-
- fetching = 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 {
- fetching = false;
- }
- };
- }, [mx, alive, setTimeline, limit, setBackwardStatus, setForwardStatus]);
-
- return { paginate, backwardStatus, forwardStatus };
-};
-
-const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) => {
- // Stable ref so the effect dep array only contains `room`. The listener is
- // registered once per room mount; onArrive can change freely without causing
- // listener churn during rapid re-renders (e.g. sync error/retry cycles).
- const onArriveRef = useRef(onArrive);
- onArriveRef.current = onArrive;
-
- useEffect(() => {
- // Capture the live timeline and registration time. Events appended to the
- // live timeline AFTER this point can be genuinely new even when
- // liveEvent=false (older sliding sync proxies that omit num_live).
- 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;
- // Standard sync: liveEvent=true for real-time events.
- // Sliding sync fallback: liveEvent=false on buggy proxies. Treat events
- // on the live timeline as new only when their server timestamp is within
- // 60 s before registration — this filters out initial-sync backfill that
- // happens to fire after mount while excluding genuine reconnect messages.
- 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]); // stable: re-register only when room changes, not on callback identity changes
-};
-
-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
- ) => {
- // Live Replace events are handled by useLiveEventArrive re-render.
- // Non-live Replace events (bundled/historical edits from sliding sync)
- // also need to trigger a re-render so makeReplaced state is reflected.
- 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;
- // App-initiated full reinit (e.g. from refreshLiveTimeline()). Rare in normal usage.
- debugLog.debug('timeline', 'TimelineRefresh: app-initiated live timeline reinit', {
- roomId: room.roomId,
- trigger: 'TimelineRefresh',
- });
- onRefreshRef.current();
- };
- // The SDK fires RoomEvent.TimelineReset on the EventTimelineSet (not the Room)
- // when a limited sync response replaces the live EventTimeline with a fresh one.
- // This happens in classic /sync on limited=true (gap after idle/reconnect) AND in
- // sliding sync when the proxy sends a limited room update.
- const handleTimelineReset: EventTimelineSetHandlerMap[RoomEvent.TimelineReset] = () => {
- debugLog.info('timeline', 'TimelineReset: SDK-initiated (limited sync / sync gap)', {
- roomId: room.roomId,
- trigger: 'TimelineReset',
- liveTimelineEvents: room.getUnfilteredTimelineSet().getLiveTimeline().getEvents().length,
- });
- Sentry.metrics.count('sable.timeline.limited_reset', 1);
- Sentry.addBreadcrumb({
- category: 'timeline.sync',
- message: 'TimelineReset: limited sync gap',
- level: 'info',
- data: { roomId: room.roomId },
- });
- 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]);
-};
-
-// Trigger re-render when thread reply counts change so the thread chip updates.
-const useThreadUpdate = (room: Room, onUpdate: () => void) => {
- const onUpdateRef = useRef(onUpdate);
- onUpdateRef.current = onUpdate;
-
- useEffect(() => {
- // Stable wrapper: the same function identity is kept for the lifetime of
- // the room so add/removeListener calls always match.
- 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]);
-};
-
-// Returns the number of replies in a thread, counting actual reply events
-// (excluding the root event, reactions, and edits) from the live timeline.
-// Always uses timeline-based counting for accuracy and live updates.
-const getThreadReplyCount = (room: Room, mEventId: string): number =>
- room
- .getUnfilteredTimelineSet()
- .getLiveTimeline()
- .getEvents()
- .filter(
- (ev) => ev.threadRootId === mEventId && ev.getId() !== mEventId && !reactionOrEditEvent(ev)
- ).length;
-
-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)}
-
- )}
-
- );
-}
-
-const getInitialTimeline = (room: Room) => {
- const linkedTimelines = getLinkedTimelines(getLiveTimeline(room));
- const evLength = getTimelinesEventsCount(linkedTimelines);
- return {
- linkedTimelines,
- range: {
- start: Math.max(evLength - PAGINATION_LIMIT, 0),
- end: evLength,
- },
- };
-};
-
-const getEmptyTimeline = () => ({
- range: { start: 0, end: 0 },
- linkedTimelines: [],
-});
-
-const getRoomUnreadInfo = (room: Room, scrollTo = false) => {
- if (!roomHaveNotification(room) && !roomHaveUnread(room.client, room)) return undefined;
-
- const readUptoEventId = room.getEventReadUpTo(room.client.getUserId() ?? '');
- if (!readUptoEventId) return undefined;
- const evtTimeline = getEventTimeline(room, readUptoEventId);
- const latestTimeline = evtTimeline && getFirstLinkedTimeline(evtTimeline, Direction.Forward);
- return {
- readUptoEventId,
- inLiveTimeline: latestTimeline === room.getLiveTimeline(),
- scrollTo,
- };
+ onEditLastMessageRef?: React.MutableRefObject<(() => void) | undefined>;
};
export function RoomTimeline({
room,
eventId,
- roomInputRef,
editor,
onEditorReset,
+ onEditLastMessageRef,
}: 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');
@@ -791,120 +131,311 @@ 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 [clientUrlPreview] = useSetting(settingsAtom, 'clientUrlPreview');
+ const [encClientUrlPreview] = useSetting(settingsAtom, 'encClientUrlPreview');
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 showClientUrlPreview = room.hasEncryptionStateEvent()
+ ? encClientUrlPreview
+ : clientUrlPreview;
+
+ 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));
- // Stable ref so listeners that only need to *read* unreadInfo don't force
- // effect re-registration (and listener churn) every time a new message arrives.
- 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 prevViewportHeightRef = useRef(0);
+ const messageListRef = useRef(null);
+
+ 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 vListRef = useRef(null);
+ const [atBottomState, setAtBottomState] = useState(true);
+ const atBottomRef = useRef(atBottomState);
+ const setAtBottom = useCallback((val: boolean) => {
+ setAtBottomState(val);
+ atBottomRef.current = val;
+ }, []);
+
+ const [shift, setShift] = useState(false);
+ const [topSpacerHeight, setTopSpacerHeight] = useState(0);
+
+ const topSpacerHeightRef = useRef(0);
+ const mountScrollWindowRef = useRef(Date.now() + 3000);
+ const hasInitialScrolledRef = useRef(false);
+ const currentRoomIdRef = useRef(room.roomId);
+
+ const [isReady, setIsReady] = useState(false);
+
+ if (currentRoomIdRef.current !== room.roomId) {
+ hasInitialScrolledRef.current = false;
+ mountScrollWindowRef.current = Date.now() + 3000;
+ currentRoomIdRef.current = room.roomId;
+ setIsReady(false);
}
- const atBottomAnchorRef = useRef(null);
+ const processedEventsRef = useRef([]);
+ const timelineSyncRef = useRef(null as unknown as typeof timelineSync);
- // TODO: The return value of "useState" should be destructured and named symmetrically (typescript:S6754)
- const [atBottom, setAtBottomState] = useState(true);
- const atBottomRef = useRef(atBottom);
- // Tracks when atBottom last changed so we can detect rapid true→false flips
- // (characteristic of the IO false-positive on bulk event loads).
- 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 },
- });
- // Rapid flip: bottom→away within 200 ms is characteristic of the known
- // IntersectionObserver false-positive triggered by bulk event loads causing
- // a DOM layout shift (see memory: "RoomTimeline Stay at Bottom False-Positive").
- 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 scrollToBottom = useCallback(() => {
+ if (!vListRef.current) return;
+ const lastIndex = processedEventsRef.current.length - 1;
+ if (lastIndex < 0) return;
+ vListRef.current.scrollTo(vListRef.current.scrollSize);
+ }, []);
- // Set to true by the useLiveTimelineRefresh callback when the timeline is
- // re-initialised (TimelineRefresh or TimelineReset). Allows the range self-heal
- // effect below to run even when atBottom=false, so the virtual paginator window
- // is restored to the live end without forcing a viewport scroll.
- const timelineJustResetRef = useRef(false);
-
- const scrollRef = useRef(null);
- const scrollToBottomRef = useRef({
- count: 0,
- smooth: true,
+ const timelineSync = useTimelineSync({
+ room,
+ mx,
+ eventId,
+ isAtBottom: atBottomState,
+ isAtBottomRef: atBottomRef,
+ scrollToBottom,
+ unreadInfo,
+ setUnreadInfo,
+ hideReadsRef,
+ readUptoEventIdRef,
});
- const [focusItem, setFocusItem] = useState<
- | {
- index: number;
- scrollTo: boolean;
- highlight: boolean;
- }
- | undefined
- >();
- const alive = useAlive();
+ timelineSyncRef.current = timelineSync;
- const linkifyOpts = useMemo(
+ const eventsLengthRef = useRef(timelineSync.eventsLength);
+ eventsLengthRef.current = timelineSync.eventsLength;
+
+ const canPaginateBackRef = useRef(timelineSync.canPaginateBack);
+ canPaginateBackRef.current = timelineSync.canPaginateBack;
+
+ const liveTimelineLinkedRef = useRef(timelineSync.liveTimelineLinked);
+ liveTimelineLinkedRef.current = timelineSync.liveTimelineLinked;
+
+ const backwardStatusRef = useRef(timelineSync.backwardStatus);
+ backwardStatusRef.current = timelineSync.backwardStatus;
+
+ const forwardStatusRef = useRef(timelineSync.forwardStatus);
+ forwardStatusRef.current = timelineSync.forwardStatus;
+
+ const getRawIndexToProcessedIndex = useCallback((rawIndex: number): number | undefined => {
+ const events = processedEventsRef.current;
+ const match = events.find((e) => e.itemIndex === rawIndex);
+ if (!match) return undefined;
+ return events.indexOf(match);
+ }, []);
+
+ useLayoutEffect(() => {
+ if (
+ !eventId &&
+ !hasInitialScrolledRef.current &&
+ timelineSync.eventsLength > 0 &&
+ vListRef.current
+ ) {
+ vListRef.current.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
+ const t = setTimeout(() => {
+ vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
+ setIsReady(true);
+ }, 80);
+ hasInitialScrolledRef.current = true;
+ return () => clearTimeout(t);
+ }
+ return () => {};
+ }, [timelineSync.eventsLength, eventId, room.roomId]);
+
+ const recalcTopSpacer = useCallback(() => {
+ const v = vListRef.current;
+ if (!v) return;
+ const prev = topSpacerHeightRef.current;
+
+ const newH = Math.max(0, v.viewportSize - v.scrollSize + prev);
+ if (Math.abs(prev - newH) > 2) {
+ topSpacerHeightRef.current = newH;
+ setTopSpacerHeight(newH);
+ if (prev > 0 && newH === 0 && processedEventsRef.current.length > 0) {
+ requestAnimationFrame(() => {
+ vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
+ });
+ }
+ }
+ }, []);
+
+ useLayoutEffect(() => {
+ const id = requestAnimationFrame(recalcTopSpacer);
+ return () => cancelAnimationFrame(id);
+ }, [recalcTopSpacer, timelineSync.eventsLength]);
+
+ const prevBackwardStatusRef = useRef(timelineSync.backwardStatus);
+ const wasAtBottomBeforePaginationRef = useRef(false);
+
+ useLayoutEffect(() => {
+ const prev = prevBackwardStatusRef.current;
+ prevBackwardStatusRef.current = timelineSync.backwardStatus;
+ if (timelineSync.backwardStatus === 'loading') {
+ wasAtBottomBeforePaginationRef.current = atBottomRef.current;
+ if (!atBottomRef.current) setShift(true);
+ } else if (prev === 'loading' && timelineSync.backwardStatus === 'idle') {
+ setShift(false);
+ if (wasAtBottomBeforePaginationRef.current) {
+ vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
+ }
+ }
+ }, [timelineSync.backwardStatus]);
+
+ useEffect(() => {
+ let timeoutId: ReturnType | undefined;
+ if (timelineSync.focusItem) {
+ if (timelineSync.focusItem.scrollTo && vListRef.current) {
+ const processedIndex = getRawIndexToProcessedIndex(timelineSync.focusItem.index);
+ if (processedIndex !== undefined) {
+ vListRef.current.scrollToIndex(processedIndex, { align: 'center' });
+ timelineSync.setFocusItem((prev) => (prev ? { ...prev, scrollTo: false } : undefined));
+ }
+ }
+ timeoutId = setTimeout(() => {
+ timelineSync.setFocusItem(undefined);
+ }, 2000);
+ }
+ return () => {
+ if (timeoutId !== undefined) clearTimeout(timeoutId);
+ };
+ }, [timelineSync.focusItem, timelineSync, reducedMotion, getRawIndexToProcessedIndex]);
+
+ useEffect(() => {
+ if (timelineSync.focusItem) {
+ setIsReady(true);
+ }
+ }, [timelineSync.focusItem]);
+
+ useEffect(() => {
+ if (!eventId) return;
+ setIsReady(false);
+ timelineSyncRef.current.loadEventTimeline(eventId);
+ }, [eventId, room.roomId]);
+
+ useEffect(() => {
+ if (eventId) return;
+ const { readUptoEventId, inLiveTimeline, scrollTo } = unreadInfo ?? {};
+ if (readUptoEventId && inLiveTimeline && scrollTo) {
+ const evtTimeline = getEventTimeline(room, readUptoEventId);
+ const absoluteIndex = evtTimeline
+ ? getEventIdAbsoluteIndex(
+ timelineSync.timeline.linkedTimelines,
+ evtTimeline,
+ readUptoEventId
+ )
+ : undefined;
+
+ if (absoluteIndex !== undefined && vListRef.current) {
+ const processedIndex = getRawIndexToProcessedIndex(absoluteIndex);
+ if (processedIndex !== undefined) {
+ vListRef.current.scrollToIndex(processedIndex, { align: 'start' });
+ setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
+ }
+ }
+ }
+ }, [
+ room,
+ unreadInfo,
+ timelineSync.timeline.linkedTimelines,
+ eventId,
+ getRawIndexToProcessedIndex,
+ ]);
+
+ useEffect(() => {
+ const el = messageListRef.current;
+ if (!el) return () => {};
+
+ const observer = new ResizeObserver((entries) => {
+ const newHeight = entries[0].contentRect.height;
+ const prev = prevViewportHeightRef.current;
+ const atBottom = atBottomRef.current;
+ const shrank = newHeight < prev;
+
+ if (shrank && atBottom) {
+ vListRef.current?.scrollTo(vListRef.current.scrollSize);
+ }
+ prevViewportHeightRef.current = newHeight;
+ });
+
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ 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 processedIndex = getRawIndexToProcessedIndex(absoluteIndex);
+ if (vListRef.current && processedIndex !== undefined) {
+ vListRef.current.scrollToIndex(processedIndex, { align: 'center' });
+ }
+ timelineSync.setFocusItem({ index: absoluteIndex, scrollTo: false, highlight: true });
+ } else {
+ timelineSync.loadEventTimeline(id);
+ }
+ },
+ });
+
+ const linkifyOpts = useMemo(
() => ({
...LINKIFY_OPTS,
render: factoryRenderLinkifyWithMention((href) =>
@@ -917,13 +448,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,
@@ -931,1801 +463,123 @@ 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);
-
- // Track previous eventsLength so we can calculate batch sizes.
- const prevEventsLengthRef = useRef(eventsLength);
-
- // Breadcrumb every time the timeline gains events so we can correlate message
- // batches (sliding sync chunks) with scroll state changes in Sentry Replay.
- useEffect(() => {
- const prev = prevEventsLengthRef.current;
- const delta = eventsLength - prev;
- prevEventsLengthRef.current = eventsLength;
-
- if (delta === 0) return;
-
- const isBatch = delta > 1;
- // Classify by size: single new message vs small batch vs large catch-up load
- 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,
- // Gap between live end and visible window — non-zero while user is scrolled back
- rangeGap: eventsLength - timeline.range.end,
- },
- });
-
- // A large batch (> 50) while liveTimelineLinked is the sliding-sync
- // adaptive load pattern that can trigger the IO false-positive scroll reset.
- // Capture a warning so it's searchable in Sentry even when no reset fires.
- 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 },
- });
- }
- // atBottomRef and timeline.range.end are intentionally read at effect time, not as deps
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [eventsLength, liveTimelineLinked]);
-
- // Log timeline component mount/unmount
- 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 },
- });
- }
- debugLog.info('timeline', 'Timeline mounted', {
- roomId: room.roomId,
- eventId,
- initialEventsCount: eventsLength,
- liveTimelineLinked,
- });
- return () => {
- debugLog.info('timeline', 'Timeline unmounted', { roomId: room.roomId });
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [room.roomId, eventId]); // Only log on mount/unmount - intentionally capturing initial values
-
- // Log live timeline linking state changes
- 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;
- }
-
- // Log range changes with scroll state so we can correlate visible-content
- // jumps with paginator window shifts. scrollRef is a stable ref — safe here.
- 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,
- });
- Sentry.addBreadcrumb({
- category: 'ui.timeline',
- message: 'Timeline window shifted',
- level: 'debug',
- data: {
- prevStart: currentTimeline.range.start,
- prevEnd: currentTimeline.range.end,
- newStart: newRange.start,
- newEnd: newRange.end,
- deltaStart: ds,
- deltaEnd: de,
- },
- });
-
- 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) => {
- // Thread reply events are re-emitted from the Thread to the Room and
- // must not increment the main timeline range or scroll it.
- // useThreadUpdate handles the chip re-render for these events.
- if (mEvt.threadRootId !== undefined) return;
-
- // if user is at bottom of timeline
- // keep paginating timeline and conditionally mark as read
- // otherwise we update timeline without paginating
- // so timeline can be updated with evt like: edits, reactions etc
- if (atBottomRef.current && atLiveEndRef.current) {
- if (
- document.hasFocus() &&
- (!unreadInfoRef.current || mEvt.getSender() === mx.getUserId())
- ) {
- // Check if the document is in focus (user is actively viewing the app),
- // and either there are no unread messages or the latest message is from the current user.
- // If either condition is met, trigger the markAsRead function to send a read receipt.
- requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideReads));
- }
-
- if (!document.hasFocus() && !unreadInfoRef.current) {
- setUnreadInfo(getRoomUnreadInfo(room));
- }
-
- scrollToBottomRef.current.count += 1;
- // Use instant scroll when the current user sent the message
- // to avoid Android WebView smooth-scroll not reaching bottom.
- 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, hideReads]
- )
- );
-
- 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
- ) => {
- debugLog.info('timeline', 'Jumping to event', {
- roomId: room.roomId,
- eventId: evtId,
- highlight,
- });
-
- 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,
- });
- debugLog.debug('timeline', 'Event found in current timeline', {
- roomId: room.roomId,
- eventId: evtId,
- index: absoluteIndex,
- });
- } else {
- debugLog.debug('timeline', 'Event not in current timeline, loading timeline', {
- roomId: room.roomId,
- eventId: evtId,
- });
- loadEventTimeline(evtId);
- }
+ pushProcessor,
+ nicknames,
+ imagePackRooms,
+ settings: {
+ messageLayout,
+ messageSpacing,
+ hideReads,
+ showDeveloperTools,
+ hour24Clock,
+ dateFormatString,
+ mediaAutoLoad,
+ showUrlPreview,
+ showClientUrlPreview,
+ autoplayStickers,
+ hideMemberInReadOnly,
+ isReadOnly,
+ hideMembershipEvents,
+ hideNickAvatarEvents,
+ showHiddenEvents,
},
- [room, timeline, scrollToItem, loadEventTimeline, reducedMotion, setAtBottom]
- );
-
- useLiveTimelineRefresh(
- room,
- useCallback(() => {
- // Always reinitialize on TimelineRefresh/TimelineReset. With sliding sync,
- // a limited response replaces the room's live EventTimeline with a brand-new
- // object. At that moment liveTimelineLinked is stale-false (stored
- // linkedTimelines reference the old detached chain), so any guard on that
- // flag would skip reinit, causing back-pagination to no-op silently and the
- // room to appear frozen. Unconditional reinit is correct: both events signal
- // that stored range/indices against the old chain are invalid.
- //
- // Only force the viewport to the bottom if the user was already there.
- // When the user has scrolled up to read history and a sync gap fires, we
- // must still reinit (the old timeline is gone), but scrolling them back to
- // the bottom is jarring. Instead we set timelineJustResetRef=true so the
- // self-heal effect below can advance the range as events arrive on the fresh
- // timeline, without atBottom=true being required.
- //
- // Also force atBottom=true and queue a scroll-to-bottom. The SDK fires
- // TimelineRefresh before adding new events to the fresh live timeline, so
- // getInitialTimeline captures range.end=0. Once events arrive the
- // rangeAtEnd self-heal useEffect needs atBottom=true to run; the
- // IntersectionObserver may have transiently fired isIntersecting=false
- // during the render transition, leaving atBottom=false and causing the
- // "Jump to Latest" button to stick permanently. Forcing atBottom here is
- // correct: TimelineRefresh always reinits to the live end, so the user
- // should be repositioned to the bottom regardless.
- Sentry.metrics.count('sable.timeline.reinit', 1);
-
- // When the user WAS at the bottom we still call setAtBottom(true) so a
- // transient isIntersecting=false from the IntersectionObserver during the
- // DOM transition cannot stick the "Jump to Latest" button on-screen.
- debugLog.info('timeline', 'Live timeline refresh triggered', { roomId: room.roomId });
- const wasAtBottom = atBottomRef.current;
- timelineJustResetRef.current = true;
- setTimeline(getInitialTimeline(room));
- if (wasAtBottom) {
- setAtBottom(true);
- scrollToBottomRef.current.count += 1;
- scrollToBottomRef.current.smooth = false;
- }
- }, [room, setAtBottom])
- );
-
- // Re-render when non-live Replace relations arrive (bundled/historical edits
- // from sliding sync that wouldn't otherwise trigger a timeline update).
- useRelationUpdate(
- room,
- useCallback(() => {
- setTimeline((ct) => ({ ...ct }));
- }, [])
- );
-
- // Re-render when thread reply counts change (new reply or thread update) so
- // the thread chip on root messages reflects the correct count.
- useThreadUpdate(
- room,
- useCallback(() => {
- setTimeline((ct) => ({ ...ct }));
- }, [])
- );
-
- // When historical events load (e.g., from active subscription), stay at bottom
- // by adjusting the range. The virtual paginator expects the range to match the
- // position we want to display. Without this, loading more history makes it look
- // like we've scrolled up because the range (0, 10) is now showing the old events
- // instead of the latest ones.
- //
- // Also runs after a timeline reset (timelineJustResetRef=true) even when
- // atBottom=false. After TimelineReset the SDK fires the event before populating
- // the fresh timeline, so getInitialTimeline sees range.end=0. When events
- // arrive eventsLength grows and we need to heal the range back to the live end
- // regardless of the user's scroll position.
- useEffect(() => {
- const resetPending = timelineJustResetRef.current;
- if ((atBottom || resetPending) && liveTimelineLinked && eventsLength > timeline.range.end) {
- if (resetPending) timelineJustResetRef.current = false;
- // More events exist than our current range shows. Adjust to the live end.
- //
- // IMPORTANT: also queue a scroll-to-bottom here. The scroll that was queued
- // during TimelineReset / initial mount fires when range.end is still 0
- // (the SDK fires Reset *before* populating the fresh timeline), so the DOM
- // has no items yet and the scroll is a no-op. This second increment fires
- // after setTimeline renders the full range, guaranteeing we actually land
- // at the bottom once the events are visible.
- const rangeGap = eventsLength - timeline.range.end;
- scrollToBottomRef.current.count += 1;
- scrollToBottomRef.current.smooth = false;
- Sentry.addBreadcrumb({
- category: 'ui.scroll',
- message: 'Timeline: stay-at-bottom range expansion + scroll',
- level: 'info',
- data: {
- eventsLength,
- prevRangeEnd: timeline.range.end,
- rangeGap,
- wasReset: resetPending,
- atBottom,
- },
- });
- setTimeline((ct) => ({
- ...ct,
- range: {
- start: Math.max(eventsLength - PAGINATION_LIMIT, 0),
- end: eventsLength,
- },
- }));
- }
- }, [atBottom, liveTimelineLinked, eventsLength, timeline.range.end]);
-
- // Recover from transient empty timeline state when the live timeline
- // already has events (can happen when opening by event id, then fallbacking).
- 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]);
-
- // Stay at bottom when room editor resize
- useResizeObserver(
- useMemo(() => {
- let mounted = false;
- return (entries) => {
- if (!mounted) {
- // skip initial mounting call
- 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) {
- // User has reached the bottom
- debugLog.debug('timeline', 'Scrolled to bottom', { roomId: room.roomId });
- setAtBottom(true);
- if (atLiveEndRef.current && document.hasFocus()) {
- tryAutoMarkAsRead();
- }
- } else {
- // User has intentionally scrolled up.
- debugLog.debug('timeline', 'Scrolled away from bottom', { roomId: room.roomId });
- setAtBottom(false);
- }
- },
- [tryAutoMarkAsRead, setAtBottom, room.roomId]
- ),
- useCallback(
- () => ({
- root: getScrollElement(),
- rootMargin: '100px',
- }),
- [getScrollElement]
- ),
- useCallback(() => atBottomAnchorRef.current, [])
- );
-
useDocumentFocusChange(
useCallback(
(inFocus) => {
- if (inFocus && atBottomRef.current) {
- tryAutoMarkAsRead();
- }
+ if (inFocus && atBottomState) tryAutoMarkAsRead();
},
- [tryAutoMarkAsRead]
+ [tryAutoMarkAsRead, atBottomState]
)
);
- // Handle up arrow edit
- 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]
- )
- );
-
- // Keep a stable ref so timeline state updates (new messages arriving) don't
- // cause handleOpenEvent to rebuild and re-trigger this effect, yanking the
- // user back to the notification event on every incoming message.
- // We only want to scroll once per unique eventId value.
- const handleOpenEventRef = useRef(handleOpenEvent);
- handleOpenEventRef.current = handleOpenEvent;
-
useEffect(() => {
- if (eventId) {
- handleOpenEventRef.current(eventId);
- }
- }, [eventId]); // handleOpenEvent intentionally omitted — use ref above
+ if (atBottomState && document.hasFocus() && timelineSync.liveTimelineLinked)
+ tryAutoMarkAsRead();
+ }, [
+ atBottomState,
+ timelineSync.liveTimelineLinked,
+ tryAutoMarkAsRead,
+ timelineSync.eventsLength,
+ ]);
- // Scroll to bottom on initial timeline load
- useLayoutEffect(() => {
- const scrollEl = scrollRef.current;
- if (scrollEl) {
- const preScrollTop = scrollEl.scrollTop;
- const preScrollHeight = scrollEl.scrollHeight;
- const { clientHeight } = scrollEl;
- scrollToBottom(scrollEl);
- // Log whether we were actually away from bottom at mount — useful for diagnosing
- // rooms that open with the wrong scroll position.
- const distanceFromBottom = preScrollHeight - preScrollTop - clientHeight;
- debugLog.debug('timeline', 'Initial scroll to bottom (mount)', {
- preScrollTop,
- preScrollHeight,
- clientHeight,
- postScrollTop: scrollEl.scrollTop,
- distanceFromBottom,
- alreadyAtBottom: distanceFromBottom <= 2,
- });
- if (distanceFromBottom > 0) {
- Sentry.metrics.distribution('sable.timeline.initial_scroll_offset_px', distanceFromBottom);
+ const handleVListScroll = useCallback(
+ (offset: number) => {
+ const v = vListRef.current;
+ if (!v) return;
+
+ const distanceFromBottom = v.scrollSize - offset - v.viewportSize;
+ const isNowAtBottom = distanceFromBottom < 100;
+ if (isNowAtBottom !== atBottomRef.current) {
+ setAtBottom(isNowAtBottom);
}
- }
- }, []);
- // Rescroll to bottom when images load at the start
- useEffect(() => {
- const scrollEl = scrollRef.current;
- const contentEl = scrollEl?.firstElementChild as HTMLElement;
- if (!scrollEl || !contentEl) return () => {};
-
- const forceScroll = () => {
- // if the user isn't scrolling jump down to latest content
- const wasAtBottom = atBottomRef.current;
- const preScrollTop = scrollEl?.scrollTop ?? 0;
- const preScrollHeight = scrollEl?.scrollHeight ?? 0;
- // Log every resize so we can see when media loads move the timeline and whether
- // we corrected it (atBottom=true) or left it (atBottom=false, user is scrolled up).
- debugLog.debug('timeline', 'Content resized (image/media load)', {
- atBottom: wasAtBottom,
- preScrollTop,
- preScrollHeight,
- clientHeight: scrollEl?.clientHeight,
- distanceFromBottom: preScrollHeight - preScrollTop - (scrollEl?.clientHeight ?? 0),
- });
- if (!wasAtBottom) return;
- scrollToBottom(scrollEl, 'instant');
- };
-
- const resizeObserver = new ResizeObserver(() => {
- requestAnimationFrame(forceScroll);
- });
-
- resizeObserver.observe(contentEl);
-
- return () => {
- resizeObserver.disconnect();
- };
- }, [room]);
-
- // if live timeline is linked and unreadInfo change
- // Scroll to last read message
- 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,
- });
+ if (offset < 500 && canPaginateBackRef.current && backwardStatusRef.current === 'idle') {
+ timelineSyncRef.current.handleTimelinePagination(true);
}
- }
- }, [room, unreadInfo, scrollToItem]);
-
- // scroll to focused message
- useLayoutEffect(() => {
- if (focusItem?.scrollTo) {
- scrollToItem(focusItem.index, {
- behavior: 'instant',
- align: 'center',
- stopInView: true,
- });
- }
-
- setTimeout(() => {
- if (!alive()) return;
- setFocusItem((currentItem) => {
- if (currentItem === focusItem) return undefined;
- return currentItem;
- });
- }, 2000);
- }, [alive, focusItem, scrollToItem]);
-
- // scroll to bottom of timeline
- const scrollToBottomCount = scrollToBottomRef.current.count;
- useLayoutEffect(() => {
- if (scrollToBottomCount > 0) {
- const scrollEl = scrollRef.current;
- if (scrollEl) {
- const behavior = scrollToBottomRef.current.smooth && !reducedMotion ? 'smooth' : 'instant';
- const wasAtBottom = atBottomRef.current;
- Sentry.addBreadcrumb({
- category: 'ui.scroll',
- message: 'Timeline: scroll-to-bottom triggered',
- level: 'info',
- data: { roomId: room.roomId, behavior, wasAtBottom },
- });
- // A scroll-to-bottom while the user was NOT at the bottom and no timeline
- // reset is expected is a sign of an unexpected scroll jump.
- if (!wasAtBottom && !timelineJustResetRef.current) {
- Sentry.captureMessage('Timeline: scroll-to-bottom fired while user was scrolled up', {
- level: 'warning',
- extra: { roomId: room.roomId, behavior },
- tags: { feature: 'timeline' },
- });
- }
- // Use requestAnimationFrame to ensure the virtual paginator has finished
- // updating the DOM before we scroll. This prevents scroll position from
- // being stale when new messages arrive while at the bottom.
- requestAnimationFrame(() => {
- const preScrollTop = scrollEl.scrollTop;
- const { scrollHeight } = scrollEl;
- scrollToBottom(scrollEl, behavior);
- debugLog.debug('timeline', 'scrollToBottom fired', {
- behavior,
- preScrollTop,
- scrollHeight,
- postScrollTop: scrollEl.scrollTop,
- remainingOffset: scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight,
- });
- // On Android WebView, layout may still settle after the initial scroll.
- // Fire a second instant scroll after a short delay to guarantee we
- // reach the true bottom (e.g. after images finish loading or the
- // virtual keyboard shifts the viewport).
- if (behavior === 'instant') {
- setTimeout(() => {
- scrollToBottom(scrollEl, 'instant');
- }, 80);
- }
- });
+ if (
+ distanceFromBottom < 500 &&
+ !liveTimelineLinkedRef.current &&
+ forwardStatusRef.current === 'idle'
+ ) {
+ timelineSyncRef.current.handleTimelinePagination(false);
}
- }
- }, [scrollToBottomCount, reducedMotion, room.roomId]);
-
- // Remove unreadInfo on mark as read
- useEffect(() => {
- if (!unread) {
- setUnreadInfo(undefined);
- }
- }, [unread]);
-
- // scroll out of view msg editor in view.
- 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]
+ [setAtBottom]
);
- 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,
- }
- );
- },
- [room, space, openUserRoomProfile, globalProfiles]
- );
-
- 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 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) {
- if (typeof body === 'string') {
- setReplyDraft({
- userId: senderId,
- eventId: replyId,
- body,
- formattedBody,
- relation,
- });
- } else {
- setReplyDraft({
- userId: senderId,
- eventId: replyId,
- body: '',
- 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) {
- // Create thread if it doesn't exist, then open the thread drawer
- const rootEvent = room.findEventById(replyId);
- if (rootEvent && !room.getThread(replyId)) {
- room.createThread(replyId, rootEvent, [], false);
- }
- setOpenThread(openThreadId === replyId ? undefined : replyId);
- return;
- }
- triggerReply(replyId, false);
- },
- [triggerReply, setReplyDraft, setOpenThread, openThreadId, room]
- );
-
- const handleReactionToggle = useCallback(
- (targetEventId: string, key: string, shortcode?: string) => {
- debugLog.info('ui', 'Reaction toggled', { roomId: room.roomId, targetEventId, key });
- Sentry.metrics.count('sable.message.reaction.toggle', 1);
- 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'];
- // If makeReplaced was called with a stripped edit (no m.new_content),
- // mEvent.getContent() returns {}. Fall back to getOriginalContent() so
- // the message renders with its original content instead of breaking.
- 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;
-
- // determine if message is forwarded by checking for the presence of the 'moe.sable.message.forward' key in the event content
- 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 = (
-
- );
-
- return (
-
-
-
- {parsed.body}
-
-
- }
- />
-
- );
- },
- [StateEvent.RoomName]: (mEventId, mEvent, item) => {
- const highlighted = focusItem?.index === item && focusItem.highlight;
- const senderId = mEvent.getSender() ?? '';
- const senderName =
- getMemberDisplayName(room, senderId, nicknames) || getMxIdLocalPart(senderId);
-
- const timeJSX = (
-
- );
-
- return (
-
-
-
- {senderName}
- {t('Organisms.RoomCommon.changed_room_name')}
-
-
- }
- />
-
- );
- },
- [StateEvent.RoomTopic]: (mEventId, mEvent, item) => {
- const highlighted = focusItem?.index === item && focusItem.highlight;
- const senderId = mEvent.getSender() ?? '';
- const senderName =
- getMemberDisplayName(room, senderId, nicknames) || getMxIdLocalPart(senderId);
-
- const timeJSX = (
-
- );
-
- return (
-
-
-
- {senderName}
- {' changed room topic'}
-
-
- }
- />
-
- );
- },
- [StateEvent.RoomAvatar]: (mEventId, mEvent, item) => {
- const highlighted = focusItem?.index === item && focusItem.highlight;
- const senderId = mEvent.getSender() ?? '';
- const senderName =
- getMemberDisplayName(room, senderId, nicknames) || getMxIdLocalPart(senderId);
-
- const timeJSX = (
-
- );
-
- return (
-
-
-
- {senderName}
- {' changed room avatar'}
-
-
- }
- />
-
- );
- },
- [StateEvent.GroupCallMemberPrefix]: (mEventId, mEvent, item) => {
- const highlighted = focusItem?.index === item && focusItem.highlight;
- const senderId = mEvent.getSender() ?? '';
- const senderName = getMemberDisplayName(room, senderId) || getMxIdLocalPart(senderId);
-
- const content = mEvent.getContent();
- const prevContent = mEvent.getPrevContent();
-
- const callJoined = content.application;
- if (callJoined && 'application' in prevContent) {
- return null;
- }
-
- const timeJSX = (
-
- );
-
- return (
-
-
-
- {senderName}
- {callJoined ? ' joined the call' : ' ended the call'}
-
-
- }
- />
-
- );
- },
- },
- (mEventId, mEvent, item) => {
- if (!showHiddenEvents) return null;
- const highlighted = focusItem?.index === item && focusItem.highlight;
- const senderId = mEvent.getSender() ?? '';
- const senderName =
- getMemberDisplayName(room, senderId, nicknames) || getMxIdLocalPart(senderId);
-
- const timeJSX = (
-
- );
-
- return (
-
-
-
- {senderName}
- {' sent '}
- {mEvent.getType()}
- {' state event'}
-
-
- }
- />
-
- );
- },
- (mEventId, mEvent, item) => {
- if (!showHiddenEvents) return null;
- if (Object.keys(mEvent.getContent()).length === 0) return null;
- if (mEvent.getRelation()) return null;
- if (mEvent.isRedaction()) return null;
-
- const highlighted = focusItem?.index === item && focusItem.highlight;
- const senderId = mEvent.getSender() ?? '';
- const senderName =
- getMemberDisplayName(room, senderId, nicknames) || getMxIdLocalPart(senderId);
-
- const timeJSX = (
-
- );
-
- return (
-
-
-
- {senderName}
- {' sent '}
- {mEvent.getType()}
- {' event'}
-
-
- }
- />
-
- );
- }
- );
-
- let prevEvent: MatrixEvent | undefined;
- let isPrevRendered = false;
- let newDivider = false;
- let dayDivider = false;
- const timelineItems = getItems();
- const eventRenderer = (item: number) => {
- const [eventTimeline, baseIndex] = getTimelineAndBaseIndex(timeline.linkedTimelines, item);
- if (!eventTimeline) return null;
- const timelineSet = eventTimeline?.getTimelineSet();
- const mEvent = getTimelineEvent(eventTimeline, getTimelineRelativeIndex(item, baseIndex));
- const mEventId = mEvent?.getId();
-
- if (!mEvent || !mEventId) return null;
-
- const eventSender = mEvent.getSender();
- if (eventSender && ignoredUsersSet.has(eventSender)) {
- return null;
- }
- if (mEvent.isRedacted() && !(showHiddenEvents || showTombstoneEvents)) {
- return null;
- }
-
- if (!newDivider && readUptoEventIdRef.current) {
- newDivider = prevEvent?.getId() === readUptoEventIdRef.current;
- }
- if (!dayDivider) {
- dayDivider = prevEvent ? !inSameDay(prevEvent.getTs(), mEvent.getTs()) : false;
- }
-
- const collapsed =
- isPrevRendered &&
- !dayDivider &&
- (!newDivider || eventSender === mx.getUserId()) &&
- prevEvent !== undefined &&
- prevEvent.getSender() === eventSender &&
- prevEvent.getType() === mEvent.getType() &&
- minuteDifference(prevEvent.getTs(), mEvent.getTs()) < 2;
-
- // Thread REPLIES belong only in the thread timeline; filter them from the
- // main room timeline. Keep thread ROOT events (threadRootId === their own
- // event ID) so they remain visible with the ThreadReplyChip attached.
- if (mEvent.threadRootId !== undefined && mEvent.threadRootId !== mEventId) return null;
-
- const eventJSX = reactionOrEditEvent(mEvent)
- ? null
- : renderMatrixEvent(
- mEvent.getType(),
- typeof mEvent.getStateKey() === 'string',
- mEventId,
- mEvent,
- item,
- timelineSet,
- collapsed
- );
- prevEvent = mEvent;
- isPrevRendered = !!eventJSX;
-
- const newDividerJSX =
- newDivider && eventJSX && eventSender !== mx.getUserId() ? (
-
-
-
- New Messages
-
-
-
- ) : null;
-
- const dayDividerJSX =
- dayDivider && eventJSX ? (
-
-
-
-
- {(() => {
- if (today(mEvent.getTs())) return 'Today';
- if (yesterday(mEvent.getTs())) return 'Yesterday';
- return timeDayMonthYear(mEvent.getTs());
- })()}
-
-
-
-
- ) : null;
-
- if (eventJSX && (newDividerJSX || dayDividerJSX)) {
- if (newDividerJSX) newDivider = false;
- if (dayDividerJSX) dayDivider = false;
-
- return (
-
- {newDividerJSX}
- {dayDividerJSX}
- {eventJSX}
-
- );
- }
-
- return eventJSX;
- };
+ const showLoadingPlaceholders =
+ timelineSync.eventsLength === 0 &&
+ (timelineSync.canPaginateBack || timelineSync.backwardStatus === 'loading');
let backPaginationJSX: ReactNode | undefined;
- if (canPaginateBack || !rangeAtStart || backwardStatus !== 'idle') {
- if (backwardStatus === 'error') {
+ if (timelineSync.canPaginateBack || timelineSync.backwardStatus !== 'idle') {
+ if (timelineSync.backwardStatus === 'error') {
backPaginationJSX = (
handleTimelinePagination(true)}
+ onClick={() => timelineSync.handleTimelinePagination(true)}
>
Retry
);
- } else if (backwardStatus === 'loading' && timelineItems.length > 0) {
+ } else if (timelineSync.backwardStatus === 'loading' && timelineSync.eventsLength > 0) {
backPaginationJSX = (
);
- } else if (timelineItems.length === 0) {
- // When eventsLength===0 AND liveTimelineLinked the live EventTimeline was
- // just reset by a sliding sync TimelineRefresh and new events haven't
- // arrived yet. Attaching the IntersectionObserver anchor here would
- // immediately fire a server-side /messages request before current events
- // land — potentially causing a "/messages hangs → spinner stuck" scenario.
- // Suppressing the anchor for this transient state is safe: the rangeAtEnd
- // self-heal useEffect will call getInitialTimeline once events arrive, and
- // at that point the correct anchor (below) will be re-observed.
- // eventsLength>0 covers the range={K,K} case from recalibratePagination
- // where items=0 but events exist — that needs the anchor for local range
- // extension (no server call since start>0).
- const placeholderBackAnchor =
- eventsLength > 0 || !liveTimelineLinked ? observeBackAnchor : undefined;
- backPaginationJSX =
- messageLayout === MessageLayout.Compact ? (
- <>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- >
- ) : (
- <>
-
-
-
-
-
-
-
-
-
- >
- );
- } else {
- backPaginationJSX = ;
}
}
let frontPaginationJSX: ReactNode | undefined;
- if (!liveTimelineLinked || !rangeAtEnd || forwardStatus !== 'idle') {
- if (forwardStatus === 'error') {
+ if (!timelineSync.liveTimelineLinked || timelineSync.forwardStatus !== 'idle') {
+ if (timelineSync.forwardStatus === 'error') {
frontPaginationJSX = (
handleTimelinePagination(false)}
+ onClick={() => timelineSync.handleTimelinePagination(false)}
>
Retry
);
- } else if (forwardStatus === 'loading' && timelineItems.length > 0) {
+ } else if (timelineSync.forwardStatus === 'loading' && timelineSync.eventsLength > 0) {
frontPaginationJSX = (
);
- } else if (timelineItems.length === 0) {
- frontPaginationJSX =
- messageLayout === MessageLayout.Compact ? (
- <>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- >
- ) : (
- <>
-
-
-
-
-
-
-
-
-
- >
- );
- } else {
- frontPaginationJSX = ;
}
}
+ const vListItemCount =
+ timelineSync.eventsLength === 0 &&
+ (timelineSync.canPaginateBack || timelineSync.backwardStatus === 'loading')
+ ? 3
+ : timelineSync.eventsLength;
+ const vListIndices = useMemo(
+ () => Array.from({ length: vListItemCount }, (_, i) => i),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [vListItemCount, timelineSync.timeline]
+ );
+
+ const processedEvents = useProcessedTimeline({
+ items: vListIndices,
+ linkedTimelines: timelineSync.timeline.linkedTimelines,
+ ignoredUsersSet,
+ showHiddenEvents,
+ showTombstoneEvents,
+ mxUserId: mx.getUserId(),
+ readUptoEventId: readUptoEventIdRef.current,
+ hideMembershipEvents,
+ hideNickAvatarEvents,
+ isReadOnly,
+ hideMemberInReadOnly,
+ });
+
+ processedEventsRef.current = processedEvents;
+
+ useEffect(() => {
+ if (!onEditLastMessageRef) return;
+ const ref = onEditLastMessageRef;
+ ref.current = () => {
+ const myUserId = mx.getUserId();
+ const found = [...processedEventsRef.current]
+ .reverse()
+ .find(
+ (e) =>
+ e.mEvent.getSender() === myUserId &&
+ e.mEvent.getType() === 'm.room.message' &&
+ !e.mEvent.isRedacted()
+ );
+ if (found?.mEvent.getId()) actions.handleEdit(found.mEvent.getId());
+ };
+ }, [onEditLastMessageRef, mx, actions]);
+
+ useEffect(() => {
+ const v = vListRef.current;
+ if (!v) return;
+ if (
+ canPaginateBackRef.current &&
+ backwardStatusRef.current === 'idle' &&
+ v.scrollSize <= v.viewportSize
+ ) {
+ timelineSyncRef.current.handleTimelinePagination(true);
+ }
+ }, [timelineSync.eventsLength, timelineSync.backwardStatus]);
+
+ useEffect(() => {
+ if (!canPaginateBackRef.current) return () => {};
+
+ let rafId: number;
+ let attempts = 0;
+ const MAX_ATTEMPTS = 20;
+ const processedLengthAtEffectStart = processedEvents.length;
+
+ const check = () => {
+ const v = vListRef.current;
+ if (!v) return;
+
+ if (v.viewportSize === 0) {
+ attempts += 1;
+ if (attempts <= MAX_ATTEMPTS) rafId = requestAnimationFrame(check);
+ return;
+ }
+
+ if (!canPaginateBackRef.current) return;
+ if (backwardStatusRef.current !== 'idle') return;
+
+ const atTop = v.scrollOffset < 500;
+ const noVisibleGrowth = processedEvents.length === processedLengthAtEffectStart;
+ const hasRealScrollRoom = v.scrollSize > v.viewportSize + 300;
+
+ if (!hasRealScrollRoom || (atTop && noVisibleGrowth)) {
+ timelineSyncRef.current.handleTimelinePagination(true);
+ }
+ };
+
+ rafId = requestAnimationFrame(check);
+ return () => cancelAnimationFrame(rafId);
+ }, [timelineSync.eventsLength, timelineSync.backwardStatus, processedEvents.length]);
+
return (
- {unreadInfo?.readUptoEventId && !unreadInfo?.inLiveTimeline && (
+ {unreadInfo?.readUptoEventId && !unreadInfo?.inLiveTimeline && isReady && (
}
- onClick={handleJumpToUnread}
+ onClick={() => timelineSync.loadEventTimeline(unreadInfo.readUptoEventId)}
>
Jump to Unread
-
}
- onClick={handleMarkAsRead}
+ onClick={() => markAsRead(mx, room.roomId, hideReads)}
>
Mark as Read
)}
-
-
+
+ ref={vListRef}
+ data={processedEvents}
+ shift={shift}
className={css.messageList}
- direction="Column"
- justifyContent="End"
- style={{ minHeight: '100%', padding: `${config.space.S600} 0` }}
+ style={{
+ flex: 1,
+ minHeight: 0,
+ display: 'flex',
+ flexDirection: 'column',
+ paddingTop: topSpacerHeight > 0 ? topSpacerHeight : config.space.S600,
+ paddingBottom: config.space.S600,
+ }}
+ onScroll={handleVListScroll}
>
- {!canPaginateBack && rangeAtStart && getItems().length > 0 && (
-
-
-
- )}
- {backPaginationJSX}
+ {(eventData, index) => {
+ if (showLoadingPlaceholders) {
+ return (
+
+ {messageLayout === MessageLayout.Compact ? (
+
+ ) : (
+
+ )}
+
+ );
+ }
- {timelineItems.map(eventRenderer)}
+ if (!eventData) {
+ if (index === 0 && !timelineSync.canPaginateBack) {
+ return (
+
+ {backPaginationJSX}
+
+
+
+
+ );
+ }
+ if (index === 0) return {backPaginationJSX};
+ return ;
+ }
- {frontPaginationJSX}
-
-
-
- {(!atBottom || !(liveTimelineLinked && rangeAtEnd)) && (
+ const renderedEvent = renderMatrixEvent(
+ eventData.mEvent.getType(),
+ typeof eventData.mEvent.getStateKey() === 'string',
+ eventData.id,
+ eventData.mEvent,
+ eventData.itemIndex,
+ eventData.timelineSet,
+ eventData.collapsed
+ );
+
+ const dividers = (
+ <>
+ {eventData.willRenderDayDivider && (
+
+
+
+ {getDayDividerText(eventData.mEvent.getTs())}
+
+
+
+ )}
+ {eventData.willRenderNewDivider && (
+
+
+
+ New Messages
+
+
+
+ )}
+ >
+ );
+
+ if (index === 0) {
+ return (
+
+ {!timelineSync.canPaginateBack && (
+
+
+
+ )}
+ {backPaginationJSX}
+ {dividers}
+ {renderedEvent}
+
+ );
+ }
+
+ return (
+
+ {dividers}
+ {renderedEvent}
+
+ );
+ }}
+
+