Skip to content

Commit 406cf79

Browse files
wesbillmanPinky
andauthored
fix(desktop): seed timeline virtualization row heights (#1887)
Signed-off-by: Wes <[email protected]> Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co>
1 parent 366567a commit 406cf79

7 files changed

Lines changed: 363 additions & 68 deletions

File tree

‎desktop/src/features/messages/lib/rowHeightEstimate.ts‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -165,18 +165,20 @@ const SYSTEM_GROUP_HEIGHT = 80;
165165
* near its true height instead of snapping the scroll position. `auto` keeps
166166
* refining once the row paints.
167167
*/
168+
export function estimateTimelineItemHeight(item: TimelineItem): number {
169+
return item.kind === "message"
170+
? estimateRowHeight(item.entry.message, {
171+
isContinuation: item.isContinuation,
172+
}) + (item.isFollowedByContinuation ? 0 : MESSAGE_ITEM_BOTTOM_PADDING)
173+
: item.kind === "system"
174+
? estimateRowHeight(item.entry.message)
175+
: item.kind === "system-group"
176+
? SYSTEM_GROUP_HEIGHT
177+
: DIVIDER_HEIGHT;
178+
}
179+
168180
export function timelineRowReserveStyle(
169181
item: TimelineItem,
170182
): React.CSSProperties {
171-
const height =
172-
item.kind === "message"
173-
? estimateRowHeight(item.entry.message, {
174-
isContinuation: item.isContinuation,
175-
}) + (item.isFollowedByContinuation ? 0 : MESSAGE_ITEM_BOTTOM_PADDING)
176-
: item.kind === "system"
177-
? estimateRowHeight(item.entry.message)
178-
: item.kind === "system-group"
179-
? SYSTEM_GROUP_HEIGHT
180-
: DIVIDER_HEIGHT;
181-
return { containIntrinsicSize: `auto ${height}px` };
183+
return { containIntrinsicSize: `auto ${estimateTimelineItemHeight(item)}px` };
182184
}

‎desktop/src/features/messages/lib/virtualizedTimelineItems.test.mjs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import test from "node:test";
44
import {
55
buildVirtualizedItems,
66
didPrependVirtualizedTimeline,
7+
estimateVirtualizedTimelineItemHeight,
78
virtualizedItemKey,
89
} from "./virtualizedTimelineItems.ts";
910

@@ -204,3 +205,23 @@ test("naive counterexample stays rejected: same key cannot precede prepended row
204205
false,
205206
);
206207
});
208+
209+
test("virtualized rows preserve their heterogeneous height estimates", () => {
210+
const short = messageItem("short");
211+
short.entry.message.body = "hello";
212+
const tall = messageItem("tall");
213+
tall.entry.message.body = Array.from(
214+
{ length: 20 },
215+
(_, index) => `line ${index}`,
216+
).join("\n");
217+
const items = buildVirtualizedItems(
218+
[{ key: "day-A", headingTimestamp: DAY_A, items: [short, tall] }],
219+
undefined,
220+
true,
221+
);
222+
const estimates = items.map(estimateVirtualizedTimelineItemHeight);
223+
224+
assert.equal(estimates[0], 32);
225+
assert.ok(estimates[2] > estimates[1] + 200);
226+
assert.equal(estimates.at(-1), 96);
227+
});

‎desktop/src/features/messages/lib/virtualizedTimelineItems.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import type * as React from "react";
1010

11+
import { estimateTimelineItemHeight } from "./rowHeightEstimate";
1112
import {
1213
getTimelineItemKey,
1314
type TimelineDayGroup,
@@ -26,6 +27,15 @@ export type VirtualizedTimelineItem =
2627
item: TimelineNonDayItem;
2728
};
2829

