-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathRowSelection.ts
668 lines (588 loc) · 21.9 KB
/
RowSelection.ts
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
import {
OnChangeFn,
Table,
Row,
RowModel,
Updater,
RowData,
TableFeature,
} from '../types'
import { getMemoOptions, makeStateUpdater, memo } from '../utils'
export type RowSelectionState = Record<string, boolean>
export interface RowSelectionTableState {
rowSelection: RowSelectionState
}
export interface RowSelectionOptions<TData extends RowData> {
/**
* - Enables/disables multiple row selection for all rows in the table OR
* - A function that given a row, returns whether to enable/disable multiple row selection for that row's children/grandchildren
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#enablemultirowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
enableMultiRowSelection?: boolean | ((row: Row<TData>) => boolean)
/**
* - Enables/disables row selection for all rows in the table OR
* - A function that given a row, returns whether to enable/disable row selection for that row
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#enablerowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
enableRowSelection?: boolean | ((row: Row<TData>) => boolean)
/**
* Enables/disables automatic sub-row selection when a parent row is selected, or a function that enables/disables automatic sub-row selection for each row.
* (Use in combination with expanding or grouping features)
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#enablesubrowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
enableSubRowSelection?: boolean | ((row: Row<TData>) => boolean)
/**
* If provided, this function will be called with an `updaterFn` when `state.rowSelection` changes. This overrides the default internal state management, so you will need to persist the state change either fully or partially outside of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#onrowselectionchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
onRowSelectionChange?: OnChangeFn<RowSelectionState>
// enableGroupingRowSelection?:
// | boolean
// | ((
// row: Row<TData>
// ) => boolean)
// isAdditiveSelectEvent?: (e: unknown) => boolean
// isInclusiveSelectEvent?: (e: unknown) => boolean
// selectRowsFn?: (
// table: Table<TData>,
// rowModel: RowModel<TData>
// ) => RowModel<TData>
}
export interface RowSelectionRow {
/**
* Returns whether or not the row can multi-select.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getcanmultiselect)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getCanMultiSelect: () => boolean
/**
* Returns whether or not the row can be selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getcanselect)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getCanSelect: () => boolean
/**
* Returns whether or not the row can select sub rows automatically when the parent row is selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getcanselectsubrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getCanSelectSubRows: () => boolean
/**
* Returns whether or not all of the row's sub rows are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisallsubrowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsAllSubRowsSelected: () => boolean
/**
* Returns whether or not the row is selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSelected: () => boolean
/**
* Returns whether or not some of the row's sub rows are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getissomeselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSomeSelected: () => boolean
/**
* Returns a handler that can be used to toggle the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#gettoggleselectedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getToggleSelectedHandler: () => (event: unknown) => void
/**
* Selects/deselects the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#toggleselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
toggleSelected: (value?: boolean, opts?: { selectChildren?: boolean }) => void
}
export interface RowSelectionInstance<TData extends RowData> {
/**
* Returns the row model of all rows that are selected after filtering has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getfilteredselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getFilteredSelectedRowModel: () => RowModel<TData>
/**
* Returns the row model of all rows that are selected after grouping has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getgroupedselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getGroupedSelectedRowModel: () => RowModel<TData>
/**
* Returns whether or not all rows on the current page are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisallpagerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsAllPageRowsSelected: () => boolean
/**
* Returns whether or not all rows in the table are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisallrowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsAllRowsSelected: () => boolean
/**
* Returns whether or not any rows on the current page are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getissomepagerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSomePageRowsSelected: () => boolean
/**
* Returns whether or not any rows in the table are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getissomerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSomeRowsSelected: () => boolean
/**
* Returns the core row model of all rows before row selection has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getpreselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getPreSelectedRowModel: () => RowModel<TData>
/**
* Returns the row model of all rows that are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getSelectedRowModel: () => RowModel<TData>
/**
* Returns a handler that can be used to toggle all rows on the current page.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#gettoggleallpagerowsselectedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getToggleAllPageRowsSelectedHandler: () => (event: unknown) => void
/**
* Returns a handler that can be used to toggle all rows in the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#gettoggleallrowsselectedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getToggleAllRowsSelectedHandler: () => (event: unknown) => void
/**
* Resets the **rowSelection** state to the `initialState.rowSelection`, or `true` can be passed to force a default blank state reset to `{}`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#resetrowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
resetRowSelection: (defaultState?: boolean) => void
/**
* Sets or updates the `state.rowSelection` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#setrowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
setRowSelection: (updater: Updater<RowSelectionState>) => void
/**
* Selects/deselects all rows on the current page.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#toggleallpagerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
toggleAllPageRowsSelected: (value?: boolean) => void
/**
* Selects/deselects all rows in the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#toggleallrowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
toggleAllRowsSelected: (value?: boolean) => void
}
//
export const RowSelection: TableFeature = {
getInitialState: (state): RowSelectionTableState => {
return {
rowSelection: {},
...state,
}
},
getDefaultOptions: <TData extends RowData>(
table: Table<TData>
): RowSelectionOptions<TData> => {
return {
onRowSelectionChange: makeStateUpdater('rowSelection', table),
enableRowSelection: true,
enableMultiRowSelection: true,
enableSubRowSelection: true,
// enableGroupingRowSelection: false,
// isAdditiveSelectEvent: (e: unknown) => !!e.metaKey,
// isInclusiveSelectEvent: (e: unknown) => !!e.shiftKey,
}
},
createTable: <TData extends RowData>(table: Table<TData>): void => {
table.setRowSelection = updater =>
table.options.onRowSelectionChange?.(updater)
table.resetRowSelection = defaultState =>
table.setRowSelection(
defaultState ? {} : table.initialState.rowSelection ?? {}
)
table.toggleAllRowsSelected = value => {
table.setRowSelection(old => {
value =
typeof value !== 'undefined' ? value : !table.getIsAllRowsSelected()
const rowSelection = { ...old }
const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows
// We don't use `mutateRowIsSelected` here for performance reasons.
// All of the rows are flat already, so it wouldn't be worth it
if (value) {
preGroupedFlatRows.forEach(row => {
if (!row.getCanSelect()) {
return
}
rowSelection[row.id] = true
})
} else {
preGroupedFlatRows.forEach(row => {
delete rowSelection[row.id]
})
}
return rowSelection
})
}
table.toggleAllPageRowsSelected = value =>
table.setRowSelection(old => {
const resolvedValue =
typeof value !== 'undefined'
? value
: !table.getIsAllPageRowsSelected()
const rowSelection: RowSelectionState = { ...old }
table.getRowModel().rows.forEach(row => {
mutateRowIsSelected(rowSelection, row.id, resolvedValue, true, table)
})
return rowSelection
})
// addRowSelectionRange: rowId => {
// const {
// rows,
// rowsById,
// options: { selectGroupingRows, selectSubRows },
// } = table
// const findSelectedRow = (rows: Row[]) => {
// let found
// rows.find(d => {
// if (d.getIsSelected()) {
// found = d
// return true
// }
// const subFound = findSelectedRow(d.subRows || [])
// if (subFound) {
// found = subFound
// return true
// }
// return false
// })
// return found
// }
// const firstRow = findSelectedRow(rows) || rows[0]
// const lastRow = rowsById[rowId]
// let include = false
// const selectedRowIds = {}
// const addRow = (row: Row) => {
// mutateRowIsSelected(selectedRowIds, row.id, true, {
// rowsById,
// selectGroupingRows: selectGroupingRows!,
// selectSubRows: selectSubRows!,
// })
// }
// table.rows.forEach(row => {
// const isFirstRow = row.id === firstRow.id
// const isLastRow = row.id === lastRow.id
// if (isFirstRow || isLastRow) {
// if (!include) {
// include = true
// } else if (include) {
// addRow(row)
// include = false
// }
// }
// if (include) {
// addRow(row)
// }
// })
// table.setRowSelection(selectedRowIds)
// },
table.getPreSelectedRowModel = () => table.getCoreRowModel()
table.getSelectedRowModel = memo(
() => [table.getState().rowSelection, table.getCoreRowModel()],
(rowSelection, rowModel) => {
if (!Object.keys(rowSelection).length) {
return {
rows: [],
flatRows: [],
rowsById: {},
}
}
return selectRowsFn(table, rowModel)
},
getMemoOptions(table.options, 'debugTable', 'getSelectedRowModel')
)
table.getFilteredSelectedRowModel = memo(
() => [table.getState().rowSelection, table.getFilteredRowModel()],
(rowSelection, rowModel) => {
if (!Object.keys(rowSelection).length) {
return {
rows: [],
flatRows: [],
rowsById: {},
}
}
return selectRowsFn(table, rowModel)
},
getMemoOptions(table.options, 'debugTable', 'getFilteredSelectedRowModel')
)
table.getGroupedSelectedRowModel = memo(
() => [table.getState().rowSelection, table.getSortedRowModel()],
(rowSelection, rowModel) => {
if (!Object.keys(rowSelection).length) {
return {
rows: [],
flatRows: [],
rowsById: {},
}
}
return selectRowsFn(table, rowModel)
},
getMemoOptions(table.options, 'debugTable', 'getGroupedSelectedRowModel')
)
///
// getGroupingRowCanSelect: rowId => {
// const row = table.getRow(rowId)
// if (!row) {
// throw new Error()
// }
// if (typeof table.options.enableGroupingRowSelection === 'function') {
// return table.options.enableGroupingRowSelection(row)
// }
// return table.options.enableGroupingRowSelection ?? false
// },
table.getIsAllRowsSelected = () => {
const preGroupedFlatRows = table.getFilteredRowModel().flatRows
const { rowSelection } = table.getState()
let isAllRowsSelected = Boolean(
preGroupedFlatRows.length && Object.keys(rowSelection).length
)
if (isAllRowsSelected) {
if (
preGroupedFlatRows.some(
row => row.getCanSelect() && !rowSelection[row.id]
)
) {
isAllRowsSelected = false
}
}
return isAllRowsSelected
}
table.getIsAllPageRowsSelected = () => {
const paginationFlatRows = table
.getPaginationRowModel()
.flatRows.filter(row => row.getCanSelect())
const { rowSelection } = table.getState()
let isAllPageRowsSelected = !!paginationFlatRows.length
if (
isAllPageRowsSelected &&
paginationFlatRows.some(row => !rowSelection[row.id])
) {
isAllPageRowsSelected = false
}
return isAllPageRowsSelected
}
table.getIsSomeRowsSelected = () => {
const totalSelected = Object.keys(
table.getState().rowSelection ?? {}
).length
return (
totalSelected > 0 &&
totalSelected < table.getFilteredRowModel().flatRows.length
)
}
table.getIsSomePageRowsSelected = () => {
const paginationFlatRows = table.getPaginationRowModel().flatRows
return table.getIsAllPageRowsSelected()
? false
: paginationFlatRows
.filter(row => row.getCanSelect())
.some(d => d.getIsSelected() || d.getIsSomeSelected())
}
table.getToggleAllRowsSelectedHandler = () => {
return (e: unknown) => {
table.toggleAllRowsSelected(
((e as MouseEvent).target as HTMLInputElement).checked
)
}
}
table.getToggleAllPageRowsSelectedHandler = () => {
return (e: unknown) => {
table.toggleAllPageRowsSelected(
((e as MouseEvent).target as HTMLInputElement).checked
)
}
}
},
createRow: <TData extends RowData>(
row: Row<TData>,
table: Table<TData>
): void => {
row.toggleSelected = (value, opts) => {
const isSelected = row.getIsSelected()
table.setRowSelection(old => {
value = typeof value !== 'undefined' ? value : !isSelected
if (row.getCanSelect() && isSelected === value) {
return old
}
const selectedRowIds = { ...old }
mutateRowIsSelected(
selectedRowIds,
row.id,
value,
opts?.selectChildren ?? true,
table
)
return selectedRowIds
})
}
row.getIsSelected = () => {
const { rowSelection } = table.getState()
return isRowSelected(row, rowSelection)
}
row.getIsSomeSelected = () => {
const { rowSelection } = table.getState()
return isSubRowSelected(row, rowSelection, table) === 'some'
}
row.getIsAllSubRowsSelected = () => {
const { rowSelection } = table.getState()
return isSubRowSelected(row, rowSelection, table) === 'all'
}
row.getCanSelect = () => {
if (typeof table.options.enableRowSelection === 'function') {
return table.options.enableRowSelection(row)
}
return table.options.enableRowSelection ?? true
}
row.getCanSelectSubRows = () => {
if (typeof table.options.enableSubRowSelection === 'function') {
return table.options.enableSubRowSelection(row)
}
return table.options.enableSubRowSelection ?? true
}
row.getCanMultiSelect = () => {
if (typeof table.options.enableMultiRowSelection === 'function') {
return table.options.enableMultiRowSelection(row)
}
return table.options.enableMultiRowSelection ?? true
}
row.getToggleSelectedHandler = () => {
const canSelect = row.getCanSelect()
return (e: unknown) => {
if (!canSelect) return
row.toggleSelected(
((e as MouseEvent).target as HTMLInputElement)?.checked
)
}
}
},
}
const mutateRowIsSelected = <TData extends RowData>(
selectedRowIds: Record<string, boolean>,
id: string,
value: boolean,
includeChildren: boolean,
table: Table<TData>
) => {
const row = table.getRow(id, true)
// const isGrouped = row.getIsGrouped()
// if ( // TODO: enforce grouping row selection rules
// !isGrouped ||
// (isGrouped && table.options.enableGroupingRowSelection)
// ) {
if (value) {
if (!row.getCanMultiSelect()) {
Object.keys(selectedRowIds).forEach(key => delete selectedRowIds[key])
}
if (row.getCanSelect()) {
selectedRowIds[id] = true
}
} else {
delete selectedRowIds[id]
}
// }
if (includeChildren && row.subRows?.length && row.getCanSelectSubRows()) {
row.subRows.forEach(row =>
mutateRowIsSelected(selectedRowIds, row.id, value, includeChildren, table)
)
}
}
export function selectRowsFn<TData extends RowData>(
table: Table<TData>,
rowModel: RowModel<TData>
): RowModel<TData> {
const rowSelection = table.getState().rowSelection
const newSelectedFlatRows: Row<TData>[] = []
const newSelectedRowsById: Record<string, Row<TData>> = {}
// Filters top level and nested rows
const recurseRows = (rows: Row<TData>[], depth = 0): Row<TData>[] => {
return rows
.map(row => {
const isSelected = isRowSelected(row, rowSelection)
if (isSelected) {
newSelectedFlatRows.push(row)
newSelectedRowsById[row.id] = row
}
if (row.subRows?.length) {
row = {
...row,
subRows: recurseRows(row.subRows, depth + 1),
}
}
if (isSelected) {
return row
}
})
.filter(Boolean) as Row<TData>[]
}
return {
rows: recurseRows(rowModel.rows),
flatRows: newSelectedFlatRows,
rowsById: newSelectedRowsById,
}
}
export function isRowSelected<TData extends RowData>(
row: Row<TData>,
selection: Record<string, boolean>
): boolean {
return selection[row.id] ?? false
}
export function isSubRowSelected<TData extends RowData>(
row: Row<TData>,
selection: Record<string, boolean>,
table: Table<TData>
): boolean | 'some' | 'all' {
if (!row.subRows?.length) return false
let allChildrenSelected = true
let someSelected = false
row.subRows.forEach(subRow => {
// Bail out early if we know both of these
if (someSelected && !allChildrenSelected) {
return
}
if (subRow.getCanSelect()) {
if (isRowSelected(subRow, selection)) {
someSelected = true
} else {
allChildrenSelected = false
}
}
// Check row selection of nested subrows
if (subRow.subRows && subRow.subRows.length) {
const subRowChildrenSelected = isSubRowSelected(subRow, selection, table)
if (subRowChildrenSelected === 'all') {
someSelected = true
} else if (subRowChildrenSelected === 'some') {
someSelected = true
allChildrenSelected = false
} else {
allChildrenSelected = false
}
}
})
return allChildrenSelected ? 'all' : someSelected ? 'some' : false
}