feat(desktop): add flat virtual-item model + useChatScrollVirtualizer

Phase 1 of the timeline virtualization migration. Adds the two foundations
the surface rewrites consume in Phase 2, with no behavior swap yet.

buildTimelineVirtualItems flattens the main-timeline entries + day
boundaries + firstUnreadMessageId into one ordered, keyed item per measured
row (dividers become their own items; the thread summary rides on its message
row so each message stays a single measured unit). Keys are byte-identical to
the legacy render keys so deep-link lookups and test selectors keep resolving.

useChatScrollVirtualizer wraps useVirtualizer directly (not the shared
VirtualizedList). It leans on virtual-core 3.17's library-native anchorTo:end
(anchored prepend) and followOnAppend (bottom-stick), and owns only the
short-channel bottom-align pad, recomputed off the live getTotalSize() on each
size-changing measurement and on container resize.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
This commit is contained in:
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
2026-06-17 19:00:59 -04:00
parent 7de5517f1d
commit 7ab6b4051c
3 changed files with 316 additions and 0 deletions

View File

@@ -4,6 +4,7 @@ import test from "node:test";
import {
BOTTOM_THRESHOLD_PX,
buildDayGroupBoundaries,
buildTimelineVirtualItems,
isNearBottomMetrics,
resolveDeepLinkTarget,
selectDeferredListRenderState,
@@ -287,3 +288,109 @@ test("deferred-render: keys the empty decision off the live count, not deferred"
assert.equal(selectDeferredListRenderState(0, 0), "empty");
assert.equal(selectDeferredListRenderState(0, 1), "pending");
});
// --- flat virtual-item model (main timeline virtualization) -----------------
//
// buildTimelineVirtualItems flattens the entries + day boundaries +
// firstUnreadMessageId into the ordered, keyed row list the virtualizer
// measures. It must mirror the legacy TimelineMessageList render walk exactly:
// one item per measured row, dividers as their own items, byte-identical keys.
function entry(overrides, summary = null) {
return { message: message(overrides), summary };
}
test("virtual-items: empty entries produce no items", () => {
assert.deepEqual(buildTimelineVirtualItems([]), []);
});
test("virtual-items: a single message opens a day then the message, no unread divider at index 0", () => {
const items = buildTimelineVirtualItems(
[entry({ id: "a", createdAt: dayAt(2026, 6, 14) })],
"a", // first-unread is the only row → divider suppressed (nothing above)
);
assert.deepEqual(
items.map((item) => item.kind),
["day", "message"],
);
assert.equal(items[0].key, `day-${dayAt(2026, 6, 14)}`);
assert.equal(items[1].key, "a");
});
test("virtual-items: a calendar-day boundary inserts a second day item", () => {
const items = buildTimelineVirtualItems([
entry({ id: "a", createdAt: dayAt(2026, 6, 14) }),
entry({ id: "b", createdAt: dayAt(2026, 6, 15) }),
]);
assert.deepEqual(
items.map((item) => item.kind),
["day", "message", "day", "message"],
);
});
test("virtual-items: unread divider precedes the first unread message when it is not index 0", () => {
const items = buildTimelineVirtualItems(
[
entry({ id: "a", createdAt: dayAt(2026, 6, 14) }),
entry({ id: "b", createdAt: dayAt(2026, 6, 14, 13) }),
],
"b",
);
assert.deepEqual(
items.map((item) => item.kind),
["day", "message", "unread", "message"],
);
// Divider sits immediately above its anchor and is keyed off that anchor.
assert.equal(items[2].key, "unread-b");
assert.equal(items[3].key, "b");
});
test("virtual-items: a system message routes to a system item", () => {
const items = buildTimelineVirtualItems([
entry({ id: "sys", kind: 40099, createdAt: dayAt(2026, 6, 14) }),
]);
assert.equal(items[1].kind, "system");
assert.equal(items[1].message.id, "sys");
});
test("virtual-items: a message item carries its inline thread summary, never a separate item", () => {
const summary = {
threadHeadId: "a",
replyCount: 2,
lastReplyAt: null,
participants: [],
};
const items = buildTimelineVirtualItems([
entry({ id: "a", createdAt: dayAt(2026, 6, 14) }, summary),
]);
// No extra item for the summary — it rides on the one measured message row.
assert.deepEqual(
items.map((item) => item.kind),
["day", "message"],
);
assert.equal(items[1].summary, summary);
});
test("virtual-items: row key prefers renderKey to keep optimistic-send identity stable", () => {
const items = buildTimelineVirtualItems([
entry({ id: "server-id", renderKey: "local-key" }),
]);
assert.equal(items[1].key, "local-key");
});
test("virtual-items: item count equals entries plus one day item per calendar day plus dividers", () => {
// 3 messages across 2 days, first-unread on the 3rd (index 2 → divider shows):
// days: 2 → 2 day items; messages: 3; unread: 1. Total = 6.
const items = buildTimelineVirtualItems(
[
entry({ id: "a", createdAt: dayAt(2026, 6, 14) }),
entry({ id: "b", createdAt: dayAt(2026, 6, 14, 13) }),
entry({ id: "c", createdAt: dayAt(2026, 6, 15) }),
],
"c",
);
assert.deepEqual(
items.map((item) => item.kind),
["day", "message", "message", "day", "unread", "message"],
);
});

