Skip to content

Commit 25e7864

Browse files
wesbillmanCarlCarl
authored
fix(desktop): consolidate prepend scroll correction (#2855)
## Summary - make Virtua the sole prepend geometry/correction owner by accumulating active prepend ResizeObserver corrections from the live DOM offset - retire prepend reconciliation on ordinary reader wheel input, while preserving it for Ctrl+wheel browser zoom - remove Buzz's competing three-second semantic-anchor watcher and corrective `scrollBy` loop - keep ESM/CJS Virtua patch behavior equivalent and update the patch lock hash ## Why Buzz admitted prepended rows using seeded estimates, then Virtua received multiple measurement corrections for the same transaction. Each correction was based on the same stale model offset, so a later write replaced an earlier correction instead of accumulating it. In the reproduced first page, that resurrected 452px of anchor drift; the app-level watcher merely corrected the lost virtualizer write afterward. This fixes the correction inside Virtua and deletes the competing app writer, following the single-owner geometry invariant used by Berd rather than copying its spacer implementation. ## Validation - watcher-off desktop virtualization matrix: 11/11 passed, including 15 cascading prepends, continued wheel input, detached rich-row growth, channel switching, bottom follow, and buffered live arrivals - focused cascading prepend/Ctrl+wheel regression passed - desktop typecheck passed - desktop unit suite passed: 3,495 tests - Biome passed on changed desktop files - `git diff --check` clean ## Manual behavior Load older history repeatedly while scrolling upward, then wheel downward during/after a prepend. The visible anchor should stay within the existing 5px contract during reconciliation, and deliberate reader movement should not be pulled back. Ctrl+wheel during the prepend commit must not cancel reconciliation. --------- Signed-off-by: Wes <[email protected]> Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz>
1 parent c7089d3 commit 25e7864

15 files changed

Lines changed: 740 additions & 210 deletions

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,7 @@ const MessageTimelineBase = React.forwardRef<
335335
scrollContainerRef: activeScrollContainerRef,
336336
splitPanelOpen: splitThreadPanelOpen,
337337
targetMessageId,
338+
virtualCancelBottomIntent: timelineVirtualizerApi?.cancelBottomIntent,
338339
virtualScrollToMessage: timelineVirtualizerApi?.scrollToMessage,
339340
virtualScrollToBottom: timelineVirtualizerApi?.scrollToBottom,
340341
virtualSettleAtBottom: timelineVirtualizerApi?.settleAtBottom,

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

Lines changed: 22 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import { useUpwardPaginationWheel } from "./useUpwardPaginationWheel";
4242
import { useVirtualizedBottomSettle } from "./useVirtualizedBottomSettle";
4343

4444
export type TimelineVirtualizerApi = {
45+
cancelBottomIntent: () => void;
4546
scrollToBottom: (behavior?: ScrollBehavior) => void;
4647
settleAtBottom: () => void;
4748
scrollToMessage: (
@@ -454,145 +455,39 @@ function VirtualizedTimelineRows({
454455
const keys = React.useMemo(() => items.map(virtualizedItemKey), [items]);
455456
itemsLengthRef.current = items.length;
456457
const previousKeysRef = React.useRef<readonly string[]>([]);
457-
const prependAnchorRef = React.useRef<{
458-
itemKey: string;
459-
top: number;
460-
} | null>(null);
461-
const prependWatcherFrameRef = React.useRef<number | null>(null);
462458
const [prependShiftEpoch, clearPrependShift] = React.useReducer(
463459
(version: number) => version + 1,
464460
0,
465461
);
466-
// Virtua's `shift` is a one-render instruction, not a persistent mode. If it
467-
// stays true after a prepend, later measurement changes can keep anchoring
468-
// from the end and leave a stale blank range until the next scroll event.
469-
const isPrepend = React.useMemo(() => {
470-
void prependShiftEpoch;
471-
return didPrependVirtualizedTimeline(previousKeysRef.current, keys);
472-
}, [keys, prependShiftEpoch]);
473-
474-
const retirePrependAnchor = React.useCallback(() => {
475-
if (prependWatcherFrameRef.current !== null) {
476-
cancelAnimationFrame(prependWatcherFrameRef.current);
477-
}
478-
prependWatcherFrameRef.current = null;
479-
prependAnchorRef.current = null;
480-
}, []);
481462
const { cancel: cancelBottomSettle, settle: settleAtBottom } =
482463
useVirtualizedBottomSettle(hostRef, listRef, itemsLengthRef);
483-
const retireTimelineSettle = React.useCallback(() => {
484-
retirePrependAnchor();
485-
cancelBottomSettle();
486-
}, [cancelBottomSettle, retirePrependAnchor]);
487-
const { arm: armUpwardMomentum, clear: clearUpwardMomentum } =
488-
useUpwardPaginationWheel(hostRef, retireTimelineSettle);
489-
490-
const capturePrependAnchor = React.useCallback(() => {
491-
// Keep the pending capture current while the fetch is in flight. Once the
492-
// prepend commits and the watcher starts, its baseline is frozen.
493-
if (prependWatcherFrameRef.current !== null) return;
494-
const scroller = hostRef.current?.firstElementChild;
495-
if (!(scroller instanceof HTMLDivElement)) return;
496-
const scrollerTop = scroller.getBoundingClientRect().top;
497-
const row = Array.from(
498-
scroller.querySelectorAll<HTMLElement>("[data-timeline-item-key]"),
499-
).find(
500-
(candidate) => candidate.getBoundingClientRect().top >= scrollerTop - 1,
501-
);
502-
const itemKey = row?.dataset.timelineItemKey;
503-
if (!row || !itemKey) return;
504-
prependAnchorRef.current = {
505-
itemKey,
506-
top: row.getBoundingClientRect().top - scrollerTop,
507-
};
508-
}, []);
509-
510-
React.useLayoutEffect(() => {
511-
if (!isPrepend || !prependAnchorRef.current) return;
512-
// Virtua's shift mode correctly absorbs prepended measurements, but
513-
// estimated offsets can misclassify late row growth deep in history. Keep
514-
// the semantic row identity as a short-lived, deviation-gated backstop.
515-
// Do not correct in this commit: Virtua has shifted its estimate but has not
516-
// applied its ResizeObserver batch yet, so that delta is transient and its
517-
// subsequent absolute correction would overwrite our relative write.
518-
// This watcher deliberately survives a temporary row unmount and waits for
519-
// stable geometry so Virtua remains the primary scroll owner.
520-
if (prependWatcherFrameRef.current !== null) {
521-
cancelAnimationFrame(prependWatcherFrameRef.current);
522-
}
523-
const anchor = prependAnchorRef.current;
524-
const deadline = performance.now() + 3_000;
525-
let previousScrollTop: number | null = null;
526-
let settledFrames = 0;
527-
528-
const watch = () => {
529-
const scroller = hostRef.current?.firstElementChild;
530-
if (!(scroller instanceof HTMLDivElement)) {
531-
prependWatcherFrameRef.current = null;
532-
prependAnchorRef.current = null;
533-
return;
534-
}
535-
const atBottom =
536-
scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop <=
537-
32;
538-
const row = Array.from(
539-
scroller.querySelectorAll<HTMLElement>("[data-timeline-item-key]"),
540-
).find(
541-
(candidate) => candidate.dataset.timelineItemKey === anchor.itemKey,
542-
);
543-
const top = row
544-
? row.getBoundingClientRect().top - scroller.getBoundingClientRect().top
545-
: null;
546-
const scrollTop = scroller.scrollTop;
547-
settledFrames =
548-
previousScrollTop !== null &&
549-
Math.abs(scrollTop - previousScrollTop) < 0.5
550-
? settledFrames + 1
551-
: 0;
552-
previousScrollTop = scrollTop;
553-
554-
if (row && top !== null && settledFrames >= 2) {
555-
const delta = top - anchor.top;
556-
if (Math.abs(delta) > 4) {
557-
scroller.scrollBy({ top: delta });
558-
settledFrames = 0;
559-
previousScrollTop = null;
560-
}
561-
}
562-
563-
const retired =
564-
performance.now() >= deadline ||
565-
atBottom ||
566-
(top !== null && top > scroller.clientHeight * 2);
567-
if (retired) {
568-
retirePrependAnchor();
569-
return;
570-
}
571-
prependWatcherFrameRef.current = requestAnimationFrame(watch);
572-
};
573-
prependWatcherFrameRef.current = requestAnimationFrame(watch);
574-
clearUpwardMomentum();
575-
}, [clearUpwardMomentum, isPrepend, retirePrependAnchor]);
464+
const { arm: armUpwardMomentum } = useUpwardPaginationWheel(
465+
hostRef,
466+
cancelBottomSettle,
467+
);
576468

577469
React.useEffect(
578470
() => () => {
579-
retirePrependAnchor();
580471
cancelBottomSettle();
581472
},
582-
[cancelBottomSettle, retirePrependAnchor],
473+
[cancelBottomSettle],
583474
);
584475

476+
const isPrepend = React.useMemo(() => {
477+
void prependShiftEpoch;
478+
return didPrependVirtualizedTimeline(previousKeysRef.current, keys);
479+
}, [keys, prependShiftEpoch]);
480+
585481
React.useLayoutEffect(() => {
586482
previousKeysRef.current = keys;
587483
if (isPrepend) {
588-
cancelBottomSettle();
589484
clearPrependShift();
590485
}
591486
if (!hasInitialPositionedRef.current && items.length > 0) {
592487
hasInitialPositionedRef.current = true;
593488
settleAtBottom();
594489
}
595-
}, [cancelBottomSettle, isPrepend, items.length, keys, settleAtBottom]);
490+
}, [isPrepend, items.length, keys, settleAtBottom]);
596491

597492
const messageItemIndexById = React.useMemo(() => {
598493
const byId = new Map<string, number>();
@@ -622,16 +517,13 @@ function VirtualizedTimelineRows({
622517
React.useLayoutEffect(() => {
623518
if (!onVirtualizerApiChange) return;
624519
const api: TimelineVirtualizerApi = {
520+
cancelBottomIntent: cancelBottomSettle,
625521
scrollToBottom() {
626-
retireTimelineSettle();
627-
const lastIndex = itemsLengthRef.current - 1;
628-
if (lastIndex >= 0) {
629-
listRef.current?.scrollToIndex(lastIndex, { align: "end" });
630-
}
522+
settleAtBottom();
631523
},
632524
settleAtBottom,
633525
scrollToMessage(messageId) {
634-
retireTimelineSettle();
526+
cancelBottomSettle();
635527
const index = messageItemIndexByIdRef.current.get(messageId);
636528
if (index === undefined) return false;
637529
listRef.current?.scrollToIndex(index, { align: "center" });
@@ -640,7 +532,7 @@ function VirtualizedTimelineRows({
640532
};
641533
onVirtualizerApiChange(api);
642534
return () => onVirtualizerApiChange(null);
643-
}, [onVirtualizerApiChange, retireTimelineSettle, settleAtBottom]);
535+
}, [cancelBottomSettle, onVirtualizerApiChange, settleAtBottom]);
644536

645537
React.useLayoutEffect(() => {
646538
const host = hostRef.current;
@@ -670,24 +562,20 @@ function VirtualizedTimelineRows({
670562
if (!list || !(scroller instanceof HTMLDivElement)) return;
671563
onVirtualizerRangeChanged?.();
672564
const distanceFromBottom = list.scrollSize - list.viewportSize - offset;
673-
if (distanceFromBottom > 32) cancelBottomSettle();
565+
// Do not infer reader intent from an intermediate virtualizer offset.
566+
// Initial channel positioning deliberately chases the floor while rows
567+
// are measured; those measurements can briefly report a large gap and
568+
// emit `onScroll` without any user input. Cancelling here strands the
569+
// channel above its newest message. The settle hook's wheel, pointer,
570+
// touch, and key listeners are the authoritative user-interaction gate.
674571
onAtBottomStateChange?.(distanceFromBottom <= 32);
675-
if (
676-
prependAnchorRef.current !== null ||
677-
offset <= 200 ||
678-
prependWatcherFrameRef.current === null
679-
) {
680-
capturePrependAnchor();
681-
}
682572
if (offset <= 200) {
683573
// Layout scrolls near the top must not poison the reader's next input.
684574
armUpwardMomentum(onStartReached?.() ?? false);
685575
}
686576
},
687577
[
688578
armUpwardMomentum,
689-
cancelBottomSettle,
690-
capturePrependAnchor,
691579
onAtBottomStateChange,
692580
onStartReached,
693581
onVirtualizerRangeChanged,

‎desktop/src/features/messages/ui/useAnchoredScroll.lifecycle.test.mjs‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@ function installDOMShim() {
4848
return this.children[0] ?? null;
4949
}
5050

51+
get firstElementChild() {
52+
return this.children[0] ?? null;
53+
}
54+
5155
get lastChild() {
5256
return this.children.at(-1) ?? null;
5357
}
@@ -122,8 +126,16 @@ function installDOMShim() {
122126
}
123127

124128
globalThis.document = new DocumentShim();
129+
const windowEvents = new EventTargetShim();
130+
globalThis.addEventListener =
131+
windowEvents.addEventListener.bind(windowEvents);
132+
globalThis.removeEventListener =
133+
windowEvents.removeEventListener.bind(windowEvents);
134+
globalThis.dispatchEvent = windowEvents.dispatchEvent.bind(windowEvents);
125135
globalThis.HTMLIFrameElement = NodeShim;
136+
globalThis.HTMLDivElement = NodeShim;
126137
globalThis.HTMLElement = NodeShim;
138+
globalThis.Node = NodeShim;
127139
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
128140
process.env.IS_REACT_ACT_ENVIRONMENT = "true";
129141
Object.defineProperty(globalThis, "window", {
@@ -142,6 +154,7 @@ import { act } from "react";
142154
import { createRoot } from "react-dom/client";
143155

144156
import { useAnchoredScroll } from "./useAnchoredScroll.ts";
157+
import { useVirtualizedBottomSettle } from "./useVirtualizedBottomSettle.ts";
145158

146159
function makePinnedCenterNodes() {
147160
const resizeObservers = [];
@@ -232,6 +245,32 @@ function Harness({ channelId, refs }) {
232245
return null;
233246
}
234247

248+
function VirtualTargetHarness({ refs }) {
249+
const didRun = React.useRef(false);
250+
const bottomApi = useVirtualizedBottomSettle(
251+
refs.host,
252+
refs.list,
253+
refs.itemsLength,
254+
);
255+
const anchored = useAnchoredScroll({
256+
channelId: "conversation",
257+
contentRef: refs.content,
258+
isLoading: false,
259+
messages: Array.from({ length: 5 }, (_, index) => ({ id: String(index) })),
260+
scrollContainerRef: refs.scroller,
261+
virtualCancelBottomIntent: bottomApi.cancel,
262+
virtualizerOwnsPrependAnchoring: true,
263+
virtualScrollToMessage: () => true,
264+
});
265+
React.useLayoutEffect(() => {
266+
if (didRun.current) return;
267+
didRun.current = true;
268+
bottomApi.settle();
269+
refs.targetResult.current = anchored.scrollToMessage("selected");
270+
}, [anchored.scrollToMessage, bottomApi.settle, refs.targetResult]);
271+
return null;
272+
}
273+
235274
test("channel change attaches pinned-center observers after refs mount", async () => {
236275
const refs = {
237276
container: { current: null },
@@ -272,3 +311,79 @@ test("channel change attaches pinned-center observers after refs mount", async (
272311
root.unmount();
273312
});
274313
});
314+
315+
test("mounted virtual target retires bottom intent before direct centering", async () => {
316+
const resizeObservers = [];
317+
globalThis.ResizeObserver = class {
318+
constructor(callback) {
319+
this.callback = callback;
320+
this.targets = [];
321+
resizeObservers.push(this);
322+
}
323+
disconnect() {}
324+
observe(target) {
325+
this.targets.push(target);
326+
}
327+
};
328+
329+
const content = document.createElement("div");
330+
const scroller = document.createElement("div");
331+
const host = document.createElement("div");
332+
scroller.appendChild(content);
333+
host.appendChild(scroller);
334+
scroller.clientHeight = 400;
335+
scroller.scrollHeight = 1_000;
336+
scroller.scrollTop = 0;
337+
scroller.getBoundingClientRect = () => ({ bottom: 400, top: 0 });
338+
const targetContentTop = 250;
339+
const row = {
340+
getBoundingClientRect: () => ({
341+
bottom: targetContentTop - scroller.scrollTop + 40,
342+
height: 40,
343+
top: targetContentTop - scroller.scrollTop,
344+
}),
345+
};
346+
scroller.querySelector = () => row;
347+
scroller.querySelectorAll = () => [];
348+
scroller.scrollTo = ({ top }) => {
349+
scroller.scrollTop = top;
350+
};
351+
352+
const bottomWrites = [];
353+
const refs = {
354+
content: { current: content },
355+
host: { current: host },
356+
itemsLength: { current: 5 },
357+
list: {
358+
current: {
359+
scrollToIndex: (index, options) =>
360+
bottomWrites.push({ index, options }),
361+
},
362+
},
363+
scroller: { current: scroller },
364+
targetResult: { current: null },
365+
};
366+
const root = createRoot(document.createElement("div"));
367+
await act(async () => {
368+
root.render(React.createElement(VirtualTargetHarness, { refs }));
369+
});
370+
371+
assert.deepEqual(bottomWrites, [{ index: 4, options: { align: "end" } }]);
372+
assert.equal(refs.targetResult.current, true);
373+
assert.equal(row.getBoundingClientRect().top, 180);
374+
const bottomGeometryObserver = resizeObservers.find(
375+
(observer) =>
376+
observer.targets.includes(content) && observer.targets.includes(scroller),
377+
);
378+
assert.ok(bottomGeometryObserver);
379+
bottomGeometryObserver.callback();
380+
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
381+
382+
assert.equal(
383+
row.getBoundingClientRect().top,
384+
180,
385+
"target remains centered after later virtual geometry activity",
386+
);
387+
assert.equal(bottomWrites.length, 1, "geometry cannot re-pin to bottom");
388+
await act(async () => root.unmount());
389+
});

0 commit comments

Comments
 (0)