import { forwardRef, useCallback, useEffect, useRef, useState, type ComponentProps } from "react"; import type { VirtualListProps } from "./types"; import { useVirtualList } from "./useVirtualList"; import { cn } from "../../hooks"; interface VirtualListComponentProps extends Omit, "children" | "onScroll">, VirtualListProps {} /** * VirtualList component - renders only visible items for efficient list rendering. * Supports both fixed and dynamic item heights. * * @param items - Array of items to render * @param itemHeight - Fixed height in pixels, or 'dynamic' for variable height items * @param estimatedItemHeight - Estimated height for dynamic mode (default: 40) * @param height - Container height (default: '100%') * @param overscan - Number of extra items to render outside visible area (default: 3) * @param getItemKey - Function to get a unique key for each item * @param children - Render function for each item * @param onScroll - Callback when scroll position changes * @param onRangeChange - Callback when visible range changes */ function VirtualListInner( { items, itemHeight, estimatedItemHeight = 40, height = "100%", overscan = 3, getItemKey, children, onScroll, onRangeChange, className, style, ...props }: VirtualListComponentProps, ref: React.ForwardedRef, ) { const containerRef = useRef(null); const [scrollTop, setScrollTop] = useState(0); const [containerHeight, setContainerHeight] = useState(0); // Combine refs const setRefs = useCallback( (node: HTMLDivElement | null) => { (containerRef as React.MutableRefObject).current = node; if (typeof ref === "function") { ref(node); } else if (ref) { ref.current = node; } }, [ref], ); // Measure container height useEffect(() => { const container = containerRef.current; if (!container) return; const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { setContainerHeight(entry.contentRect.height); } }); resizeObserver.observe(container); setContainerHeight(container.clientHeight); return () => resizeObserver.disconnect(); }, []); const { visibleRange, totalHeight, getItemStyle, measureItem } = useVirtualList({ items, itemHeight, estimatedItemHeight, containerHeight, overscan, scrollTop, }); // Handle scroll const handleScroll = useCallback( (e: React.UIEvent) => { const newScrollTop = e.currentTarget.scrollTop; setScrollTop(newScrollTop); onScroll?.(newScrollTop); }, [onScroll], ); // Notify range changes const prevRangeRef = useRef({ start: -1, end: -1 }); useEffect(() => { if ( visibleRange.start !== prevRangeRef.current.start || visibleRange.end !== prevRangeRef.current.end ) { prevRangeRef.current = visibleRange; onRangeChange?.(visibleRange.start, visibleRange.end); } }, [visibleRange, onRangeChange]); // Render visible items const visibleItems = []; const isDynamic = itemHeight === "dynamic"; // For dynamic mode, children should fill the wrapper const dynamicChildStyle = { width: "100%" }; for (let i = visibleRange.start; i <= visibleRange.end && i < items.length; i++) { const item = items[i]; const key = getItemKey ? getItemKey(item, i) : i; const itemStyle = getItemStyle(i); // For dynamic height, positioning is on wrapper, children just need width // For fixed height, full style is passed to children render function visibleItems.push( {children(item, i, isDynamic ? dynamicChildStyle : itemStyle)} , ); } return (
{visibleItems}
); } /** * Individual item wrapper that handles measurement for dynamic heights */ function VirtualListItem({ children, index, isDynamic, measureItem, style, }: { children: React.ReactNode; index: number; isDynamic: boolean; measureItem: (index: number, height: number) => void; style: React.CSSProperties; }) { const itemRef = useRef(null); useEffect(() => { if (!isDynamic || !itemRef.current) return; const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { measureItem(index, entry.contentRect.height); } }); resizeObserver.observe(itemRef.current); measureItem(index, itemRef.current.offsetHeight); return () => resizeObserver.disconnect(); }, [index, isDynamic, measureItem]); if (!isDynamic) { return <>{children}; } // For dynamic height items, apply positioning to wrapper and let content define height return (
{children}
); } // Use a generic forwardRef pattern export const VirtualList = forwardRef(VirtualListInner) as ( props: VirtualListComponentProps & { ref?: React.ForwardedRef }, ) => React.ReactElement; export type { VirtualListProps };