iterate.com / ui

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

ui / src / components / virtual-log / virtual-log.tsxmain at d68d7e1

// THE VIRTUAL LOG: a log as ONE virtual list in its own scroll region (TanStack Virtual), the root
// every view of a log stands on. A view brings its rows and how to draw one, and gets the rest: only
// the rows in view, plus an overscan, are in the DOM, so 100,000 rows scroll like 100. The list opens
// at its newest row and stays there as rows arrive, a reader in history is never moved, older pages
// load near the top, and once a reader is in history a bubble at the bottom counts what came in and
// leads back to it, and one at the top goes all the way up. `ContextView`'s feed, the agent chat and an LLM trace are each this and
// their own rows, as a view of any other domain is. A view has three places for what it shows:
// - `rows`: what is in the log, virtual, as many as there are.
// - `tail`: what is not in the log yet and ends the list: work in flight, an answer streaming in, any
//   stack of them. It scrolls with the rows, so a reader can leave it behind, and it can grow.
// - `footer`: what is always there, a composer: the rows scroll behind it.
//
//   const DEPLOY_ROWS: VirtualLogRowInfo<DeployEvent> = {
//     key: (event) => String(event.offset),
//     estimateSize: () => 72,
//     offset: (event) => event.offset,
//   };
//   const deploys = useMemo(() => context.events.filter(isDeploy), [context.events]);
//   <VirtualLog
//     rows={deploys}
//     rowInfo={DEPLOY_ROWS}
//     renderRow={(event) => <DeployCard event={event} />}
//     tail={running ? <DeployInProgress state={running} /> : undefined}
//     footer={<DeployComposer />}
//     older={context.older}
//     label="Deploys"
//   />
//
// The scheme is TanStack Virtual's chat mode (https://tanstack.com/virtual/latest/docs/chat):
// `anchorTo: "end"` keeps what a reader sees still as rows land above them, `scrollToEnd()` opens,
// jumps and follows. Rows are keyed by identity, never by index, which is what lets the anchor find
// its row after a prepend. Load state stays out of the list, as the guide asks: index i is row i.
// Two things here go past the guide, each through a public option:
// - `footer` (a composer of any height) sits inside the scroller, sticky at the bottom, so the
//   scrollbar runs past it. `observeElementRect` reports the scroller less the footer: the part the
//   rows have is the viewport the virtualizer should reason about.
// - The view follows by `scrollToEnd()` itself, not `followOnAppend`, which needs the last key to
//   change: rows settling above the tail leave that key as it was. A layout effect does it for new
//   rows and `onChange` for measured ones: with `directDomUpdates` the sizer is already the new size
//   there, so the view lands on the true end before the frame is painted.
//   `rangeExtractor` has the rows at the end mounted before the view gets there.
// 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, useState, type ReactNode } from "react";
import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";
import {
  elementScroll,
  useVirtualizer,
  type Range,
  type Rect,
  type Virtualizer,
  type VirtualizerOptions,
} from "@tanstack/react-virtual";
import { cn } from "cn";
import {
  NEWER_EXHAUSTED,
  OLDER_EXHAUSTED,
  type NewerPages,
  type OlderPages,
} from "./older-pages.ts";
import { SCROLL_END_THRESHOLD, useReader } from "./use-reader.ts";

/** Rows kept mounted at the edge the view is bound for: a view's worth at the smallest rows on a
 *  usual screen, so that a jump there, which the virtualizer only reads back a frame later, lands on
 *  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";

/** The tail's height until it is measured. */
const TAIL_ESTIMATE = 48;

/** Newer pages (a detached window of history) are asked for when the view's end is this near the
 *  end of what is loaded. */
const LOAD_NEWER_WITHIN_PX = 1_500;

/** READ AHEAD OF THE READER. An older page is asked for while fewer than this many px stand over
 *  the view: about ten screens, and each page that lands asks for the next until they do. A page
 *  is one read of the mind and takes about a second, so at 1,500 px a reader who went up at a
 *  steady pace met the list's top and its "reading older" line again and again (Jonas, 28 Nov
 *  2026: "proactively load more events in the past […] too many loading breaks when scrolling
 *  up"). A view that wants its pages later wraps `older.loadOlder` (the agent chat does). */