30+
export function estimateVirtualizedTimelineItemHeight(
31+
item: VirtualizedTimelineItem,
32+
): number {
33+
if (item.kind === "bottom-spacer") return 96;
34+
if (item.kind === "leading-content") return 60;
35+
if (item.kind === "day-divider") return 32;
36+
return estimateTimelineItemHeight(item.item);
37+
}
38+
2939
export function virtualizedItemKey(item: VirtualizedTimelineItem): string {
3040
if (item.kind === "bottom-spacer") return "bottom-spacer";
3141
if (item.kind === "leading-content") return "leading-content";

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

Lines changed: 102 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import {
1414
import {
1515
buildVirtualizedItems,
1616
didPrependVirtualizedTimeline,
17+
estimateVirtualizedTimelineItemHeight,
18+
type VirtualizedTimelineItem,
1719
virtualizedItemKey,
1820
} from "@/features/messages/lib/virtualizedTimelineItems";
1921
import { THREAD_REPLY_ROW_MARGIN_INLINE_REM } from "@/features/messages/lib/threadTreeLayout";
@@ -370,6 +372,33 @@ type VirtualizedTimelineRowsProps = {
370372
renderItem: (item: TimelineNonDayItem) => React.ReactNode;
371373
};
372374

375+
type VirtualizedTimelineItemShellProps = {
376+
children: React.ReactNode;
377+
index: number;
378+
ref?: React.LegacyRef<HTMLDivElement>;
379+
style: React.CSSProperties;
380+
};
381+
382+
const PreserveVirtualizedItemVisibilityContext = React.createContext(false);
383+
384+
function VirtualizedTimelineItemShell({
385+
children,
386+
ref,
387+
style,
388+
}: VirtualizedTimelineItemShellProps) {
389+
const preserveVisibility = React.useContext(
390+
PreserveVirtualizedItemVisibilityContext,
391+
);
392+
return (
393+
<div
394+
ref={ref}
395+
style={preserveVisibility ? style : { ...style, visibility: undefined }}
396+
>
397+
{children}
398+
</div>
399+
);
400+
}
401+
373402
function VirtualizedTimelineRows({
374403
dayGroups,
375404
historyExhausted,
@@ -391,6 +420,20 @@ function VirtualizedTimelineRows({
391420
typeof window === "undefined" ? 1_000 : window.innerHeight,
392421
);
393422
const hasInitialPositionedRef = React.useRef(false);
423+
const estimateCallCountRef = React.useRef(0);
424+
const estimateItemSize = React.useCallback(
425+
(item: VirtualizedTimelineItem) => {
426+
estimateCallCountRef.current += 1;
427+
const scroller = hostRef.current?.firstElementChild;
428+
if (scroller instanceof HTMLDivElement) {
429+
scroller.dataset.virtuaEstimateCallCount = String(
430+
estimateCallCountRef.current,
431+
);
432+
}
433+
return estimateVirtualizedTimelineItemHeight(item);
434+
},
435+
[],
436+
);
394437
const items = React.useMemo(
395438
() => buildVirtualizedItems(dayGroups, leadingContent, historyExhausted),
396439
[dayGroups, historyExhausted, leadingContent],
@@ -555,6 +598,9 @@ function VirtualizedTimelineRows({
555598
if (element) {
556599
element.dataset.buzzConversationScroll = "true";
557600
element.dataset.testid = "message-timeline";
601+
element.dataset.virtuaEstimateCallCount = String(
602+
estimateCallCountRef.current,
603+
);
558604
}
559605
onVirtualizerScrollerChange?.(element);
560606
return () => onVirtualizerScrollerChange?.(null);
@@ -637,62 +683,66 @@ function VirtualizedTimelineRows({
637683

638684
return (
639685
<div className="h-full min-h-0 w-full" ref={hostRef}>
640-
<VList
641-
ref={listRef}
642-
className="h-full min-h-0 w-full overflow-y-auto overflow-x-hidden overscroll-contain px-2 pt-[var(--channel-top-chrome-height,4.5rem)]"
643-
data={items}
644-
bufferSize={offscreenBufferSize}
645-
keepMounted={retainedIndices}
646-
style={{ overflowAnchor: "none" }}
647-
shift={isPrepend}
648-
onScroll={handleScroll}
649-
onScrollEnd={handleScrollEnd}
650-
>
651-
{(item) => {
652-
if (item.kind === "bottom-spacer") {
653-
return (
654-
<div
655-
aria-hidden
656-
className="h-[var(--composer-overlay-height,6rem)]"
657-
key={virtualizedItemKey(item)}
658-
/>
659-
);
660-
}
661-
if (item.kind === "leading-content") {
662-
return <div key={virtualizedItemKey(item)}>{item.content}</div>;
663-
}
664-
if (item.kind === "day-divider") {
665-
const dayLabel = formatDayHeading(item.headingTimestamp);
686+
<PreserveVirtualizedItemVisibilityContext value={isPrepend}>
687+
<VList
688+
ref={listRef}
689+
className="h-full min-h-0 w-full overflow-y-auto overflow-x-hidden overscroll-contain px-2 pt-[var(--channel-top-chrome-height,4.5rem)]"
690+
data={items}
691+
item={VirtualizedTimelineItemShell}
692+
itemSize={estimateItemSize}
693+
bufferSize={offscreenBufferSize}
694+
keepMounted={retainedIndices}
695+
style={{ overflowAnchor: "none" }}
696+
shift={isPrepend}
697+
onScroll={handleScroll}
698+
onScrollEnd={handleScrollEnd}
699+
>
700+
{(item) => {
701+
if (item.kind === "bottom-spacer") {
702+
return (
703+
<div
704+
aria-hidden
705+
className="h-[var(--composer-overlay-height,6rem)]"
706+
key={virtualizedItemKey(item)}
707+
/>
708+
);
709+
}
710+
if (item.kind === "leading-content") {
711+
return <div key={virtualizedItemKey(item)}>{item.content}</div>;
712+
}
713+
if (item.kind === "day-divider") {
714+
const dayLabel = formatDayHeading(item.headingTimestamp);
715+
return (
716+
<div
717+
// The sticky pill needs travel room, but its containing block
718+
// is this item wrapper. The trailing spacer extends the content
719+
// box by 4rem while the matching negative margin keeps the
720+
// measured layout height at exactly the divider's height, so
721+
// row spacing and Virtua's size cache are unaffected. Both the
722+
// spacer and the pill are pointer-events-none, and the later
723+
// (absolutely positioned) row siblings paint above the spacer.
724+
className="relative -mb-16 flex flex-col before:absolute before:inset-x-0 before:top-4 before:h-px before:bg-border/35 before:content-['']"
725+
data-day-label={dayLabel}
726+
data-testid="message-timeline-day-group"
727+
key={virtualizedItemKey(item)}
728+
>
729+
<DayDivider label={dayLabel} />
730+
<div aria-hidden className="pointer-events-none h-16" />
731+
</div>
732+
);
733+
}
666734
return (
667-
<div
668-
// The sticky pill needs travel room, but its containing block
669-
// is this item wrapper. The trailing spacer extends the content
670-
// box by 4rem while the matching negative margin keeps the
671-
// measured layout height at exactly the divider's height, so
672-
// row spacing and Virtua's size cache are unaffected. Both the
673-
// spacer and the pill are pointer-events-none, and the later
674-
// (absolutely positioned) row siblings paint above the spacer.
675-
className="relative -mb-16 flex flex-col before:absolute before:inset-x-0 before:top-4 before:h-px before:bg-border/35 before:content-['']"
676-
data-day-label={dayLabel}
677-
data-testid="message-timeline-day-group"
735+
<TimelineRowShell
736+
item={item.item}
678737
key={virtualizedItemKey(item)}
738+
useContentVisibility={false}
679739
>
680-
<DayDivider label={dayLabel} />
681-
<div aria-hidden className="pointer-events-none h-16" />
682-
</div>
740+
{renderItem(item.item)}
741+
</TimelineRowShell>
683742
);
684-
}
685-
return (
686-
<TimelineRowShell
687-
item={item.item}
688-
key={virtualizedItemKey(item)}
689-
useContentVisibility={false}
690-
>
691-
{renderItem(item.item)}
692-
</TimelineRowShell>
693-
);
694-
}}
695-
</VList>
743+
}}
744+
</VList>
745+
</PreserveVirtualizedItemVisibilityContext>
696746
</div>
697747
);
698748
}

‎desktop/tests/e2e/timeline-no-shift.spec.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,56 @@ function expectAnchorOrderUnchanged(
202202
expect(after.rowsFromAnchor).toEqual(before.rowsFromAnchor);
203203
}
204204

205+
test("timeline does not recompute row estimates during ordinary scroll", async ({
206+
page,
207+
}) => {
208+
await installMockBridge(page);
209+
await page.goto("/");
210+
await waitForMockTimelineBridge(page);
211+
await page.evaluate(() => {
212+
for (let index = 0; index < 120; index += 1) {
213+
window.__BUZZ_E2E_EMIT_MOCK_MESSAGE__?.({
214+
channelName: "general",
215+
content: `estimate memo row ${index}\nsecond line ${index}`,
216+
createdAt: 1_700_500_000 + index,
217+
});
218+
}
219+
});
220+
221+
await page.getByTestId("channel-general").click();
222+
await expect(page.getByTestId("chat-title")).toHaveText("general");
223+
const timeline = page.getByTestId("message-timeline");
224+
await expect(timeline).toContainText("estimate memo row 119");
225+
await page.waitForFunction(() => {
226+
const element = document.querySelector<HTMLDivElement>(
227+
'[data-testid="message-timeline"]',
228+
);
229+
return element && element.scrollHeight > element.clientHeight * 3;
230+
});
231+
232+
const estimateCallsBefore = await timeline.evaluate((element) =>
233+
Number((element as HTMLDivElement).dataset.virtuaEstimateCallCount ?? "0"),
234+
);
235+
expect(estimateCallsBefore).toBeGreaterThan(0);
236+
237+
await timeline.evaluate(async (element) => {
238+
const scroller = element as HTMLDivElement;
239+
const maxOffset = scroller.scrollHeight - scroller.clientHeight;
240+
for (const fraction of [0.75, 0.5, 0.25, 0.6, 0.4]) {
241+
scroller.scrollTop = maxOffset * fraction;
242+
scroller.dispatchEvent(new Event("scroll", { bubbles: true }));
243+
await new Promise<void>((resolve) =>
244+
requestAnimationFrame(() => resolve()),
245+
);
246+
}
247+
});
248+
249+
const estimateCallsAfter = await timeline.evaluate((element) =>
250+
Number((element as HTMLDivElement).dataset.virtuaEstimateCallCount ?? "0"),
251+
);
252+
expect(estimateCallsAfter).toBe(estimateCallsBefore);
253+
});
254+
205255
test("timeline reserves mixed-media rows before fast scrollback", async ({
206256
page,
207257
}, testInfo) => {
@@ -450,6 +500,15 @@ test("timeline prepend plus late row reflow keeps the reading row stable", async
450500
const before = await snapshotAnchor(timeline);
451501
expect(before.anchorId).not.toBe("");
452502
expect(before.oldestOlderIndex).not.toBeNull();
503+
await timeline.evaluate((element, anchorId) => {
504+
const anchor = element.querySelector<HTMLElement>(
505+
`[data-message-id="${CSS.escape(anchorId)}"]`,
506+
);
507+
if (!anchor) throw new Error("prepend mount-identity anchor missing");
508+
(
509+
window as typeof window & { __PREPEND_MOUNT_IDENTITY__?: HTMLElement }
510+
).__PREPEND_MOUNT_IDENTITY__ = anchor;
511+
}, before.anchorId);
453512
await startAnchorDriftSampler(timeline, before.anchorId, before.anchorTop);
454513

455514
await expect
@@ -469,6 +528,22 @@ test("timeline prepend plus late row reflow keeps the reading row stable", async
469528

470529
const afterPrepend = await snapshotAnchor(timeline);
471530
expect(afterPrepend.anchorId).toBe(before.anchorId);
531+
expect(
532+
await timeline.evaluate((element, anchorId) => {
533+
const anchor = element.querySelector<HTMLElement>(
534+
`[data-message-id="${CSS.escape(anchorId)}"]`,
535+
);
536+
return (
537+
anchor ===
538+
(
539+
window as typeof window & {
540+
__PREPEND_MOUNT_IDENTITY__?: HTMLElement;
541+
}
542+
).__PREPEND_MOUNT_IDENTITY__
543+
);
544+
}, before.anchorId),
545+
"prepend must preserve the mounted anchor DOM node",
546+
).toBe(true);
472547
expect(
473548
Math.abs(afterPrepend.anchorTop - before.anchorTop),
474549
// First-pass prepended rows realize from content-visibility estimates to

0 commit comments

Comments
 (0)