-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
GridRow.tsx
543 lines (488 loc) · 18.2 KB
/
GridRow.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
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import { fastMemo } from '@mui/x-internals/fastMemo';
import { GridRowEventLookup } from '../models/events';
import { GridRowId, GridRowModel } from '../models/gridRows';
import { GridEditModes, GridRowModes, GridCellModes } from '../models/gridEditRowModel';
import { gridClasses } from '../constants/gridClasses';
import { composeGridClasses } from '../utils/composeGridClasses';
import { useGridRootProps } from '../hooks/utils/useGridRootProps';
import { GridPinnedColumns } from '../hooks/features/columns';
import type { GridStateColDef } from '../models/colDef/gridColDef';
import type { GridRenderContext } from '../models/params/gridScrollParams';
import { gridColumnPositionsSelector } from '../hooks/features/columns/gridColumnsSelector';
import { useGridSelector, objectShallowCompare } from '../hooks/utils/useGridSelector';
import { GridRowClassNameParams } from '../models/params/gridRowParams';
import { useGridVisibleRows } from '../hooks/utils/useGridVisibleRows';
import { findParentElementFromClassName, isEventTargetInPortal } from '../utils/domUtils';
import { GRID_CHECKBOX_SELECTION_COL_DEF } from '../colDef/gridCheckboxSelectionColDef';
import { GRID_ACTIONS_COLUMN_TYPE } from '../colDef/gridActionsColDef';
import { GRID_DETAIL_PANEL_TOGGLE_FIELD } from '../internals/constants';
import type { GridDimensions } from '../hooks/features/dimensions';
import { gridSortModelSelector } from '../hooks/features/sorting/gridSortingSelector';
import { gridRowMaximumTreeDepthSelector } from '../hooks/features/rows/gridRowsSelector';
import { gridEditRowsStateSelector } from '../hooks/features/editing/gridEditingSelectors';
import { PinnedPosition, gridPinnedColumnPositionLookup } from './cell/GridCell';
import { GridScrollbarFillerCell as ScrollbarFiller } from './GridScrollbarFillerCell';
import { getPinnedCellOffset } from '../internals/utils/getPinnedCellOffset';
import { useGridConfiguration } from '../hooks/utils/useGridConfiguration';
import { useGridPrivateApiContext } from '../hooks/utils/useGridPrivateApiContext';
export interface GridRowProps extends React.HTMLAttributes<HTMLDivElement> {
row: GridRowModel;
rowId: GridRowId;
selected: boolean;
/**
* Index of the row in the whole sorted and filtered dataset.
* If some rows above have expanded children, this index also take those children into account.
*/
index: number;
rowHeight: number | 'auto';
offsetTop: number | undefined;
offsetLeft: number;
dimensions: GridDimensions;
renderContext: GridRenderContext;
visibleColumns: GridStateColDef[];
pinnedColumns: GridPinnedColumns;
/**
* Determines which cell has focus.
* If `null`, no cell in this row has focus.
*/
focusedColumnIndex: number | undefined;
/**
* Determines which cell should be tabbable by having tabIndex=0.
* If `null`, no cell in this row is in the tab sequence.
*/
tabbableCell: string | null;
isFirstVisible: boolean;
isLastVisible: boolean;
isNotVisible: boolean;
showBottomBorder: boolean;
onClick?: React.MouseEventHandler<HTMLDivElement>;
onDoubleClick?: React.MouseEventHandler<HTMLDivElement>;
onMouseEnter?: React.MouseEventHandler<HTMLDivElement>;
onMouseLeave?: React.MouseEventHandler<HTMLDivElement>;
[x: `data-${string}`]: string;
}
const GridRow = React.forwardRef<HTMLDivElement, GridRowProps>(function GridRow(props, refProp) {
const {
selected,
rowId,
row,
index,
style: styleProp,
rowHeight,
className,
visibleColumns,
pinnedColumns,
offsetTop,
offsetLeft,
dimensions,
renderContext,
focusedColumnIndex,
isFirstVisible,
isLastVisible,
isNotVisible,
showBottomBorder,
tabbableCell,
onClick,
onDoubleClick,
onMouseEnter,
onMouseLeave,
onMouseOut,
onMouseOver,
...other
} = props;
const apiRef = useGridPrivateApiContext();
const configuration = useGridConfiguration();
const ref = React.useRef<HTMLDivElement>(null);
const rootProps = useGridRootProps();
const currentPage = useGridVisibleRows(apiRef, rootProps);
const sortModel = useGridSelector(apiRef, gridSortModelSelector);
const treeDepth = useGridSelector(apiRef, gridRowMaximumTreeDepthSelector);
const columnPositions = useGridSelector(apiRef, gridColumnPositionsSelector);
const editRowsState = useGridSelector(apiRef, gridEditRowsStateSelector);
const handleRef = useForkRef(ref, refProp);
const rowNode = apiRef.current.getRowNode(rowId);
const scrollbarWidth = dimensions.hasScrollY ? dimensions.scrollbarSize : 0;
const gridHasFiller = dimensions.columnsTotalWidth < dimensions.viewportOuterSize.width;
const editing = apiRef.current.getRowMode(rowId) === GridRowModes.Edit;
const editable = rootProps.editMode === GridEditModes.Row;
const hasFocusCell = focusedColumnIndex !== undefined;
const hasVirtualFocusCellLeft =
hasFocusCell &&
focusedColumnIndex >= pinnedColumns.left.length &&
focusedColumnIndex < renderContext.firstColumnIndex;
const hasVirtualFocusCellRight =
hasFocusCell &&
focusedColumnIndex < visibleColumns.length - pinnedColumns.right.length &&
focusedColumnIndex >= renderContext.lastColumnIndex;
const classes = composeGridClasses(rootProps.classes, {
root: [
'row',
selected && 'selected',
editable && 'row--editable',
editing && 'row--editing',
isFirstVisible && 'row--firstVisible',
isLastVisible && 'row--lastVisible',
showBottomBorder && 'row--borderBottom',
rowHeight === 'auto' && 'row--dynamicHeight',
],
});
const getRowAriaAttributes = configuration.hooks.useGridRowAriaAttributes();
React.useLayoutEffect(() => {
if (currentPage.range) {
const rowIndex = apiRef.current.getRowIndexRelativeToVisibleRows(rowId);
// Pinned rows are not part of the visible rows
if (rowIndex !== undefined) {
apiRef.current.unstable_setLastMeasuredRowIndex(rowIndex);
}
}
if (ref.current && rowHeight === 'auto') {
return apiRef.current.observeRowHeight(ref.current, rowId);
}
return undefined;
}, [apiRef, currentPage.range, rowHeight, rowId]);
const publish = React.useCallback(
(
eventName: keyof GridRowEventLookup,
propHandler: React.MouseEventHandler<HTMLDivElement> | undefined,
): React.MouseEventHandler<HTMLDivElement> =>
(event) => {
// Ignore portal
if (isEventTargetInPortal(event)) {
return;
}
// The row might have been deleted
if (!apiRef.current.getRow(rowId)) {
return;
}
apiRef.current.publishEvent(eventName, apiRef.current.getRowParams(rowId), event);
if (propHandler) {
propHandler(event);
}
},
[apiRef, rowId],
);
const publishClick = React.useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
const cell = findParentElementFromClassName(event.target as HTMLDivElement, gridClasses.cell);
const field = cell?.getAttribute('data-field');
// Check if the field is available because the cell that fills the empty
// space of the row has no field.
if (field) {
// User clicked in the checkbox added by checkboxSelection
if (field === GRID_CHECKBOX_SELECTION_COL_DEF.field) {
return;
}
// User opened a detail panel
if (field === GRID_DETAIL_PANEL_TOGGLE_FIELD) {
return;
}
// User reorders a row
if (field === '__reorder__') {
return;
}
// User is editing a cell
if (apiRef.current.getCellMode(rowId, field) === GridCellModes.Edit) {
return;
}
// User clicked a button from the "actions" column type
const column = apiRef.current.getColumn(field);
if (column?.type === GRID_ACTIONS_COLUMN_TYPE) {
return;
}
}
publish('rowClick', onClick)(event);
},
[apiRef, onClick, publish, rowId],
);
const { slots, slotProps, disableColumnReorder } = rootProps;
const rowReordering = (rootProps as any).rowReordering as boolean;
const heightEntry = useGridSelector(
apiRef,
() => ({ ...apiRef.current.getRowHeightEntry(rowId) }),
objectShallowCompare,
);
const style = React.useMemo(() => {
if (isNotVisible) {
return {
opacity: 0,
width: 0,
height: 0,
};
}
const rowStyle = {
...styleProp,
maxHeight: rowHeight === 'auto' ? 'none' : rowHeight, // max-height doesn't support "auto"
minHeight: rowHeight,
'--height': typeof rowHeight === 'number' ? `${rowHeight}px` : rowHeight,
};
if (heightEntry.spacingTop) {
const property = rootProps.rowSpacingType === 'border' ? 'borderTopWidth' : 'marginTop';
rowStyle[property] = heightEntry.spacingTop;
}
if (heightEntry.spacingBottom) {
const property = rootProps.rowSpacingType === 'border' ? 'borderBottomWidth' : 'marginBottom';
let propertyValue = rowStyle[property];
// avoid overriding existing value
if (typeof propertyValue !== 'number') {
propertyValue = parseInt(propertyValue || '0', 10);
}
propertyValue += heightEntry.spacingBottom;
rowStyle[property] = propertyValue;
}
return rowStyle;
}, [isNotVisible, rowHeight, styleProp, heightEntry, rootProps.rowSpacingType]);
const rowClassNames = apiRef.current.unstable_applyPipeProcessors('rowClassName', [], rowId);
const ariaAttributes = rowNode ? getRowAriaAttributes(rowNode, index) : undefined;
if (typeof rootProps.getRowClassName === 'function') {
const indexRelativeToCurrentPage = index - (currentPage.range?.firstRowIndex || 0);
const rowParams: GridRowClassNameParams = {
...apiRef.current.getRowParams(rowId),
isFirstVisible: indexRelativeToCurrentPage === 0,
isLastVisible: indexRelativeToCurrentPage === currentPage.rows.length - 1,
indexRelativeToCurrentPage,
};
rowClassNames.push(rootProps.getRowClassName(rowParams));
}
const getCell = (
column: GridStateColDef,
indexInSection: number,
indexRelativeToAllColumns: number,
sectionLength: number,
pinnedPosition = PinnedPosition.NONE,
) => {
const cellColSpanInfo = apiRef.current.unstable_getCellColSpanInfo(
rowId,
indexRelativeToAllColumns,
);
if (cellColSpanInfo?.spannedByColSpan) {
return null;
}
const width = cellColSpanInfo?.cellProps.width ?? column.computedWidth;
const colSpan = cellColSpanInfo?.cellProps.colSpan ?? 1;
const pinnedOffset = getPinnedCellOffset(
gridPinnedColumnPositionLookup[pinnedPosition],
column.computedWidth,
indexRelativeToAllColumns,
columnPositions,
dimensions,
);
if (rowNode?.type === 'skeletonRow') {
return (
<slots.skeletonCell
key={column.field}
type={column.type}
width={width}
height={rowHeight}
field={column.field}
align={column.align}
/>
);
}
const editCellState = editRowsState[rowId]?.[column.field] ?? null;
// when the cell is a reorder cell we are not allowing to reorder the col
// fixes https://github.com/mui/mui-x/issues/11126
const isReorderCell = column.field === '__reorder__';
const isEditingRows = Object.keys(editRowsState).length > 0;
const canReorderColumn = !(disableColumnReorder || column.disableReorder);
const canReorderRow = rowReordering && !sortModel.length && treeDepth <= 1 && !isEditingRows;
const disableDragEvents = !(canReorderColumn || (isReorderCell && canReorderRow));
const cellIsNotVisible = pinnedPosition === PinnedPosition.VIRTUAL;
return (
<slots.cell
key={column.field}
column={column}
width={width}
rowId={rowId}
align={column.align || 'left'}
colIndex={indexRelativeToAllColumns}
colSpan={colSpan}
disableDragEvents={disableDragEvents}
editCellState={editCellState}
isNotVisible={cellIsNotVisible}
pinnedOffset={pinnedOffset}
pinnedPosition={pinnedPosition}
sectionIndex={indexInSection}
sectionLength={sectionLength}
gridHasFiller={gridHasFiller}
{...slotProps?.cell}
/>
);
};
/* Start of rendering */
if (!rowNode) {
return null;
}
const leftCells = pinnedColumns.left.map((column, i) => {
const indexRelativeToAllColumns = i;
return getCell(
column,
i,
indexRelativeToAllColumns,
pinnedColumns.left.length,
PinnedPosition.LEFT,
);
});
const rightCells = pinnedColumns.right.map((column, i) => {
const indexRelativeToAllColumns = visibleColumns.length - pinnedColumns.right.length + i;
return getCell(
column,
i,
indexRelativeToAllColumns,
pinnedColumns.right.length,
PinnedPosition.RIGHT,
);
});
const middleColumnsLength =
visibleColumns.length - pinnedColumns.left.length - pinnedColumns.right.length;
const cells = [] as React.ReactNode[];
if (hasVirtualFocusCellLeft) {
cells.push(
getCell(
visibleColumns[focusedColumnIndex],
focusedColumnIndex - pinnedColumns.left.length,
focusedColumnIndex,
middleColumnsLength,
PinnedPosition.VIRTUAL,
),
);
}
for (let i = renderContext.firstColumnIndex; i < renderContext.lastColumnIndex; i += 1) {
const column = visibleColumns[i];
const indexInSection = i - pinnedColumns.left.length;
if (!column) {
continue;
}
cells.push(getCell(column, indexInSection, i, middleColumnsLength));
}
if (hasVirtualFocusCellRight) {
cells.push(
getCell(
visibleColumns[focusedColumnIndex],
focusedColumnIndex - pinnedColumns.left.length,
focusedColumnIndex,
middleColumnsLength,
PinnedPosition.VIRTUAL,
),
);
}
const eventHandlers = row
? {
onClick: publishClick,
onDoubleClick: publish('rowDoubleClick', onDoubleClick),
onMouseEnter: publish('rowMouseEnter', onMouseEnter),
onMouseLeave: publish('rowMouseLeave', onMouseLeave),
onMouseOut: publish('rowMouseOut', onMouseOut),
onMouseOver: publish('rowMouseOver', onMouseOver),
}
: null;
return (
<div
ref={handleRef}
data-id={rowId}
data-rowindex={index}
role="row"
className={clsx(...rowClassNames, classes.root, className)}
style={style}
{...ariaAttributes}
{...eventHandlers}
{...other}
>
{leftCells}
<div
role="presentation"
className={gridClasses.cellOffsetLeft}
style={{ width: offsetLeft }}
/>
{cells}
<div role="presentation" className={clsx(gridClasses.cell, gridClasses.cellEmpty)} />
{rightCells}
{scrollbarWidth !== 0 && <ScrollbarFiller pinnedRight={pinnedColumns.right.length > 0} />}
</div>
);
});
GridRow.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
dimensions: PropTypes.shape({
bottomContainerHeight: PropTypes.number.isRequired,
columnsTotalWidth: PropTypes.number.isRequired,
contentSize: PropTypes.shape({
height: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
}).isRequired,
groupHeaderHeight: PropTypes.number.isRequired,
hasScrollX: PropTypes.bool.isRequired,
hasScrollY: PropTypes.bool.isRequired,
headerFilterHeight: PropTypes.number.isRequired,
headerHeight: PropTypes.number.isRequired,
headersTotalHeight: PropTypes.number.isRequired,
isReady: PropTypes.bool.isRequired,
leftPinnedWidth: PropTypes.number.isRequired,
minimumSize: PropTypes.shape({
height: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
}).isRequired,
rightPinnedWidth: PropTypes.number.isRequired,
root: PropTypes.shape({
height: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
}).isRequired,
rowHeight: PropTypes.number.isRequired,
rowWidth: PropTypes.number.isRequired,
scrollbarSize: PropTypes.number.isRequired,
topContainerHeight: PropTypes.number.isRequired,
viewportInnerSize: PropTypes.shape({
height: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
}).isRequired,
viewportOuterSize: PropTypes.shape({
height: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
}).isRequired,
}).isRequired,
/**
* Determines which cell has focus.
* If `null`, no cell in this row has focus.
*/
focusedColumnIndex: PropTypes.number,
/**
* Index of the row in the whole sorted and filtered dataset.
* If some rows above have expanded children, this index also take those children into account.
*/
index: PropTypes.number.isRequired,
isFirstVisible: PropTypes.bool.isRequired,
isLastVisible: PropTypes.bool.isRequired,
isNotVisible: PropTypes.bool.isRequired,
offsetLeft: PropTypes.number.isRequired,
offsetTop: PropTypes.number,
onClick: PropTypes.func,
onDoubleClick: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
pinnedColumns: PropTypes.object.isRequired,
renderContext: PropTypes.shape({
firstColumnIndex: PropTypes.number.isRequired,
firstRowIndex: PropTypes.number.isRequired,
lastColumnIndex: PropTypes.number.isRequired,
lastRowIndex: PropTypes.number.isRequired,
}).isRequired,
row: PropTypes.object.isRequired,
rowHeight: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number]).isRequired,
rowId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
selected: PropTypes.bool.isRequired,
showBottomBorder: PropTypes.bool.isRequired,
/**
* Determines which cell should be tabbable by having tabIndex=0.
* If `null`, no cell in this row is in the tab sequence.
*/
tabbableCell: PropTypes.string,
visibleColumns: PropTypes.arrayOf(PropTypes.object).isRequired,
} as any;
const MemoizedGridRow = fastMemo(GridRow);
export { MemoizedGridRow as GridRow };