export const READ_AHEAD_PX = 8_000;

/** What the list needs to know of a row. Stable across renders (a constant, or `useMemo`): the
 *  virtualizer lays every row out again when these change. */
export type VirtualLogRowInfo<Row> = {
  /** A row's identity, stable as rows arrive at either end. */
  key: (row: Row) => string;
  /** A row's height until it is measured. */
  estimateSize: (row: Row) => number;
  /** Where a row sits in the log: what the pill counts and what `reveal` finds. A row that is not
   *  in the log (a day mark, the work in flight) has none. */
  offset: (row: Row) => number | undefined;
  /** Optional inclusive `[from, to]` offset span covered by a folded row so `reveal` lands on it. */
  span?: (row: Row) => readonly [from: number, to: number] | undefined;
};

export function VirtualLog<Row>({
  rows,
  rowInfo,
  renderRow,
  older = OLDER_EXHAUSTED,
  newer = NEWER_EXHAUSTED,
  readingOlder,
  empty,
  label,
  arrivals,
  tail,
  footer,
  followTail,
  reveal,
  onJumpToLatest,
  onAtEndChange,
  paddingStart = 0,
  paddingEnd = 0,
  columnClassName,
  shortLogAt = "start",
  className,
}: {
  rows: readonly Row[];
  rowInfo: VirtualLogRowInfo<Row>;
  renderRow: (row: Row, index: number) => ReactNode;
  older?: OlderPages;
  /** Pages toward the live head when viewing a detached history window. */
  newer?: NewerPages;
  /** What shows at the top of the view while an older page is read. */
  readingOlder?: ReactNode;
  /** What shows when there are no rows. */
  empty?: ReactNode;
  /** The list's accessible name, which makes it a `log`. */
  label?: string;
  /** What is not in the log yet and ends the list: work in flight, an answer streaming in, any stack
   *  of them. It scrolls with the rows and can grow, and a view at the end stays at the end of it. */
  tail?: ReactNode;
  /** What the bubble counts, when a row can stand for many (a fold): the log's entries as they
   *  arrive. By default, the rows with an `offset`. */
  arrivals?: readonly { offset: number }[];
  /** What is always there, in front of the rows at the bottom of the view: a composer, whatever its
   *  height. Its own background says how the rows go behind it. */
  footer?: ReactNode;
  /** Each change pins the view to the tail again, wherever the reader was (the person's own words
   *  or append: the next rows to arrive are theirs, and they land in view). */
  followTail?: number;
  /** An offset to bring into view, once per change (a link, an inspector paging the log), never
   *  again as rows arrive, so a reader who scrolled away from it stays there. One not loaded yet is
   *  brought in when a page brings it: reading that far is the caller's. */
  reveal?: number;
  /** Swaps a detached history window back to the live tail window when the bottom bubble is pressed. */
  onJumpToLatest?: () => void;
  /** Reports whether the reader is currently at the bottom (`true`) or scrolled up in history (`false`). */
  onAtEndChange?: (atEnd: boolean) => void;
  paddingStart?: number;
  paddingEnd?: number;
  /** The column the rows sit in, inside the scroller, so its scrollbar stays at the edge. */
  columnClassName?: string;
  /** Where a log that is shorter than the view stands. `"end"` is for a chat: its rows stand on the
   *  list's end, so a page of older rows that lands above them moves nothing that the reader sees.
   *  At `"start"` each such page pushes the rows down, and no scroll can make up for it. */
  shortLogAt?: "start" | "end";
  className?: string;
}) {
  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 count = rows.length + (visibleTail ? 1 : 0);
  const virtualizer = useLogVirtualizer({
    rows,
    rowInfo,
    count,
    paddingStart,
    paddingEnd,
    scrollRef,
    footerRef,
    listContainerRef,
    reader,
  });
  const setListContainerRef = useCallback(
    (node: HTMLDivElement | null) => {
      listContainerRef.current = node;
      virtualizer.containerRef(node);
    },
    [virtualizer],
  );

  const prevFollowTailRef = useRef(followTail);
  useLayoutEffect(() => {
    if (Object.is(prevFollowTailRef.current, followTail)) return;
    prevFollowTailRef.current = followTail;
    follow(true);
    goingToTopRef.current = false;
    runOwnScroll(() => virtualizer.scrollToEnd());
  }, [followTail, virtualizer, follow, goingToTopRef, runOwnScroll]);

  useLayoutEffect(() => {
    if (attachedToHead && atEndRef.current && !touchingRef.current)
      runOwnScroll(() => virtualizer.scrollToEnd());
  }, [rows, count, paddingEnd, attachedToHead, virtualizer, atEndRef, touchingRef, runOwnScroll]);
  // rows arriving: the press is over, and what opens later is not its doing
  useLayoutEffect(() => {
    pressedRef.current = null;
  }, [count, pressedRef]);

  useLayoutEffect(() => {
    if (!goingToTopRef.current) return;
    runOwnScroll(() => virtualizer.scrollToOffset(0));
    goingToTopRef.current = !older.exhausted;
  });

  usePageEdges(scrollRef, older, newer);
  useRevealRow({
    rows,
    rowInfo,
    reveal,
    older,
    newer,
    goingToTopRef,
    follow,
    runOwnScroll,
    virtualizer,
  });

  const arrived = useArrivedSince(
    (arrivals || rows).length,
    arrivals ? (at) => arrivals[at]!.offset : (at) => rowInfo.offset(rows[at]!),
    atEnd,
  );
  return (
    <div
      ref={scrollRef}
      data-slot="virtual-log"
      role="presentation"
      tabIndex={-1}
      style={{ overflowAnchor: "none" }}
      {...reader.scrollerProps(virtualizer)}
      className={cn(
        "flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto overscroll-contain outline-none",
        className,
      )}
    >
      <VirtualLogTopChrome
        columnClassName={columnClassName}
        showReadingOlder={older.loading && rows.length > 0}
        readingOlder={readingOlder}
        showScrollToTop={!atTop && !atEnd}
        onScrollToTop={() => {
          follow(false);
          goingToTopRef.current = true;
          scrollRef.current!.focus({ preventScroll: true });
          runOwnScroll(() => virtualizer.scrollToOffset(0));
        }}
      />
      <div
        role={label ? "log" : undefined}
        aria-label={label}
        data-short-log-at={shortLogAt}
        className={cn(
          "shrink-0 grow",
          shortLogAt === "end" && count > 0 && "flex flex-col justify-end",
          columnClassName,
        )}
      >
        {count === 0 ? (
          empty
        ) : (
          <div ref={setListContainerRef} className="relative w-full">
            {virtualizer.getVirtualItems().map((virtualItem) => (
              <div
                key={virtualItem.key}
                data-index={virtualItem.index}
                ref={virtualizer.measureElement}
                className="absolute top-0 left-0 w-full"
              >
                {virtualItem.index < rows.length
                  ? renderRow(rows[virtualItem.index]!, virtualItem.index)
                  : visibleTail}
              </div>
            ))}
          </div>
        )}
      </div>
      <div ref={footerRef} className="sticky bottom-0 z-10 shrink-0">
        <VirtualLogBottomBubble
          visible={!atEnd || !attachedToHead}
          arrived={arrived}
          onScrollToBottom={() => {
            goingToTopRef.current = false;
            scrollRef.current!.focus({ preventScroll: true });
            onJumpToLatest?.();
            follow(true);
            runOwnScroll(() => virtualizer.scrollToEnd());
          }}
        />
        {footer}
      </div>
    </div>
  );
}

