Skip to content

Commit c4face9

Browse files
author
npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757
committed
fix(desktop): preserve timeline anchor across prepends
Co-authored-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co>
1 parent 31fe8d3 commit c4face9

3 files changed

Lines changed: 174 additions & 6 deletions

File tree

‎desktop/src/features/messages/ui/MessageTimeline.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,15 +501,18 @@ const MessageTimelineBase = React.forwardRef<
501501
if (
502502
searchActiveMessageId ||
503503
!fetchOlder ||
504+
isFetchingOlder ||
504505
showTimelineSkeleton ||
505506
!hasOlderMessages
506507
) {
507-
return;
508+
return false;
508509
}
509510
void fetchOlder();
511+
return true;
510512
}, [
511513
fetchOlder,
512514
hasOlderMessages,
515+
isFetchingOlder,
513516
searchActiveMessageId,
514517
showTimelineSkeleton,
515518
]);
@@ -652,6 +655,7 @@ const MessageTimelineBase = React.forwardRef<
652655
isSendingVideoReviewComment={isSendingVideoReviewComment}
653656
onSendVideoReviewComment={onSendVideoReviewComment}
654657
onStartReached={loadOlderViaVirtualizer}
658+
isFetchingOlder={isFetchingOlder}
655659
onToggleReaction={onToggleReaction}
656660
onVirtualizerApiChange={setTimelineVirtualizerApi}
657661
onVirtualizerRangeChanged={handleVirtualizerRangeChanged}

‎desktop/src/features/messages/ui/TimelineMessageList.tsx‎

