import { useCallback, useMemo, type CSSProperties } from "react"; import type { ColumnWidth, GridRange, RowHeight, UseVirtualGridOptions, UseVirtualGridResult, } from "./types"; /** * Get the height for a row */ function getHeight(rowHeight: RowHeight, rowIndex: number): number { return typeof rowHeight === "function" ? rowHeight(rowIndex) : rowHeight; } /** * Get the width for a column */ function getWidth(columnWidth: ColumnWidth, colIndex: number): number { return typeof columnWidth === "function" ? columnWidth(colIndex) : columnWidth; } /** * Binary search to find the start index for a given offset */ function findStartIndex( count: number, scrollOffset: number, getSize: (index: number) => number, ): number { if (count === 0) return 0; let offset = 0; let low = 0; let high = count - 1; // Binary search approximation while (low <= high) { const mid = Math.floor((low + high) / 2); // Calculate offset for mid let midOffset = 0; for (let i = 0; i < mid; i++) { midOffset += getSize(i); } if (midOffset < scrollOffset) { low = mid + 1; offset = midOffset; } else if (midOffset > scrollOffset) { high = mid - 1; } else { return mid; } } // Fine-tune by scanning from low let index = Math.max(0, low - 1); offset = 0; for (let i = 0; i < index; i++) { offset += getSize(i); } while (index < count - 1 && offset + getSize(index) <= scrollOffset) { offset += getSize(index); index++; } return index; } /** * Hook for virtualizing a 2D grid of items */ export function useVirtualGrid({ rowCount, columnCount, rowHeight, columnWidth, containerWidth, containerHeight, scrollTop, scrollLeft, overscanRows, overscanColumns, getColSpan = () => 1, getRowSpan = () => 1, }: UseVirtualGridOptions): UseVirtualGridResult { // Memoize size functions const getRowHeightFn = useCallback((index: number) => getHeight(rowHeight, index), [rowHeight]); const getColumnWidthFn = useCallback( (index: number) => getWidth(columnWidth, index), [columnWidth], ); // Calculate total dimensions const totalHeight = useMemo(() => { let height = 0; for (let i = 0; i < rowCount; i++) { height += getRowHeightFn(i); } return height; }, [rowCount, getRowHeightFn]); const totalWidth = useMemo(() => { let width = 0; for (let i = 0; i < columnCount; i++) { width += getColumnWidthFn(i); } return width; }, [columnCount, getColumnWidthFn]); // Calculate row offsets (memoized) const rowOffsets = useMemo(() => { const offsets: number[] = [0]; for (let i = 0; i < rowCount; i++) { offsets.push(offsets[i] + getRowHeightFn(i)); } return offsets; }, [rowCount, getRowHeightFn]); // Calculate column offsets (memoized) const columnOffsets = useMemo(() => { const offsets: number[] = [0]; for (let i = 0; i < columnCount; i++) { offsets.push(offsets[i] + getColumnWidthFn(i)); } return offsets; }, [columnCount, getColumnWidthFn]); // Get offset for a row const getRowOffset = useCallback((rowIndex: number) => rowOffsets[rowIndex] ?? 0, [rowOffsets]); // Get offset for a column const getColumnOffset = useCallback( (colIndex: number) => columnOffsets[colIndex] ?? 0, [columnOffsets], ); // Calculate visible range const visibleRange = useMemo(() => { if (rowCount === 0 || columnCount === 0) { return { startRow: 0, endRow: 0, startCol: 0, endCol: 0 }; } // Find start row const startRow = findStartIndex(rowCount, scrollTop, getRowHeightFn); // Find end row let endRow = startRow; let accumulatedHeight = getRowOffset(startRow) - scrollTop; while (endRow < rowCount - 1 && accumulatedHeight < containerHeight) { accumulatedHeight += getRowHeightFn(endRow); endRow++; } // Find start column const startCol = findStartIndex(columnCount, scrollLeft, getColumnWidthFn); // Find end column let endCol = startCol; let accumulatedWidth = getColumnOffset(startCol) - scrollLeft; while (endCol < columnCount - 1 && accumulatedWidth < containerWidth) { accumulatedWidth += getColumnWidthFn(endCol); endCol++; } return { startRow: Math.max(0, startRow - overscanRows), endRow: Math.min(rowCount - 1, endRow + overscanRows), startCol: Math.max(0, startCol - overscanColumns), endCol: Math.min(columnCount - 1, endCol + overscanColumns), }; }, [ rowCount, columnCount, scrollTop, scrollLeft, containerHeight, containerWidth, overscanRows, overscanColumns, getRowHeightFn, getColumnWidthFn, getRowOffset, getColumnOffset, ]); // Get style for a cell const getCellStyle = useCallback( (row: number, col: number): CSSProperties => { const top = getRowOffset(row); const left = getColumnOffset(col); // Calculate width with colspan const colspan = getColSpan(row, col); let width = 0; for (let c = col; c < col + colspan && c < columnCount; c++) { width += getColumnWidthFn(c); } // Calculate height with rowspan const rowspan = getRowSpan(row, col); let height = 0; for (let r = row; r < row + rowspan && r < rowCount; r++) { height += getRowHeightFn(r); } return { position: "absolute", top: 0, left: 0, width, height, transform: `translate(${left}px, ${top}px)`, }; }, [ getRowOffset, getColumnOffset, getColSpan, getRowSpan, columnCount, rowCount, getColumnWidthFn, getRowHeightFn, ], ); return { visibleRange, totalWidth, totalHeight, getRowOffset, getColumnOffset, getRowHeight: getRowHeightFn, getColumnWidth: getColumnWidthFn, getCellStyle, }; }