function VirtualLogTopChrome({
  columnClassName,
  showReadingOlder,
  readingOlder,
  showScrollToTop,
  onScrollToTop,
}: {
  columnClassName: string | undefined;
  showReadingOlder: boolean;
  readingOlder: ReactNode;
  showScrollToTop: boolean;
  onScrollToTop: () => void;
}) {
  return (
    <div className={cn("sticky top-0 z-10 h-0 shrink-0", columnClassName)}>
      {showReadingOlder ? (
        <div className="flex h-6 items-center bg-background animate-in fade-in-0 fill-mode-both delay-300">
          {readingOlder}
        </div>
      ) : null}
      {showScrollToTop ? (
        <ScrollBubble
          label="Scroll to top"
          className="absolute top-8 right-3 sm:right-auto sm:left-1/2 sm:-translate-x-1/2"
          onClick={onScrollToTop}
        >
          <ArrowUpIcon className="size-3.5" />
        </ScrollBubble>
      ) : null}
    </div>
  );
}

function VirtualLogBottomBubble({
  visible,
  arrived,
  onScrollToBottom,
}: {
  visible: boolean;
  arrived: number;
  onScrollToBottom: () => void;
}) {
  if (!visible) return null;
  return (
    <ScrollBubble
      label={arrived > 0 ? `Scroll to bottom, ${String(arrived)} new` : "Scroll to bottom"}
      className="absolute right-3 bottom-full mb-1 sm:right-auto sm:left-1/2 sm:-translate-x-1/2"
      onClick={onScrollToBottom}
    >
      <ArrowDownIcon className="size-3.5" />
      {arrived > 0 ? <span className="tabular-nums text-foreground">{arrived} new</span> : null}
    </ScrollBubble>
  );
}