Lines changed: 90 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,8 @@ type TimelineMessageListProps = {
9696
leadingContent?: React.ReactNode;
9797
/** The virtualized timeline owns its scroll node when enabled. */
9898
useVirtualizer?: boolean;
99-
onStartReached?: () => void;
99+
onStartReached?: () => boolean;
100+
isFetchingOlder?: boolean;
100101
onAtBottomStateChange?: (atBottom: boolean) => void;
101102
onVirtualizerApiChange?: (api: TimelineVirtualizerApi | null) => void;
102103
onVirtualizerRangeChanged?: () => void;
@@ -137,6 +138,7 @@ export const TimelineMessageList = React.memo(function TimelineMessageList({
137138
leadingContent,
138139
useVirtualizer = false,
139140
onStartReached,
141+
isFetchingOlder = false,
140142
onAtBottomStateChange,
141143
onVirtualizerApiChange,
142144
onVirtualizerRangeChanged,
@@ -289,6 +291,7 @@ export const TimelineMessageList = React.memo(function TimelineMessageList({
289291
leadingContent={leadingContent}
290292
onAtBottomStateChange={onAtBottomStateChange}
291293
onStartReached={onStartReached}
294+
isFetchingOlder={isFetchingOlder}
292295
onVirtualizerApiChange={onVirtualizerApiChange}
293296
onVirtualizerRangeChanged={onVirtualizerRangeChanged}
294297
onVirtualizerScrollerChange={onVirtualizerScrollerChange}
@@ -371,7 +374,8 @@ type VirtualizedTimelineRowsProps = {
371374
dayGroups: TimelineDayGroup[];
372375
leadingContent?: React.ReactNode;
373376
onAtBottomStateChange?: (atBottom: boolean) => void;
374-
onStartReached?: () => void;
377+
onStartReached?: () => boolean;
378+
isFetchingOlder?: boolean;
375379
onVirtualizerApiChange?: (api: TimelineVirtualizerApi | null) => void;
376380
onVirtualizerRangeChanged?: () => void;
377381
onVirtualizerScrollerChange?: (element: HTMLDivElement | null) => void;
@@ -390,11 +394,34 @@ function didPrependVirtualizedTimeline(
390394
);
391395
}
392396

397+
type PrependAnchor = {
398+
messageId: string;
399+
topOffset: number;
400+
};
401+
402+
function capturePrependAnchor(scroller: HTMLElement): PrependAnchor | null {
403+
const scrollerTop = scroller.getBoundingClientRect().top;
404+
const rows = Array.from(
405+
scroller.querySelectorAll<HTMLElement>("[data-message-id]"),
406+
);
407+
const row =
408+
rows.find(
409+
(candidate) => candidate.getBoundingClientRect().top >= scrollerTop,
410+
) ?? rows[rows.length - 1];
411+
const messageId = row?.dataset.messageId;
412+
if (!row || !messageId) return null;
413+
return {
414+
messageId,
415+
topOffset: row.getBoundingClientRect().top - scrollerTop,
416+
};
417+
}
418+
393419
function VirtualizedTimelineRows({
394420
dayGroups,
395421
leadingContent,
396422
onAtBottomStateChange,
397423
onStartReached,
424+
isFetchingOlder,
398425
onVirtualizerApiChange,
399426
onVirtualizerRangeChanged,
400427
onVirtualizerScrollerChange,
@@ -411,6 +438,9 @@ function VirtualizedTimelineRows({
411438
[dayGroups, leadingContent],
412439
);
413440
const previousFirstTimelineKeyRef = React.useRef<string | null>(null);
441+
const pendingPrependAnchorRef = React.useRef<PrependAnchor | null>(null);
442+
const isLoadingOlderRef = React.useRef(false);
443+
const observedOlderFetchRef = React.useRef(false);
414444
const [prependShiftEpoch, clearPrependShift] = React.useReducer(
415445
(version: number) => version + 1,
416446
0,
@@ -433,14 +463,58 @@ function VirtualizedTimelineRows({
433463
keys,
434464
);
435465
}, [firstTimelineKey, keys, prependShiftEpoch]);
466+
React.useEffect(() => {
467+
if (!isLoadingOlderRef.current) return;
468+
if (isFetchingOlder) {
469+
observedOlderFetchRef.current = true;
470+
} else if (observedOlderFetchRef.current) {
471+
// No prepend committed before the request settled (error, cancellation,
472+
// or an empty page). Re-arm top-edge loading for a later retry.
473+
observedOlderFetchRef.current = false;
474+
isLoadingOlderRef.current = false;
475+
pendingPrependAnchorRef.current = null;
476+
}
477+
}, [isFetchingOlder]);
436478
React.useLayoutEffect(() => {
437479
previousFirstTimelineKeyRef.current = firstTimelineKey;
438-
if (isPrepend) clearPrependShift();
480+
if (isPrepend) {
481+
clearPrependShift();
482+
isLoadingOlderRef.current = false;
483+
observedOlderFetchRef.current = false;
484+
const anchor = pendingPrependAnchorRef.current;
485+
pendingPrependAnchorRef.current = null;
486+
const scroller = hostRef.current?.firstElementChild;
487+
if (anchor && scroller instanceof HTMLElement) {
488+
// Virtua normally preserves a prepend with `shift`, but a transient
489+
// end-anchored cache can occasionally win and jump near the tail. The
490+
// pre-fetch message identity is the semantic invariant; restore it once
491+
// after the prepended rows commit, then leave all later measurement
492+
// correction to Virtua.
493+
const anchorIndex = items.findIndex(
494+
(item) =>
495+
item.kind === "timeline-item" &&
496+
timelineItemMessageId(item.item) === anchor.messageId,
497+
);
498+
if (anchorIndex >= 0) {
499+
listRef.current?.scrollToIndex(anchorIndex, { align: "start" });
500+
}
501+
window.requestAnimationFrame(() => {
502+
const row = scroller.querySelector<HTMLElement>(
503+
`[data-message-id="${CSS.escape(anchor.messageId)}"]`,
504+
);
505+
if (!row) return;
506+
const currentTopOffset =
507+
row.getBoundingClientRect().top -
508+
scroller.getBoundingClientRect().top;
509+
listRef.current?.scrollBy(currentTopOffset - anchor.topOffset);
510+
});
511+
}
512+
}
439513
if (!hasInitialPositionedRef.current && items.length > 0) {
440514
hasInitialPositionedRef.current = true;
441515
listRef.current?.scrollToIndex(items.length - 1, { align: "end" });
442516
}
443-
}, [firstTimelineKey, isPrepend, items.length]);
517+
}, [firstTimelineKey, isPrepend, items]);
444518

445519
const messageItemIndexById = React.useMemo(() => {
446520
const byId = new Map<string, number>();
@@ -504,7 +578,18 @@ function VirtualizedTimelineRows({
504578
onAtBottomStateChange?.(
505579
list.scrollSize - list.viewportSize - offset <= 32,
506580
);
507-
if (offset <= 200) onStartReached?.();
581+
if (offset <= 200 && !isLoadingOlderRef.current) {
582+
const scroller = hostRef.current?.firstElementChild;
583+
pendingPrependAnchorRef.current =
584+
scroller instanceof HTMLElement
585+
? capturePrependAnchor(scroller)
586+
: null;
587+
if (onStartReached?.()) {
588+
isLoadingOlderRef.current = true;
589+
} else {
590+
pendingPrependAnchorRef.current = null;
591+
}
592+
}
508593
},
509594
[onAtBottomStateChange, onStartReached, onVirtualizerRangeChanged],
510595
);

‎desktop/tests/e2e/virtualization.spec.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,85 @@ test.describe("list virtualization", () => {
305305
expect(Math.abs(settled1 - settled2)).toBeLessThan(2);
306306
}
307307
});
308+
309+
test("08 — cascading older pages never snap the viewport toward newest", async ({
310+
page,
311+
}) => {
312+
await installMockBridge(page);
313+
await page.goto("/#/channels/feedf00d-0000-4000-8000-000000000007");
314+
const timeline = page.getByTestId("message-timeline");
315+
await expect(timeline.locator("[data-message-id]").first()).toBeVisible();
316+
// Initial bottom positioning can momentarily cross the start threshold. Let
317+
// any resulting page transaction settle before driving explicit crossings.
318+
await page.waitForTimeout(1_000);
319+
320+
const sampleVisibleAnchor = (expectedId?: string) =>
321+
timeline.evaluate(async (scroller, anchorId) => {
322+
const s = scroller as HTMLElement;
323+
for (let frame = 0; frame < 60; frame += 1) {
324+
const scrollerTop = s.getBoundingClientRect().top;
325+
const rows = Array.from(
326+
s.querySelectorAll<HTMLElement>("[data-message-id]"),
327+
);
328+
const row = anchorId
329+
? rows.find((candidate) => candidate.dataset.messageId === anchorId)
330+
: rows.find(
331+
(candidate) =>
332+
candidate.getBoundingClientRect().top >= scrollerTop,
333+
);
334+
if (row) {
335+
return {
336+
id: row.dataset.messageId ?? "",
337+
top: row.getBoundingClientRect().top - scrollerTop,
338+
scrollHeight: s.scrollHeight,
339+
bottomDistance: s.scrollHeight - s.clientHeight - s.scrollTop,
340+
};
341+
}
342+
await new Promise((resolve) => requestAnimationFrame(resolve));
343+
}
344+
throw new Error(
345+
`anchor row ${anchorId ?? "at viewport top"} not mounted`,
346+
);
347+
}, expectedId);
348+
349+
// Load three consecutive server pages in one mounted virtualizer. This is
350+
// the production shape that exposed the intermittent end-cache snap: each
351+
// restored position can immediately approach the next history boundary.
352+
for (let pageIndex = 0; pageIndex < 3; pageIndex += 1) {
353+
// Leave the threshold first so Virtua emits a fresh start-edge crossing;
354+
// initial positioning can briefly report offset 0 while mounting.
355+
await timeline.evaluate((element) => {
356+
element.scrollTop = 4000;
357+
});
358+
await page.waitForTimeout(300);
359+
await timeline.evaluate((element) => {
360+
element.scrollTop = 250;
361+
});
362+
await page.waitForTimeout(150);
363+
const before = await sampleVisibleAnchor();
364+
await timeline.evaluate((element) => {
365+
element.scrollTop = 150;
366+
});
367+
368+
await expect
369+
.poll(
370+
async () => timeline.evaluate((element) => element.scrollHeight),
371+
{
372+
timeout: 10_000,
373+
},
374+
)
375+
.toBeGreaterThan(before.scrollHeight + 800);
376+
377+
const after = await sampleVisibleAnchor(before.id);
378+
expect(Math.abs(after.top - before.top)).toBeLessThan(120);
379+
// A snap to newest leaves this near zero. Keep a full viewport of history
380+
// below the reader after every prepend, rather than checking only the
381+
// final page and missing a transient cascade failure.
382+
expect(after.bottomDistance).toBeGreaterThan(
383+
await timeline.evaluate((element) => element.clientHeight),
384+
);
385+
}
386+
});
308387
});
309388

310389
test("thread-heavy history keeps a bounded mounted window", async ({

0 commit comments

Comments
 (0)