VirtualLog & ContextView: anchor same-day prepends on content rows and trim prepend main-thread work
Jonas Templestein, 2026-11-28 01:02 UTC · 963a61dfceef4c042123efe61c11daa3228690e7 · parent 406137a
4 files changed
- M src/components/context-view/feed-list.tsx
- M src/components/context-view/folds.tsx
- M src/components/virtual-log/virtual-log.tsx
- M src/lib/saved-log-tail.ts
M src/components/context-view/feed-list.tsx
@@ -81,8 +81,8 @@ const rowInfo = useMemo( (): VirtualLogRowInfo<FeedItem | MemberRow> => ({ key: (row) => row.key, - // every row is one line of 26px (event-row.tsx `rowClass`); a day mark is 36 - estimateSize: (row) => (row.kind === "day" ? 36 : 26), + // every row is one line of 26px (event-row.tsx `rowClass`); a day mark is 32px (`pt-3 pb-1 text-xs`) + estimateSize: (row) => (row.kind === "day" ? 32 : 26), // an event's, an opened run's event's, a run's last; none for a day mark offset: (row) => (row.kind === "member" ? row.event.offset : lastEventOf(row)?.offset), }),
M src/components/context-view/folds.tsx
@@ -149,7 +149,31 @@ const first = previous.items[1]!; // items[0] is the first day's mark const refolded = foldEvents(events.slice(0, growth.start.length + sizeOf(first))); const items = refolded.concat(previous.items.slice(2)); - return { events, items, namedBefore: whoBefore(items, actorOf) }; + const refoldedNamed = whoBefore(refolded, actorOf); + // Carry the last actor of `refolded` into `previous.namedBefore.slice(2)` only up to the first + // day mark or non-empty actor, avoiding an O(total items) rescan on every older page. + let carry = ""; + for (let i = refolded.length - 1; i >= 0; i -= 1) { + const item = refolded[i]!; + if (item.kind === "day") break; + const event = lastEventOf(item); + const who = event ? actorOf(event) : ""; + if (who) { + carry = who; + break; + } + } + const rest = previous.namedBefore.slice(2); + if (rest.length > 0 && previous.items[2]!.kind !== "day" && carry !== rest[0]) { + for (let j = 0; j < rest.length; j += 1) { + const item = previous.items[2 + j]!; + if (item.kind === "day") break; + rest[j] = carry; + const event = lastEventOf(item); + if (event && actorOf(event)) break; + } + } + return { events, items, namedBefore: refoldedNamed.concat(rest) }; } const items = foldEvents(events); return { events, items, namedBefore: whoBefore(items, actorOf) };
M src/components/virtual-log/virtual-log.tsx
@@ -348,14 +348,17 @@ } type LayoutSnapshot = { - firstKey: string | null; - count: number; - items: Array<{ key: string; start: number; end: number }>; + rows: readonly unknown[]; + /** Index and key of the first log row (`offset !== undefined`, else index 0): stays in place on + * tail appends and shifts/changes on any prepend, even when a floating day header keeps index 0. */ + headIndex: number; + headKey: string | null; + items: Array<{ key: string; index: number; start: number; end: number; hasOffset: boolean }>; }; /** Configures TanStack Virtual for a log with pixel-based overscan, live-`scrollTop` compensation * writes, backward-safe size-change anchoring, and a surviving-row fallback anchor when a prepend - * re-keys the oldest row. */ + * re-keys or floats the oldest row (such as a day separator). */ function useLogVirtualizer<Row>({ rows, rowInfo, @@ -378,7 +381,6 @@ reader: ReturnType<typeof useReader>; }) { const { atEnd, atEndRef, goingToTopRef, touchingRef, pressedRef, ownWriteRef } = reader; - const currentFirstKey = rows.length > 0 ? rowInfo.key(rows[0]!) : null; const measuredSizesRef = useRef<Map<string, number>>(new Map()); const prevLayoutRef = useRef<LayoutSnapshot | null>(null); const prependAnchoredRef = useRef(false); @@ -414,10 +416,7 @@ if (!el) return; const prev = prevLayoutRef.current; const isPendingPrepend = - prev !== null && - prev.count > 0 && - currentFirstKey !== null && - prev.firstKey !== currentFirstKey && + isHeadPrepended(prev, rows, rowInfo) && !prependAnchoredRef.current && !atEndRef.current && !goingToTopRef.current; @@ -448,9 +447,9 @@ return; } // Prepend anchor write from `_willUpdate` (`pendingScrollAnchor`): compute the exact shift - // from a surviving visible row and apply it to live `el.scrollTop` so wheel input between - // the last `scroll` event and the prepend commit is never overwritten. - if (isPendingPrepend && !ownWriteRef.current && options.behavior === undefined) { + // from a surviving content row and apply it to live `el.scrollTop` so wheel/rAF scroll + // between the last `scroll` event and the prepend commit is never overwritten. + if (isPendingPrepend && prev && !ownWriteRef.current && options.behavior === undefined) { prependAnchoredRef.current = true; const liveTop = el.scrollTop; const delta = computePrependDelta(prev, rows, rowInfo, instance, liveTop); @@ -461,7 +460,7 @@ } elementScroll(offset, options, instance); }, - [atEndRef, currentFirstKey, goingToTopRef, listContainerRef, ownWriteRef, rows, rowInfo], + [atEndRef, goingToTopRef, listContainerRef, ownWriteRef, rows, rowInfo], ); const virtualizer = useVirtualizer({ count, @@ -482,8 +481,8 @@ reader.keepAtEnd(instance); syncMeasuredSizes(instance, measuredSizesRef.current); const prev = prevLayoutRef.current; - if (prev && prev.firstKey === currentFirstKey && prev.count === rows.length) { - prevLayoutRef.current = snapshotLayout(instance, currentFirstKey, rows.length); + if (prev && prev.rows === rows) { + prevLayoutRef.current = snapshotLayout(instance, rows, rowInfo); } }, }); @@ -519,40 +518,28 @@ el && prev && !handled && - prev.count > 0 && - rows.length > 0 && - prev.firstKey !== currentFirstKey && + isHeadPrepended(prev, rows, rowInfo) && !atEndRef.current && !goingToTopRef.current && !touchingRef.current && !(isIOSWebKit() && virtualizer.isScrolling) ) { - // virtual-core's single-key anchor missed (typically because the oldest loaded row merged - // with earlier events and changed key). Keep the first surviving visible row still instead. + // virtual-core's single-key anchor missed (oldest row merged/re-keyed, or a floating day + // separator stayed at index 0 at scrollTop 0). Keep the first surviving content row still. const liveTop = el.scrollTop; const fallbackDelta = computePrependDelta(prev, rows, rowInfo, virtualizer, liveTop); if (fallbackDelta !== null && fallbackDelta !== 0) { const nextOffset = Math.max(0, liveTop + fallbackDelta); el.scrollTop = nextOffset; virtualizer.scrollOffset = nextOffset; - prevLayoutRef.current = snapshotLayout(virtualizer, currentFirstKey, rows.length); + prevLayoutRef.current = snapshotLayout(virtualizer, rows, rowInfo); setAnchorTick((n) => n + 1); return; } } - prevLayoutRef.current = snapshotLayout(virtualizer, currentFirstKey, rows.length); - }, [ - rows, - count, - rowInfo, - currentFirstKey, - scrollRef, - virtualizer, - atEndRef, - goingToTopRef, - touchingRef, - ]); + prevLayoutRef.current = snapshotLayout(virtualizer, rows, rowInfo); + }, [rows, count, rowInfo, scrollRef, virtualizer, atEndRef, goingToTopRef, touchingRef]); return virtualizer; } @@ -587,18 +574,40 @@ return Array.from({ length: end - start + 1 }, (_, at) => start + at); } -function snapshotLayout( +function isHeadPrepended<Row>( + prev: LayoutSnapshot | null, + rows: readonly Row[], + rowInfo: VirtualLogRowInfo<Row>, +): boolean { + if (!prev || prev.headKey === null || prev.rows === rows || rows.length === 0) return false; + const atHead = rows[prev.headIndex]; + return atHead === undefined || rowInfo.key(atHead) !== prev.headKey; +} + +function snapshotLayout<Row>( instance: Virtualizer<HTMLDivElement, Element>, - firstKey: string | null, - count: number, + rows: readonly Row[], + rowInfo: VirtualLogRowInfo<Row>, ): LayoutSnapshot { + let headIndex = 0; + let headKey: string | null = rows.length > 0 ? rowInfo.key(rows[0]!) : null; + for (let i = 0; i < rows.length && i < 8; i += 1) { + if (rowInfo.offset(rows[i]!) !== undefined) { + headIndex = i; + headKey = rowInfo.key(rows[i]!); + break; + } + } return { - firstKey, - count, + rows, + headIndex, + headKey, items: instance.getVirtualItems().map((item) => ({ key: String(item.key), + index: item.index, start: item.start, end: item.end, + hasOffset: item.index < rows.length && rowInfo.offset(rows[item.index]!) !== undefined, })), }; } @@ -614,8 +623,9 @@ } /** Finds the first surviving visible row from the previous layout and returns how far its layout - * `start` shifted, or `null` if no visible row survived. Stops at the first match in `rows`, so - * prepends stay O(prepended rows) even on 100,000-row logs. */ + * `start` shifted, or `null` if no visible row survived. Prefers log rows (`offset !== undefined`) + * over floating dividers such as day headers, which move to the top of their day on same-day + * prepends. Stops at the first match in `rows`, staying O(prepended rows) on 100,000-row logs. */ function computePrependDelta<Row>( prev: LayoutSnapshot, rows: readonly Row[], @@ -623,11 +633,14 @@ instance: Virtualizer<HTMLDivElement, Element>, liveTop: number, ): number | null { - const candidates = new Map<string, number>(); + const offsetCandidates = new Map<string, number>(); + const anyCandidates = new Map<string, number>(); for (const oldItem of prev.items) { if (oldItem.end < liveTop) continue; - candidates.set(oldItem.key, oldItem.start); + if (oldItem.hasOffset) offsetCandidates.set(oldItem.key, oldItem.start); + anyCandidates.set(oldItem.key, oldItem.start); } + const candidates = offsetCandidates.size > 0 ? offsetCandidates : anyCandidates; if (candidates.size === 0) return null; instance.getTotalSize(); for (let i = 0; i < rows.length; i += 1) {
M src/lib/saved-log-tail.ts
@@ -347,18 +347,29 @@ exhausted: boolean, version: number, ): SavedTail | undefined { - // an ephemeral event is never in the log again: a copy of one would show what a read cannot - const durable = events.filter((event) => event.ephemeral !== true); - let from = durable.length; + // Walk backward from the tail so prepending older pages never scans or copies earlier events. + // Ephemeral events are skipped: a copy of one would show what a read cannot. + const tail: SavedEvent[] = []; let total = 0; - while (from > 0 && durable.length - from < MOST_EVENTS) { - const more = total + charactersOf(durable[from - 1]!); - if (more > MOST_CHARACTERS) break; + let cut = false; + for (let i = events.length - 1; i >= 0; i -= 1) { + const event = events[i]!; + if (event.ephemeral === true) continue; + if (tail.length >= MOST_EVENTS) { + cut = true; + break; + } + const more = total + charactersOf(event); + if (more > MOST_CHARACTERS) { + cut = true; + break; + } total = more; - from -= 1; + tail.push(event); } - if (from === durable.length) return undefined; - return { events: durable.slice(from), exhausted: exhausted && from === 0, version }; + if (tail.length === 0) return undefined; + tail.reverse(); + return { events: tail, exhausted: exhausted && !cut, version }; } function charactersOf(event: SavedEvent) {