type LayoutSnapshot = {
  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 or floats the oldest row (such as a day separator). */
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 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 =
        isHeadPrepended(prev, rows, rowInfo) &&
        !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 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);
        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, 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.rows === rows) {
        prevLayoutRef.current = snapshotLayout(instance, rows, rowInfo);
      }
    },
  });

  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 &&
      isHeadPrepended(prev, rows, rowInfo) &&
      !atEndRef.current &&
      !goingToTopRef.current &&
      !touchingRef.current &&
      !(isIOSWebKit() && virtualizer.isScrolling)
    ) {
      // 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, rows, rowInfo);
        setAnchorTick((n) => n + 1);
        return;
      }
    }

    prevLayoutRef.current = snapshotLayout(virtualizer, rows, rowInfo);
  }, [rows, count, rowInfo, 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 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>,
  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 {
    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,
    })),
  };
}

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. 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[],
  rowInfo: VirtualLogRowInfo<Row>,
  instance: Virtualizer<HTMLDivElement, Element>,
  liveTop: number,
): number | null {
  const offsetCandidates = new Map<string, number>();
  const anyCandidates = new Map<string, number>();
  for (const oldItem of prev.items) {
    if (oldItem.end < liveTop) continue;
    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();
  // THE ROW THAT THE READER LOOKS AT STANDS STILL: of the rows that are still there, the one that
  // began nearest the view's middle. A page that lands can also change rows in the view (a fold
  // that takes older events in, a row that hides): held by the first row of the view, everything
  // under such a row moved (the Dash's feed, 28 Nov 2026: 1,263 px, 0.4 s after the reader left
  // the list's end).
  const middle = liveTop + (instance.scrollRect?.height ?? 0) / 2;
  let delta: number | null = null;
  let nearest = Infinity;
  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;
    const distance = Math.abs(oldStart - middle);
    if (distance >= nearest) continue;
    nearest = distance;
    delta = nextItem.start - oldStart;
  }
  return delta;
}

/** 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
 *  viewport the virtualizer should reason about. When the rows lose room the end moves with no row
 *  changing, which it does not pin for (TanStack/virtual#1298), so a view at the end goes on. */
function observeRowsRect(
  instance: Virtualizer<HTMLDivElement, Element>,
  report: (rect: Rect) => void,
  footer: HTMLElement,
  keepAtEnd: () => void,
) {
  const scroller = instance.scrollElement!;
  const reportRect = () =>
    report({
      width: scroller.clientWidth,
      height: Math.max(scroller.clientHeight - footer.offsetHeight, 0),
    });
  reportRect();
  const observer = new ResizeObserver(() => {
    reportRect();
    keepAtEnd();
  });
  observer.observe(scroller);
  observer.observe(footer);
  return () => observer.disconnect();
}

