fix(timeline): preserve permalink context during sync reset (#1743)

<!-- 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:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] 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:
Erwan Leboucher authored and GitHub committed 2026-08-13 01:45:36 +00:00
commit 938cb2482e
9 files changed
+515 -226

No files matched your search

+1 -1
View File
@@ -120,7 +120,7 @@
"slate-react": "^0.125.1",
"tauri-plugin-android-fs-api": "28.4.0",
"ua-parser-js": "^2.0.10",
"virtua": "^0.49.2",
"virtua": "^0.50.1",
"workbox-precaching": "^7.4.1"
},
"devDependencies": {
+5 -5
View File
@@ -260,8 +260,8 @@ importers:
specifier: ^2.0.10
version: 2.0.10
virtua:
specifier: ^0.49.2
version: 0.49.2([email protected]([email protected]))([email protected])
specifier: ^0.50.1
version: 0.50.1([email protected]([email protected]))([email protected])
workbox-precaching:
specifier: ^7.4.1
version: 7.4.1
@@ -5529,8 +5529,8 @@ packages:
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
hasBin: true
virtua@0.49.2:
resolution: {integrity: sha512-aEp3+6cmIRjHUlQnWdgGXYMYtrIG26QnN9jJDZEE5LRhvo1Z9HzoJwLDgyVULUPWcSdCnZAroQm7raXJyTG0AA==}
virtua@0.50.1:
resolution: {integrity: sha512-rNue/Cv/0Z14Yg9Pj6Xx9QaQPKhmlNWkx7Y7SytRnhojxvZ0z3GhCWr4QH2+tJm5mYL2vm4GudZPPt0i1PLzSA==}
peerDependencies:
react: '>=16.14.0'
react-dom: '>=16.14.0'
@@ -10965,7 +10965,7 @@ snapshots:
[email protected]: {}
virtua@0.49.2([email protected]([email protected]))([email protected]):
virtua@0.50.1([email protected]([email protected]))([email protected]):
optionalDependencies:
react: 18.3.1
react-dom: 18.3.1([email protected])
+118 -10
View File
@@ -42,7 +42,6 @@ const {
},
timelineSync: {
eventsLength: 1,
prependVersion: 0,
timeline: { linkedTimelines: [] },
liveTimelineLinked: true,
backwardStatus: 'idle',
@@ -391,7 +390,6 @@ beforeEach(() => {
vListProps.shift = false;
vListProps.shiftValues.length = 0;
timelineSync.eventsLength = 1;
timelineSync.prependVersion = 0;
timelineSync.focusItem = undefined;
timelineSync.canPaginateBack = false;
timelineSync.canPaginateForward = false;
@@ -456,6 +454,42 @@ describe('RoomTimeline content ResizeObserver', () => {
expect(vListHandle.scrollToIndex).not.toHaveBeenCalled();
});
it('cancels the delayed initial bottom scroll when the user scrolls up', async () => {
const { container } = renderTimeline();
vListHandle.scrollToIndex.mockClear();
act(() => {
getScrollEl(container).dispatchEvent(new Event('wheel', { bubbles: true }));
lastOnScroll?.(0);
});
await settleInitialScroll();
expect(vListHandle.scrollToIndex).not.toHaveBeenCalled();
});
it('does not cancel the delayed initial bottom scroll for a Virtua scroll callback', async () => {
renderTimeline();
vListHandle.scrollToIndex.mockClear();
act(() => lastOnScroll?.(0));
await settleInitialScroll();
expect(vListHandle.scrollToIndex).toHaveBeenCalled();
});
it('does not treat a pointer press as an initial timeline scroll', async () => {
const { container } = renderTimeline();
vListHandle.scrollToIndex.mockClear();
act(() => {
getScrollEl(container).dispatchEvent(new Event('pointerdown', { bubbles: true }));
lastOnScroll?.(0);
});
await settleInitialScroll();
expect(vListHandle.scrollToIndex).toHaveBeenCalled();
});
it('resolves a jump target by event id, not by raw timeline index', async () => {
timelineSync.liveTimelineLinked = false;
const { rerender } = renderTimeline();
@@ -538,24 +572,19 @@ describe('RoomTimeline content ResizeObserver', () => {
expect(getByText('Jump to Latest')).toBeTruthy();
});
it('keeps the jump target anchored across a prepend', async () => {
it('shifts the virtual list when rendered history prepends', async () => {
timelineSync.liveTimelineLinked = false;
const { rerender } = render(<RoomTimeline room={room} editor={{} as Editor} eventId="$evt1" />);
await settleInitialScroll();
vListHandle.scrollToIndex.mockClear();
timelineSync.focusItem = { eventId: '$evt1', scrollTo: false, highlight: true };
timelineSync.eventsLength = 2;
timelineSync.prependVersion = 1;
processedRowIds.current = ['$older', '$evt1'];
vListProps.shiftValues.length = 0;
rerender(<RoomTimeline room={room} editor={{} as Editor} eventId="$evt1" />);
expect(vListProps.shiftValues).toContain(true);
expect(vListHandle.scrollToIndex).toHaveBeenCalledWith(
0,
expect.objectContaining({ align: 'center' })
);
});
it('stops anchoring the jump target once the user scrolls', async () => {
@@ -572,12 +601,77 @@ describe('RoomTimeline content ResizeObserver', () => {
timelineSync.focusItem = { eventId: '$evt1', scrollTo: false, highlight: true };
timelineSync.eventsLength = 2;
timelineSync.prependVersion = 1;
rerender(<RoomTimeline room={room} editor={{} as Editor} eventId="$evt1" />);
expect(vListHandle.scrollToIndex).not.toHaveBeenCalled();
});
it('back-paginates after the user scrolls up from a focused event', async () => {
timelineSync.liveTimelineLinked = false;
timelineSync.canPaginateBack = true;
const { container } = render(
<RoomTimeline room={room} editor={{} as Editor} eventId="$evt1" />
);
await settleInitialScroll();
act(() => {
getScrollEl(container).dispatchEvent(
new WheelEvent('wheel', { bubbles: true, deltaY: -100 })
);
lastOnScroll?.(0);
});
expect(timelineSync.handleTimelinePagination).toHaveBeenCalledWith(true);
expect(timelineSync.handleTimelinePagination).not.toHaveBeenCalledWith(true, true);
});
it('does not back-paginate from a settled permalink scroll callback', async () => {
timelineSync.liveTimelineLinked = false;
timelineSync.canPaginateBack = true;
render(<RoomTimeline room={room} editor={{} as Editor} eventId="$evt1" />);
await settleInitialScroll();
act(() => lastOnScroll?.(0));
expect(timelineSync.handleTimelinePagination).not.toHaveBeenCalled();
});
it('does not back-paginate when the focused reader scrolls toward the bottom', async () => {
timelineSync.liveTimelineLinked = false;
timelineSync.canPaginateBack = true;
const { container } = render(
<RoomTimeline room={room} editor={{} as Editor} eventId="$evt1" />
);
await settleInitialScroll();
act(() => {
getScrollEl(container).dispatchEvent(new WheelEvent('wheel', { bubbles: true, deltaY: 100 }));
lastOnScroll?.(0);
});
expect(timelineSync.handleTimelinePagination).not.toHaveBeenCalled();
});
it('consumes focused scroll intent after requesting one page', async () => {
timelineSync.liveTimelineLinked = false;
timelineSync.canPaginateBack = true;
const { container } = render(
<RoomTimeline room={room} editor={{} as Editor} eventId="$evt1" />
);
await settleInitialScroll();
act(() => {
getScrollEl(container).dispatchEvent(
new WheelEvent('wheel', { bubbles: true, deltaY: -100 })
);
lastOnScroll?.(0);
lastOnScroll?.(0);
});
expect(timelineSync.handleTimelinePagination).toHaveBeenCalledTimes(1);
expect(timelineSync.handleTimelinePagination).toHaveBeenCalledWith(true);
});
it('retries an unresolved focus after timeline events are rendered', async () => {
timelineSync.liveTimelineLinked = false;
timelineSync.focusItem = { eventId: '$evt1', scrollTo: true, highlight: true };
@@ -880,6 +974,20 @@ describe('jump reveal and focus-regain read receipts', () => {
});
describe('unread read marker (normal sync)', () => {
it('does not let the delayed initial bottom scroll overwrite an unread marker', async () => {
getRoomUnreadInfoMock.mockReturnValue({
readUptoEventId: '$evt1',
inLiveTimeline: true,
scrollTo: true,
});
renderTimeline();
vListHandle.scrollToIndex.mockClear();
await settleInitialScroll();
expect(vListHandle.scrollToIndex).not.toHaveBeenCalled();
});
it('feeds the read marker to timeline processing and clears it on window blur', () => {
getRoomUnreadInfoMock.mockReturnValue({
readUptoEventId: '$read:example.org',
+151 -46
View File
@@ -1,5 +1,4 @@
import type { ReactNode } from 'react';
import * as Sentry from '@sentry/react';
import {
Fragment,
useCallback,
@@ -83,7 +82,7 @@ import type { Persona } from '$app/persona';
const MAX_VIEWPORT_FILL_PAGINATIONS = 5;
const VIRTUA_SCROLL_SETTLE_MS = 200;
const FOCUSED_PAGINATION_EDGE_PX = 64;
const SCROLL_KEYS = new Set(['PageUp', 'PageDown', 'Home', 'End', 'ArrowUp', 'ArrowDown', ' ']);
const TimelineFloat = as<'div', css.TimelineFloatVariants>(
@@ -418,6 +417,8 @@ export function RoomTimeline({
const ignoredUsersSet = useMemo(() => new Set(ignoredUsersList), [ignoredUsersList]);
const [unreadInfo, setUnreadInfo] = useState(() => getRoomUnreadInfo(room, true));
const unreadScrollToRef = useRef(unreadInfo?.scrollTo === true);
unreadScrollToRef.current = unreadInfo?.scrollTo === true;
const readUptoEventIdRef = useRef<string | undefined>(undefined);
if (unreadInfo) readUptoEventIdRef.current = unreadInfo.readUptoEventId;
@@ -471,6 +472,10 @@ export function RoomTimeline({
const mountScrollWindowRef = useRef<number>(Date.now() + 3000);
const hasInitialScrolledRef = useRef(false);
const initialScrollTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const initialScrollCancelledRef = useRef(false);
const hasUserScrollIntentRef = useRef(false);
const focusedPaginationIntentRef = useRef<'backward' | 'forward'>();
const touchStartYRef = useRef<number>();
const pendingReadyRef = useRef(false);
const currentRoomIdRef = useRef(room.roomId);
@@ -480,6 +485,10 @@ export function RoomTimeline({
hasInitialScrolledRef.current = false;
mountScrollWindowRef.current = Date.now() + 3000;
currentRoomIdRef.current = room.roomId;
initialScrollCancelledRef.current = false;
hasUserScrollIntentRef.current = false;
focusedPaginationIntentRef.current = undefined;
touchStartYRef.current = undefined;
pendingReadyRef.current = false;
if (initialScrollTimerRef.current !== undefined) {
clearTimeout(initialScrollTimerRef.current);
@@ -492,6 +501,7 @@ export function RoomTimeline({
const timelineSyncRef = useRef<typeof timelineSync>(null as unknown as typeof timelineSync);
const scrollElRef = useRef<HTMLElement | null>(null);
const [scrollElementVersion, setScrollElementVersion] = useState(0);
const scrollToBottom = useCallback(
(behavior: 'instant' | 'smooth' = 'instant') => {
@@ -516,14 +526,21 @@ export function RoomTimeline({
);
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' },
});
}
const messageListEl = messageListRef.current;
if (!messageListEl) return () => {};
const resolveScrollElement = () => {
const scrollEl = messageListEl.firstElementChild;
const nextScrollEl = scrollEl instanceof HTMLElement ? scrollEl : null;
if (nextScrollEl === scrollElRef.current) return;
scrollElRef.current = nextScrollEl;
setScrollElementVersion((version) => version + 1);
};
resolveScrollElement();
const observer = new MutationObserver(resolveScrollElement);
observer.observe(messageListEl, { childList: true });
return () => observer.disconnect();
}, []);
const jumpToEvent = useCallback(
@@ -539,6 +556,7 @@ export function RoomTimeline({
setAtBottom(true);
}, [setAtBottom]);
const handleReturnToLive = useCallback(() => {
scrollAnchorRef.current = undefined;
if (eventId) navigateRoom(room.roomId, undefined, { replace: true });
setAtBottom(true);
}, [eventId, navigateRoom, room.roomId, setAtBottom]);
@@ -654,12 +672,7 @@ export function RoomTimeline({
});
timelineSyncRef.current = timelineSync;
const previousPrependVersionRef = useRef(timelineSync.prependVersion);
const shiftForPrepend = previousPrependVersionRef.current !== timelineSync.prependVersion;
useLayoutEffect(() => {
previousPrependVersionRef.current = timelineSync.prependVersion;
}, [timelineSync.prependVersion]);
const focusLiveTimeline = timelineSync.focusLiveTimeline;
const eventsLengthRef = useRef(timelineSync.eventsLength);
eventsLengthRef.current = timelineSync.eventsLength;
@@ -734,12 +747,19 @@ export function RoomTimeline({
timelineSync.liveTimelineLinked &&
vListRef.current
) {
initialScrollCancelledRef.current = false;
scrollToBottom();
initialScrollTimerRef.current = setTimeout(() => {
initialScrollTimerRef.current = undefined;
if (initialScrollCancelledRef.current) return;
if (unreadScrollToRef.current) {
setIsReady(true);
return;
}
if (processedEventsRef.current.length > 0) {
scrollToBottom();
requestAnimationFrame(() => {
if (initialScrollCancelledRef.current) return;
if (processedEventsRef.current.length > 0) {
scrollToBottom();
setIsReady(true);
@@ -795,10 +815,6 @@ export function RoomTimeline({
return () => cancelAnimationFrame(id);
}, [recalcTopSpacer, timelineSync.eventsLength]);
useLayoutEffect(() => {
restoreScrollPosition();
});
const prevBackwardStatusRef = useRef(timelineSync.backwardStatus);
const wasAtBottomBeforePaginationRef = useRef(false);
@@ -808,8 +824,9 @@ export function RoomTimeline({
if (timelineSync.backwardStatus === 'loading') {
wasAtBottomBeforePaginationRef.current = atBottomRef.current;
} else if (prev === 'loading' && timelineSync.backwardStatus === 'idle') {
if (scrollAnchorRef.current !== undefined) restoreScrollAnchor();
else if (wasAtBottomBeforePaginationRef.current) scrollToBottom();
if (scrollOwnerRef.current === 'event' && scrollAnchorRef.current !== undefined) {
restoreScrollAnchor();
} else if (wasAtBottomBeforePaginationRef.current) scrollToBottom();
}
}, [timelineSync.backwardStatus, restoreScrollAnchor, scrollToBottom]);
@@ -880,6 +897,17 @@ export function RoomTimeline({
jumpToEvent(eventId);
}, [eventId, room, jumpToEvent]);
const previousEventIdRef = useRef(eventId);
useEffect(() => {
const previousEventId = previousEventIdRef.current;
previousEventIdRef.current = eventId;
if (previousEventId === undefined || eventId !== undefined) return;
scrollAnchorRef.current = undefined;
focusLiveTimeline();
setAtBottom(true);
}, [eventId, focusLiveTimeline, setAtBottom]);
useEffect(() => {
if (eventId) return;
if (isReady) return;
@@ -904,6 +932,7 @@ export function RoomTimeline({
if (processedIndex !== undefined && vListRef.current) {
vListRef.current.scrollToIndex(processedIndex, { align: 'start' });
}
unreadScrollToRef.current = false;
setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
}
}
@@ -917,14 +946,13 @@ export function RoomTimeline({
let contentObserver: ResizeObserver | undefined;
if (contentEl) {
contentObserver = new ResizeObserver(() => {
restoreScrollPosition();
if (scrollOwnerRef.current === 'live' && atBottomRef.current) scrollToBottom();
syncAtBottom();
});
contentObserver.observe(contentEl);
}
const observer = new ResizeObserver(() => {
restoreScrollPosition();
syncAtBottom();
});
@@ -933,7 +961,7 @@ export function RoomTimeline({
observer.disconnect();
contentObserver?.disconnect();
};
}, [syncAtBottom, restoreScrollPosition]);
}, [scrollElementVersion, scrollToBottom, syncAtBottom]);
const actions = useTimelineActions({
room,
@@ -1090,25 +1118,49 @@ export function RoomTimeline({
]);
useEffect(() => {
const scrollEl = scrollElRef.current;
if (!scrollEl) return () => {};
const release = () => {
const messageListEl = messageListRef.current;
if (!messageListEl) return () => {};
const setFocusedPaginationIntent = (direction: 'backward' | 'forward') => {
hasUserScrollIntentRef.current = true;
scrollAnchorRef.current = undefined;
if (eventId === undefined && !timelineSyncRef.current.focusItem) return;
focusedPaginationIntentRef.current = direction;
};
const releaseOnScrollKey = (evt: KeyboardEvent) => {
if (SCROLL_KEYS.has(evt.key)) release();
const recordWheelIntent = (evt: WheelEvent) => {
if (evt.deltaY === 0) return;
setFocusedPaginationIntent(evt.deltaY < 0 ? 'backward' : 'forward');
};
scrollEl.addEventListener('wheel', release, { passive: true });
scrollEl.addEventListener('touchstart', release, { passive: true });
scrollEl.addEventListener('pointerdown', release, { passive: true });
scrollEl.addEventListener('keydown', releaseOnScrollKey);
const recordKeyIntent = (evt: KeyboardEvent) => {
if (!SCROLL_KEYS.has(evt.key)) return;
if (evt.key === 'Home' || evt.key === 'PageUp' || evt.key === 'ArrowUp') {
setFocusedPaginationIntent('backward');
} else if (evt.key === 'End' || evt.key === 'PageDown' || evt.key === 'ArrowDown') {
setFocusedPaginationIntent('forward');
} else {
setFocusedPaginationIntent(evt.shiftKey ? 'backward' : 'forward');
}
};
const recordTouchStart = (evt: TouchEvent) => {
touchStartYRef.current = evt.touches[0]?.clientY;
};
const recordTouchIntent = (evt: TouchEvent) => {
const startY = touchStartYRef.current;
const currentY = evt.touches[0]?.clientY;
if (startY === undefined || currentY === undefined || startY === currentY) return;
setFocusedPaginationIntent(currentY < startY ? 'forward' : 'backward');
touchStartYRef.current = currentY;
};
messageListEl.addEventListener('wheel', recordWheelIntent, { passive: true });
messageListEl.addEventListener('keydown', recordKeyIntent);
messageListEl.addEventListener('touchstart', recordTouchStart, { passive: true });
messageListEl.addEventListener('touchmove', recordTouchIntent, { passive: true });
return () => {
scrollEl.removeEventListener('wheel', release);
scrollEl.removeEventListener('touchstart', release);
scrollEl.removeEventListener('pointerdown', release);
scrollEl.removeEventListener('keydown', releaseOnScrollKey);
messageListEl.removeEventListener('wheel', recordWheelIntent);
messageListEl.removeEventListener('keydown', recordKeyIntent);
messageListEl.removeEventListener('touchstart', recordTouchStart);
messageListEl.removeEventListener('touchmove', recordTouchIntent);
};
}, []);
}, [eventId]);
const handleVListScroll = useCallback(
(offset: number) => {
@@ -1119,6 +1171,37 @@ export function RoomTimeline({
const distanceFromBottom = v.scrollSize - offset - v.viewportSize;
syncAtBottom(offset);
if (hasUserScrollIntentRef.current && distanceFromBottom >= 100) {
initialScrollCancelledRef.current = true;
if (initialScrollTimerRef.current !== undefined) {
clearTimeout(initialScrollTimerRef.current);
initialScrollTimerRef.current = undefined;
}
setIsReady(true);
}
if (eventId !== undefined || timelineSyncRef.current.focusItem) {
const intent = focusedPaginationIntentRef.current;
if (
intent === 'backward' &&
offset <= FOCUSED_PAGINATION_EDGE_PX &&
canPaginateBackRef.current &&
backwardStatusRef.current === 'idle'
) {
focusedPaginationIntentRef.current = undefined;
void timelineSyncRef.current.handleTimelinePagination(true);
} else if (
intent === 'forward' &&
distanceFromBottom <= FOCUSED_PAGINATION_EDGE_PX &&
canPaginateForwardRef.current &&
forwardStatusRef.current === 'idle'
) {
focusedPaginationIntentRef.current = undefined;
void timelineSyncRef.current.handleTimelinePagination(false);
}
return;
}
if (scrollAnchorRef.current !== undefined) return;
if (offset < 500 && canPaginateBackRef.current && backwardStatusRef.current === 'idle') {
@@ -1132,7 +1215,7 @@ export function RoomTimeline({
void timelineSyncRef.current.handleTimelinePagination(false);
}
},
[notifyScroll, syncAtBottom]
[eventId, notifyScroll, syncAtBottom]
);
const handleVListScrollEnd = useCallback(() => {
if (!timelineSyncRef.current.focusItem?.scrollTo) return;
@@ -1244,8 +1327,23 @@ export function RoomTimeline({
});
processedEventsRef.current = processedEvents;
// Virtua shift only supports prepends.
const shouldShift = shiftForPrepend;
const previousProcessedEventIdsRef = useRef<string[]>();
const processedEventIds = processedEvents.map((event) => event.id);
const previousProcessedEventIds = previousProcessedEventIdsRef.current;
const shouldShift =
previousProcessedEventIds !== undefined &&
processedEventIds.length > previousProcessedEventIds.length &&
previousProcessedEventIds.every(
(id, index) =>
id ===
processedEventIds[index + processedEventIds.length - previousProcessedEventIds.length]
);
useLayoutEffect(() => {
previousProcessedEventIdsRef.current = processedEventIds;
}, [processedEventIds]);
const vListKeyRef = useRef(room.roomId);
if (!isReady && scrollOwner === 'live')
vListKeyRef.current = `${room.roomId}:${processedEvents.map((event) => event.id).join(',')}`;
useLayoutEffect(() => {
if (!pendingReadyRef.current) return;
@@ -1276,16 +1374,20 @@ export function RoomTimeline({
viewportFillCountRef.current = 0;
}, [room.roomId]);
// Re-enters on every length change, so an unfillable viewport pages to the start of the
// room. Scrolling up is handled by handleVListScroll.
// Fill an initially short live timeline. Focused history is user-owned and must not
// auto-continue after its anchor is released.
useEffect(() => {
if (scrollOwner !== 'live') return () => {};
if (!canPaginateBackRef.current) return () => {};
if (scrollAnchorRef.current !== undefined) return () => {};
let rafId: number;
let attempts = 0;
const MAX_ATTEMPTS = 20;
const check = () => {
if (scrollAnchorRef.current !== undefined) return;
const v = vListRef.current;
if (!v) return;
@@ -1302,13 +1404,13 @@ export function RoomTimeline({
if (v.scrollSize <= v.viewportSize + 300) {
viewportFillCountRef.current += 1;
void timelineSyncRef.current.handleTimelinePagination(true);
void timelineSyncRef.current.handleTimelinePagination(true, true);
}
};
rafId = requestAnimationFrame(check);
return () => cancelAnimationFrame(rafId);
}, [room.roomId, timelineSync.eventsLength, timelineSync.backwardStatus]);
}, [room.roomId, scrollOwner, timelineSync.eventsLength, timelineSync.backwardStatus]);
return (
<Box grow="Yes" style={{ position: 'relative' }}>
@@ -1346,6 +1448,7 @@ export function RoomTimeline({
<div
ref={messageListRef}
data-testid="timeline"
style={{
flex: 1,
minHeight: 0,
@@ -1360,9 +1463,11 @@ export function RoomTimeline({
>
<TimelineScrollingProvider value={isTimelineScrolling}>
<VList<ProcessedEvent>
key={vListKeyRef.current}
ref={vListRef}
data={processedEvents}
shift={shouldShift}
id="timeline-scroller"
className={css.messageList}
style={{
flex: 1,
+42 -41
View File
@@ -727,7 +727,7 @@ describe('back-pagination', () => {
);
await act(async () => {
await result.current.handleTimelinePagination(true);
await result.current.handleTimelinePagination(true, true);
});
// Nothing rendered, so the loader keeps going up to MAX_AUTO_CONTINUATIONS.
@@ -745,7 +745,7 @@ describe('back-pagination', () => {
useTimelineSync(syncOpts(thinPage.room, thinPaginate, () => true))
);
await act(async () => {
await thin.result.current.handleTimelinePagination(true);
await thin.result.current.handleTimelinePagination(true, true);
});
expect(thinPaginate).toHaveBeenCalledTimes(4);
@@ -763,6 +763,23 @@ describe('back-pagination', () => {
expect(fullPaginate).toHaveBeenCalledTimes(1);
});
it('loads one sparse page for a user-driven scroll', async () => {
const { room, events } = createPaginableRoom();
const paginateEventTimeline = vi.fn<() => Promise<boolean>>(async () => {
events.push({});
return true;
});
const { result } = renderHook(() =>
useTimelineSync(syncOpts(room, paginateEventTimeline, () => false))
);
await act(async () => {
await result.current.handleTimelinePagination(true);
});
expect(paginateEventTimeline).toHaveBeenCalledTimes(1);
});
it('never reports idle before the fetched page is committed', async () => {
// The sdk puts a fetched page in a fresh EventTimeline linked behind the
// live one, so the new events only become visible once setTimeline commits.
@@ -1171,45 +1188,6 @@ describe('live-arrive edge cases', () => {
expect(scrollToBottom).toHaveBeenCalledWith('instant');
});
it('signals a prepend on the displayed timeline', async () => {
const { room, timeline } = createRoom();
const { result } = renderSyncHook(room, { isAtBottom: false });
expect(result.current.prependVersion).toBe(0);
await act(async () => {
room.emit(RoomEvent.Timeline, makeLiveEvent(room.roomId, Date.now()), room, true, false, {
liveEvent: false,
timeline,
});
await Promise.resolve();
});
expect(result.current.prependVersion).toBe(1);
});
it('signals a filtered prepend batched with a visible append', async () => {
const { room, timeline, events } = createRoom();
const prependedEvent = makeLiveEvent(room.roomId, 1) as unknown as MatrixEvent;
const appendedEvent = makeLiveEvent(room.roomId, 2) as unknown as MatrixEvent;
const isEventVisible = (mEvent: MatrixEvent) => mEvent === appendedEvent;
const { result } = renderSyncHook(room, { isAtBottom: false, isEventVisible });
await act(async () => {
room.emit(RoomEvent.Timeline, prependedEvent, room, true, false, {
liveEvent: false,
timeline,
});
events.push({});
room.emit(RoomEvent.Timeline, appendedEvent, room, false, false, {
liveEvent: true,
timeline,
});
await Promise.resolve();
});
expect(result.current.prependVersion).toBe(1);
});
it('ignores timeline events emitted for a different room', async () => {
const { room, timeline, events } = createRoom();
const otherRoom = createRoom('!other:test');
@@ -2170,6 +2148,29 @@ describe('event jump recovery', () => {
});
});
it('keeps a permalink context window when sliding sync resets the live timeline', async () => {
const fixture = setupUnloadedTarget('$target:test');
const { result } = renderSyncHook(fixture.room, { isAtBottom: false, mx: fixture.mx });
await act(async () => {
await result.current.loadEventTimeline('$target:test');
});
const contextTimeline = result.current.timeline;
const timelineSet = fixture.room.getUnfilteredTimelineSet();
await act(async () => {
timelineSet.emit(RoomEvent.TimelineReset, undefined, timelineSet, true);
await Promise.resolve();
});
expect(result.current.timeline).toBe(contextTimeline);
expect(result.current.focusItem).toEqual({
eventId: '$target:test',
scrollTo: true,
highlight: true,
});
});
it('falls back to the initial timeline when a jump load times out', async () => {
vi.useFakeTimers();
try {
+5 -9
View File
@@ -206,7 +206,7 @@ const useTimelinePagination = (
const edgeTimeline = (lTimelines: EventTimeline[], backwards: boolean) =>
backwards ? lTimelines[0] : lTimelines.at(-1);
return async (backwards: boolean) => {
return async (backwards: boolean, autoContinue = false) => {
const directionKey = backwards ? 'backward' : 'forward';
if (fetchingRef.current[directionKey]) return;
@@ -231,7 +231,8 @@ const useTimelinePagination = (
let settledStatus: PaginationStatus = 'idle';
try {
for (let attempt = 0; attempt <= MAX_AUTO_CONTINUATIONS; attempt += 1) {
const maxAttempts = autoContinue ? MAX_AUTO_CONTINUATIONS : 0;
for (let attempt = 0; attempt <= maxAttempts; attempt += 1) {
const lTimelines = timelineRef.current.linkedTimelines;
const timelineToPaginate = edgeTimeline(lTimelines, backwards);
if (!timelineToPaginate) return;
@@ -448,7 +449,6 @@ export function useTimelineSync({
const [focusItem, setFocusItem] = useState<TimelineFocusItem>();
const [jumpFailedFor, setJumpFailedFor] = useState<string | undefined>();
const [prependVersion, setPrependVersion] = useState(0);
const jumpFailed = jumpFailedFor !== undefined && jumpFailedFor === eventId;
const resetAutoScrollPendingRef = useRef(false);
@@ -621,16 +621,13 @@ export function useTimelineSync({
useLiveEventArrive(
room,
useCallback(
(mEvt: MatrixEvent, isLive: boolean, evtTimeline?: EventTimeline, prepended?: boolean) => {
(mEvt: MatrixEvent, isLive: boolean, evtTimeline?: EventTimeline) => {
if (mEvt.isRedaction()) redactInFocusedWindow(mEvt);
const isDisplayedTimeline =
evtTimeline === undefined || linkedTimelinesRef.current.includes(evtTimeline);
if (isDisplayedTimeline) {
setActiveTimeline((ct) => ({ ...ct }));
if (prepended) {
setPrependVersion((version) => version + 1);
}
}
if (!isLive) return;
@@ -729,8 +726,8 @@ export function useTimelineSync({
useLiveTimelineRefresh(
room,
useCallback(() => {
applyLiveTimeline(getInitialTimeline(room).linkedTimelines);
if (focusedTimelineRef.current || inFlightJumpRef.current) return;
applyLiveTimeline(getInitialTimeline(room).linkedTimelines);
if (eventId) {
void loadEventTimeline(eventId);
return;
@@ -798,7 +795,6 @@ export function useTimelineSync({
return {
timeline,
eventsLength,
prependVersion,
liveTimelineLinked,
canPaginateBack,
canPaginateForward,
+42 -2
View File
@@ -1,4 +1,4 @@
import { expect, type Page } from '@playwright/test';
import { expect, type Locator, type Page } from '@playwright/test';
import { getRoomMessages } from './continuwuity';
/** Event IDs for `tag`, in the server's canonical order. */
@@ -52,8 +52,48 @@ export function expectNoDuplicateRows(rendered: string[]): void {
/** Scrolls the timeline up until `text` back-paginates into view. */
export async function wheelToTopUntilVisible(page: Page, text: string): Promise<void> {
await expect(async () => {
await page.mouse.move(640, 400);
await timelineScroller(page).hover();
await page.mouse.wheel(0, -2400);
expect(await page.getByText(text, { exact: true }).count()).toBeGreaterThan(0);
}).toPass({ timeout: 120_000, intervals: [500] });
}
/** Scrolls the timeline down until `text` forward-paginates into view. */
export async function wheelToBottomUntilVisible(page: Page, text: string): Promise<void> {
await expect(async () => {
await timelineScroller(page).hover();
await page.mouse.wheel(0, 2400);
expect(await page.getByText(text, { exact: true }).count()).toBeGreaterThan(0);
}).toPass({ timeout: 120_000, intervals: [500] });
}
export const timelineScroller = (page: Page): Locator => page.locator('#timeline-scroller');
export async function timelineDistanceFromBottom(page: Page): Promise<number> {
return timelineScroller(page).evaluate(
(element) => element.scrollHeight - element.scrollTop - element.clientHeight
);
}
export async function waitForTimelineScrollSettle(page: Page): Promise<void> {
await expect
.poll(async () => {
const first = await timelineScroller(page).evaluate((element) => element.scrollTop);
await page.evaluate(
() =>
new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(resolve))
)
);
const second = await timelineScroller(page).evaluate((element) => element.scrollTop);
return Math.abs(second - first);
})
.toBeLessThanOrEqual(1);
}
/** Waits for a rendered message's scroll container to settle at the live edge. */
export async function expectTimelineAtBottom(page: Page): Promise<void> {
await expect
.poll(() => timelineDistanceFromBottom(page), { timeout: 10_000 })
.toBeLessThanOrEqual(2);
}
+15 -1
View File
@@ -1,6 +1,7 @@
import { readFile } from 'node:fs/promises';
import { test, expect, type Page } from '@playwright/test';
import { createRoom, registerUser, sendMessage, sendText } from './fixtures/continuwuity';
import { wheelToBottomUntilVisible, wheelToTopUntilVisible } from './fixtures/timelineOrder';
import { AppShell } from './pages/AppShell';
const PASSWORD = 'test-passw0rd';
@@ -75,7 +76,6 @@ test.describe('permalink jumps', () => {
test('jumps to a message beyond the loaded window when its permalink is clicked', async ({
page,
}, testInfo) => {
test.skip(testInfo.project.name !== 'desktop', 'desktop-focused');
test.setTimeout(300_000);
const storageStatePath = testInfo.project.use.storageState as string;
const hsBaseUrl = await homeserverBaseUrl(storageStatePath);
@@ -90,10 +90,12 @@ test.describe('permalink jumps', () => {
// The client initially loads only the latest 60 events, so message 20 sits
// outside the loaded timeline: the jump has to fetch its context.
let firstId = '';
let targetId = '';
let latestId = '';
for (let i = 1; i <= HISTORY_SIZE; i += 1) {
const eventId = await sendText(hsBaseUrl, user.accessToken, room, `${tag}-${i}`, i);
if (i === 1) firstId = eventId;
if (i === 20) targetId = eventId;
latestId = eventId;
}
@@ -111,6 +113,18 @@ test.describe('permalink jumps', () => {
await expect(targetRow).toBeVisible({ timeout: 60_000 });
await expect(app.messageByEventId(latestId)).toHaveCount(0);
await expect(app.messageByEventId(firstId)).toHaveCount(0);
await page.reload();
await expect(targetRow).toBeInViewport({ timeout: 60_000 });
await expect(app.messageByEventId(latestId)).toHaveCount(0);
await expect(app.messageByEventId(firstId)).toHaveCount(0);
await wheelToTopUntilVisible(page, `${tag}-1`);
await expect(app.messageByEventId(firstId)).toBeVisible({ timeout: 60_000 });
await wheelToBottomUntilVisible(page, `${tag}-${HISTORY_SIZE}`);
await expect(app.messageByEventId(latestId)).toBeVisible({ timeout: 60_000 });
const sentBody = `${tag}-after-jump`;
await app.sendTextMessage(sentBody);
+136 -111
View File
@@ -1,11 +1,19 @@
import { readFile } from 'node:fs/promises';
import { test, expect, type Page } from '@playwright/test';
import { createRoom, registerUser, sendText } from './fixtures/continuwuity';
import { createRoom, inviteUser, joinRoom, registerUser, sendText } from './fixtures/continuwuity';
import {
expectTimelineAtBottom,
timelineScroller,
wheelToBottomUntilVisible,
} from './fixtures/timelineOrder';
import { AppShell } from './pages/AppShell';
const PASSWORD = 'test-passw0rd';
const HISTORY_SIZE = 100;
const SEND_DELAYS_MS = [0, 150, 0, 400, 50];
const TEST_TIMEOUT = 60_000;
const SYNC_TIMEOUT = 45_000;
const UI_TIMEOUT = 30_000;
type InjectedSession = {
baseUrl: string;
@@ -26,7 +34,8 @@ async function homeserverBaseUrl(storageStatePath: string): Promise<string> {
async function loginAsFreshUser(
page: Page,
baseUrl: string,
name: string
name: string,
slidingSyncOptIn: boolean
): Promise<{ accessToken: string }> {
const user = await registerUser(baseUrl, name, PASSWORD);
const session: InjectedSession = {
@@ -34,7 +43,7 @@ async function loginAsFreshUser(
userId: user.userId,
deviceId: user.deviceId,
accessToken: user.accessToken,
slidingSyncOptIn: true,
slidingSyncOptIn,
};
await page.addInitScript((injected: InjectedSession) => {
localStorage.setItem('matrixSessions', JSON.stringify([injected]));
@@ -74,120 +83,136 @@ async function sendHistory(
async function wheelToTopUntilVisible(page: Page, text: string): Promise<void> {
await expect(async () => {
await page.mouse.move(640, 400);
await timelineScroller(page).hover();
await page.mouse.wheel(0, -2400);
expect(await page.getByText(text, { exact: true }).count()).toBeGreaterThan(0);
}).toPass({ timeout: 120_000, intervals: [500] });
}).toPass({ timeout: UI_TIMEOUT, intervals: [500] });
}
test.describe('sliding sync timeline', () => {
test('paginates backwards through pre-subscription history after leaving and reopening a room', async ({
page,
}, testInfo) => {
test.skip(testInfo.project.name !== 'desktop', 'desktop-focused');
test.setTimeout(300_000);
const storageStatePath = testInfo.project.use.storageState as string;
const hsBaseUrl = await homeserverBaseUrl(storageStatePath);
const tag = `hist-${process.pid}-${Date.now().toString(36)}`;
const app = new AppShell(page);
const user = await loginAsFreshUser(page, hsBaseUrl, `${tag}-u`);
const syncTransports = [
{ name: 'sliding sync', slidingSyncOptIn: true },
{ name: 'legacy sync', slidingSyncOptIn: false },
];
const room = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} History`,
preset: 'private_chat',
});
const away = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} Away`,
preset: 'private_chat',
});
for (const transport of syncTransports) {
test.describe(`timeline lifecycle (${transport.name})`, () => {
test('paginates backwards through pre-subscription history after leaving and reopening a room', async ({
page,
}, testInfo) => {
test.setTimeout(TEST_TIMEOUT);
const storageStatePath = testInfo.project.use.storageState as string;
const hsBaseUrl = await homeserverBaseUrl(storageStatePath);
const tag = `hist-${process.pid}-${Date.now().toString(36)}`;
const app = new AppShell(page);
const user = await loginAsFreshUser(page, hsBaseUrl, `${tag}-u`, transport.slidingSyncOptIn);
const bodies = ['sentinel', ...Array.from({ length: HISTORY_SIZE - 1 }, (_, i) => `m${i}`)];
const latest = `${tag}-m${HISTORY_SIZE - 2}`;
const sentinel = `${tag}-sentinel`;
await sendHistory(hsBaseUrl, user.accessToken, room, tag, bodies);
await sendMessage(hsBaseUrl, user.accessToken, away, `${tag}-away-msg`);
await page.goto('/');
await expect(page.getByText(`${tag} History`).first()).toBeVisible({
timeout: 180_000,
});
await app.openRoom(`${tag} History`);
await expect(page.getByText(latest, { exact: true }).first()).toBeVisible({
timeout: 180_000,
});
expect(await page.getByText(sentinel, { exact: true }).count()).toBe(0);
await app.openRoom(`${tag} Away`);
await expect(page.getByText(`${tag}-away-msg`, { exact: true })).toBeVisible({
timeout: 120_000,
});
await app.openRoom(`${tag} History`);
await expect(page.getByText(latest, { exact: true }).first()).toBeVisible({
timeout: 120_000,
});
expect(await page.getByText(sentinel, { exact: true }).count()).toBe(0);
await wheelToTopUntilVisible(page, sentinel);
});
test('renders messages received while the room was inactive exactly once, in order, after reopening', async ({
page,
}, testInfo) => {
test.skip(testInfo.project.name !== 'desktop', 'desktop-focused');
test.setTimeout(300_000);
const storageStatePath = testInfo.project.use.storageState as string;
const hsBaseUrl = await homeserverBaseUrl(storageStatePath);
const tag = `live-${process.pid}-${Date.now().toString(36)}`;
const app = new AppShell(page);
const user = await loginAsFreshUser(page, hsBaseUrl, `${tag}-u`);
const room = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} Home`,
preset: 'private_chat',
});
const away = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} Away`,
preset: 'private_chat',
});
await sendMessage(hsBaseUrl, user.accessToken, room, `${tag}-seed`);
await sendMessage(hsBaseUrl, user.accessToken, away, `${tag}-away-msg`);
await page.goto('/');
await expect(page.getByText(`${tag} Home`).first()).toBeVisible({
timeout: 180_000,
});
await app.openRoom(`${tag} Home`);
await expect(page.getByText(`${tag}-seed`, { exact: true })).toBeVisible({
timeout: 180_000,
});
await app.openRoom(`${tag} Away`);
await expect(page.getByText(`${tag}-away-msg`, { exact: true })).toBeVisible({
timeout: 120_000,
});
for (let i = 0; i < SEND_DELAYS_MS.length; i += 1) {
if (SEND_DELAYS_MS[i]! > 0) await page.waitForTimeout(SEND_DELAYS_MS[i]!);
await sendMessage(hsBaseUrl, user.accessToken, room, `${tag}-live-${i + 1}`);
}
await app.openRoom(`${tag} Home`);
await expect(page.getByText(`${tag}-seed`, { exact: true })).toBeVisible({
timeout: 120_000,
});
for (let i = 0; i < SEND_DELAYS_MS.length; i += 1) {
await expect(page.getByText(`${tag}-live-${i + 1}`, { exact: true })).toHaveCount(1, {
timeout: 120_000,
const room = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} DM`,
preset: 'private_chat',
});
const remote = await registerUser(hsBaseUrl, `${tag}-remote`, PASSWORD);
await inviteUser(hsBaseUrl, user.accessToken, room, remote.userId);
await joinRoom(hsBaseUrl, remote.accessToken, room);
const away = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} Away`,
preset: 'private_chat',
});
await expect(page.getByText(`${tag}-live-${i + 1}`, { exact: true })).toBeVisible();
}
const domOrder = await page.getByText(new RegExp(`^${tag}-live-\\d+$`)).allTextContents();
expect(domOrder).toEqual(SEND_DELAYS_MS.map((_, i) => `${tag}-live-${i + 1}`));
const bodies = ['sentinel', ...Array.from({ length: HISTORY_SIZE - 1 }, (_, i) => `m${i}`)];
const latest = `${tag}-m${HISTORY_SIZE - 2}`;
const sentinel = `${tag}-sentinel`;
await sendHistory(hsBaseUrl, remote.accessToken, room, tag, bodies);
await sendMessage(hsBaseUrl, user.accessToken, away, `${tag}-away-msg`);
await page.goto('/');
await expect(page.getByText(`${tag} DM`).first()).toBeVisible({
timeout: SYNC_TIMEOUT,
});
await app.openRoom(`${tag} DM`);
await expect(page.getByText(latest, { exact: true }).first()).toBeVisible({
timeout: SYNC_TIMEOUT,
});
await expectTimelineAtBottom(page);
expect(await page.getByText(sentinel, { exact: true }).count()).toBe(0);
if (testInfo.project.name === 'mobile') await page.goto('/');
await app.openRoom(`${tag} Away`);
await expect(page.getByText(`${tag}-away-msg`, { exact: true })).toBeVisible({
timeout: UI_TIMEOUT,
});
if (testInfo.project.name === 'mobile') await page.goto('/');
await app.openRoom(`${tag} DM`);
await expect(page.getByText(latest, { exact: true }).first()).toBeVisible({
timeout: UI_TIMEOUT,
});
await expectTimelineAtBottom(page);
expect(await page.getByText(sentinel, { exact: true }).count()).toBe(0);
await wheelToTopUntilVisible(page, sentinel);
await wheelToBottomUntilVisible(page, latest);
});
test('renders messages received while the room was inactive exactly once, in order, after reopening', async ({
page,
}, testInfo) => {
test.setTimeout(TEST_TIMEOUT);
const storageStatePath = testInfo.project.use.storageState as string;
const hsBaseUrl = await homeserverBaseUrl(storageStatePath);
const tag = `live-${process.pid}-${Date.now().toString(36)}`;
const app = new AppShell(page);
const user = await loginAsFreshUser(page, hsBaseUrl, `${tag}-u`, transport.slidingSyncOptIn);
const room = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} Home`,
preset: 'private_chat',
});
const away = await createRoom(hsBaseUrl, user.accessToken, {
name: `${tag} Away`,
preset: 'private_chat',
});
await sendMessage(hsBaseUrl, user.accessToken, room, `${tag}-seed`);
await sendMessage(hsBaseUrl, user.accessToken, away, `${tag}-away-msg`);
await page.goto('/');
await expect(page.getByText(`${tag} Home`).first()).toBeVisible({
timeout: SYNC_TIMEOUT,
});
await app.openRoom(`${tag} Home`);
await expect(page.getByText(`${tag}-seed`, { exact: true })).toBeVisible({
timeout: SYNC_TIMEOUT,
});
if (testInfo.project.name === 'mobile') await page.goto('/');
await app.openRoom(`${tag} Away`);
await expect(page.getByText(`${tag}-away-msg`, { exact: true })).toBeVisible({
timeout: UI_TIMEOUT,
});
for (let i = 0; i < SEND_DELAYS_MS.length; i += 1) {
if (SEND_DELAYS_MS[i]! > 0) await page.waitForTimeout(SEND_DELAYS_MS[i]!);
await sendMessage(hsBaseUrl, user.accessToken, room, `${tag}-live-${i + 1}`);
}
if (testInfo.project.name === 'mobile') await page.goto('/');
await app.openRoom(`${tag} Home`);
await expect(page.getByText(`${tag}-seed`, { exact: true })).toBeVisible({
timeout: UI_TIMEOUT,
});
for (let i = 0; i < SEND_DELAYS_MS.length; i += 1) {
await expect(page.getByText(`${tag}-live-${i + 1}`, { exact: true })).toHaveCount(1, {
timeout: UI_TIMEOUT,
});
await expect(page.getByText(`${tag}-live-${i + 1}`, { exact: true })).toBeVisible();
}
const domOrder = await page.getByText(new RegExp(`^${tag}-live-\\d+$`)).allTextContents();
expect(domOrder).toEqual(SEND_DELAYS_MS.map((_, i) => `${tag}-live-${i + 1}`));
});
});
});
}