import { useCallback, useMemo, useRef, type CSSProperties } from "react"; import type { ItemHeight, ItemMeasurement, UseVirtualListOptions, UseVirtualListResult, } from "./types"; /** * Binary search to find the start index for a given scroll position */ function findStartIndex( measurements: Map, itemCount: number, scrollTop: number, itemHeight: ItemHeight, estimatedItemHeight: number, ): number { if (itemCount === 0) return 0; if (typeof itemHeight === "number") { return Math.floor(scrollTop / itemHeight); } // For dynamic heights, use binary search on measured items let low = 0; let high = itemCount - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); const measurement = measurements.get(mid); const offset = measurement?.offset ?? mid * estimatedItemHeight; if (offset < scrollTop) { low = mid + 1; } else if (offset > scrollTop) { high = mid - 1; } else { return mid; } } return Math.max(0, low - 1); } /** * Hook for virtualizing a list of items */ export function useVirtualList({ items, itemHeight, estimatedItemHeight, containerHeight, overscan, scrollTop, }: UseVirtualListOptions): UseVirtualListResult { const measurementsRef = useRef>(new Map()); const measurements = measurementsRef.current; const isFixed = typeof itemHeight === "number"; // Calculate total height const totalHeight = useMemo(() => { if (isFixed) { return items.length * itemHeight; } // For dynamic heights, use measured heights + estimated for unmeasured let height = 0; for (let i = 0; i < items.length; i++) { const measurement = measurements.get(i); height += measurement?.height ?? estimatedItemHeight; } return height; }, [items.length, itemHeight, isFixed, estimatedItemHeight, measurements]); // Calculate visible range const visibleRange = useMemo(() => { if (items.length === 0) { return { start: 0, end: 0 }; } const startIndex = findStartIndex( measurements, items.length, scrollTop, itemHeight, estimatedItemHeight, ); let endIndex: number; if (isFixed) { endIndex = Math.min(items.length - 1, Math.ceil((scrollTop + containerHeight) / itemHeight)); } else { // For dynamic, scan forward until we exceed container let accumulatedHeight = 0; endIndex = startIndex; // Get starting offset const startMeasurement = measurements.get(startIndex); const startOffset = startMeasurement?.offset ?? startIndex * estimatedItemHeight; accumulatedHeight = startOffset - scrollTop; while (endIndex < items.length - 1 && accumulatedHeight < containerHeight) { const measurement = measurements.get(endIndex); accumulatedHeight += measurement?.height ?? estimatedItemHeight; endIndex++; } } // Apply overscan const start = Math.max(0, startIndex - overscan); const end = Math.min(items.length - 1, endIndex + overscan); return { start, end }; }, [ items.length, scrollTop, containerHeight, overscan, itemHeight, isFixed, estimatedItemHeight, measurements, ]); // Get style for an item at a given index const getItemStyle = useCallback( (index: number): CSSProperties => { let top: number; if (isFixed) { top = index * (itemHeight as number); } else { const measurement = measurements.get(index); if (measurement) { top = measurement.offset; } else { // Estimate offset based on previous measurements let offset = 0; for (let i = 0; i < index; i++) { const m = measurements.get(i); offset += m?.height ?? estimatedItemHeight; } top = offset; } } return { position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${top}px)`, ...(isFixed && { height: itemHeight as number }), }; }, [itemHeight, isFixed, estimatedItemHeight, measurements], ); // Measure an item (for dynamic heights) const measureItem = useCallback( (index: number, height: number) => { const currentMeasurement = measurements.get(index); // Only update if height changed if (currentMeasurement?.height === height) { return; } // Calculate offset based on previous items let offset = 0; for (let i = 0; i < index; i++) { const m = measurements.get(i); offset += m?.height ?? estimatedItemHeight; } measurements.set(index, { offset, height }); // Update offsets for subsequent measured items let currentOffset = offset + height; for (let i = index + 1; i < items.length; i++) { const m = measurements.get(i); if (m) { measurements.set(i, { ...m, offset: currentOffset }); currentOffset += m.height; } else { break; } } }, [items.length, estimatedItemHeight, measurements], ); return { visibleRange, totalHeight, getItemStyle, measureItem, measurements, }; }