/** Asks for an older page while fewer than `READ_AHEAD_PX` stand over the view, and for a newer one
 *  within `LOAD_NEWER_WITHIN_PX` of the end. After each render: a page that lands asks for the next. */
function usePageEdges(
  scrollRef: { current: HTMLDivElement | null },
  older: OlderPages,
  newer: NewerPages,
) {
  useEffect(() => {
    const el = scrollRef.current!;
    if (!older.loading && !older.exhausted && el.scrollTop < READ_AHEAD_PX) older.loadOlder();
    if (
      !newer.loading &&
      !newer.exhausted &&
      el.scrollHeight - el.clientHeight - el.scrollTop < LOAD_NEWER_WITHIN_PX
    )
      newer.loadNewer();
  });
}

function findRowForOffset<Row>(
  rows: readonly Row[],
  rowInfo: VirtualLogRowInfo<Row>,
  offset: number,
): number {
  return rows.findIndex((row) => {
    if (rowInfo.offset(row) === offset) return true;
    const range = rowInfo.span?.(row);
    return Boolean(range && range[0] <= offset && offset <= range[1]);
  });
}

function useRevealRow<Row>({
  rows,
  rowInfo,
  reveal,
  older,
  newer,
  goingToTopRef,
  follow,
  runOwnScroll,
  virtualizer,
}: {
  rows: readonly Row[];
  rowInfo: VirtualLogRowInfo<Row>;
  reveal: number | undefined;
  older: OlderPages;
  newer: NewerPages;
  goingToTopRef: { current: boolean };
  follow: (toEnd: boolean) => void;
  runOwnScroll: (fn: () => void) => void;
  virtualizer: Virtualizer<HTMLDivElement, Element>;
}) {
  const revealRef = useRef<number | undefined>(undefined);
  useEffect(() => {
    revealRef.current = reveal;
  }, [reveal]);
  useEffect(() => {
    const offset = revealRef.current;
    if (offset === undefined || rows.length === 0) return;
    const index = findRowForOffset(rows, rowInfo, offset);
    // not loaded yet: it is wanted until the pages run out (folded away, it never comes)
    if (index < 0 && (!older.exhausted || !newer.exhausted)) return;
    revealRef.current = undefined;
    if (index < 0) return;
    goingToTopRef.current = false;
    follow(false);
    runOwnScroll(() => virtualizer.scrollToIndex(index, { align: "auto" }));
  });
}

/** How many entries came in since the reader left the tail. */
function useArrivedSince(
  length: number,
  offsetAt: (at: number) => number | undefined,
  atEnd: boolean,
) {
  let newest = 0;
  for (let at = length - 1; at >= 0 && newest === 0; at--) newest = offsetAt(at) ?? 0;
  const leftAtRef = useRef(newest);
  useEffect(() => {
    if (atEnd) leftAtRef.current = newest;
  }, [atEnd, newest]);
  if (atEnd) return 0;
  let arrived = 0;
  for (let at = length - 1; at >= 0; at--) {
    const offset = offsetAt(at);
    if (offset === undefined) continue;
    if (offset <= leftAtRef.current) break;
    arrived += 1;
  }
  return arrived;
}

/** A way to an end of the log, over the rows. */
function ScrollBubble({
  label,
  className,
  onClick,
  children,
}: {
  label: string;
  className: string;
  onClick: () => void;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      aria-label={label}
      onClick={onClick}
      className={cn(
        // small on the rows it sits over, and a finger's size to press
        "flex h-8 min-w-8 items-center justify-center gap-1.5 rounded-full border bg-background px-2 text-xs text-muted-foreground shadow-sm animate-in fade-in-0 hover:text-foreground before:absolute before:-inset-1.5 before:content-['']",
        className,
      )}
    >
      {children}
    </button>
  );
}