import { useCallback, useEffect, useMemo, useState, type ReactNode, type RefObject, } from "react"; export type VirtualListProps = { items: T[]; height: number; rowHeight: number | ((index: number) => number); overscan?: number; renderRow: (item: T, index: number) => ReactNode; containerRef?: RefObject; testId?: string; onVisibleRange?: (start: number, end: number) => void; onScrollTop?: (top: number) => void; }; export function VirtualList({ items, height, rowHeight, overscan = 4, renderRow, containerRef, testId = "virtual-row", onVisibleRange, onScrollTop, }: VirtualListProps) { const [scrollTop, setScrollTop] = useState(0); const offsets = useMemo(() => { const next = new Array(items.length + 1); next[0] = 0; for (let index = 0; index < items.length; index += 1) { const size = typeof rowHeight === "number" ? rowHeight : rowHeight(index); next[index + 1] = (next[index] ?? 0) + size; } return next; }, [items.length, rowHeight]); const total = offsets[items.length] ?? 0; const findStart = useCallback( (top: number): number => { let low = 0; let high = items.length - 1; let result = 0; while (low <= high) { const mid = Math.floor((low + high) / 2); if ((offsets[mid] ?? 0) <= top) { result = mid; low = mid + 1; } else { high = mid - 1; } } return Math.max(0, result - overscan); }, [items.length, offsets, overscan], ); const start = findStart(scrollTop); const budget = scrollTop + height; let end = start; while (end < items.length && (offsets[end] ?? 0) < budget) end += 1; end = Math.min(items.length, end + overscan); useEffect(() => { onVisibleRange?.(start, end); }, [end, onVisibleRange, start]); return (
{ setScrollTop(event.currentTarget.scrollTop); onScrollTop?.(event.currentTarget.scrollTop); }} >
{items.slice(start, end).map((item, offset) => { const index = start + offset; const top = offsets[index] ?? 0; const size = (offsets[index + 1] ?? top) - top; return (
{renderRow(item, index)}
); })}
); }