-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathTreeDataGrid.tsx
More file actions
487 lines (434 loc) · 14.6 KB
/
TreeDataGrid.tsx
File metadata and controls
487 lines (434 loc) · 14.6 KB
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
import { useCallback, useMemo } from 'react';
import type { Key } from 'react';
import { useLatestFunc } from './hooks';
import { assertIsValidKeyGetter, classnames, getLeftRightKey } from './utils';
import type {
CellClipboardEvent,
CellCopyArgs,
CellKeyboardEvent,
CellKeyDownArgs,
CellPasteArgs,
Column,
GroupRow,
Maybe,
Omit,
RenderRowProps,
RenderSummaryRowProps,
RowHeightArgs,
RowsChangeData
} from './types';
import { renderToggleGroup } from './cellRenderers';
import { SELECT_COLUMN_KEY } from './Columns';
import { DataGrid } from './DataGrid';
import type { DataGridProps } from './DataGrid';
import { useDefaultRenderers } from './DataGridDefaultRenderersContext';
import GroupedRow from './GroupRow';
import { defaultRenderRow } from './Row';
import { rowFocusable, rowActiveClassname } from './style/row';
import SummaryRowComponent from './SummaryRow';
export interface TreeDataGridProps<R, SR = unknown, K extends Key = Key> extends Omit<
DataGridProps<R, SR, K>,
'columns' | 'role' | 'aria-rowcount' | 'rowHeight' | 'onFill' | 'isRowSelectionDisabled'
> {
columns: readonly Column<NoInfer<R>, NoInfer<SR>>[];
rowHeight?: Maybe<number | ((args: RowHeightArgs<NoInfer<R>>) => number)>;
groupBy: readonly string[];
rowGrouper: (
rows: readonly NoInfer<R>[],
columnKey: string
) => Record<string, readonly NoInfer<R>[]>;
expandedGroupIds: ReadonlySet<unknown>;
onExpandedGroupIdsChange: (expandedGroupIds: Set<unknown>) => void;
groupIdGetter?: Maybe<(groupKey: string, parentId?: string) => string>;
}
type GroupByDictionary<TRow> = Record<
string,
{
readonly childRows: readonly TRow[];
readonly childGroups: readonly TRow[] | Readonly<GroupByDictionary<TRow>>;
readonly startRowIndex: number;
}
>;
export function TreeDataGrid<R, SR = unknown, K extends Key = Key>({
columns: rawColumns,
rows: rawRows,
rowHeight: rawRowHeight,
rowKeyGetter: rawRowKeyGetter,
onCellKeyDown: rawOnCellKeyDown,
onCellCopy: rawOnCellCopy,
onCellPaste: rawOnCellPaste,
onRowsChange,
selectedRows: rawSelectedRows,
onSelectedRowsChange: rawOnSelectedRowsChange,
renderers,
groupBy: rawGroupBy,
rowGrouper,
expandedGroupIds,
onExpandedGroupIdsChange,
groupIdGetter: rawGroupIdGetter,
...props
}: TreeDataGridProps<R, SR, K>) {
const defaultRenderers = useDefaultRenderers<R, SR>();
const rawRenderRow = renderers?.renderRow ?? defaultRenderers?.renderRow ?? defaultRenderRow;
const headerAndTopSummaryRowsCount = 1 + (props.topSummaryRows?.length ?? 0);
const { leftKey, rightKey } = getLeftRightKey(props.direction);
const toggleGroupLatest = useLatestFunc(toggleGroup);
const groupIdGetter = rawGroupIdGetter ?? defaultGroupIdGetter;
const { columns, groupBy } = useMemo(() => {
const columns = rawColumns.toSorted(({ key: aKey }, { key: bKey }) => {
// Sort select column first:
if (aKey === SELECT_COLUMN_KEY) return -1;
if (bKey === SELECT_COLUMN_KEY) return 1;
// Sort grouped columns second, following the groupBy order:
if (rawGroupBy.includes(aKey)) {
if (rawGroupBy.includes(bKey)) {
return rawGroupBy.indexOf(aKey) - rawGroupBy.indexOf(bKey);
}
return -1;
}
if (rawGroupBy.includes(bKey)) return 1;
// Sort other columns last:
return 0;
});
const groupBy: string[] = [];
for (const [index, column] of columns.entries()) {
if (rawGroupBy.includes(column.key)) {
groupBy.push(column.key);
columns[index] = {
...column,
frozen: true,
renderCell: () => null,
renderGroupCell: column.renderGroupCell ?? renderToggleGroup,
editable: false
};
}
}
return { columns, groupBy };
}, [rawColumns, rawGroupBy]);
const [groupedRows, rowsCount] = useMemo(() => {
if (groupBy.length === 0) return [undefined, rawRows.length];
const groupRows = (
rows: readonly R[],
[groupByKey, ...remainingGroupByKeys]: readonly string[],
startRowIndex: number
): [Readonly<GroupByDictionary<R>>, number] => {
let groupRowsCount = 0;
const groups: GroupByDictionary<R> = {};
for (const [key, childRows] of Object.entries(rowGrouper(rows, groupByKey))) {
// Recursively group each parent group
const [childGroups, childRowsCount] =
remainingGroupByKeys.length === 0
? [childRows, childRows.length]
: groupRows(childRows, remainingGroupByKeys, startRowIndex + groupRowsCount + 1); // 1 for parent row
groups[key] = { childRows, childGroups, startRowIndex: startRowIndex + groupRowsCount };
groupRowsCount += childRowsCount + 1; // 1 for parent row
}
return [groups, groupRowsCount];
};
return groupRows(rawRows, groupBy, 0);
}, [groupBy, rowGrouper, rawRows]);
const [rows, isGroupRow] = useMemo((): [
readonly (R | GroupRow<R>)[],
(row: R | GroupRow<R>) => row is GroupRow<R>
] => {
const allGroupRows = new Set<unknown>();
if (!groupedRows) return [rawRows, isGroupRow];
const flattenedRows: (R | GroupRow<R>)[] = [];
const expandGroup = (
rows: GroupByDictionary<R> | readonly R[],
parentId: string | undefined,
level: number
): void => {
if (isReadonlyArray(rows)) {
flattenedRows.push(...rows);
return;
}
Object.keys(rows).forEach((groupKey, posInSet, keys) => {
const id = groupIdGetter(groupKey, parentId);
const isExpanded = expandedGroupIds.has(id);
const { childRows, childGroups, startRowIndex } = rows[groupKey];
const groupRow: GroupRow<R> = {
id,
parentId,
groupKey,
isExpanded,
childRows,
level,
posInSet,
startRowIndex,
setSize: keys.length
};
flattenedRows.push(groupRow);
allGroupRows.add(groupRow);
if (isExpanded) {
expandGroup(childGroups, id, level + 1);
}
});
};
expandGroup(groupedRows, undefined, 0);
return [flattenedRows, isGroupRow];
function isGroupRow(row: R | GroupRow<R>): row is GroupRow<R> {
return allGroupRows.has(row);
}
}, [expandedGroupIds, groupedRows, rawRows, groupIdGetter]);
const rowHeight = useMemo(() => {
if (typeof rawRowHeight === 'function') {
return (row: R | GroupRow<R>): number => {
if (isGroupRow(row)) {
return rawRowHeight({ type: 'GROUP', row });
}
return rawRowHeight({ type: 'ROW', row });
};
}
return rawRowHeight;
}, [isGroupRow, rawRowHeight]);
const getParentRowAndIndex = useCallback(
(row: R | GroupRow<R>) => {
const rowIdx = rows.indexOf(row);
for (let i = rowIdx - 1; i >= 0; i--) {
const parentRow = rows[i];
if (isGroupRow(parentRow) && (!isGroupRow(row) || row.parentId === parentRow.id)) {
return [parentRow, i] as const;
}
}
return undefined;
},
[isGroupRow, rows]
);
const rowKeyGetter = useCallback(
(row: R | GroupRow<R>) => {
if (isGroupRow(row)) {
return row.id;
}
if (typeof rawRowKeyGetter === 'function') {
return rawRowKeyGetter(row);
}
const parentRowAndIndex = getParentRowAndIndex(row);
if (parentRowAndIndex !== undefined) {
const { startRowIndex, childRows } = parentRowAndIndex[0];
const groupIndex = childRows.indexOf(row);
return startRowIndex + groupIndex + 1;
}
return rows.indexOf(row);
},
[getParentRowAndIndex, isGroupRow, rawRowKeyGetter, rows]
);
const selectedRows = useMemo((): Maybe<ReadonlySet<Key>> => {
if (rawSelectedRows == null) return null;
assertIsValidKeyGetter<R, K>(rawRowKeyGetter);
const selectedRows = new Set<Key>(rawSelectedRows);
for (const row of rows) {
if (isGroupRow(row)) {
// select parent row if all the children are selected
const isGroupRowSelected = row.childRows.every((cr) =>
rawSelectedRows.has(rawRowKeyGetter(cr))
);
if (isGroupRowSelected) {
selectedRows.add(row.id);
}
}
}
return selectedRows;
}, [isGroupRow, rawRowKeyGetter, rawSelectedRows, rows]);
function onSelectedRowsChange(newSelectedRows: Set<Key>) {
if (!rawOnSelectedRowsChange) return;
assertIsValidKeyGetter<R, K>(rawRowKeyGetter);
const newRawSelectedRows = new Set(rawSelectedRows);
for (const row of rows) {
const key = rowKeyGetter(row);
if (selectedRows?.has(key) && !newSelectedRows.has(key)) {
if (isGroupRow(row)) {
// select all children if the parent row is selected
for (const cr of row.childRows) {
newRawSelectedRows.delete(rawRowKeyGetter(cr));
}
} else {
newRawSelectedRows.delete(key as K);
}
} else if (!selectedRows?.has(key) && newSelectedRows.has(key)) {
if (isGroupRow(row)) {
// unselect all children if the parent row is unselected
for (const cr of row.childRows) {
newRawSelectedRows.add(rawRowKeyGetter(cr));
}
} else {
newRawSelectedRows.add(key as K);
}
}
}
rawOnSelectedRowsChange(newRawSelectedRows);
}
function handleKeyDown(args: CellKeyDownArgs<R, SR>, event: CellKeyboardEvent) {
rawOnCellKeyDown?.(args, event);
if (event.isGridDefaultPrevented()) return;
if (args.mode === 'EDIT') return;
const { column, rowIdx, setActivePosition } = args;
const idx = column?.idx ?? -1;
const row = rows[rowIdx];
if (!isGroupRow(row)) return;
if (
idx === -1 &&
// Collapse the current group row if it is focused and is in expanded state
((event.key === leftKey && row.isExpanded) ||
// Expand the current group row if it is focused and is in collapsed state
(event.key === rightKey && !row.isExpanded))
) {
// prevent scrolling
event.preventDefault();
event.preventGridDefault();
toggleGroup(row.id);
}
// If a group row is focused, and it is collapsed, move to the parent group row (if there is one).
if (idx === -1 && event.key === leftKey && !row.isExpanded && row.level !== 0) {
const parentRowAndIndex = getParentRowAndIndex(row);
if (parentRowAndIndex !== undefined) {
event.preventGridDefault();
setActivePosition({ idx, rowIdx: parentRowAndIndex[1] });
}
}
}
// Prevent copy/paste on group rows
function handleCellCopy(
{ row, column }: CellCopyArgs<NoInfer<R>, NoInfer<SR>>,
event: CellClipboardEvent
) {
if (!isGroupRow(row)) {
rawOnCellCopy?.({ row, column }, event);
}
}
function handleCellPaste(
{ row, column }: CellPasteArgs<NoInfer<R>, NoInfer<SR>>,
event: CellClipboardEvent
) {
return isGroupRow(row) ? row : rawOnCellPaste!({ row, column }, event);
}
function handleRowsChange(updatedRows: R[], { indexes, column }: RowsChangeData<R, SR>) {
if (!onRowsChange) return;
const updatedRawRows = [...rawRows];
const rawIndexes: number[] = [];
for (const index of indexes) {
const rawIndex = rawRows.indexOf(rows[index] as R);
updatedRawRows[rawIndex] = updatedRows[index];
rawIndexes.push(rawIndex);
}
onRowsChange(updatedRawRows, {
indexes: rawIndexes,
column
});
}
function toggleGroup(groupId: unknown) {
const newExpandedGroupIds = new Set(expandedGroupIds);
if (newExpandedGroupIds.has(groupId)) {
newExpandedGroupIds.delete(groupId);
} else {
newExpandedGroupIds.add(groupId);
}
onExpandedGroupIdsChange(newExpandedGroupIds);
}
function renderRow(
key: Key,
{
row,
rowClass,
onCellMouseDown,
onCellClick,
onCellDoubleClick,
onCellContextMenu,
onRowChange,
draggedOverCellIdx,
activeCellEditor,
className,
isRowSelectionDisabled,
...rowProps
}: RenderRowProps<R, SR>
) {
const isPositionOnRow = rowProps.activeCellIdx === -1;
const tabIndex = isPositionOnRow ? 0 : -1;
className = classnames(className, rowFocusable, isPositionOnRow && rowActiveClassname);
if (isGroupRow(row)) {
const { startRowIndex } = row;
return (
<GroupedRow
key={key}
{...rowProps}
aria-rowindex={headerAndTopSummaryRowsCount + startRowIndex + 1}
className={className}
tabIndex={tabIndex}
row={row}
groupBy={groupBy}
toggleGroup={toggleGroupLatest}
/>
);
}
let ariaRowIndex = rowProps['aria-rowindex'];
const parentRowAndIndex = getParentRowAndIndex(row);
if (parentRowAndIndex !== undefined) {
const { startRowIndex, childRows } = parentRowAndIndex[0];
const groupIndex = childRows.indexOf(row);
ariaRowIndex = startRowIndex + headerAndTopSummaryRowsCount + groupIndex + 2;
}
return rawRenderRow(key, {
...rowProps,
'aria-rowindex': ariaRowIndex,
row,
rowClass,
className,
tabIndex,
onCellMouseDown,
onCellClick,
onCellDoubleClick,
onCellContextMenu,
onRowChange,
draggedOverCellIdx,
activeCellEditor,
isRowSelectionDisabled
});
}
return (
<DataGrid<R, SR>
{...props}
role="treegrid"
aria-rowcount={
rowsCount + 1 + (props.topSummaryRows?.length ?? 0) + (props.bottomSummaryRows?.length ?? 0)
}
columns={columns}
rows={rows as R[]} // TODO: check types
rowHeight={rowHeight}
rowKeyGetter={rowKeyGetter}
onRowsChange={handleRowsChange}
selectedRows={selectedRows}
onSelectedRowsChange={onSelectedRowsChange}
onCellKeyDown={handleKeyDown}
onCellCopy={handleCellCopy}
onCellPaste={rawOnCellPaste ? handleCellPaste : undefined}
renderers={{
...renderers,
renderRow,
renderSummaryRow
}}
/>
);
}
function defaultGroupIdGetter(groupKey: string, parentId: string | undefined) {
return parentId !== undefined ? `${parentId}__${groupKey}` : groupKey;
}
function renderSummaryRow<R, SR>(
key: React.Key,
{ activeCellIdx, className, ...props }: RenderSummaryRowProps<R, SR>
) {
const isPositionOnRow = activeCellIdx === -1;
const tabIndex = isPositionOnRow ? 0 : -1;
className = classnames(className, rowFocusable, isPositionOnRow && rowActiveClassname);
return (
<SummaryRowComponent
key={key}
tabIndex={tabIndex}
activeCellIdx={activeCellIdx}
className={className}
{...props}
/>
);
}
function isReadonlyArray(arr: unknown): arr is readonly unknown[] {
return Array.isArray(arr);
}