-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
DataGrid.tsx
753 lines (672 loc) · 23.5 KB
/
DataGrid.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
import React, {
forwardRef,
useState,
useRef,
useMemo,
useLayoutEffect,
useEffect,
useImperativeHandle,
useCallback,
createElement
} from 'react';
import clsx from 'clsx';
import EventBus from './EventBus';
import HeaderRow from './HeaderRow';
import FilterRow from './FilterRow';
import Row from './Row';
import SummaryRow from './SummaryRow';
import { ValueFormatter } from './formatters';
import { legacyCellInput, EditorContainer, EditorPortal } from './editors';
import {
assertIsValidKey,
getColumnMetrics,
getColumnScrollPosition,
getHorizontalRangeToRender,
getScrollbarSize,
getVerticalRangeToRender,
getViewportColumns,
getNextSelectedCellPosition,
isSelectedCellEditable,
canExitGrid,
isCtrlKeyHeldDown
} from './utils';
import {
CalculatedColumn,
CheckCellIsEditableEvent,
Column,
Filters,
FormatterProps,
Position,
RowRendererProps,
RowsUpdateEvent,
SelectRowEvent,
CommitEvent
} from './common/types';
import { CellNavigationMode, SortDirection, UpdateActions } from './common/enums';
interface SelectCellState extends Position {
mode: 'SELECT';
}
interface EditCellState extends Position {
mode: 'EDIT';
key: string | null;
}
export interface DataGridHandle {
scrollToColumn: (colIdx: number) => void;
scrollToRow: (rowIdx: number) => void;
selectCell: (position: Position, openEditor?: boolean) => void;
}
export interface DataGridProps<R, K extends keyof R, SR = unknown> {
/**
* Grid and data Props
*/
/** An array of objects representing each column on the grid */
columns: readonly Column<R, SR>[];
/** A function called for each rendered row that should return a plain key/value pair object */
rows: readonly R[];
/**
* Rows to be pinned at the bottom of the rows view for summary, the vertical scroll bar will not scroll these rows.
* Bottom horizontal scroll bar can move the row left / right. Or a customized row renderer can be used to disabled the scrolling support.
*/
summaryRows?: readonly SR[];
/** The primary key property of each row */
rowKey?: K;
/**
* Callback called whenever row data is updated
* When editing is enabled, this callback will be called for the following scenarios
* 1. Using the supplied editor of the column. The default editor is the SimpleTextEditor.
* 2. Copy/pasting the value from one cell to another <kbd>CTRL</kbd>+<kbd>C</kbd>, <kbd>CTRL</kbd>+<kbd>V</kbd>
* 3. Update multiple cells by dragging the fill handle of a cell up or down to a destination cell.
* 4. Update all cells under a given cell by double clicking the cell's fill handle.
*/
onRowsUpdate?: <E extends RowsUpdateEvent>(event: E) => void;
/**
* Dimensions props
*/
/** The width of the grid in pixels */
width?: number;
/** The height of the grid in pixels */
height?: number;
/** Minimum column width in pixels */
minColumnWidth?: number;
/** The height of each row in pixels */
rowHeight?: number;
/** The height of the header row in pixels */
headerRowHeight?: number;
/** The height of the header filter row in pixels */
headerFiltersHeight?: number;
/**
* Feature props
*/
/** Set of selected row keys */
selectedRows?: ReadonlySet<R[K]>;
/** Function called whenever row selection is changed */
onSelectedRowsChange?: (selectedRows: Set<R[K]>) => void;
/** The key of the column which is currently being sorted */
sortColumn?: string;
/** The direction to sort the sortColumn*/
sortDirection?: SortDirection;
/** Function called whenever grid is sorted*/
onSort?: (columnKey: string, direction: SortDirection) => void;
filters?: Filters;
onFiltersChange?: (filters: Filters) => void;
/**
* Custom renderers
*/
defaultFormatter?: React.ComponentType<FormatterProps<R, SR>>;
rowRenderer?: React.ComponentType<RowRendererProps<R, SR>>;
emptyRowsRenderer?: React.ComponentType;
/**
* Event props
*/
/** Function called whenever a row is clicked */
onRowClick?: (rowIdx: number, row: R, column: CalculatedColumn<R, SR>) => void;
/** Called when the grid is scrolled */
onScroll?: (event: React.UIEvent<HTMLDivElement>) => void;
/** Called when a column is resized */
onColumnResize?: (idx: number, width: number) => void;
/** Function called whenever selected cell is changed */
onSelectedCellChange?: (position: Position) => void;
/** called before cell is set active, returns a boolean to determine whether cell is editable */
onCheckCellIsEditable?: (event: CheckCellIsEditableEvent<R, SR>) => boolean;
/**
* Toggles and modes
*/
/** Toggles whether filters row is displayed or not */
enableFilters?: boolean;
enableCellCopyPaste?: boolean;
enableCellDragAndDrop?: boolean;
cellNavigationMode?: CellNavigationMode;
/**
* Miscellaneous
*/
/** The node where the editor portal should mount. */
editorPortalTarget?: Element;
rowClass?: (row: R) => string | undefined;
}
function getNextPosition(key: string, shiftKey: boolean, currentPosition: Position) {
const { idx, rowIdx } = currentPosition;
switch (key) {
case 'ArrowUp':
return { idx, rowIdx: rowIdx - 1 };
case 'ArrowDown':
return { idx, rowIdx: rowIdx + 1 };
case 'ArrowLeft':
return { idx: idx - 1, rowIdx };
case 'ArrowRight':
return { idx: idx + 1, rowIdx };
case 'Tab':
return { idx: idx + (shiftKey ? -1 : 1), rowIdx };
default:
return currentPosition;
}
}
/**
* Main API Component to render a data grid of rows and columns
*
* @example
*
* <DataGrid columns={columns} rows={rows} />
*/
function DataGrid<R, K extends keyof R, SR>({
// Grid and data Props
columns: rawColumns,
rows,
summaryRows,
rowKey,
onRowsUpdate,
// Dimensions props
width,
height = 350,
minColumnWidth = 80,
rowHeight = 35,
headerRowHeight = rowHeight,
headerFiltersHeight = 45,
// Feature props
selectedRows,
onSelectedRowsChange,
sortColumn,
sortDirection,
onSort,
filters,
onFiltersChange,
// Custom renderers
defaultFormatter = ValueFormatter,
rowRenderer: RowRenderer = Row,
emptyRowsRenderer,
// Event props
onRowClick,
onScroll,
onColumnResize,
onSelectedCellChange,
onCheckCellIsEditable,
// Toggles and modes
enableFilters = false,
enableCellCopyPaste = false,
enableCellDragAndDrop = false,
cellNavigationMode = CellNavigationMode.NONE,
// Miscellaneous
editorPortalTarget = document.body,
rowClass
}: DataGridProps<R, K, SR>, ref: React.Ref<DataGridHandle>) {
/**
* refs
* */
const gridRef = useRef<HTMLDivElement>(null);
const lastSelectedRowIdx = useRef(-1);
/**
* states
*/
const [eventBus] = useState(() => new EventBus());
const [gridWidth, setGridWidth] = useState(0);
const [scrollTop, setScrollTop] = useState(0);
const [scrollLeft, setScrollLeft] = useState(0);
const [columnWidths, setColumnWidths] = useState<ReadonlyMap<string, number>>(() => new Map());
const [selectedPosition, setSelectedPosition] = useState<SelectCellState | EditCellState>({ idx: -1, rowIdx: -1, mode: 'SELECT' });
const [copiedPosition, setCopiedPosition] = useState<Position & { value: unknown } | null>(null);
const [isDragging, setDragging] = useState(false);
const [draggedOverRowIdx, setDraggedOverRowIdx] = useState<number | undefined>(undefined);
/**
* computed values
*/
const viewportWidth = (width || gridWidth) - 2; // 2 for border width;
const { columns, lastFrozenColumnIndex, totalColumnWidth } = useMemo(() => {
return getColumnMetrics<R, SR>({
columns: rawColumns,
minColumnWidth,
viewportWidth,
columnWidths,
defaultFormatter
});
}, [columnWidths, rawColumns, defaultFormatter, minColumnWidth, viewportWidth]);
const [colOverscanStartIdx, colOverscanEndIdx] = useMemo((): [number, number] => {
return getHorizontalRangeToRender(
columns,
lastFrozenColumnIndex,
viewportWidth,
scrollLeft
);
}, [scrollLeft, columns, lastFrozenColumnIndex, viewportWidth]);
const viewportColumns = useMemo((): readonly CalculatedColumn<R, SR>[] => {
return getViewportColumns(
columns,
colOverscanStartIdx,
colOverscanEndIdx
);
}, [colOverscanEndIdx, colOverscanStartIdx, columns]);
const totalHeaderHeight = headerRowHeight + (enableFilters ? headerFiltersHeight : 0);
const clientHeight = height
- 2 // border width
- totalHeaderHeight
- (summaryRows?.length ?? 0) * rowHeight
- (totalColumnWidth > viewportWidth ? getScrollbarSize() : 0);
const [rowOverscanStartIdx, rowOverscanEndIdx] = getVerticalRangeToRender(
clientHeight,
rowHeight,
scrollTop,
rows.length
);
/**
* effects
*/
useLayoutEffect(() => {
// Do not calculate the width if width is provided
if (typeof width === 'number') return;
function onResize() {
// Immediately re-render when the component is mounted to get valid columnMetrics.
setGridWidth(gridRef.current!.getBoundingClientRect().width);
}
onResize();
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
}, [width]);
useEffect(() => {
if (!onSelectedRowsChange) return;
const handleRowSelectionChange = ({ rowIdx, checked, isShiftClick }: SelectRowEvent) => {
assertIsValidKey(rowKey);
const newSelectedRows = new Set(selectedRows);
const rowId = rows[rowIdx][rowKey];
if (checked) {
newSelectedRows.add(rowId);
const previousRowIdx = lastSelectedRowIdx.current;
lastSelectedRowIdx.current = rowIdx;
if (isShiftClick && previousRowIdx !== -1 && previousRowIdx !== rowIdx) {
const step = Math.sign(rowIdx - previousRowIdx);
for (let i = previousRowIdx + step; i !== rowIdx; i += step) {
newSelectedRows.add(rows[i][rowKey]);
}
}
} else {
newSelectedRows.delete(rowId);
lastSelectedRowIdx.current = -1;
}
onSelectedRowsChange(newSelectedRows);
};
return eventBus.subscribe('ROW_SELECT', handleRowSelectionChange);
}, [eventBus, onSelectedRowsChange, rows, rowKey, selectedRows]);
useEffect(() => {
return eventBus.subscribe('CELL_SELECT', selectCell);
});
useEffect(() => {
if (!enableCellDragAndDrop || isDragging || draggedOverRowIdx === undefined) return;
const { idx, rowIdx } = selectedPosition;
const column = columns[idx];
const cellKey = column.key;
const value = rows[rowIdx][cellKey as keyof R];
onRowsUpdate?.({
cellKey,
fromRow: rowIdx,
toRow: draggedOverRowIdx,
updated: { [cellKey]: value } as unknown as never,
action: UpdateActions.CELL_DRAG
});
setDraggedOverRowIdx(undefined);
});
useImperativeHandle(ref, () => ({
scrollToColumn(idx: number) {
scrollToCell({ idx });
},
scrollToRow(rowIdx: number) {
const { current } = gridRef;
if (!current) return;
current.scrollTop = rowIdx * rowHeight;
},
selectCell
}));
/**
* event handlers
*/
function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
if (enableCellCopyPaste && isCtrlKeyHeldDown(event)) {
// event.key may be uppercase `C` or `V`
const lowerCaseKey = event.key.toLowerCase();
if (lowerCaseKey === 'c') return handleCopy();
if (lowerCaseKey === 'v') return handlePaste();
}
switch (event.key) {
case 'Escape':
setCopiedPosition(null);
return;
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight':
case 'Tab':
event.preventDefault();
navigate(event.key, event.shiftKey);
break;
default:
handleCellInput(event);
break;
}
}
function handleScroll(event: React.UIEvent<HTMLDivElement>) {
const { scrollTop, scrollLeft } = event.currentTarget;
setScrollTop(scrollTop);
setScrollLeft(scrollLeft);
onScroll?.(event);
}
const handleColumnResize = useCallback((column: CalculatedColumn<R, SR>, width: number) => {
const newColumnWidths = new Map(columnWidths);
newColumnWidths.set(column.key, width);
setColumnWidths(newColumnWidths);
onColumnResize?.(column.idx, width);
}, [columnWidths, onColumnResize]);
function handleCommit({ cellKey, rowIdx, updated }: CommitEvent) {
onRowsUpdate?.({
cellKey,
fromRow: rowIdx,
toRow: rowIdx,
updated,
action: UpdateActions.CELL_UPDATE
});
setSelectedPosition(({ idx, rowIdx }) => ({ idx, rowIdx, mode: 'SELECT' }));
}
function handleCopy() {
const { idx, rowIdx } = selectedPosition;
const value = rows[rowIdx][columns[idx].key as keyof R];
setCopiedPosition({ idx, rowIdx, value });
}
function handlePaste() {
if (
copiedPosition === null
|| !isCellEditable(selectedPosition)
|| (copiedPosition.idx === selectedPosition.idx && copiedPosition.rowIdx === selectedPosition.rowIdx)
) {
return;
}
const { rowIdx: toRow } = selectedPosition;
const cellKey = columns[selectedPosition.idx].key;
const { rowIdx: fromRow, idx, value } = copiedPosition;
const fromCellKey = columns[idx].key;
onRowsUpdate?.({
cellKey,
fromRow,
toRow,
updated: { [cellKey]: value } as unknown as never,
action: UpdateActions.COPY_PASTE,
fromCellKey
});
}
function handleCellInput(event: React.KeyboardEvent<HTMLDivElement>) {
const { key } = event;
const column = columns[selectedPosition.idx];
const row = rows[selectedPosition.rowIdx];
const canOpenEditor = selectedPosition.mode === 'SELECT' && isCellEditable(selectedPosition);
const isActivatedByUser = (column.unsafe_onCellInput ?? legacyCellInput)(event, row) === true;
if (canOpenEditor && (key === 'Enter' || isActivatedByUser)) {
setSelectedPosition(({ idx, rowIdx }) => ({ idx, rowIdx, key, mode: 'EDIT' }));
}
}
function handleMouseDown() {
setDragging(true);
window.addEventListener('mouseover', onMouseover);
window.addEventListener('mouseup', onMouseup);
function onMouseover(event: MouseEvent) {
// Trigger onMouseup in edge cases where we release the mouse button but `mouseup` isn't triggered,
// for example when releasing the mouse button outside the iframe the grid is rendered in.
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
if (event.buttons !== 1) onMouseup();
}
function onMouseup() {
window.removeEventListener('mouseover', onMouseover);
window.removeEventListener('mouseup', onMouseup);
setDragging(false);
}
}
function handleDoubleClick(event: React.MouseEvent<HTMLDivElement>) {
event.stopPropagation();
const column = columns[selectedPosition.idx];
const cellKey = column.key;
const value = rows[selectedPosition.rowIdx][cellKey as keyof R];
onRowsUpdate?.({
cellKey,
fromRow: selectedPosition.rowIdx,
toRow: rows.length - 1,
updated: { [cellKey]: value } as unknown as never,
action: UpdateActions.COLUMN_FILL
});
}
/**
* utils
*/
function isCellWithinBounds({ idx, rowIdx }: Position): boolean {
return rowIdx >= 0 && rowIdx < rows.length && idx >= 0 && idx < columns.length;
}
function isCellEditable(position: Position) {
return isCellWithinBounds(position)
&& isSelectedCellEditable<R, SR>({ columns, rows, selectedPosition: position, onCheckCellIsEditable });
}
function selectCell(position: Position, enableEditor = false): void {
if (!isCellWithinBounds(position)) return;
if (enableEditor && isCellEditable(position)) {
setSelectedPosition({ ...position, mode: 'EDIT', key: null });
} else {
setSelectedPosition({ ...position, mode: 'SELECT' });
}
scrollToCell(position);
onSelectedCellChange?.({ ...position });
}
function getFrozenColumnsWidth() {
if (lastFrozenColumnIndex === -1) return 0;
const lastFrozenCol = columns[lastFrozenColumnIndex];
return lastFrozenCol.left + lastFrozenCol.width;
}
function scrollToCell({ idx, rowIdx }: Partial<Position>) {
const { current } = gridRef;
if (!current) return;
if (typeof idx === 'number' && idx > lastFrozenColumnIndex) {
const { clientWidth } = current;
const { left, width } = columns[idx];
const isCellAtLeftBoundary = left < scrollLeft + width + getFrozenColumnsWidth();
const isCellAtRightBoundary = left + width > clientWidth + scrollLeft;
if (isCellAtLeftBoundary || isCellAtRightBoundary) {
const newScrollLeft = getColumnScrollPosition(columns, idx, scrollLeft, clientWidth);
current.scrollLeft = scrollLeft + newScrollLeft;
}
}
if (typeof rowIdx === 'number') {
if (rowIdx * rowHeight < scrollTop) {
// at top boundary, scroll to the row's top
current.scrollTop = rowIdx * rowHeight;
} else if ((rowIdx + 1) * rowHeight > scrollTop + clientHeight) {
// at bottom boundary, scroll the next row's top to the bottom of the viewport
current.scrollTop = (rowIdx + 1) * rowHeight - clientHeight;
}
}
}
function isDraggedOver(currentRowIdx: number) {
if (draggedOverRowIdx === undefined) return;
const { rowIdx } = selectedPosition;
return rowIdx < draggedOverRowIdx
? rowIdx < currentRowIdx && currentRowIdx <= draggedOverRowIdx
: rowIdx > currentRowIdx && currentRowIdx >= draggedOverRowIdx;
}
function navigate(key: string, shiftKey: boolean) {
let nextPosition = getNextPosition(key, shiftKey, selectedPosition);
let mode = cellNavigationMode;
if (key === 'Tab') {
// If we are in a position to leave the grid, stop editing but stay in that cell
if (canExitGrid({ shiftKey, cellNavigationMode, columns, rowsCount: rows.length, selectedPosition })) {
// Reset the selected position before exiting
setSelectedPosition({ idx: -1, rowIdx: -1, mode: 'SELECT' });
return;
}
mode = cellNavigationMode === CellNavigationMode.NONE
? CellNavigationMode.CHANGE_ROW
: cellNavigationMode;
}
nextPosition = getNextSelectedCellPosition<R, SR>({
columns,
rowsCount: rows.length,
cellNavigationMode: mode,
nextPosition
});
selectCell(nextPosition);
}
function getEditorContainer() {
if (selectedPosition.mode === 'SELECT') return null;
const column = columns[selectedPosition.idx];
const row = rows[selectedPosition.rowIdx];
let editorLeft = 0;
let editorTop = 0;
if (gridRef.current !== null) {
const { left, top } = gridRef.current.getBoundingClientRect();
const { scrollTop: docTop, scrollLeft: docLeft } = document.scrollingElement || document.documentElement;
const gridLeft = left + docLeft;
const gridTop = top + docTop;
editorLeft = gridLeft + column.left - (column.frozen ? 0 : scrollLeft);
editorTop = gridTop + totalHeaderHeight + selectedPosition.rowIdx * rowHeight - scrollTop;
}
return (
<EditorPortal target={editorPortalTarget}>
<EditorContainer<R, SR>
firstEditorKeyPress={selectedPosition.key}
onCommit={handleCommit}
onCommitCancel={() => setSelectedPosition(({ idx, rowIdx }) => ({ idx, rowIdx, mode: 'SELECT' }))}
rowIdx={selectedPosition.rowIdx}
row={row}
rowHeight={rowHeight}
column={column}
scrollLeft={scrollLeft}
scrollTop={scrollTop}
left={editorLeft}
top={editorTop}
/>
</EditorPortal>
);
}
function getDragHandle() {
if (!enableCellDragAndDrop || !isCellEditable(selectedPosition) || selectedPosition.mode === 'EDIT') return null;
return (
<div
className="rdg-cell-drag-handle"
onMouseDown={handleMouseDown}
onDoubleClick={handleDoubleClick}
/>
);
}
function getViewportRows() {
const rowElements = [];
for (let rowIdx = rowOverscanStartIdx; rowIdx <= rowOverscanEndIdx; rowIdx++) {
const row = rows[rowIdx];
let key: string | number = rowIdx;
let isRowSelected = false;
if (rowKey !== undefined) {
const rowId = row[rowKey];
isRowSelected = selectedRows?.has(rowId) ?? false;
if (typeof rowId === 'string' || typeof rowId === 'number') {
key = rowId;
}
}
rowElements.push(
<RowRenderer
key={key}
rowIdx={rowIdx}
row={row}
viewportColumns={viewportColumns}
lastFrozenColumnIndex={lastFrozenColumnIndex}
selectedCellIdx={selectedPosition.rowIdx === rowIdx && selectedPosition.mode === 'SELECT' ? selectedPosition.idx : undefined}
copiedCellIdx={copiedPosition?.rowIdx === rowIdx ? copiedPosition.idx : undefined}
draggedOverCellIdx={isDraggedOver(rowIdx) ? selectedPosition.idx : undefined}
eventBus={eventBus}
isRowSelected={isRowSelected}
onRowClick={onRowClick}
rowClass={rowClass}
top={rowIdx * rowHeight + totalHeaderHeight}
setDraggedOverRowIdx={isDragging ? setDraggedOverRowIdx : undefined}
dragHandle={selectedPosition.rowIdx === rowIdx ? getDragHandle() : undefined}
/>
);
}
return rowElements;
}
// Reset the positions if the current values are no longer valid. This can happen if a column or row is removed
if (selectedPosition.idx >= columns.length || selectedPosition.rowIdx >= rows.length) {
setSelectedPosition({ idx: -1, rowIdx: -1, mode: 'SELECT' });
setCopiedPosition(null);
setDraggedOverRowIdx(undefined);
}
return (
<div
className="rdg"
style={{
width,
height,
'--header-row-height': `${headerRowHeight}px`,
'--filter-row-height': `${headerFiltersHeight}px`,
'--row-width': `${totalColumnWidth}px`,
'--row-height': `${rowHeight}px`
} as unknown as React.CSSProperties}
ref={gridRef}
onScroll={handleScroll}
>
<HeaderRow<R, K, SR>
rowKey={rowKey}
rows={rows}
columns={viewportColumns}
onColumnResize={handleColumnResize}
lastFrozenColumnIndex={lastFrozenColumnIndex}
allRowsSelected={selectedRows?.size === rows.length}
onSelectedRowsChange={onSelectedRowsChange}
sortColumn={sortColumn}
sortDirection={sortDirection}
onSort={onSort}
/>
{enableFilters && (
<FilterRow<R, SR>
lastFrozenColumnIndex={lastFrozenColumnIndex}
columns={viewportColumns}
filters={filters}
onFiltersChange={onFiltersChange}
/>
)}
{rows.length === 0 && emptyRowsRenderer ? createElement(emptyRowsRenderer) : (
<>
<div style={{ height: Math.max(rows.length * rowHeight, clientHeight) }} />
<div
className={clsx({ 'rdg-viewport-dragging': isDragging })}
onKeyDown={handleKeyDown}
>
{viewportWidth > 0 && getViewportRows()}
{getEditorContainer()}
</div>
{summaryRows?.map((row, rowIdx) => (
<SummaryRow<R, SR>
key={rowIdx}
rowIdx={rowIdx}
row={row}
bottom={rowHeight * (summaryRows.length - 1 - rowIdx)}
viewportColumns={viewportColumns}
lastFrozenColumnIndex={lastFrozenColumnIndex}
/>
))}
</>
)}
</div>
);
}
export default forwardRef(
DataGrid as React.RefForwardingComponent<DataGridHandle>
) as <R, K extends keyof R, SR = unknown>(props: DataGridProps<R, K, SR> & { ref?: React.Ref<DataGridHandle> }) => JSX.Element;