import { useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react'; import type { Key, KeyboardEvent } from 'react'; import { flushSync } from 'react-dom'; import { HeaderRowSelectionChangeContext, HeaderRowSelectionContext, RowSelectionChangeContext, useActivePosition, useCalculatedColumns, useColumnWidths, useGridDimensions, useLatestFunc, useScrollState, useScrollToPosition, useViewportColumns, useViewportRows, type ActivePosition, type HeaderRowSelectionContextValue, type PartialPosition } from './hooks'; import { assertIsValidGetRowKey, canExitGrid, classnames, createCellEvent, focusCell, getCellStyle, getCellToScroll, getLeftRightKey, getNextActivePosition, isCellEditableUtil, isCtrlKeyHeldDown, isDefaultCellInput, isElement, renderMeasuringCells, scrollIntoView } from './utils'; import type { CalculatedColumn, CellClipboardEvent, CellCopyArgs, CellKeyboardEvent, CellKeyDownArgs, CellMouseEventHandler, CellNavigationMode, CellPasteArgs, PositionChangeArgs, Column, ColumnOrColumnGroup, ColumnWidths, Direction, FillEvent, Maybe, Position, Renderers, RowsChangeData, SetActivePositionOptions, SelectHeaderRowEvent, SelectRowEvent, SortColumn } from './types'; import { defaultRenderCell } from './Cell'; import { renderCheckbox as defaultRenderCheckbox } from './cellRenderers'; import { DataGridRenderersContext, useRenderers } from './DataGridRenderersContext'; import EditCell from './EditCell'; import GroupedColumnHeaderRow from './GroupedColumnHeaderRow'; import HeaderRow from './HeaderRow'; import { defaultRenderRow } from './Row'; import { default as defaultRenderSortStatus } from './sortStatus'; import { cellDragHandleClassname, cellDragHandleFrozenClassname } from './style/cell'; import { rootClassname, frozenColumnShadowEndClassname, frozenColumnShadowEndTopClassname, frozenColumnShadowStartClassname, frozenColumnShadowStartTopClassname, viewportDraggingClassname } from './style/core'; import SummaryRow from './SummaryRow'; export type DefaultColumnOptions = Pick< Column, | 'renderCell' | 'renderHeaderCell' | 'width' | 'minWidth' | 'maxWidth' | 'resizable' | 'sortable' | 'draggable' >; export interface DataGridHandle { element: HTMLDivElement | null; scrollToCell: (position: PartialPosition) => void; setActivePosition: (position: Position, options?: SetActivePositionOptions) => void; } type SharedDivProps = Pick< React.ComponentProps<'div'>, | 'role' | 'aria-label' | 'aria-labelledby' | 'aria-description' | 'aria-describedby' | 'aria-rowcount' | 'className' | 'style' | 'onScroll' >; export interface DataGridProps extends SharedDivProps { ref?: Maybe>; /** * Grid and data props */ /** An array of column definitions */ columns: readonly ColumnOrColumnGroup, NoInfer>[]; /** An array of rows, which can be of any type */ rows: readonly R[]; /** Rows pinned at the top of the grid for summary purposes */ topSummaryRows?: Maybe; /** Rows pinned at the bottom of the grid for summary purposes */ bottomSummaryRows?: Maybe; /** * Function to get the key of each row. * Required for row selection. * Recommended otherwise, as the key is also used as the `key` prop of the row elements. * @returns a unique key for the row */ getRowKey?: Maybe<(row: NoInfer) => K>; /** Callback triggered when rows are changed */ onRowsChange?: Maybe<(rows: NoInfer[], data: RowsChangeData, NoInfer>) => void>; /** * Dimensions props */ /** * Height of each row in pixels * @default 35 */ rowHeight?: Maybe) => number)>; /** * Height of the header row in pixels * @default `rowHeight` when it is a number, otherwise 35 */ headerRowHeight?: Maybe; /** * Height of each summary row in pixels * @default `rowHeight` when it is a number, otherwise 35 */ summaryRowHeight?: Maybe; /** A map of column widths */ columnWidths?: Maybe; /** Callback triggered when column widths change */ onColumnWidthsChange?: Maybe<(columnWidths: ColumnWidths) => void>; /** * Feature props */ /** A set of selected row keys */ selectedRows?: Maybe>; /** Function to determine if row selection is disabled for a specific row */ isRowSelectionDisabled?: Maybe<(row: NoInfer) => boolean>; /** Callback triggered when the selection changes */ onSelectedRowsChange?: Maybe<(selectedRows: Set>) => void>; /** An array of sorted columns */ sortColumns?: Maybe; /** Callback triggered when sorting changes */ onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>; /** Default options applied to all columns */ defaultColumnOptions?: Maybe, NoInfer>>; /** * Event props */ /** Callback triggered when a pointer becomes active in a cell */ onCellMouseDown?: CellMouseEventHandler; /** Callback triggered when a cell is clicked */ onCellClick?: CellMouseEventHandler; /** Callback triggered when a cell is double-clicked */ onCellDoubleClick?: CellMouseEventHandler; /** Callback triggered when a cell is right-clicked */ onCellContextMenu?: CellMouseEventHandler; /** Callback triggered when a key is pressed in a cell */ onCellKeyDown?: Maybe< (args: CellKeyDownArgs, NoInfer>, event: CellKeyboardEvent) => void >; /** Callback triggered when a cell's content is copied */ onCellCopy?: Maybe< (args: CellCopyArgs, NoInfer>, event: CellClipboardEvent) => void >; /** Callback triggered when content is pasted into a cell */ onCellPaste?: Maybe< (args: CellPasteArgs, NoInfer>, event: CellClipboardEvent) => NoInfer >; /** Function called whenever the active position is changed */ onActivePositionChange?: Maybe<(args: PositionChangeArgs, NoInfer>) => void>; /** Callback triggered when a column is resized */ onColumnResize?: Maybe<(column: CalculatedColumn, width: number) => void>; /** Callback triggered when columns are reordered */ onColumnsReorder?: Maybe<(sourceColumnKey: string, targetColumnKey: string) => void>; /** Callback triggered when the value of the active cell is dragged to fill other cells */ onFill?: Maybe<(event: FillEvent>) => NoInfer>; /** * Toggles and modes */ /** @default true */ enableVirtualization?: Maybe; /** * Miscellaneous */ /** Custom renderers for cells, rows, and other components */ renderers?: Maybe, NoInfer>>; /** Function to apply custom class names to rows */ rowClass?: Maybe<(row: NoInfer, rowIdx: number) => Maybe>; /** Custom class name for the header row */ headerRowClass?: Maybe; /** * Text direction of the grid ('ltr' or 'rtl') * @default 'ltr' */ direction?: Maybe; 'data-testid'?: Maybe; 'data-cy'?: Maybe; } /** * Main API component to render a data grid of rows and columns * * @example * * */ export function DataGrid(props: DataGridProps) { const { ref, // Grid and data props columns: rawColumns, rows, topSummaryRows, bottomSummaryRows, getRowKey, onRowsChange, // Dimensions props rowHeight: rawRowHeight, headerRowHeight: rawHeaderRowHeight, summaryRowHeight: rawSummaryRowHeight, columnWidths: columnWidthsRaw, onColumnWidthsChange: onColumnWidthsChangeRaw, // Feature props selectedRows, isRowSelectionDisabled, onSelectedRowsChange, sortColumns, onSortColumnsChange, defaultColumnOptions, // Event props onCellMouseDown, onCellClick, onCellDoubleClick, onCellContextMenu, onCellKeyDown, onActivePositionChange, onScroll, onColumnResize, onColumnsReorder, onFill, onCellCopy, onCellPaste, // Toggles and modes enableVirtualization: rawEnableVirtualization, // Miscellaneous renderers, className, style, rowClass, headerRowClass, direction: rawDirection, // ARIA role: rawRole, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-description': ariaDescription, 'aria-describedby': ariaDescribedBy, 'aria-rowcount': rawAriaRowCount, 'data-testid': testId, 'data-cy': dataCy } = props; /** * defaults */ const contextRenderers = useRenderers(); const role = rawRole ?? 'grid'; const rowHeight = rawRowHeight ?? 35; const headerRowHeight = rawHeaderRowHeight ?? (typeof rowHeight === 'number' ? rowHeight : 35); const summaryRowHeight = rawSummaryRowHeight ?? (typeof rowHeight === 'number' ? rowHeight : 35); const renderRow = renderers?.renderRow ?? contextRenderers?.renderRow ?? defaultRenderRow; const renderCell = renderers?.renderCell ?? contextRenderers?.renderCell ?? defaultRenderCell; const renderSortStatus = renderers?.renderSortStatus ?? contextRenderers?.renderSortStatus ?? defaultRenderSortStatus; const renderCheckbox = renderers?.renderCheckbox ?? contextRenderers?.renderCheckbox ?? defaultRenderCheckbox; const noRowsFallback = renderers?.noRowsFallback ?? contextRenderers?.noRowsFallback; const enableVirtualization = rawEnableVirtualization ?? true; const direction = rawDirection ?? 'ltr'; /** * ref */ const gridRef = useRef(null); /** * states */ const { scrollTop, scrollLeft } = useScrollState(gridRef); const [gridWidth, gridHeight] = useGridDimensions(gridRef); const [columnWidthsInternal, setColumnWidthsInternal] = useState( (): ColumnWidths => columnWidthsRaw ?? new Map() ); const [isColumnResizing, setIsColumnResizing] = useState(false); const [isDragging, setIsDragging] = useState(false); const [draggedOverRowIdx, setDraggedOverRowIdx] = useState(); const [previousRowIdx, setPreviousRowIdx] = useState(-1); const isColumnWidthsControlled = columnWidthsRaw != null && onColumnWidthsChangeRaw != null && !isColumnResizing; const columnWidths = isColumnWidthsControlled ? columnWidthsRaw : columnWidthsInternal; const onColumnWidthsChange = isColumnWidthsControlled ? (columnWidths: ColumnWidths) => { // we keep the internal state in sync with the prop but this prevents an extra render setColumnWidthsInternal(columnWidths); onColumnWidthsChangeRaw(columnWidths); } : setColumnWidthsInternal; const getColumnWidth = useCallback( (column: CalculatedColumn) => { return columnWidths.get(column.key)?.width ?? column.width; }, [columnWidths] ); const { columns, colSpanColumns, lastStartFrozenColumnIndex, firstEndFrozenColumnIndex, headerRowsCount, colOverscanStartIdx, colOverscanEndIdx, templateColumns, layoutCssVars, totalStartFrozenColumnWidth, totalEndFrozenColumnWidth } = useCalculatedColumns({ rawColumns, defaultColumnOptions, getColumnWidth, scrollLeft, viewportWidth: gridWidth, enableVirtualization }); /** * computed values */ const isTreeGrid = role === 'treegrid'; const topSummaryRowsCount = topSummaryRows?.length ?? 0; const bottomSummaryRowsCount = bottomSummaryRows?.length ?? 0; const summaryRowsCount = topSummaryRowsCount + bottomSummaryRowsCount; const headerAndTopSummaryRowsCount = headerRowsCount + topSummaryRowsCount; const groupedColumnHeaderRowsCount = headerRowsCount - 1; const minRowIdx = -headerAndTopSummaryRowsCount; const maxRowIdx = rows.length + bottomSummaryRowsCount - 1; const mainHeaderRowIdx = minRowIdx + groupedColumnHeaderRowsCount; const maxColIdx = columns.length - 1; const headerRowsHeight = headerRowsCount * headerRowHeight; const summaryRowsHeight = summaryRowsCount * summaryRowHeight; const clientHeight = gridHeight - headerRowsHeight - summaryRowsHeight; const isSelectable = selectedRows != null && onSelectedRowsChange != null; const { leftKey, rightKey } = getLeftRightKey(direction); const ariaRowCount = rawAriaRowCount ?? headerRowsCount + rows.length + summaryRowsCount; const frozenStartShadowStyles: React.CSSProperties = { gridColumnStart: lastStartFrozenColumnIndex + 2, insetInlineStart: totalStartFrozenColumnWidth }; const frozenEndShadowStyles: React.CSSProperties = { gridColumnStart: firstEndFrozenColumnIndex + 1, gridColumnEnd: -1, insetInlineEnd: totalEndFrozenColumnWidth }; const { activePosition, setActivePosition, setPositionToFocus, activePositionIsInActiveBounds, activePositionIsInViewport, activePositionIsRow, activePositionIsCellInViewport, validatePosition, queryActiveColumn, getActiveColumn, getActiveRow } = useActivePosition({ gridRef, columns, rows, isTreeGrid, maxColIdx, minRowIdx, maxRowIdx, setDraggedOverRowIdx }); const { setScrollToPosition, scrollToPositionElement } = useScrollToPosition({ gridRef }); const defaultGridComponents = useMemo( (): Renderers => ({ renderCheckbox, renderSortStatus, renderCell }), [renderCheckbox, renderSortStatus, renderCell] ); // no rows to select = explicitly unchecked let hasSelectedRow = false; let hasUnselectedRow = false; // keep this loop out of `useMemo`: React Compiler memoizes it here, but not in the callback if (getRowKey != null && selectedRows != null && selectedRows.size > 0) { for (const row of rows) { if (selectedRows.has(getRowKey(row))) { hasSelectedRow = true; } else { hasUnselectedRow = true; } if (hasSelectedRow && hasUnselectedRow) break; } } const headerSelectionValue = useMemo( (): HeaderRowSelectionContextValue => ({ isRowSelected: hasSelectedRow && !hasUnselectedRow, isIndeterminate: hasSelectedRow && hasUnselectedRow }), [hasSelectedRow, hasUnselectedRow] ); const { rowOverscanStartIdx, rowOverscanEndIdx, totalRowHeight, gridTemplateRows, getRowTop, getRowHeight, findRowIdx } = useViewportRows({ rows, rowHeight, clientHeight, scrollTop, enableVirtualization }); const { viewportColumns, mapViewportColumns, mapViewportColumnsOutsideOfViewport } = useViewportColumns({ columns, colSpanColumns, colOverscanStartIdx, colOverscanEndIdx, lastStartFrozenColumnIndex, firstEndFrozenColumnIndex, rowOverscanStartIdx, rowOverscanEndIdx, rows, topSummaryRows, bottomSummaryRows }); const { gridTemplateColumns, handleColumnResize } = useColumnWidths( columns, viewportColumns, templateColumns, gridRef, gridWidth, columnWidths, onColumnWidthsChange, onColumnResize, setIsColumnResizing ); /** * The identity of the wrapper function is stable, so it won't break memoization */ const handleColumnResizeLatest = useLatestFunc(handleColumnResize); const handleColumnResizeEndLatest = useLatestFunc(handleColumnResizeEnd); const onColumnsReorderLatest = useLatestFunc(onColumnsReorder); const onSortColumnsChangeLatest = useLatestFunc(onSortColumnsChange); const onCellMouseDownLatest = useLatestFunc(onCellMouseDown); const onCellClickLatest = useLatestFunc(onCellClick); const onCellDoubleClickLatest = useLatestFunc(onCellDoubleClick); const onCellContextMenuLatest = useLatestFunc(onCellContextMenu); const selectHeaderRowLatest = useLatestFunc(selectHeaderRow); const selectRowLatest = useLatestFunc(selectRow); const updateRowLatest = useLatestFunc(updateRow); const setPositionLatest = useLatestFunc(setPosition); const selectHeaderCellLatest = useLatestFunc(selectHeaderCell); /** * Misc hooks */ useImperativeHandle(ref, (): DataGridHandle => ({ element: gridRef.current, scrollToCell({ idx, rowIdx }) { // frozen columns are always visible — scrolling to them is a no-op const scrollToIdx = idx != null && idx > lastStartFrozenColumnIndex && (firstEndFrozenColumnIndex === -1 || idx < firstEndFrozenColumnIndex) && idx < columns.length ? idx : undefined; const scrollToRowIdx = rowIdx != null && validatePosition({ idx: 0, rowIdx }).isPositionInViewport ? rowIdx + headerAndTopSummaryRowsCount : undefined; if (scrollToIdx != null || scrollToRowIdx != null) { setScrollToPosition({ idx: scrollToIdx, rowIdx: scrollToRowIdx }); } }, setActivePosition: setPositionLatest })); /** * event handlers */ function selectHeaderRow(args: SelectHeaderRowEvent) { if (!onSelectedRowsChange) return; assertIsValidGetRowKey(getRowKey); const newSelectedRows = new Set(selectedRows); for (const row of rows) { if (isRowSelectionDisabled?.(row) === true) continue; const rowKey = getRowKey(row); if (args.checked) { newSelectedRows.add(rowKey); } else { newSelectedRows.delete(rowKey); } } onSelectedRowsChange(newSelectedRows); } function selectRow(args: SelectRowEvent) { if (!onSelectedRowsChange) return; assertIsValidGetRowKey(getRowKey); const { row, checked, isShiftClick } = args; if (isRowSelectionDisabled?.(row) === true) return; const newSelectedRows = new Set(selectedRows); const rowKey = getRowKey(row); const rowIdx = rows.indexOf(row); setPreviousRowIdx(rowIdx); if (checked) { newSelectedRows.add(rowKey); } else { newSelectedRows.delete(rowKey); } if ( isShiftClick && previousRowIdx !== -1 && previousRowIdx !== rowIdx && previousRowIdx < rows.length ) { const [min, max] = previousRowIdx < rowIdx ? [previousRowIdx, rowIdx] : [rowIdx, previousRowIdx]; for (let i = min + 1; i < max; i++) { const row = rows[i]; if (isRowSelectionDisabled?.(row) === true) continue; if (checked) { newSelectedRows.add(getRowKey(row)); } else { newSelectedRows.delete(getRowKey(row)); } } } onSelectedRowsChange(newSelectedRows); } function handleKeyDown(event: KeyboardEvent) { const { idx, rowIdx, mode } = activePosition; if (mode === 'EDIT') return; if (onCellKeyDown && activePositionIsInViewport) { const cellEvent = createCellEvent(event); onCellKeyDown( { mode: 'ACTIVE', row: rows[rowIdx], column: columns[idx], rowIdx, setActivePosition: setPosition }, cellEvent ); if (cellEvent.isGridDefaultPrevented()) return; } const { target } = event; if (!isElement(target)) return; const cell = target.closest('.rdg-cell'); const isCellEvent = cell !== null; const isRowEvent = isTreeGrid && target.role === 'row'; if (!isCellEvent && !isRowEvent) return; switch (event.key) { case 'ArrowUp': case 'ArrowDown': case 'ArrowLeft': case 'ArrowRight': case 'Tab': case 'Home': case 'End': case 'PageUp': case 'PageDown': navigate(event); break; default: handleCellInput(event, cell); break; } } function updateRow(column: CalculatedColumn, rowIdx: number, row: R) { if (typeof onRowsChange !== 'function') return; if (row === rows[rowIdx]) return; const updatedRows = rows.with(rowIdx, row); onRowsChange(updatedRows, { indexes: [rowIdx], column }); } function commitEditorChanges() { if (activePosition.mode !== 'EDIT') return; updateRow(getActiveColumn(), activePosition.rowIdx, activePosition.row); } function handleCellCopy(event: CellClipboardEvent) { if (!activePositionIsCellInViewport) return; onCellCopy?.({ row: getActiveRow(), column: getActiveColumn() }, event); } function handleCellPaste(event: CellClipboardEvent) { if ( typeof onCellPaste !== 'function' || typeof onRowsChange !== 'function' || !isCellEditable(activePosition) ) { return; } const column = getActiveColumn(); const row = getActiveRow(); const updatedRow = onCellPaste({ row, column }, event); updateRow(column, activePosition.rowIdx, updatedRow); } function handleCellInput(event: KeyboardEvent, cell: Element | null) { if (!activePositionIsCellInViewport) return; const row = getActiveRow(); const { key, shiftKey } = event; // Select the row on Shift + Space if (isSelectable && shiftKey && key === ' ') { assertIsValidGetRowKey(getRowKey); const rowKey = getRowKey(row); selectRow({ row, checked: !selectedRows.has(rowKey), isShiftClick: false }); // prevent scrolling event.preventDefault(); return; } if (isCellEditable(activePosition) && isDefaultCellInput(event, onCellPaste != null)) { // ensure cell is fully visible scrollIntoView(cell); // ensure we render the editor quickly enough, // otherwise the user input might be lost in Firefox flushSync(() => { setActivePosition(({ idx, rowIdx }) => ({ idx, rowIdx, mode: 'EDIT', row, originalRow: row })); }); } } function handleColumnResizeEnd() { // This check is needed as double-clicking the resize handle triggers onLostPointerCapture without resizing the column if (isColumnResizing) { onColumnWidthsChangeRaw?.(columnWidths); setIsColumnResizing(false); } } function handleDragHandlePointerDown(event: React.PointerEvent) { // keep the focus on the cell event.preventDefault(); if (event.pointerType === 'mouse' && event.button !== 0) { return; } setIsDragging(true); event.currentTarget.setPointerCapture(event.pointerId); } function handleDragHandlePointerMove(event: React.PointerEvent) { // find the dragged-over row using the pointer position const gridEl = gridRef.current!; const headerAndTopSummaryRowsHeight = headerRowsHeight + topSummaryRowsCount * summaryRowHeight; const offset = scrollTop - headerAndTopSummaryRowsHeight + event.clientY - gridEl.getBoundingClientRect().top; const overRowIdx = findRowIdx(offset); setDraggedOverRowIdx(overRowIdx); const ariaRowIndex = headerAndTopSummaryRowsCount + overRowIdx + 1; const el = gridEl.querySelector( `& > [aria-rowindex="${ariaRowIndex}"] > [aria-colindex="${activePosition.idx + 1}"]` ); scrollIntoView(el); } function handleDragHandleLostPointerCapture() { setIsDragging(false); if (draggedOverRowIdx === undefined) return; const { rowIdx } = activePosition; const [startRowIndex, endRowIndex] = rowIdx < draggedOverRowIdx ? [rowIdx + 1, draggedOverRowIdx + 1] : [draggedOverRowIdx, rowIdx]; updateRows(startRowIndex, endRowIndex); setDraggedOverRowIdx(undefined); } function handleDragHandleClick() { // keep the focus on the cell but do not scroll focusCell(gridRef.current!, false); } function handleDragHandleDoubleClick(event: React.MouseEvent) { event.stopPropagation(); updateRows(activePosition.rowIdx + 1, rows.length); } function updateRows(startRowIdx: number, endRowIdx: number) { if (onRowsChange == null) return; const { idx } = activePosition; const column = getActiveColumn(); const sourceRow = getActiveRow(); const updatedRows = [...rows]; const indexes: number[] = []; for (let i = startRowIdx; i < endRowIdx; i++) { if (isCellEditable({ idx, rowIdx: i })) { const updatedRow = onFill!({ columnKey: column.key, sourceRow, targetRow: rows[i] }); if (updatedRow !== rows[i]) { updatedRows[i] = updatedRow; indexes.push(i); } } } if (indexes.length > 0) { onRowsChange(updatedRows, { indexes, column }); } } function isCellEditable(position: Position): boolean { return ( validatePosition(position).isCellInViewport && isCellEditableUtil(columns[position.idx], rows[position.rowIdx]) ); } function setPosition(position: Position, options?: SetActivePositionOptions): void { const { isPositionInActiveBounds } = validatePosition(position); if (!isPositionInActiveBounds) return; commitEditorChanges(); // Copy the coordinates instead of spreading `position`, // so the shape of the active position doesn't depend on the object passed in const { idx, rowIdx } = position; const samePosition = isSamePosition(activePosition, position); if (options?.enableEditor && isCellEditable(position)) { // avoid selecting text in the editor, for example // after double-clicking and displayCellContent is enabled gridRef.current?.ownerDocument.getSelection()?.removeAllRanges(); const row = rows[rowIdx]; setActivePosition({ idx, rowIdx, mode: 'EDIT', row, originalRow: row }); } else if (samePosition) { // Avoid re-renders if the active position is the same scrollIntoView(getCellToScroll(gridRef.current!)); } else { const newPosition: ActivePosition = { idx, rowIdx, mode: 'ACTIVE' }; setActivePosition(newPosition); if (options?.shouldFocus) { setPositionToFocus(newPosition); } } if (onActivePositionChange && !samePosition) { onActivePositionChange({ rowIdx, row: rows[rowIdx], column: columns[idx] }); } } function selectHeaderCell({ idx, rowIdx }: Position): void { setPosition({ idx, rowIdx: minRowIdx + rowIdx - 1 }); } function getNextPosition(key: string, ctrlKey: boolean, shiftKey: boolean): Position { const { idx, rowIdx } = activePosition; switch (key) { case 'ArrowUp': { const nextRowIdx = rowIdx - 1; return { // avoid focusing header rows idx: idx === -1 && nextRowIdx < -topSummaryRowsCount ? 0 : idx, rowIdx: nextRowIdx }; } case 'ArrowDown': return { idx, rowIdx: rowIdx + 1 }; case leftKey: { const nextIdx = idx - 1; return { // avoid focusing header rows idx: rowIdx < -topSummaryRowsCount && nextIdx < 0 ? 0 : nextIdx, rowIdx }; } case rightKey: return { idx: idx + 1, rowIdx }; case 'Tab': return { idx: idx + (shiftKey ? -1 : 1), rowIdx }; case 'Home': // If the active position is a row, move focus to the first header row's cell. if (activePositionIsRow || ctrlKey) return { idx: 0, rowIdx: minRowIdx }; return { idx: 0, rowIdx }; case 'End': // If the active position is a row, move focus to the last row. if (activePositionIsRow) return { idx, rowIdx: maxRowIdx }; return { idx: maxColIdx, rowIdx: ctrlKey ? maxRowIdx : rowIdx }; case 'PageUp': { // Header and top summary rows are above the rows, so there's nothing to page up to. if (rowIdx < 0) return activePosition; const nextRowY = getRowTop(rowIdx) + getRowHeight(rowIdx) - clientHeight; return { idx, rowIdx: nextRowY > 0 ? findRowIdx(nextRowY) : 0 }; } case 'PageDown': { if (rowIdx >= rows.length) return activePosition; const nextRowY = getRowTop(rowIdx) + clientHeight; return { idx, rowIdx: nextRowY < totalRowHeight ? findRowIdx(nextRowY) : rows.length - 1 }; } default: return activePosition; } } function navigate(event: KeyboardEvent) { const { key, shiftKey } = event; let cellNavigationMode: CellNavigationMode = 'NONE'; if (key === 'Tab') { if ( canExitGrid({ shiftKey, maxColIdx, minRowIdx, maxRowIdx, activePosition }) ) { commitEditorChanges(); // Allow focus to leave the grid so the next control in the tab order can be focused return; } cellNavigationMode = 'CHANGE_ROW'; } // prevent scrolling and do not allow focus to leave event.preventDefault(); const ctrlKey = isCtrlKeyHeldDown(event); const nextPosition = getNextPosition(key, ctrlKey, shiftKey); if (isSamePosition(activePosition, nextPosition)) return; const nextActivePosition = getNextActivePosition({ moveUp: key === 'ArrowUp', moveNext: key === rightKey || (key === 'Tab' && !shiftKey), columns, colSpanColumns, rows, topSummaryRows, bottomSummaryRows, minRowIdx, mainHeaderRowIdx, maxRowIdx, cellNavigationMode, activePosition, nextPosition, nextPositionIsCellInActiveBounds: validatePosition(nextPosition).isCellInActiveBounds }); setPosition(nextActivePosition, { shouldFocus: true }); } function getDraggedOverCellIdx(currentRowIdx: number): number | undefined { if (draggedOverRowIdx === undefined) return; const { rowIdx } = activePosition; const isDraggedOver = rowIdx < draggedOverRowIdx ? rowIdx < currentRowIdx && currentRowIdx <= draggedOverRowIdx : rowIdx > currentRowIdx && currentRowIdx >= draggedOverRowIdx; return isDraggedOver ? activePosition.idx : undefined; } function getDragHandle() { if (onFill == null || activePosition.mode !== 'ACTIVE' || !activePositionIsCellInViewport) { return; } const { rowIdx } = activePosition; const column = getActiveColumn(); if (column.renderEditCell == null || column.editable === false) { return; } const isLastRow = rowIdx === maxRowIdx; const colSpan = column.getColSpan({ type: 'ROW', row: getActiveRow() }); const style = getCellStyle(column, colSpan); // the drag handle is at the end of the last column that the cell spans, // where it sticks when the column is start-frozen const lastColumn = columns[column.idx + colSpan - 1]; const columnWidth = getColumnWidth(lastColumn); const { insetInlineStart } = getCellStyle(lastColumn, 1); const marginEnd = 'calc(var(--rdg-drag-handle-size) * -0.5 + 1px)'; const isLastColumn = lastColumn.idx === maxColIdx; const dragHandleStyle: React.CSSProperties = { ...style, gridRowStart: headerAndTopSummaryRowsCount + rowIdx + 1, marginInlineEnd: isLastColumn ? undefined : marginEnd, marginBlockEnd: isLastRow ? undefined : marginEnd, insetInlineStart: insetInlineStart ? `calc(${insetInlineStart} + ${columnWidth}px + var(--rdg-drag-handle-size) * -0.5 - 1px)` : undefined }; return (
); } function renderFrozenShadow( shadowStyles: React.CSSProperties, bodyClassname: string, topClassname: string ) { return ( <>
{rows.length > 0 && (
)} {bottomSummaryRowsCount > 0 && (
totalRowHeight ? gridHeight - summaryRowHeight * bottomSummaryRowsCount : undefined, insetBlockEnd: clientHeight > totalRowHeight ? undefined : 0 }} /> )} ); } function getCellEditor(rowIdx: number) { if ( !activePositionIsCellInViewport || activePosition.rowIdx !== rowIdx || activePosition.mode !== 'EDIT' ) { return; } const { row } = activePosition; const column = getActiveColumn(); function closeEditor(shouldFocus: boolean) { const newPosition: ActivePosition = { idx: activePosition.idx, rowIdx, mode: 'ACTIVE' }; setActivePosition(newPosition); if (shouldFocus) { setPositionToFocus(newPosition); } } function onRowChange(row: R, commitChanges: boolean, shouldFocus: boolean) { if (commitChanges) { // Prevents an issue when the editor is closed by clicking on a different cell: // otherwise, commitEditorChanges may be called before the cell state is changed to // ACTIVE, which results in onRowChange getting called twice. flushSync(() => { updateRow(column, activePosition.rowIdx, row); closeEditor(shouldFocus); }); } else { setActivePosition((position) => ({ ...position, row })); } } return ( ); } function getViewportRows() { const activeRowIdx = activePosition.rowIdx; const viewportRows: React.ReactNode[] = []; if (activePositionIsInViewport && activeRowIdx < rowOverscanStartIdx) { viewportRows.push(renderViewportRow(activeRowIdx)); } for (let rowIdx = rowOverscanStartIdx; rowIdx <= rowOverscanEndIdx; rowIdx++) { viewportRows.push(renderViewportRow(rowIdx)); } if (activePositionIsInViewport && activeRowIdx > rowOverscanEndIdx) { viewportRows.push(renderViewportRow(activeRowIdx)); } return viewportRows; } function renderViewportRow(rowIdx: number) { const { idx: activeIdx, rowIdx: activeRowIdx } = activePosition; const isActiveRow = rowIdx === activeRowIdx; // if the row is outside the viewport then only render its active column, if any const mapColumns = isActiveRow && (rowIdx < rowOverscanStartIdx || rowIdx > rowOverscanEndIdx) ? mapViewportColumnsOutsideOfViewport : mapViewportColumns; const row = rows[rowIdx]; const gridRowStart = headerAndTopSummaryRowsCount + rowIdx + 1; let key: K | number = rowIdx; let isRowSelected = false; if (typeof getRowKey === 'function') { key = getRowKey(row); isRowSelected = selectedRows?.has(key) ?? false; } return renderRow(key, { // aria-rowindex is 1-based 'aria-rowindex': headerAndTopSummaryRowsCount + rowIdx + 1, 'aria-selected': isSelectable ? isRowSelected : undefined, rowIdx, row, mapViewportColumns: mapColumns, isRowSelectionDisabled: isRowSelectionDisabled?.(row) ?? false, isRowSelected, onCellMouseDown: onCellMouseDownLatest, onCellClick: onCellClickLatest, onCellDoubleClick: onCellDoubleClickLatest, onCellContextMenu: onCellContextMenuLatest, rowClass, gridRowStart, activeCellIdx: isActiveRow ? activeIdx : undefined, draggedOverCellIdx: getDraggedOverCellIdx(rowIdx), onRowChange: updateRowLatest, setActivePosition: setPositionLatest, activeCellEditor: getCellEditor(rowIdx), isTreeGrid }); } // Keep the state and prop in sync if (isColumnWidthsControlled && columnWidthsInternal !== columnWidthsRaw) { setColumnWidthsInternal(columnWidthsRaw); } let templateRows = `repeat(${headerRowsCount}, ${headerRowHeight}px)`; if (topSummaryRowsCount > 0) { templateRows += ` repeat(${topSummaryRowsCount}, ${summaryRowHeight}px)`; } if (rows.length > 0) { templateRows += gridTemplateRows; } if (bottomSummaryRowsCount > 0) { templateRows += ` repeat(${bottomSummaryRowsCount}, ${summaryRowHeight}px)`; } // Frozen cells, header rows, and summary rows are sticky, so they are already visible on their sticky axis. // A sticky cell inside the scroll padding would be scrolled out of it when it's focused or scrolled into view, // so the padding only applies when the active cell is a non-sticky cell on that axis, or when scrolling to a position. const isScrollingToPosition = scrollToPositionElement !== null; const hasInlineScrollPadding = isScrollingToPosition || queryActiveColumn()?.frozen === false; const hasBlockScrollPadding = isScrollingToPosition || activePositionIsInViewport; return (
{Array.from({ length: groupedColumnHeaderRowsCount }, (_, index) => ( ))} {rows.length === 0 && noRowsFallback ? ( noRowsFallback ) : ( <> {topSummaryRows?.map((row, rowIdx) => { const gridRowStart = headerRowsCount + 1 + rowIdx; const summaryRowIdx = mainHeaderRowIdx + 1 + rowIdx; const isSummaryRowActive = activePosition.rowIdx === summaryRowIdx; const top = headerRowsHeight + summaryRowHeight * rowIdx; return ( ); })} {getViewportRows()} {bottomSummaryRows?.map((row, rowIdx) => { const gridRowStart = headerAndTopSummaryRowsCount + rows.length + rowIdx + 1; const summaryRowIdx = rows.length + rowIdx; const isSummaryRowActive = activePosition.rowIdx === summaryRowIdx; const top = clientHeight > totalRowHeight ? gridHeight - summaryRowHeight * (bottomSummaryRowsCount - rowIdx) : undefined; const bottom = top === undefined ? summaryRowHeight * (bottomSummaryRowsCount - 1 - rowIdx) : undefined; return ( ); })} )} {lastStartFrozenColumnIndex > -1 && renderFrozenShadow( frozenStartShadowStyles, frozenColumnShadowStartClassname, frozenColumnShadowStartTopClassname )} {firstEndFrozenColumnIndex > -1 && renderFrozenShadow( frozenEndShadowStyles, frozenColumnShadowEndClassname, frozenColumnShadowEndTopClassname )} {getDragHandle()} {/* render empty cells that span only 1 column so we can safely measure column widths, regardless of colSpan */} {renderMeasuringCells(viewportColumns)} {scrollToPositionElement}
); } function isSamePosition(p1: Position, p2: Position) { return p1.idx === p2.idx && p1.rowIdx === p2.rowIdx; }