-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathReactable.js
More file actions
2326 lines (2156 loc) · 72.7 KB
/
Reactable.js
File metadata and controls
2326 lines (2156 loc) · 72.7 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
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { Fragment } from 'react'
import {
safeUseLayoutEffect,
useExpanded,
useFilters,
useGetLatest,
useGlobalFilter,
useMountedLayoutEffect,
useSortBy,
useTable
} from 'react-table'
import PropTypes from 'prop-types'
import { hydrate } from 'reactR'
import Pagination from './Pagination'
import WidgetContainer from './WidgetContainer'
import useFlexLayout from './useFlexLayout'
import useStickyColumns from './useStickyColumns'
import useGroupBy from './useGroupBy'
import useResizeColumns from './useResizeColumns'
import useRowSelect from './useRowSelect'
import usePagination from './usePagination'
import useMeta from './useMeta'
import {
buildColumnDefs,
emptyValue,
getSubRows,
materializedRowsToData,
normalizeColumnData,
rowExpandedKey,
rowSelectedKey,
rowStateKey,
RawHTML
} from './columns'
import { defaultLanguage, renderTemplate } from './language'
import { createTheme, css } from './theme'
import {
classNames,
convertRowsToV6,
getLeafColumns,
rowsToCSV,
downloadCSV,
useAsyncDebounce
} from './utils'
import './react-table.css'
import './reactable.css'
const tableInstances = {}
export function getInstance(tableId) {
if (!tableId) {
throw new Error('A reactable table ID must be provided')
}
const getInstance = tableInstances[tableId]
if (!getInstance) {
throw new Error(`reactable instance '${tableId}' not found`)
}
return getInstance()
}
export function getState(tableId) {
return getInstance(tableId).state
}
export function setFilter(tableId, columnId, value) {
getInstance(tableId).setFilter(columnId, value)
}
export function setAllFilters(tableId, value) {
getInstance(tableId).setAllFilters(value)
}
export function setSearch(tableId, value) {
getInstance(tableId).setGlobalFilter(value)
}
export function toggleGroupBy(tableId, columnId, isGrouped) {
getInstance(tableId).toggleGroupBy(columnId, isGrouped)
}
export function setGroupBy(tableId, columnIds) {
getInstance(tableId).setGroupBy(columnIds)
}
export function toggleAllRowsExpanded(tableId, isExpanded) {
getInstance(tableId).toggleAllRowsExpanded(isExpanded)
}
export function downloadDataCSV(tableId, filename = 'data.csv', options = {}) {
getInstance(tableId).downloadDataCSV(filename, options)
}
export function getDataCSV(tableId, options = {}) {
return getInstance(tableId).getDataCSV(options)
}
export function setMeta(tableId, meta) {
getInstance(tableId).setMeta(meta)
}
export function toggleHideColumn(tableId, columnId, isHidden) {
getInstance(tableId).toggleHideColumn(columnId, isHidden)
}
export function setHiddenColumns(tableId, columns) {
getInstance(tableId).setHiddenColumns(columns)
}
export function setData(tableId, data, options) {
getInstance(tableId).setData(data, options)
}
export function onStateChange(tableId, listenerFn) {
return getInstance(tableId).onStateChange(listenerFn)
}
export function gotoPage(tableId, pageIndex) {
getInstance(tableId).gotoPage(pageIndex)
}
export function setPageSize(tableId, pageSize) {
getInstance(tableId).setPageSize(pageSize)
}
export default function Reactable({
data,
columns,
columnGroups,
sortable,
defaultSortDesc,
showSortIcon,
showSortable,
filterable,
resizable,
theme,
language,
dataKey,
...rest
}) {
data = normalizeColumnData(data, columns)
columns = buildColumnDefs(columns, columnGroups, {
sortable,
defaultSortDesc,
showSortIcon,
showSortable,
filterable,
resizable
})
theme = createTheme(theme) || {}
language = { ...defaultLanguage, ...language }
for (let key in language) {
language[key] = language[key] || null
}
return (
<Table
data={data}
columns={columns}
theme={theme}
language={language}
// Reset all state when the data changes. By default, most of the table state
// persists when the data changes (sorted, filtered, grouped state, etc.).
key={dataKey}
{...rest}
/>
)
}
// Objects and arrays must be memoized to prevent unnecessary recalculations of data
function useMemoizedObject(obj) {
const objStr = JSON.stringify(obj)
return React.useMemo(() => {
return obj
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [objStr])
}
export function ReactableData({
data,
columns,
columnGroups,
sortable,
defaultSortDesc,
showSortIcon,
showSortable,
filterable,
resizable,
// Controlled state
sortBy,
filters,
searchValue,
groupBy,
expanded,
selectedRowIds,
...rest
}) {
data = React.useMemo(
() => normalizeColumnData(data, columns),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
columns = React.useMemo(
() =>
buildColumnDefs(columns, columnGroups, {
sortable,
defaultSortDesc,
showSortIcon,
showSortable,
filterable,
resizable
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
// Objects and arrays must be memoized to prevent unnecessary recalculations of data
sortBy = useMemoizedObject(sortBy || [])
filters = useMemoizedObject(filters || [])
groupBy = useMemoizedObject(groupBy || [])
expanded = useMemoizedObject(expanded || {})
selectedRowIds = useMemoizedObject(selectedRowIds || {})
return (
<TableData
data={data}
columns={columns}
sortBy={sortBy}
filters={filters}
searchValue={searchValue}
groupBy={groupBy}
expanded={expanded}
selectedRowIds={selectedRowIds}
{...rest}
/>
)
}
const RootComponent = React.forwardRef(function RootComponent({ className, ...rest }, ref) {
// Keep ReactTable class for legacy compatibility (deprecated in v0.3.0)
return <div ref={ref} className={classNames('Reactable', 'ReactTable', className)} {...rest} />
})
const TableComponent = React.forwardRef(function TableComponent({ className, ...rest }, ref) {
return <div ref={ref} className={classNames('rt-table', className)} role="table" {...rest} />
})
function TheadComponent({ className, ...rest }) {
return <div className={classNames('rt-thead', className)} role="rowgroup" {...rest} />
}
function TbodyComponent({ className, ...rest }) {
return <div className={classNames('rt-tbody', className)} role="rowgroup" {...rest} />
}
function TfootComponent({ className, ...rest }) {
return <div className={classNames('rt-tfoot', className)} role="rowgroup" {...rest} />
}
function TrGroupComponent({ className, ...rest }) {
return <div className={classNames('rt-tr-group', className)} {...rest} />
}
function TrComponent({ className, ...rest }) {
return <div className={classNames('rt-tr', className)} role="row" {...rest} />
}
const ThComponent = React.forwardRef(function ThComponent(props, ref) {
let {
canSort,
sortDescFirst,
isSorted,
isSortedDesc,
toggleSortBy,
canResize,
isResizing,
className,
innerClassName,
children,
...thProps
} = props
const [skipNextSort, setSkipNextSort] = React.useState(false)
if (canSort) {
const currentSortOrder = isSorted ? (isSortedDesc ? 'descending' : 'ascending') : 'none'
const defaultSortOrder = sortDescFirst ? 'descending' : 'ascending'
const toggleSort = isMultiSort => {
let sortDesc = isSorted ? !isSortedDesc : sortDescFirst
// Allow sort clearing if multi-sorting
if (isMultiSort) {
sortDesc = null
}
toggleSortBy && toggleSortBy(sortDesc, isMultiSort)
}
thProps = {
...thProps,
'aria-sort': currentSortOrder,
tabIndex: '0',
onClick: e => {
if (!skipNextSort) {
toggleSort(e.shiftKey)
}
},
onKeyPress: e => {
const keyCode = e.which || e.keyCode
if (keyCode === 13 || keyCode === 32) {
toggleSort(e.shiftKey)
}
},
onMouseUp: () => {
// Prevent resizer clicks from toggling sort (since resizer is in the header)
if (isResizing) {
setSkipNextSort(true)
} else {
setSkipNextSort(false)
}
},
onMouseDown: e => {
// Prevent text selection on double clicks, only when sorting
if (e.detail > 1 || e.shiftKey) {
e.preventDefault()
}
},
// Focus indicator for keyboard navigation
'data-sort-hint': isSorted ? null : defaultSortOrder
}
}
// The inner wrapper is a block container that prevents the outer flex container from
// breaking text overflow and ellipsis truncation. Text nodes can't shrink below their
// minimum content size.
return (
<div
className={classNames('rt-th', canResize && 'rt-th-resizable', className)}
role="columnheader"
ref={ref}
{...thProps}
>
<div className={classNames('rt-th-inner', innerClassName)}>{children}</div>
</div>
)
})
ThComponent.propTypes = {
defaultSortOrder: PropTypes.string,
canSort: PropTypes.bool,
sortDescFirst: PropTypes.bool,
isSorted: PropTypes.bool,
isSortedDesc: PropTypes.bool,
toggleSortBy: PropTypes.func,
canResize: PropTypes.bool,
isResizing: PropTypes.bool,
className: PropTypes.string,
innerClassName: PropTypes.string,
children: PropTypes.node
}
function TdComponent({ className, innerClassName, children, ...rest }) {
// The inner wrapper is a block container that prevents the outer flex container from
// breaking text overflow and ellipsis truncation. Text nodes can't shrink below their
// minimum content size.
return (
<div className={classNames('rt-td', className)} role="cell" {...rest}>
<div className={classNames('rt-td-inner', innerClassName)}>{children}</div>
</div>
)
}
// Get class names for a cell theme. Padding is set on the inner wrapper to prevent
// the inner wrapper (with overflow hidden) from clipping borders, box shadows, etc.
function getCellTheme(style) {
if (!style) {
return {}
}
if (style.padding != null) {
const { padding, ...cellStyle } = style
return {
className: css(cellStyle),
innerClassName: css({ padding })
}
}
return { className: css(style) }
}
function ResizerComponent({ onMouseDown, onTouchStart, className, ...rest }) {
return (
<div
className={classNames('rt-resizer', className)}
onMouseDown={onMouseDown}
onTouchStart={onTouchStart}
aria-hidden={true}
{...rest}
/>
)
}
ResizerComponent.propTypes = {
onMouseDown: PropTypes.func,
onTouchStart: PropTypes.func,
className: PropTypes.string
}
class RowDetails extends React.Component {
componentDidMount() {
if (window.Shiny && window.Shiny.bindAll) {
window.Shiny.bindAll(this.el)
}
}
componentWillUnmount() {
if (window.Shiny && window.Shiny.unbindAll) {
window.Shiny.unbindAll(this.el)
}
}
render() {
const { children, html } = this.props
let props = { ref: el => (this.el = el) }
if (html) {
props = { ...props, dangerouslySetInnerHTML: { __html: html } }
} else {
props = { ...props, children }
}
return <div className="rt-tr-details" {...props} />
}
}
RowDetails.propTypes = {
children: PropTypes.node,
html: PropTypes.string
}
function ExpanderComponent({ isExpanded, className, 'aria-label': ariaLabel }) {
return (
<button
className="rt-expander-button"
aria-label={ariaLabel}
aria-expanded={isExpanded ? 'true' : 'false'}
>
<span
className={classNames('rt-expander', isExpanded && 'rt-expander-open', className)}
tabIndex="-1"
aria-hidden="true"
>
​
</span>
</button>
)
}
ExpanderComponent.propTypes = {
isExpanded: PropTypes.bool,
className: PropTypes.string,
'aria-label': PropTypes.string
}
function FilterComponent({
filterValue,
setFilter,
className,
placeholder,
'aria-label': ariaLabel
}) {
return (
<input
type="text"
className={classNames('rt-filter', className)}
value={filterValue || ''}
// Filter value must be undefined (not empty string) to clear the filter
onChange={e => setFilter(e.target.value || undefined)}
placeholder={placeholder}
aria-label={ariaLabel}
/>
)
}
FilterComponent.propTypes = {
filterValue: PropTypes.string,
setFilter: PropTypes.func.isRequired,
className: PropTypes.string,
placeholder: PropTypes.string,
'aria-label': PropTypes.string
}
function SearchComponent({
searchValue,
setSearch,
className,
placeholder,
'aria-label': ariaLabel
}) {
return (
<input
type="text"
value={searchValue || ''}
// Search value must be undefined (not empty string) to clear the search
onChange={e => setSearch(e.target.value || undefined)}
className={classNames('rt-search', className)}
placeholder={placeholder}
aria-label={ariaLabel}
/>
)
}
SearchComponent.propTypes = {
searchValue: PropTypes.string,
setSearch: PropTypes.func.isRequired,
className: PropTypes.string,
placeholder: PropTypes.string,
'aria-label': PropTypes.string
}
function NoDataComponent({ className, ...rest }) {
return <div className={classNames('rt-no-data', className)} aria-live="assertive" {...rest} />
}
function SelectInputComponent({ type, checked, onChange, 'aria-label': ariaLabel }) {
// Use zero-width space character to properly align checkboxes with first
// line of text in other cells, even if the text spans multiple lines.
return (
<div className="rt-select">
<input
type={type}
checked={checked}
onChange={onChange}
className="rt-select-input"
aria-label={ariaLabel}
/>
​
</div>
)
}
SelectInputComponent.propTypes = {
type: PropTypes.oneOf(['checkbox', 'radio']).isRequired,
checked: PropTypes.bool,
onChange: PropTypes.func,
'aria-label': PropTypes.string
}
function TableData({
data,
columns,
groupBy,
searchMethod,
pagination,
paginateSubRows,
selection,
crosstalkGroup,
crosstalkId,
setResolvedData,
// Controlled state
pageSize,
pageIndex,
sortBy,
filters,
searchValue,
expanded,
selectedRowIds
}) {
const dataColumns = React.useMemo(
() => columns.reduce((cols, col) => cols.concat(getLeafColumns(col)), []),
[columns]
)
// Must be memoized to prevent re-filtering on every render
const globalFilter = React.useMemo(() => {
if (searchMethod) {
return searchMethod
}
return function globalFilter(rows, columnIds, searchValue) {
const matchers = dataColumns.reduce((obj, col) => {
obj[col.id] = col.createMatcher(searchValue)
return obj
}, {})
rows = rows.filter(row => {
for (const id of columnIds) {
const value = row.values[id]
if (matchers[id](value)) {
return true
}
}
})
return rows
}
}, [dataColumns, searchMethod])
const useRowSelectColumn = function useRowSelectColumn(hooks) {
if (selection) {
hooks.visibleColumns.push(columns => {
const selectionCol = {
// Apply defaults from existing selection column
...columns.find(col => col.selectable),
selectable: true,
// Disable sorting, filtering, and searching for selection columns
disableSortBy: true,
filterable: false,
disableFilters: true,
disableGlobalFilter: true
}
// Make selection column the first column, even before grouped columns
return [selectionCol, ...columns.filter(col => !col.selectable)]
})
}
}
const useCrosstalkColumn = function useCrosstalkColumn(hooks) {
if (crosstalkGroup) {
hooks.visibleColumns.push(columns => {
const ctCol = {
id: crosstalkId,
filter: (rows, id, value) => {
if (!value) {
return rows
}
return rows.filter(row => {
if (value.includes(row.index)) {
return true
}
})
},
disableGlobalFilter: true
}
return columns.concat(ctCol)
})
hooks.stateReducers.push(state => {
if (!state.hiddenColumns.includes(crosstalkId)) {
return {
...state,
hiddenColumns: state.hiddenColumns.concat(crosstalkId)
}
}
return state
})
}
}
const instance = useTable(
{
columns,
data,
useControlledState: state => {
return React.useMemo(
() => ({
...state,
pageIndex,
pageSize,
sortBy,
filters,
globalFilter: searchValue,
groupBy,
expanded,
selectedRowIds
}),
// These dependencies are required for proper table updates
// eslint-disable-next-line react-hooks/exhaustive-deps
[
state,
pageIndex,
pageSize,
sortBy,
filters,
searchValue,
groupBy,
expanded,
selectedRowIds
]
)
},
globalFilter,
paginateExpandedRows: paginateSubRows ? true : false,
disablePagination: !pagination,
getSubRows,
// Disable manual row expansion
manualExpandedKey: null,
// Maintain grouped state when the data changes
autoResetGroupBy: false,
// Maintain sorted state when the data changes
autoResetSortBy: false,
// Maintain expanded state when groupBy, sortBy, defaultPageSize change.
// Expanded state is still reset when the data changes via dataKey or updateReactable.
autoResetExpanded: false,
// Maintain filtered state when the data changes
autoResetFilters: false,
autoResetGlobalFilter: false,
// Maintain selected state when groupBy, sortBy, defaultPageSize change.
// Selected state is still reset when the data changes via dataKey or updateReactable.
autoResetSelectedRows: false,
// Maintain resized state when the data changes
autoResetResize: false,
// Reset current page when the data changes (e.g., sorting, filtering, searching)
autoResetPage: true
},
useResizeColumns,
useFlexLayout,
useStickyColumns,
useFilters,
useGlobalFilter,
useGroupBy,
useSortBy,
useExpanded,
usePagination,
useRowSelect,
useRowSelectColumn,
useCrosstalkColumn
)
// Track the max number of rows for auto-shown pagination. Unfortunately, the max
// number of rows can't be determined up front in a grouped and filtered table
// because grouping happens after filtering (and swapping these hooks would
// disable dynamic aggregation). Instead, we track the max number of rows
// per dataset, so at least the pagination doesn't disappear upon filtering.
const maxRowCount = React.useRef(
paginateSubRows ? instance.flatRows.length : instance.rows.length
)
React.useEffect(() => {
maxRowCount.current = 0
}, [data])
React.useEffect(() => {
const rowCount = paginateSubRows ? instance.flatRows.length : instance.rows.length
if (rowCount > maxRowCount.current) {
maxRowCount.current = rowCount
}
}, [paginateSubRows, instance.flatRows, instance.rows])
if (setResolvedData) {
setResolvedData({
data: materializedRowsToData(instance.page, paginateSubRows),
rowCount: instance.rows.length,
maxRowCount: maxRowCount.current
})
}
return null
}
function Table({
data: originalData,
columns,
groupBy,
searchable,
searchMethod,
defaultSorted,
pagination,
paginationType,
showPagination,
showPageSizeOptions,
showPageInfo,
defaultPageSize,
pageSizeOptions,
minRows,
paginateSubRows,
defaultExpanded,
selection,
defaultSelected,
selectionId,
onClick,
outlined,
bordered,
borderless,
compact,
nowrap,
striped,
highlight,
className,
style,
rowClassName,
rowStyle,
inline,
width,
height,
theme,
language,
meta: initialMeta,
crosstalkKey,
crosstalkGroup,
crosstalkId,
elementId,
nested,
dataURL,
serverRowCount: initialServerRowCount,
serverMaxRowCount: initialServerMaxRowCount
}) {
const [newData, setNewData] = React.useState(null)
const data = React.useMemo(() => {
return newData ? newData : originalData
}, [newData, originalData])
const useServerData = dataURL != null
const [serverRowCount, setServerRowCount] = React.useState(initialServerRowCount)
const [serverMaxRowCount, setServerMaxRowCount] = React.useState(initialServerMaxRowCount)
const dataColumns = React.useMemo(() => {
return columns.reduce((cols, col) => cols.concat(getLeafColumns(col)), [])
}, [columns])
// Must be memoized to prevent re-filtering on every render
const globalFilter = React.useMemo(() => {
if (searchMethod) {
return searchMethod
}
return function globalFilter(rows, columnIds, searchValue) {
const matchers = dataColumns.reduce((obj, col) => {
obj[col.id] = col.createMatcher(searchValue)
return obj
}, {})
rows = rows.filter(row => {
for (const id of columnIds) {
const value = row.values[id]
if (matchers[id](value)) {
return true
}
}
})
return rows
}
}, [dataColumns, searchMethod])
const useRowSelectColumn = function useRowSelectColumn(hooks) {
if (selection) {
hooks.visibleColumns.push(columns => {
const selectionCol = {
// Apply defaults from existing selection column
...columns.find(col => col.selectable),
selectable: true,
// Disable sorting, filtering, and searching for selection columns
disableSortBy: true,
filterable: false,
disableFilters: true,
disableGlobalFilter: true
}
// Make selection column the first column, even before grouped columns
return [selectionCol, ...columns.filter(col => !col.selectable)]
})
}
}
const useCrosstalkColumn = function useCrosstalkColumn(hooks) {
if (crosstalkGroup) {
hooks.visibleColumns.push(columns => {
const ctCol = {
id: crosstalkId,
filter: (rows, id, value) => {
if (!value) {
return rows
}
return rows.filter(row => {
if (value.includes(row.index)) {
return true
}
})
},
disableGlobalFilter: true
}
return columns.concat(ctCol)
})
hooks.stateReducers.push(state => {
if (!state.hiddenColumns.includes(crosstalkId)) {
return {
...state,
hiddenColumns: state.hiddenColumns.concat(crosstalkId)
}
}
return state
})
}
}
const [meta, setMeta] = useMeta(initialMeta)
function useServerSideRows(hooks) {
hooks.useInstance.push(instance => {
const { rows, manualPagination, rowsById } = instance
if (!manualPagination) {
return
}
// Set proper row indexes and IDs
const setRowProps = rows => {
rows.forEach(row => {
const rowState = row.original[rowStateKey]
// Fall back for backends that don't implement row state
if (!rowState) {
return
}
row.index = rowState.index
// Not used for now because we need ability to select/expand all first
if (rowState.selected) {
row.original[rowSelectedKey] = rowState.selected
}
// Not used for now because we need ability to select/expand all first
if (rowState.expanded) {
row.original[rowExpandedKey] = rowState.expanded
}
if (rowState.grouped) {
row.isGrouped = true
}
// Rebuild sub rows
if (rowState.parentId != null) {
rowsById[rowState.parentId].subRows.push(row)
// Set parentId on row to tell useGroupBy that this is a nested row
// TODO change this so useGroupBy gets a properly nested row structure, not flat rows
row.parentId = rowState.parentId
}
// Set row props on sub rows. Skip this when sub rows are paginated, since sub rows
// exist in both row.subRows and the flat list of rows.
if (!paginateSubRows) {
setRowProps(row.subRows, row)
}
})
// Add placeholder subRows for aggregated row counts
if (paginateSubRows) {
rows.forEach(row => {
const rowState = row.original[rowStateKey]
row.subRows.length = rowState.subRowCount
})
}
}
setRowProps(rows)
})
}
const getRowId = React.useMemo(() => {
const defaultGetRowId = (row, index, parent) => {
return `${parent ? [parent.id, index].join('.') : index}`
}
if (!useServerData) {
return defaultGetRowId
}
return (row, index, parent) => {
if (row[rowStateKey]) {
return row[rowStateKey].id
}
// Fall back for backends that don't implement row state
return defaultGetRowId(row, index, parent)
}
}, [useServerData])
const { state, ...instance } = useTable(
{
columns,
data,
initialState: {
hiddenColumns: dataColumns.filter(col => col.show === false).map(col => col.id),
groupBy: groupBy || [],
sortBy: defaultSorted || [],
pageSize: defaultPageSize,
selectedRowIds: defaultSelected
? defaultSelected.reduce((obj, index) => ({ ...obj, [index]: true }), {})
: {}
},
globalFilter,
paginateExpandedRows: paginateSubRows ? true : false,
disablePagination: !pagination,
getSubRows,
getRowId,
// Maintain grouped state when the data changes
autoResetGroupBy: false,
// Maintain sorted state when the data changes
autoResetSortBy: false,
// Maintain expanded state when groupBy, sortBy, defaultPageSize change.
// Expanded state is still reset when the data changes via dataKey or updateReactable.
autoResetExpanded: false,
// Maintain filtered state when the data changes
autoResetFilters: false,
autoResetGlobalFilter: false,
// Maintain selected state when groupBy, sortBy, defaultPageSize change.
// Selected state is still reset when the data changes via dataKey or updateReactable.
autoResetSelectedRows: false,
// Maintain resized state when the data changes
autoResetResize: false,
// Reset current page when the data changes (e.g., sorting, filtering, searching)
autoResetPage: true,
manualPagination: useServerData,
manualSortBy: useServerData,
manualGlobalFilter: useServerData,
manualFilters: useServerData,
manualGroupBy: useServerData,
// TODO for when server-side row selection is implemented - need the ability to select all first
// manualRowSelectedKey: useServerData ? rowSelectedKey : null,
// TODO for when server-side row expansion is implemented
// Disable manual row expansion
manualExpandedKey: null,
// Prevent duplicate sub rows when sub rows are paginated server-side
expandSubRows: !(useServerData && paginateSubRows),
rowCount: useServerData ? serverRowCount : null
},
useServerSideRows,
useResizeColumns,
useFlexLayout,