View File

@@ -11,7 +11,13 @@
*/
import type { TimelineMessage } from "@/features/messages/types";
import { KIND_SYSTEM_MESSAGE } from "@/shared/constants/kinds";
import { isSameDay } from "./dateFormatters";
import {
type MainTimelineEntry,
type TimelineThreadSummary,
shouldRenderUnreadDivider,
} from "./threadPanel";
/** Distance (px) from the bottom within which the timeline counts as "at bottom". */
export const BOTTOM_THRESHOLD_PX = 72;
@@ -148,3 +154,76 @@ export function selectDeferredListRenderState(
}
return "pending";
}
/**
* One row in the flattened, virtualizer-ready timeline. Each item is the unit
* the virtualizer measures and positions, so every divider that the legacy
* `TimelineMessageList` rendered as a sibling node becomes its own item here.
*
* - "day" → a day-boundary heading; renders the sticky `DayDivider`
* - "unread" → the "New" read/unread boundary above the first unread message
* - "system" → a system message (join/leave); renders `SystemMessageRow`
* - "message" → a normal message; carries the thread `summary` it renders
* inline beneath the row (never a separate item — keeping the
* summary on the message row preserves one measured unit per
* message, which the virtualizer's height cache depends on)
*
* `key` is the React/virtualizer key and is byte-identical to the keys the
* legacy list used, so deep-link `data-message-id` lookups and test selectors
* keep resolving across the migration.
*/
export type TimelineVirtualItem =
| { kind: "day"; key: string; headingTimestamp: number }
| { kind: "unread"; key: string }
| { kind: "system"; key: string; message: TimelineMessage }
| {
kind: "message";
key: string;
message: TimelineMessage;
summary: TimelineThreadSummary | null;
};
/**
* Flattens the main-timeline entries into the ordered virtual-item list the
* virtualizer consumes. Mirrors the legacy `TimelineMessageList` render walk
* exactly: a day divider opens each new calendar-day group, an unread divider
* precedes the first unread top-level message (suppressed at index 0), and each
* entry becomes a `system` or `message` item. Pure over the snapshot so the
* ordering and divider rules stay lib-tested without a DOM.
*/
export function buildTimelineVirtualItems(
entries: readonly MainTimelineEntry[],
firstUnreadMessageId: string | null = null,
): TimelineVirtualItem[] {
const items: TimelineVirtualItem[] = [];
const dayGroupStartIndices = new Set(
buildDayGroupBoundaries(entries.map((entry) => entry.message)).map(
(boundary) => boundary.startIndex,
),
);
for (let i = 0; i < entries.length; i++) {
const { message, summary } = entries[i];
const messageKey = message.renderKey ?? message.id;
if (dayGroupStartIndices.has(i)) {
items.push({
kind: "day",
key: `day-${message.createdAt}`,
headingTimestamp: message.createdAt,
});
}
if (shouldRenderUnreadDivider(i, message.id, firstUnreadMessageId)) {
items.push({ kind: "unread", key: `unread-${messageKey}` });
}
if (message.kind === KIND_SYSTEM_MESSAGE) {
items.push({ kind: "system", key: messageKey, message });
} else {
items.push({ kind: "message", key: messageKey, message, summary });
}
}
return items;
}

View File

