fix(timeline): pin to the true bottom, size images to their frame, and rebuild rows on mid-timeline inserts (#1426)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-07-27 19:29:33 +00:00
commit 4c8f39bada
4 files changed
+194 -32

No files matched your search

@@ -451,6 +451,8 @@ export function MImage({ content, renderImageContent, outlined, fitParent }: MIm
// lazy approach to make sure that both horizontal and vertical images fit
// checks whether the image has width and height and if it does it sets a width that matches the aspect ratio
const hasIntrinsicSize =
isNumber(imgInfo?.w) && imgInfo.w > 0 && isNumber(imgInfo?.h) && imgInfo.h > 0;
const portraitWidth =
!imgInfo || !imgInfo.w || !imgInfo.h || imgInfo.w > imgInfo.h
? undefined
@@ -462,10 +464,13 @@ export function MImage({ content, renderImageContent, outlined, fitParent }: MIm
flexShrink: 0,
width: fitParent ? '100%' : portraitWidth,
height: fitParent ? '100%' : undefined,
maxWidth: fitParent ? undefined : toRem(MAX_SIZE),
// A bare MAX_SIZE cap would drop the container's own `max-width: 100%`.
maxWidth: fitParent ? undefined : `min(100%, ${toRem(MAX_SIZE)})`,
maxHeight: fitParent ? undefined : toRem(MAX_SIZE),
minWidth: fitParent ? undefined : MIN_SIZE,
minHeight: fitParent ? undefined : MIN_SIZE,
// ImageContent's aspect-ratio box already reserves the space when the
// dimensions are known; a square floor on top of it letterboxes wide images.
minWidth: fitParent || hasIntrinsicSize ? undefined : MIN_SIZE,
minHeight: fitParent || hasIntrinsicSize ? undefined : MIN_SIZE,
}}
outlined={outlined}
>
+51 -20
View File
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react';
import * as Sentry from '@sentry/react';
import {
Fragment,
useCallback,
@@ -282,6 +283,8 @@ const MemoizedTimelineItem = memo(
return (
prev.eventData.id === next.eventData.id &&
// A filtered mid-timeline insert shifts this without changing `index`.
prev.eventData.itemIndex === next.eventData.itemIndex &&
prev.eventData.collapsed === next.eventData.collapsed &&
prev.eventData.willRenderNewDivider === next.eventData.willRenderNewDivider &&
prev.eventData.willRenderDayDivider === next.eventData.willRenderDayDivider &&
@@ -444,19 +447,45 @@ export function RoomTimeline({
const processedEventsRef = useRef<ProcessedEvent[]>([]);
const timelineSyncRef = useRef<typeof timelineSync>(null as unknown as typeof timelineSync);
// VList owns the scroll container and renders it as the wrapper's only child.
const scrollElRef = useRef<HTMLElement | null>(null);
const scrollToBottom = useCallback(
(behavior: 'instant' | 'smooth' = 'instant') => {
if (!vListRef.current) return;
const v = vListRef.current;
const lastIndex = processedEventsRef.current.length - 1;
if (lastIndex < 0) return;
vListRef.current.scrollToIndex(lastIndex, {
if (!v || lastIndex < 0) return;
// virtua aims at the last row's end from its cached item sizes, which
// under-report while a just-grown row is still being measured, landing above
// the real bottom. Overshoot by the shortfall; the browser clamps it.
const scrollEl = scrollElRef.current;
let offset = 0;
if (scrollEl) {
const target = v.getItemOffset(lastIndex) + v.getItemSize(lastIndex) - v.viewportSize;
offset = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight - target);
}
v.scrollToIndex(lastIndex, {
align: 'end',
offset,
smooth: behavior === 'smooth' && !reducedMotion,
});
},
[reducedMotion]
);
useLayoutEffect(() => {
const scrollEl = messageListRef.current?.firstElementChild;
scrollElRef.current = scrollEl instanceof HTMLElement ? scrollEl : null;
if (!scrollElRef.current) {
Sentry.captureMessage('Timeline: could not resolve the VList scroll container', {
level: 'warning',
tags: { feature: 'timeline' },
});
}
}, []);
// A jump target is by definition not the bottom. Clear the flag synchronously,
// before the async load resolves: the growth-follow is a useLayoutEffect, so it
// runs before any passive effect on the render that first paints the new rows.
@@ -605,14 +634,14 @@ export function RoomTimeline({
timelineSync.liveTimelineLinked &&
vListRef.current
) {
vListRef.current.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
scrollToBottom();
// Store in a ref rather than a local so subsequent eventsLength changes
// (e.g. the onLifecycle timeline reset firing within 80 ms) do NOT
// cancel this timer through the useLayoutEffect cleanup.
initialScrollTimerRef.current = setTimeout(() => {
initialScrollTimerRef.current = undefined;
if (processedEventsRef.current.length > 0) {
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
scrollToBottom();
// Only mark ready once we've successfully scrolled. If processedEvents
// was empty when the timer fired (e.g. the onLifecycle reset cleared the
// timeline within the 80 ms window), defer setIsReady until the recovery
@@ -626,7 +655,13 @@ export function RoomTimeline({
}
// No cleanup return — the timer must survive eventsLength fluctuations.
// It is cancelled on unmount by the dedicated effect below.
}, [timelineSync.eventsLength, timelineSync.liveTimelineLinked, eventId, room.roomId]);
}, [
timelineSync.eventsLength,
timelineSync.liveTimelineLinked,
eventId,
room.roomId,
scrollToBottom,
]);
// Cancel the initial-scroll timer on unmount (the useLayoutEffect above
// intentionally does not cancel it when deps change).
@@ -658,12 +693,10 @@ export function RoomTimeline({
topSpacerHeightRef.current = newH;
setTopSpacerHeight(newH);
if (prev > 0 && newH === 0 && processedEventsRef.current.length > 0) {
requestAnimationFrame(() => {
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
});
requestAnimationFrame(() => scrollToBottom());
}
}
}, []);
}, [scrollToBottom]);
useLayoutEffect(() => {
const id = requestAnimationFrame(recalcTopSpacer);
@@ -682,10 +715,10 @@ export function RoomTimeline({
} else if (prev === 'loading' && timelineSync.backwardStatus === 'idle') {
setShift(false);
if (wasAtBottomBeforePaginationRef.current) {
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
scrollToBottom();
}
}
}, [timelineSync.backwardStatus]);
}, [timelineSync.backwardStatus, scrollToBottom]);
useEffect(() => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
@@ -769,10 +802,9 @@ export function RoomTimeline({
prevViewportHeightRef.current = newHeight;
const lastIndex = processedEventsRef.current.length - 1;
if (shrank && atBottom && lastIndex >= 0) {
if (shrank && atBottom && processedEventsRef.current.length > 0) {
// Geometry is still pre-scroll here; the repin's own scroll event resyncs.
vListRef.current?.scrollToIndex(lastIndex, { align: 'end' });
scrollToBottom();
return;
}
syncAtBottom();
@@ -780,7 +812,7 @@ export function RoomTimeline({
observer.observe(el);
return () => observer.disconnect();
}, [syncAtBottom]);
}, [syncAtBottom, scrollToBottom]);
// Decrypting rows and late-loading images grow without changing eventsLength,
// so useTimelineSync's auto-scroll never re-fires for them.
@@ -794,8 +826,7 @@ export function RoomTimeline({
if (!grew || !atBottomRef.current || !liveTimelineLinkedRef.current) return;
const lastIndex = processedEventsRef.current.length - 1;
if (lastIndex >= 0) v.scrollToIndex(lastIndex, { align: 'end' });
scrollToBottom();
});
const actions = useTimelineActions({
@@ -1054,9 +1085,9 @@ export function RoomTimeline({
if (!pendingReadyRef.current) return;
if (processedEvents.length === 0) return;
pendingReadyRef.current = false;
vListRef.current?.scrollToIndex(processedEvents.length - 1, { align: 'end' });
scrollToBottom();
setIsReady(true);
}, [processedEvents.length]);
}, [processedEvents.length, scrollToBottom]);
useEffect(() => {
if (!onEditLastMessageRef) return;
@@ -1,6 +1,8 @@
import { renderHook } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { M_POLL_RESPONSE } from 'matrix-js-sdk';
import type { EventTimeline, EventTimelineSet, MatrixEvent } from '$types/matrix-sdk';
import { EventType, RelationType } from '$types/matrix-sdk';
import type { ResolvedHiddenEventSettings } from '$state/hooks/settings';
import type { ProcessedEvent } from './useProcessedTimeline';
import {
@@ -32,17 +34,19 @@ type FakeEventOptions = {
relation?: { rel_type: string; event_id: string; key?: string };
threadRootId?: string;
ts?: number;
isRedaction?: boolean;
};
function createEvent({
id,
type = 'm.room.message',
type = EventType.RoomMessage as string,
sender = OTHER_USER,
content = { msgtype: 'm.text', body: 'hello' },
prevContent = {},
relation,
threadRootId,
ts = 1_000_000,
isRedaction = false,
}: FakeEventOptions): MatrixEvent {
return {
getId: () => id,
@@ -53,7 +57,7 @@ function createEvent({
getWireContent: () => content,
getTs: () => ts,
isRedacted: () => false,
isRedaction: () => false,
isRedaction: () => isRedaction,
isEncrypted: () => false,
getRelation: () => relation ?? null,
threadRootId,
@@ -61,17 +65,17 @@ function createEvent({
}
function createReaction(id: string, targetId: string): MatrixEvent {
const relation = { rel_type: 'm.annotation', event_id: targetId, key: '👍' };
const relation = { rel_type: RelationType.Annotation, event_id: targetId, key: '👍' };
return createEvent({
id,
type: 'm.reaction',
type: EventType.Reaction,
content: { 'm.relates_to': relation },
relation,
});
}
function createEdit(id: string, targetId: string): MatrixEvent {
const relation = { rel_type: 'm.replace', event_id: targetId };
const relation = { rel_type: RelationType.Replace, event_id: targetId };
return createEvent({
id,
content: {
@@ -85,7 +89,7 @@ function createEdit(id: string, targetId: string): MatrixEvent {
}
function createThreadReply(id: string, rootId: string): MatrixEvent {
const relation = { rel_type: 'm.thread', event_id: rootId };
const relation = { rel_type: RelationType.Thread, event_id: rootId };
return createEvent({
id,
content: { msgtype: 'm.text', body: 'thread reply', 'm.relates_to': relation },
@@ -94,10 +98,29 @@ function createThreadReply(id: string, rootId: string): MatrixEvent {
});
}
function createPollResponse(id: string, pollStartId: string): MatrixEvent {
const relation = { rel_type: RelationType.Reference, event_id: pollStartId };
return createEvent({
id,
type: M_POLL_RESPONSE.name,
content: { 'm.relates_to': relation },
relation,
});
}
function createRedaction(id: string, targetId: string): MatrixEvent {
return createEvent({
id,
type: EventType.RoomRedaction,
content: { redacts: targetId },
isRedaction: true,
});
}
function createMembership(id: string): MatrixEvent {
return createEvent({
id,
type: 'm.room.member',
type: EventType.RoomMember,
content: { membership: 'join' },
});
}
@@ -189,6 +212,41 @@ describe('useProcessedTimeline new-messages divider', () => {
expect(result.current[2]).toMatchObject({ id: '$c', collapsed: true });
});
it('rebuilds rows when an event lands mid-prefix instead of being appended', () => {
const events = [
createEvent({ id: '$a', ts: 1_000_000 }),
createEvent({ id: '$b', ts: 1_000_500 }),
createEvent({ id: '$c', ts: 1_001_000 }),
];
const timeline = createTimeline(events);
const ignoredUsersSet = new Set<string>();
const { result, rerender } = renderHook(
({ count }: { count: number }) =>
useProcessedTimeline({
items: Array.from({ length: count }, (_, index) => index),
linkedTimelines: [timeline],
ignoredUsersSet,
hiddenEvents,
mxUserId: MY_USER,
readUptoEventId: undefined,
hideMembershipEvents: true,
hideNickAvatarEvents: true,
isReadOnly: false,
hideMemberInReadOnly: false,
}),
{ initialProps: { count: events.length } }
);
// Both anchors — the first event and the one at the old last index — survive,
// so only a full prefix check can tell this from an append.
events.splice(1, 1, createEvent({ id: '$mid', ts: 1_000_200 }));
events.push(createEvent({ id: '$d', ts: 1_001_500 }));
rerender({ count: events.length });
expect(renderedIds(result.current)).toEqual(['$a', '$mid', '$c', '$d']);
expect(result.current.map((e) => e.itemIndex)).toEqual([0, 1, 2, 3]);
});
it('rebuilds relation state when an appended event can change an existing row', () => {
const events = [createEvent({ id: '$a' }), createEvent({ id: '$b' })];
const timeline = createTimeline(events);
@@ -329,6 +387,71 @@ describe('useProcessedTimeline new-messages divider', () => {
});
});
describe('useProcessedTimeline append-only fast path', () => {
function appendToTimeline(initial: MatrixEvent[], appended: MatrixEvent) {
const events = [...initial];
const timeline = createTimeline(events);
const ignoredUsersSet = new Set<string>();
const { result, rerender } = renderHook(
({ count }: { count: number }) =>
useProcessedTimeline({
items: Array.from({ length: count }, (_, index) => index),
linkedTimelines: [timeline],
ignoredUsersSet,
hiddenEvents,
mxUserId: MY_USER,
readUptoEventId: undefined,
hideMembershipEvents: true,
hideNickAvatarEvents: true,
isReadOnly: false,
hideMemberInReadOnly: false,
}),
{ initialProps: { count: events.length } }
);
const before = [...result.current];
events.push(appended);
rerender({ count: events.length });
return { before, after: result.current };
}
// Every relation type can retarget an event already in the cached prefix.
it.each([
['an edit', () => createEdit('$new', '$a')],
['a reaction', () => createReaction('$new', '$a')],
['a thread reply', () => createThreadReply('$new', '$a')],
['a poll response', () => createPollResponse('$new', '$a')],
['a redaction', () => createRedaction('$new', '$a')],
])('reprocesses the cached prefix when %s arrives', (_label, makeEvent) => {
const { before, after } = appendToTimeline(
[createEvent({ id: '$a' }), createEvent({ id: '$b' })],
makeEvent()
);
expect(after[0]).not.toBe(before[0]);
expect(after[1]).not.toBe(before[1]);
});
it.each([
['a message', () => createEvent({ id: '$new', ts: 1_000_001 })],
['a membership change', () => createMembership('$new')],
['a sticker', () => createEvent({ id: '$new', type: EventType.Sticker, ts: 1_000_001 })],
[
'a room name change',
() => createEvent({ id: '$new', type: EventType.RoomName, ts: 1_000_001 }),
],
])('reuses the cached prefix when %s arrives', (_label, makeEvent) => {
const { before, after } = appendToTimeline(
[createEvent({ id: '$a' }), createEvent({ id: '$b' })],
makeEvent()
);
expect(after[0]).toBe(before[0]);
expect(after[1]).toBe(before[1]);
});
});
describe('getProcessedRowIndexForRawTimelineIndex', () => {
it('finds the nearest preceding visible row in one pass', () => {
const processed = processTimeline(
@@ -633,8 +633,11 @@ export function useProcessedTimeline({
previous.itemsLength === previous.timelineEvents.length &&
items.length > previous.itemsLength &&
items.every((item, index) => item === index) &&
previous.timelineEvents[0]?.mEvent === timelineEvents[0]?.mEvent &&
previous.timelineEvents.at(-1)?.mEvent === timelineEvents[previous.itemsLength - 1]?.mEvent &&
// Cached rows are reused verbatim, so anchoring on the first and last event
// alone would accept a run that both inserted and removed within the prefix.
previous.timelineEvents.every(
(entry, index) => entry.mEvent === timelineEvents[index]?.mEvent
) &&
(appendedEntries.length === 0 ||
(previous.timelineEvents.at(-1)?.mEvent.getTs() ?? 0) <=
(appendedEntries[0]?.getTs() ?? 0)) &&