import React, { forwardRef, useCallback, useEffect, useLayoutEffect, useRef, useState, type ComponentProps, } from "react"; import type { VirtualGridProps } from "./types"; import { useVirtualGrid } from "./useVirtualGrid"; import { cn } from "../../hooks"; interface VirtualGridComponentProps extends Omit, "children">, VirtualGridProps {} /** * VirtualGrid component - renders only visible cells for efficient grid rendering. * Supports both fixed and variable row/column sizes, cell spanning, and sticky headers/columns. * * @param data - 2D array of cell data * @param rowCount - Number of rows in the grid * @param columnCount - Number of columns in the grid * @param rowHeight - Height for each row (fixed or function) * @param columnWidth - Width for each column (fixed or function) * @param height - Container height * @param width - Container width (default: '100%') * @param overscanRows - Extra rows to render outside visible area (default: 2) * @param overscanColumns - Extra columns to render outside visible area (default: 2) * @param getCellKey - Function to get a unique key for each cell * @param getColSpan - Function to get column span for a cell * @param getRowSpan - Function to get row span for a cell * @param children - Render function for each cell * @param stickyHeader - Keep first row visible * @param stickyColumn - Keep first column visible */ function VirtualGridInner( { data, rowCount, columnCount, rowHeight, columnWidth, height, width = "100%", overscanRows = 2, overscanColumns = 2, getCellKey, getColSpan, getRowSpan, children, stickyHeader = false, stickyColumn = false, className, style, ...props }: VirtualGridComponentProps, ref: React.ForwardedRef, ) { const containerRef = useRef(null); const stickyLayerRef = useRef(null); const [scrollTop, setScrollTop] = useState(0); const [scrollLeft, setScrollLeft] = useState(0); const [containerWidth, setContainerWidth] = useState(0); const [containerHeight, setContainerHeight] = useState(0); // Track scroll position in ref for immediate updates const scrollRef = useRef({ top: 0, left: 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 dimensions useEffect(() => { const container = containerRef.current; if (!container) return; const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { setContainerWidth(entry.contentRect.width); setContainerHeight(entry.contentRect.height); } }); resizeObserver.observe(container); setContainerWidth(container.clientWidth); setContainerHeight(container.clientHeight); return () => resizeObserver.disconnect(); }, []); const { visibleRange, totalWidth, totalHeight, getCellStyle, getRowOffset, getColumnOffset, getRowHeight, getColumnWidth, } = useVirtualGrid({ rowCount, columnCount, rowHeight, columnWidth, containerWidth, containerHeight, scrollTop, scrollLeft, overscanRows, overscanColumns, getColSpan, getRowSpan, }); // Handle scroll - update CSS variables immediately, debounce state updates const rafRef = useRef(null); const handleScroll = useCallback((e: React.UIEvent) => { const newScrollTop = e.currentTarget.scrollTop; const newScrollLeft = e.currentTarget.scrollLeft; // Update ref immediately scrollRef.current = { top: newScrollTop, left: newScrollLeft }; // Update CSS variables immediately for smooth sticky positioning // Round to prevent sub-pixel jitter if (stickyLayerRef.current) { stickyLayerRef.current.style.setProperty("--scroll-top", `${Math.round(newScrollTop)}px`); stickyLayerRef.current.style.setProperty("--scroll-left", `${Math.round(newScrollLeft)}px`); } // Debounce state updates for virtualization range calculation if (rafRef.current) { cancelAnimationFrame(rafRef.current); } rafRef.current = requestAnimationFrame(() => { setScrollTop(newScrollTop); setScrollLeft(newScrollLeft); }); }, []); // Cleanup RAF on unmount useEffect(() => { return () => { if (rafRef.current) { cancelAnimationFrame(rafRef.current); } }; }, []); // Initialize CSS variables useLayoutEffect(() => { if (stickyLayerRef.current) { stickyLayerRef.current.style.setProperty("--scroll-top", "0px"); stickyLayerRef.current.style.setProperty("--scroll-left", "0px"); } }, []); // Track which cells are covered by spans const coveredCells = new Set(); // Pre-calculate covered cells from spans if (getColSpan || getRowSpan) { for (let row = visibleRange.startRow; row <= visibleRange.endRow; row++) { for (let col = visibleRange.startCol; col <= visibleRange.endCol; col++) { const colspan = getColSpan?.(row, col) ?? 1; const rowspan = getRowSpan?.(row, col) ?? 1; if (colspan > 1 || rowspan > 1) { for (let r = row; r < row + rowspan; r++) { for (let c = col; c < col + colspan; c++) { if (r !== row || c !== col) { coveredCells.add(`${r}-${c}`); } } } } } } } // Render visible cells const visibleCells = []; for (let row = visibleRange.startRow; row <= visibleRange.endRow && row < rowCount; row++) { for (let col = visibleRange.startCol; col <= visibleRange.endCol && col < columnCount; col++) { // Skip cells covered by spans if (coveredCells.has(`${row}-${col}`)) { continue; } // Skip header row and sticky column cells - they're rendered separately if ((stickyHeader && row === 0) || (stickyColumn && col === 0)) { continue; } const cellData = data[row]?.[col]; const key = getCellKey ? getCellKey(row, col) : `${row}-${col}`; const cellStyle = getCellStyle(row, col); visibleCells.push( {children(cellData, row, col, cellStyle)}, ); } } // Style for sticky cell content - fills the wrapper const stickyContentStyle = { width: "100%", height: "100%" }; // Render sticky header cells (using CSS variable for Y position) const stickyHeaderCells = []; if (stickyHeader && rowCount > 0) { for (let col = visibleRange.startCol; col <= visibleRange.endCol && col < columnCount; col++) { // Skip first column if sticky column is enabled if (stickyColumn && col === 0) continue; if (coveredCells.has(`0-${col}`)) continue; const cellData = data[0]?.[col]; const key = getCellKey ? getCellKey(0, col) : `header-${col}`; stickyHeaderCells.push(
{children(cellData, 0, col, stickyContentStyle)}
, ); } } // Render sticky column cells (using CSS variable for X position) const stickyColumnCells = []; if (stickyColumn && columnCount > 0) { for (let row = visibleRange.startRow; row <= visibleRange.endRow && row < rowCount; row++) { // Skip first row if sticky header is enabled if (stickyHeader && row === 0) continue; if (coveredCells.has(`${row}-0`)) continue; const cellData = data[row]?.[0]; const key = getCellKey ? getCellKey(row, 0) : `sticky-col-${row}`; stickyColumnCells.push(
{children(cellData, row, 0, stickyContentStyle)}
, ); } } // Render sticky corner cell (using CSS variables for both X and Y) const stickyCornerCell = stickyHeader && stickyColumn && rowCount > 0 && columnCount > 0 ? (
{children(data[0]?.[0], 0, 0, stickyContentStyle)}
) : null; const hasStickyElements = stickyHeader || stickyColumn; return (
{/* Sticky elements first - stable position in DOM during scroll */} {stickyCornerCell} {stickyHeaderCells} {stickyColumnCells} {/* Visible cells last - changes frequently during scroll */} {visibleCells}
); } // Use a generic forwardRef pattern export const VirtualGrid = forwardRef(VirtualGridInner) as ( props: VirtualGridComponentProps & { ref?: React.ForwardedRef }, ) => React.ReactElement; export type { VirtualGridProps };