@@ -0,0 +1,130 @@
import { type Virtualizer, useVirtualizer } from "@tanstack/react-virtual";
import * as React from "react";
export type ChatVirtualizer = Virtualizer<HTMLElement, Element>;
/**
* Single scroll owner for the chat surfaces (main timeline + thread pane).
*
* The hard scroll behaviors are owned by `@tanstack/react-virtual` (over
* `virtual-core@3.17.0`), NOT hand-built here — that is the whole point of the
* migration off the manual scroll manager:
*
* - **Anchored prepend** (load-older holds the viewport): `anchorTo: "end"`.
* On a prepend the library captures the bottom anchor's key + relative
* offset and re-applies it after the new rows measure, so the viewport
* does not jump. This is the ResizeObserver-during-prepend race killed at
* the root.
* - **Bottom-stick during a burst**: `followOnAppend`. While pinned to the
* end the library re-scrolls to end on append, surviving measurement
* settle — no per-frame manual re-pin.
* - **Deep-link settle** (`scrollToIndex`): the library's internal
* reconcile loop re-targets the index until the offset is stable once the
* never-before-measured target row measures.
*
* What the library does NOT own — and this hook does:
*
* - **Short-channel bottom-align pad.** A 2-3 message channel must sit at the
* bottom of the viewport. The virtualizer lays rows from the top, so we add
* a top pad of `max(0, viewportHeight - totalSize)`. It is recomputed off
* the LIVE `getTotalSize()` on every measurement pass (via `onChange`) so
* it collapses to 0 the instant content exceeds the viewport — see the
* ordering note below.
*/
export type ChatScrollVirtualizerOptions = {
/** Number of flat virtual items. */
count: number;
/** Scroll container the surface owns (timeline/thread both own their own). */
scrollRef: React.RefObject<HTMLElement | null>;
/** Stable per-item key — byte-identical to the legacy render keys. */
getItemKey: (index: number) => string;
/** Estimated row height (px) before measurement. */
estimateSize?: number;
/** Rows rendered outside the viewport on each side. */
overscan?: number;
/**
* Bottom-stick mode. The main timeline and thread pane both want to follow
* new messages, so both pass `"auto"`; pass `false` to disable following.
*/
followOnAppend?: boolean | "auto" | "smooth" | "instant";
};
export type ChatScrollVirtualizer = {
virtualizer: ChatVirtualizer;
/**
* Top padding (px) that bottom-aligns a channel whose content is shorter
* than the viewport. Apply it to the row spacer's `paddingTop`. Always `0`
* once content fills the viewport.
*/
topPad: number;
};
export function useChatScrollVirtualizer({
count,
scrollRef,
getItemKey,
estimateSize = 80,
overscan = 6,
followOnAppend = "auto",
}: ChatScrollVirtualizerOptions): ChatScrollVirtualizer {
// Read the element lazily so the virtualizer binds once the ref attaches;
// capturing `ref.current` at render time would freeze it at the first-render
// `null` (mirrors VirtualizedList).
const getScrollElement = React.useCallback(
() => scrollRef.current,
[scrollRef],
);
const [topPad, setTopPad] = React.useState(0);
// Recompute the short-channel pad off the LIVE total whenever a row's
// measured size changes. virtual-core fires `onChange` directly from
// `resizeItem` on any size delta (not only on a visible-range change), which
// is exactly when `getTotalSize()` moves — so a short channel whose rows
// measure taller/shorter than the estimate re-pads with the settled total.
// Running it here, before paint and before the library re-applies its
// end-anchoring/follow in the same pass, orders "recompute pad -> re-pin
// bottom" and avoids a one-frame sliver when a short channel grows past the
// viewport.
const recomputePad = React.useCallback(
(instance: ChatVirtualizer) => {
const scrollEl = scrollRef.current;
if (!scrollEl) {
return;
}
const pad = Math.max(0, scrollEl.clientHeight - instance.getTotalSize());
setTopPad((prev) => (prev === pad ? prev : pad));
},
[scrollRef],
);
const virtualizer = useVirtualizer({
count,
getScrollElement,
estimateSize: () => estimateSize,
getItemKey,
overscan,
// Hold the viewport on prepend and pin to the bottom anchor for follow —
// the two library-native behaviors that replace the manual scroll manager.
anchorTo: "end",
followOnAppend,
onChange: recomputePad,
});
// The pad also depends on the viewport height, which `onChange` does not
// track — a window/pane resize that changes `clientHeight` without resizing a
// row would leave a short channel's pad stale. Observe the container so the
// bottom-align holds across resizes too.
React.useEffect(() => {
const scrollEl = scrollRef.current;
if (!scrollEl) {
return;
}
const observer = new ResizeObserver(() => recomputePad(virtualizer));
observer.observe(scrollEl);
return () => observer.disconnect();
}, [scrollRef, recomputePad, virtualizer]);
return { virtualizer, topPad };
}