iterate.com / ui

git clone https://git.iterate.com/repos/ui

VirtualLog: keep visible rows still on older-page prepends and upward scroll

Jonas Templestein, 2026-11-28 00:21 UTC · 3dc305c0f458dc850ca41dfe60c58c9dd9afefc9 · parent 31a71d9

2 files changed

M src/components/virtual-log/use-reader.ts
@@ -184,6 +184,7 @@
     touchingRef,
     pressedRef,
     scrollingRef,
+    ownWriteRef,
     follow,
     keepAtEnd,
     runOwnScroll,
M src/components/virtual-log/virtual-log.tsx
@@ -42,14 +42,15 @@
 // Vertical breathing room is `paddingStart` and `paddingEnd`, not wrapper padding the virtualizer
 // cannot see. A row's spacing is padding, not margin, and a row renders its real height at once (no
 // deferred content): the first measurement is the one the anchor trusts.
-import { useCallback, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
 import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";
 import {
-  defaultRangeExtractor,
+  elementScroll,
   useVirtualizer,
   type Range,
   type Rect,
   type Virtualizer,
+  type VirtualizerOptions,
 } from "@tanstack/react-virtual";
 import { cn } from "cn";
 import {
@@ -65,6 +66,12 @@
  *  rows and not on blank. */
 const EDGE_ROWS = 40;
 
+/** Pixel overscan above and below the viewport, so runs of tiny 4 px rows still hold enough
+ *  runway to measure off-screen before scrolling into view, while 2,000 px rows are not over-mounted. */
+const OVERSCAN_PX = 1_600;
+const MIN_OVERSCAN_ROWS = 4;
+const MAX_OVERSCAN_ROWS = 120;
+
 /** The tail's virtual key: its index moves up as rows land above it, and keyed by index its (often
  *  tall) measurement would pass to the row that takes its place. */
 const TAIL_KEY = "virtual-log/tail";
@@ -150,47 +157,31 @@
 }) {
   const scrollRef = useRef<HTMLDivElement>(null);
   const footerRef = useRef<HTMLDivElement>(null);
+  const listContainerRef = useRef<HTMLDivElement | null>(null);
   const reader = useReader(footerRef, rows.length, onAtEndChange);
   const { atEnd, atTop, atEndRef, goingToTopRef, touchingRef, pressedRef, follow, runOwnScroll } =
     reader;
   const attachedToHead = newer.exhausted;
   const visibleTail = attachedToHead ? tail : undefined;
-  const rangeExtractor = useCallback(
-    (range: Range) => {
-      const indexes = defaultRangeExtractor(range);
-      const bound = goingToTopRef.current ? 0 : atEnd ? range.count - EDGE_ROWS : null;
-      if (bound === null) return indexes;
-      const from = Math.max(bound, 0);
-      const edge = Array.from({ length: Math.min(EDGE_ROWS, range.count) }, (_, at) => from + at);
-      return [...new Set([...indexes, ...edge])].sort((a, b) => a - b);
-    },
-    [atEnd, goingToTopRef],
-  );
-  const getItemKey = useCallback(
-    (index: number) => (index < rows.length ? rowInfo.key(rows[index]!) : TAIL_KEY),
-    [rowInfo, rows],
-  );
-  const estimateSize = useCallback(
-    (index: number) => (index < rows.length ? rowInfo.estimateSize(rows[index]!) : TAIL_ESTIMATE),
-    [rowInfo, rows],
-  );
   const count = rows.length + (visibleTail ? 1 : 0);
-  const virtualizer = useVirtualizer({
+  const virtualizer = useLogVirtualizer({
+    rows,
+    rowInfo,
     count,
-    getScrollElement: () => scrollRef.current,
-    estimateSize,
-    getItemKey,
-    anchorTo: "end",
-    scrollEndThreshold: SCROLL_END_THRESHOLD,
-    overscan: 16,
     paddingStart,
     paddingEnd,
-    observeElementRect: (instance, report) =>
-      observeRowsRect(instance, report, footerRef.current!, () => reader.keepAtEnd(instance)),
-    rangeExtractor,
-    directDomUpdates: true,
-    onChange: reader.keepAtEnd,
+    scrollRef,
+    footerRef,
+    listContainerRef,
+    reader,
   });
+  const setListContainerRef = useCallback(
+    (node: HTMLDivElement | null) => {
+      listContainerRef.current = node;
+      virtualizer.containerRef(node);
+    },
+    [virtualizer],
+  );
 
   const prevFollowTailRef = useRef(followTail);
   useLayoutEffect(() => {
@@ -267,7 +258,7 @@
         {count === 0 ? (
           empty
         ) : (
-          <div ref={virtualizer.containerRef} className="relative w-full">
+          <div ref={setListContainerRef} className="relative w-full">
             {virtualizer.getVirtualItems().map((virtualItem) => (
               <div
                 key={virtualItem.key}
@@ -354,6 +345,307 @@
       {arrived > 0 ? <span className="tabular-nums text-foreground">{arrived} new</span> : null}
     </ScrollBubble>
   );
+}
+
+type LayoutSnapshot = {
+  firstKey: string | null;
+  count: number;
+  items: Array<{ key: string; start: number; end: number }>;
+};
+
+/** 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. */
+function useLogVirtualizer<Row>({
+  rows,
+  rowInfo,
+  count,
+  paddingStart,
+  paddingEnd,
+  scrollRef,
+  footerRef,
+  listContainerRef,
+  reader,
+}: {
+  rows: readonly Row[];
+  rowInfo: VirtualLogRowInfo<Row>;
+  count: number;
+  paddingStart: number;
+  paddingEnd: number;
+  scrollRef: { current: HTMLDivElement | null };
+  footerRef: { current: HTMLDivElement | null };
+  listContainerRef: { current: HTMLDivElement | null };
+  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);
+  const [, setAnchorTick] = useState(0);
+
+  const getItemKey = useCallback(
+    (index: number) => (index < rows.length ? rowInfo.key(rows[index]!) : TAIL_KEY),
+    [rowInfo, rows],
+  );
+  const estimateSize = useCallback(
+    (index: number) => (index < rows.length ? rowInfo.estimateSize(rows[index]!) : TAIL_ESTIMATE),
+    [rowInfo, rows],
+  );
+  const rangeExtractor = useCallback(
+    (range: Range) => {
+      if (range.count === 0) return [];
+      const sizeOf = (index: number) => {
+        const key = index < rows.length ? rowInfo.key(rows[index]!) : TAIL_KEY;
+        return measuredSizesRef.current.get(key) ?? estimateSize(index);
+      };
+      const indexes = extractPixelOverscanRange(range, sizeOf);
+      const bound = goingToTopRef.current ? 0 : atEnd ? range.count - EDGE_ROWS : null;
+      if (bound === null) return indexes;
+      const from = Math.max(bound, 0);
+      const edge = Array.from({ length: Math.min(EDGE_ROWS, range.count) }, (_, at) => from + at);
+      return [...new Set([...indexes, ...edge])].sort((a, b) => a - b);
+    },
+    [atEnd, goingToTopRef, rows, rowInfo, estimateSize],
+  );
+  const scrollToFn = useCallback<VirtualizerOptions<HTMLDivElement, Element>["scrollToFn"]>(
+    (offset, options, instance) => {
+      const el = instance.scrollElement;
+      if (!el) return;
+      const prev = prevLayoutRef.current;
+      const isPendingPrepend =
+        prev !== null &&
+        prev.count > 0 &&
+        currentFirstKey !== null &&
+        prev.firstKey !== currentFirstKey &&
+        !prependAnchoredRef.current &&
+        !atEndRef.current &&
+        !goingToTopRef.current;
+      // Size-change compensation (`applyScrollAdjustment(delta)`):
+      // During a prepend commit's ref phase (before `_willUpdate` grows the container and anchors
+      // the prepend), defer scroll writes so we do not clamp against the old height or double-count
+      // with the prepend anchor that runs immediately after in `useLayoutEffect`.
+      // Otherwise `offset` is virtual-core's cached `scrollOffset`, which lags live `el.scrollTop`
+      // during active wheel scrolling: apply `adjustments` relative to live `el.scrollTop`.
+      if (options.adjustments) {
+        if (isPendingPrepend) return;
+        const liveTop = el.scrollTop;
+        const drift = liveTop - offset;
+        const target = Math.max(0, liveTop + options.adjustments);
+        // Inside a ResizeObserver batch, `applyScrollAdjustment` runs before `notify()` grows the
+        // list container's height. Grow it now when a positive adjustment would otherwise clamp.
+        if (
+          options.adjustments > 0 &&
+          listContainerRef.current &&
+          target > el.scrollHeight - el.clientHeight
+        ) {
+          listContainerRef.current.style.height = `${instance.getTotalSize()}px`;
+        }
+        el.scrollTop = target;
+        if (drift !== 0 && instance.scrollOffset !== null) {
+          instance.scrollOffset = Math.max(0, instance.scrollOffset + drift);
+        }
+        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) {
+        prependAnchoredRef.current = true;
+        const liveTop = el.scrollTop;
+        const delta = computePrependDelta(prev, rows, rowInfo, instance, liveTop);
+        const target = delta !== null ? Math.max(0, liveTop + delta) : Math.max(0, offset);
+        el.scrollTop = target;
+        instance.scrollOffset = target;
+        return;
+      }
+      elementScroll(offset, options, instance);
+    },
+    [atEndRef, currentFirstKey, goingToTopRef, listContainerRef, ownWriteRef, rows, rowInfo],
+  );
+  const virtualizer = useVirtualizer({
+    count,
+    getScrollElement: () => scrollRef.current,
+    estimateSize,
+    getItemKey,
+    scrollToFn,
+    anchorTo: "end",
+    scrollEndThreshold: SCROLL_END_THRESHOLD,
+    overscan: 16,
+    paddingStart,
+    paddingEnd,
+    observeElementRect: (instance, report) =>
+      observeRowsRect(instance, report, footerRef.current!, () => reader.keepAtEnd(instance)),
+    rangeExtractor,
+    directDomUpdates: true,
+    onChange: (instance) => {
+      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);
+      }
+    },
+  });
+
+  useLayoutEffect(() => {
+    virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
+      const scrollOffset = instance.scrollOffset ?? 0;
+      // Any row wholly above the viewport must compensate regardless of scroll direction
+      // (virtual-core's default skips re-measurement when `scrollDirection === "backward"`).
+      if (item.end <= scrollOffset) return true;
+      const viewportHeight = instance.scrollRect?.height ?? 0;
+      const mid = scrollOffset + viewportHeight / 2;
+      const isFirstMeasure = !instance.itemSizeCache.has(item.key);
+      if (isFirstMeasure) {
+        if (item.start < scrollOffset) return true;
+        if (viewportHeight > 0 && item.end <= mid) return true;
+      }
+      // Late reflow of a row strictly in the top half of the viewport keeps the middle row still,
+      // unless the reader just pressed a row to open/close it.
+      if (!pressedRef.current && viewportHeight > 0 && item.end <= mid) return true;
+      return false;
+    };
+  }, [virtualizer, pressedRef]);
+
+  useLayoutEffect(() => {
+    const el = scrollRef.current;
+    const prev = prevLayoutRef.current;
+    const handled = prependAnchoredRef.current;
+    prependAnchoredRef.current = false;
+    syncMeasuredSizes(virtualizer, measuredSizesRef.current);
+
+    if (
+      el &&
+      prev &&
+      !handled &&
+      prev.count > 0 &&
+      rows.length > 0 &&
+      prev.firstKey !== currentFirstKey &&
+      !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.
+      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);
+        setAnchorTick((n) => n + 1);
+        return;
+      }
+    }
+
+    prevLayoutRef.current = snapshotLayout(virtualizer, currentFirstKey, rows.length);
+  }, [
+    rows,
+    count,
+    rowInfo,
+    currentFirstKey,
+    scrollRef,
+    virtualizer,
+    atEndRef,
+    goingToTopRef,
+    touchingRef,
+  ]);
+
+  return virtualizer;
+}
+
+/** Expands `[startIndex, endIndex]` by at least `OVERSCAN_PX` (and `MIN_OVERSCAN_ROWS`) on each
+ *  side, capped at `MAX_OVERSCAN_ROWS`. */
+function extractPixelOverscanRange(range: Range, sizeOf: (index: number) => number): number[] {
+  let start = range.startIndex;
+  let pxBefore = 0;
+  let rowsBefore = 0;
+  while (
+    start > 0 &&
+    rowsBefore < MAX_OVERSCAN_ROWS &&
+    (pxBefore < OVERSCAN_PX || rowsBefore < MIN_OVERSCAN_ROWS)
+  ) {
+    start -= 1;
+    pxBefore += sizeOf(start);
+    rowsBefore += 1;
+  }
+  let end = range.endIndex;
+  let pxAfter = 0;
+  let rowsAfter = 0;
+  while (
+    end < range.count - 1 &&
+    rowsAfter < MAX_OVERSCAN_ROWS &&
+    (pxAfter < OVERSCAN_PX || rowsAfter < MIN_OVERSCAN_ROWS)
+  ) {
+    end += 1;
+    pxAfter += sizeOf(end);
+    rowsAfter += 1;
+  }
+  return Array.from({ length: end - start + 1 }, (_, at) => start + at);
+}
+
+function snapshotLayout(
+  instance: Virtualizer<HTMLDivElement, Element>,
+  firstKey: string | null,
+  count: number,
+): LayoutSnapshot {
+  return {
+    firstKey,
+    count,
+    items: instance.getVirtualItems().map((item) => ({
+      key: String(item.key),
+      start: item.start,
+      end: item.end,
+    })),
+  };
+}
+
+function syncMeasuredSizes(
+  instance: Virtualizer<HTMLDivElement, Element>,
+  target: Map<string, number>,
+) {
+  for (const item of instance.getVirtualItems()) {
+    const size = instance.itemSizeCache.get(item.key);
+    if (size !== undefined) target.set(String(item.key), size);
+  }
+}
+
+/** 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. */
+function computePrependDelta<Row>(
+  prev: LayoutSnapshot,
+  rows: readonly Row[],
+  rowInfo: VirtualLogRowInfo<Row>,
+  instance: Virtualizer<HTMLDivElement, Element>,
+  liveTop: number,
+): number | null {
+  const candidates = new Map<string, number>();
+  for (const oldItem of prev.items) {
+    if (oldItem.end < liveTop) continue;
+    candidates.set(oldItem.key, oldItem.start);
+  }
+  if (candidates.size === 0) return null;
+  instance.getTotalSize();
+  for (let i = 0; i < rows.length; i += 1) {
+    const oldStart = candidates.get(rowInfo.key(rows[i]!));
+    if (oldStart === undefined) continue;
+    const nextItem = instance.measurementsCache[i];
+    if (!nextItem) continue;
+    return nextItem.start - oldStart;
+  }
+  return null;
+}
+
+/** Matches `@tanstack/virtual-core`'s iOS WebKit check so we never write `scrollTop` during an
+ *  iOS momentum fling. */
+function isIOSWebKit(): boolean {
+  if (typeof navigator === "undefined") return false;
+  if (/iP(hone|od|ad)/.test(navigator.userAgent)) return true;
+  return navigator.platform === "MacIntel" && navigator.maxTouchPoints > 0;
 }
 
 /** Reports the part of the scroller the rows have: all of it less the footer over them. It is the