-
Notifications
You must be signed in to change notification settings - Fork 931
/
MUIDataTable.js
2039 lines (1844 loc) · 65.5 KB
/
MUIDataTable.js
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 Paper from '@material-ui/core/Paper';
import { withStyles } from '@material-ui/core/styles';
import MuiTable from '@material-ui/core/Table';
import clsx from 'clsx';
import assignwith from 'lodash.assignwith';
import cloneDeep from 'lodash.clonedeep';
import find from 'lodash.find';
import isUndefined from 'lodash.isundefined';
import merge from 'lodash.merge';
import PropTypes from 'prop-types';
import React from 'react';
import DefaultTableBody from './components/TableBody';
import DefaultTableFilter from './components/TableFilter';
import DefaultTableFilterList from './components/TableFilterList';
import DefaultTableFooter from './components/TableFooter';
import DefaultTableHead from './components/TableHead';
import DefaultTableResize from './components/TableResize';
import DefaultTableToolbar from './components/TableToolbar';
import DefaultTableToolbarSelect from './components/TableToolbarSelect';
import MuiTooltip from '@material-ui/core/Tooltip';
import getTextLabels from './textLabels';
import { buildMap, getCollatorComparator, sortCompare, getPageValue, warnDeprecated, warnInfo } from './utils';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
const defaultTableStyles = theme => ({
root: {},
paper: {},
paperResponsiveScrollFullHeightFullWidth: {
position: 'absolute',
},
tableRoot: {
outline: 'none',
},
responsiveBase: {
overflow: 'auto',
'@media print': {
height: 'auto !important',
},
},
// deprecated, but continuing support through v3.x
responsiveScroll: {
overflow: 'auto',
height: '100%',
},
// deprecated, but continuing support through v3.x
responsiveScrollMaxHeight: {
overflow: 'auto',
height: '100%',
},
// deprecated, but continuing support through v3.x
responsiveScrollFullHeight: {
height: '100%',
},
// deprecated, but continuing support through v3.x
responsiveStacked: {
overflow: 'auto',
[theme.breakpoints.down('sm')]: {
overflow: 'hidden',
},
},
// deprecated, but continuing support through v3.x
responsiveStackedFullWidth: {},
caption: {
position: 'absolute',
left: '-3000px',
},
liveAnnounce: {
border: '0',
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: '0',
position: 'absolute',
width: '1px',
},
'@global': {
'@media print': {
'.datatables-noprint': {
display: 'none',
},
},
},
});
const TABLE_LOAD = {
INITIAL: 1,
UPDATE: 2,
};
// Populate this list with anything that might render in the toolbar to determine if we hide the toolbar
const TOOLBAR_ITEMS = ['title', 'filter', 'search', 'print', 'download', 'viewColumns', 'customToolbar'];
const hasToolbarItem = (options, title) => {
options.title = title;
return !isUndefined(find(TOOLBAR_ITEMS, i => options[i]));
};
// Select Toolbar Placement options
const STP = {
REPLACE: 'replace',
ABOVE: 'above',
NONE: 'none',
};
class MUIDataTable extends React.Component {
static propTypes = {
/** Title of the table */
title: PropTypes.oneOfType([PropTypes.string, PropTypes.element]).isRequired,
/** Data used to describe table */
data: PropTypes.array.isRequired,
/** Columns used to describe table */
columns: PropTypes.PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.string,
PropTypes.shape({
label: PropTypes.string,
name: PropTypes.string.isRequired,
options: PropTypes.shape({
display: PropTypes.oneOf(['true', 'false', 'excluded', 'always']),
empty: PropTypes.bool,
filter: PropTypes.bool,
sort: PropTypes.bool,
print: PropTypes.bool,
searchable: PropTypes.bool,
download: PropTypes.bool,
viewColumns: PropTypes.bool,
filterList: PropTypes.array,
filterOptions: PropTypes.oneOfType([
PropTypes.array,
PropTypes.shape({
names: PropTypes.array,
logic: PropTypes.func,
display: PropTypes.func,
}),
]),
filterType: PropTypes.oneOf(['dropdown', 'checkbox', 'multiselect', 'textField', 'custom']),
customHeadRender: PropTypes.func,
customBodyRender: PropTypes.func,
customBodyRenderLite: PropTypes.func,
customHeadLabelRender: PropTypes.func,
customFilterListOptions: PropTypes.oneOfType([
PropTypes.shape({
render: PropTypes.func,
update: PropTypes.func,
}),
]),
customFilterListRender: PropTypes.func,
setCellProps: PropTypes.func,
setCellHeaderProps: PropTypes.func,
sortThirdClickReset: PropTypes.bool,
sortDescFirst: PropTypes.bool,
}),
}),
]),
).isRequired,
/** Options used to describe table */
options: PropTypes.shape({
caseSensitive: PropTypes.bool,
columnOrder: PropTypes.array,
count: PropTypes.number,
confirmFilters: PropTypes.bool,
consoleWarnings: PropTypes.bool,
customFilterDialogFooter: PropTypes.func,
customFooter: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
customRowRender: PropTypes.func,
customSearch: PropTypes.func,
customSearchRender: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
customSort: PropTypes.func,
customToolbar: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
customToolbarSelect: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
draggableColumns: PropTypes.object,
enableNestedDataAccess: PropTypes.string,
expandableRows: PropTypes.bool,
expandableRowsHeader: PropTypes.bool,
expandableRowsOnClick: PropTypes.bool,
disableToolbarSelect: PropTypes.bool,
download: PropTypes.bool,
downloadOptions: PropTypes.shape({
filename: PropTypes.string,
separator: PropTypes.string,
filterOptions: PropTypes.shape({
useDisplayedColumnsOnly: PropTypes.bool,
useDisplayedRowsOnly: PropTypes.bool,
}),
}),
filter: PropTypes.bool,
filterType: PropTypes.oneOf(['dropdown', 'checkbox', 'multiselect', 'textField', 'custom']),
fixedHeader: PropTypes.bool,
fixedSelectColumn: PropTypes.bool,
getTextLabels: PropTypes.func,
isRowExpandable: PropTypes.func,
isRowSelectable: PropTypes.func,
jumpToPage: PropTypes.bool,
onDownload: PropTypes.func,
onFilterChange: PropTypes.func,
onFilterChipClose: PropTypes.func,
onFilterConfirm: PropTypes.func,
onFilterDialogOpen: PropTypes.func,
onFilterDialogClose: PropTypes.func,
onRowClick: PropTypes.func,
onRowsExpand: PropTypes.func,
onRowExpansionChange: PropTypes.func,
onRowsSelect: PropTypes.func,
onRowSelectionChange: PropTypes.func,
onTableChange: PropTypes.func,
onTableInit: PropTypes.func,
page: PropTypes.number,
pagination: PropTypes.bool,
print: PropTypes.bool,
searchProps: PropTypes.object,
selectableRows: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['none', 'single', 'multiple'])]),
selectableRowsHeader: PropTypes.bool,
selectableRowsHideCheckboxes: PropTypes.bool,
selectableRowsOnClick: PropTypes.bool,
serverSide: PropTypes.bool,
tableBodyHeight: PropTypes.string,
tableBodyMaxHeight: PropTypes.string,
renderExpandableRow: PropTypes.func,
resizableColumns: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
responsive: PropTypes.oneOf(['standard', 'vertical', 'verticalAlways', 'simple']),
rowHover: PropTypes.bool,
rowsExpanded: PropTypes.array,
rowsPerPage: PropTypes.number,
rowsPerPageOptions: PropTypes.array,
rowsSelected: PropTypes.array,
search: PropTypes.bool,
searchOpen: PropTypes.bool,
searchPlaceholder: PropTypes.string,
searchText: PropTypes.string,
setFilterChipProps: PropTypes.func,
setRowProps: PropTypes.func,
selectToolbarPlacement: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf([STP.REPLACE, STP.ABOVE, STP.NONE]),
]),
setTableProps: PropTypes.func,
sort: PropTypes.bool,
sortOrder: PropTypes.object,
viewColumns: PropTypes.bool,
}),
/** Pass and use className to style MUIDataTable as desired */
className: PropTypes.string,
components: PropTypes.objectOf(PropTypes.any),
};
static defaultProps = {
title: '',
options: {},
data: [],
columns: [],
components: {
TableBody: DefaultTableBody,
TableFilter: DefaultTableFilter,
TableFilterList: DefaultTableFilterList,
TableFooter: DefaultTableFooter,
TableHead: DefaultTableHead,
TableResize: DefaultTableResize,
TableToolbar: DefaultTableToolbar,
TableToolbarSelect: DefaultTableToolbarSelect,
Tooltip: MuiTooltip,
},
};
constructor(props) {
super(props);
this.tableId = (Math.random() + '').replace(/\./, '');
this.tableRef = React.createRef();
this.tableContent = React.createRef();
this.draggableHeadCellRefs = {};
this.resizeHeadCellRefs = {};
this.timers = {};
this.setHeadResizeable = () => {};
this.updateDividers = () => {};
let defaultState = {
activeColumn: null,
announceText: null,
count: 0,
columns: [],
expandedRows: {
data: [],
lookup: {},
},
data: [],
displayData: [],
filterData: [],
filterList: [],
page: 0,
previousSelectedRow: null,
rowsPerPage: 10,
searchProps: {},
searchText: null,
selectedRows: {
data: [],
lookup: {},
},
showResponsive: false,
sortOrder: {},
};
this.mergeDefaultOptions(props);
this.state = Object.assign(defaultState, this.getInitTableOptions());
this.setTableData = this.setTableData.bind(this);
this.setTableData(props, TABLE_LOAD.INITIAL, true, null, true);
}
componentDidMount() {
this.setHeadResizeable(this.resizeHeadCellRefs, this.tableRef);
// When we have a search, we must reset page to view it unless on serverSide since paging is handled by the user.
if (this.props.options.searchText && !this.props.options.serverSide) this.setState({ page: 0 });
this.setTableInit('tableInitialized');
}
componentDidUpdate(prevProps) {
if (
this.props.data !== prevProps.data ||
this.props.columns !== prevProps.columns ||
this.props.options !== prevProps.options
) {
this.updateOptions(this.options, this.props);
var didDataUpdate = this.props.data !== prevProps.data;
if (this.props.data && prevProps.data) {
didDataUpdate = didDataUpdate && this.props.data.length === prevProps.data.length;
}
this.setTableData(this.props, TABLE_LOAD.INITIAL, didDataUpdate, () => {
this.setTableAction('propsUpdate');
});
}
if (this.props.options.searchText !== prevProps.options.searchText && !this.props.options.serverSide) {
// When we have a search, we must reset page to view it unless on serverSide since paging is handled by the user.
this.setState({ page: 0 });
}
if (
this.options.resizableColumns === true ||
(this.options.resizableColumns && this.options.resizableColumns.enabled)
) {
this.setHeadResizeable(this.resizeHeadCellRefs, this.tableRef);
this.updateDividers();
}
}
updateOptions(options, props) {
// set backwards compatibility options
if (props.options.disableToolbarSelect === true && props.options.selectToolbarPlacement === undefined) {
// if deprecated option disableToolbarSelect is set and selectToolbarPlacement is default then use it
props.options.selectToolbarPlacement = STP.NONE;
}
this.options = assignwith(options, props.options, (objValue, srcValue, key) => {
// Merge any default options that are objects, as they will be overwritten otherwise
if (key === 'textLabels' || key === 'downloadOptions') return merge(objValue, srcValue);
return;
});
this.handleOptionDeprecation(props);
}
getDefaultOptions = () => ({
caseSensitive: false,
consoleWarnings: true,
disableToolbarSelect: false,
download: true,
downloadOptions: {
filename: 'tableDownload.csv',
separator: ',',
},
draggableColumns: {
enabled: false,
transitionTime: 300,
},
elevation: 4,
enableNestedDataAccess: '',
expandableRows: false,
expandableRowsHeader: true,
expandableRowsOnClick: false,
filter: true,
filterType: 'dropdown',
fixedHeader: true,
fixedSelectColumn: true,
pagination: true,
print: true,
resizableColumns: false,
responsive: 'vertical',
rowHover: true,
//rowsPerPage: 10,
rowsPerPageOptions: [10, 15, 100],
search: true,
selectableRows: 'multiple',
selectableRowsHideCheckboxes: false,
selectableRowsOnClick: false,
selectableRowsHeader: true,
serverSide: false,
serverSideFilterList: null,
setTableProps: () => ({}),
sort: true,
sortFilterList: true,
tableBodyHeight: 'auto',
tableBodyMaxHeight: null, // if set, it will override tableBodyHeight
sortOrder: {},
textLabels: getTextLabels(),
viewColumns: true,
selectToolbarPlacement: STP.REPLACE,
});
warnDep = (msg, consoleWarnings) => {
warnDeprecated(msg, this.options.consoleWarnings);
};
warnInfo = (msg, consoleWarnings) => {
warnInfo(msg, this.options.consoleWarnings);
};
handleOptionDeprecation = props => {
if (typeof this.options.selectableRows === 'boolean') {
this.warnDep(
'Using a boolean for selectableRows has been deprecated. Please use string option: multiple | single | none',
);
this.options.selectableRows = this.options.selectableRows ? 'multiple' : 'none';
}
if (['standard', 'vertical', 'verticalAlways', 'simple'].indexOf(this.options.responsive) === -1) {
if (
[
'scrollMaxHeight',
'scrollFullHeight',
'stacked',
'stackedFullWidth',
'scrollFullHeightFullWidth',
'scroll',
].indexOf(this.options.responsive) !== -1
) {
this.warnDep(
this.options.responsive +
' has been deprecated, but will still work in version 3.x. Please use string option: standard | vertical | simple. More info: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
} else {
this.warnInfo(
this.options.responsive +
' is not recognized as a valid input for responsive option. Please use string option: standard | vertical | simple. More info: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
}
}
if (this.options.onRowsSelect) {
this.warnDep(
'onRowsSelect has been renamed onRowSelectionChange. More info: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
}
if (this.options.onRowsExpand) {
this.warnDep(
'onRowsExpand has been renamed onRowExpansionChange. More info: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
}
if (this.options.fixedHeaderOptions) {
if (
typeof this.options.fixedHeaderOptions.yAxis !== 'undefined' &&
typeof this.options.fixedHeader === 'undefined'
) {
this.options.fixedHeader = this.options.fixedHeaderOptions.yAxis;
}
if (
typeof this.options.fixedHeaderOptions.xAxis !== 'undefined' &&
typeof this.options.fixedSelectColumn === 'undefined'
) {
this.options.fixedSelectColumn = this.options.fixedHeaderOptions.xAxis;
}
this.warnDep(
'fixedHeaderOptions will still work but has been deprecated in favor of fixedHeader and fixedSelectColumn. More info: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
}
if (this.options.serverSideFilterList) {
this.warnDep(
'serverSideFilterList will still work but has been deprecated in favor of the confirmFilters option. See this example for details: https://github.com/gregnb/mui-datatables/blob/master/examples/serverside-filters/index.js More info here: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
}
props.columns.map(c => {
if (c.options && c.options.customFilterListRender) {
this.warnDep(
'The customFilterListRender option has been deprecated. It is being replaced by customFilterListOptions.render (Specify customFilterListOptions: { render: Function } in column options.)',
);
}
});
if (this.options.disableToolbarSelect === true) {
this.warnDep(
'disableToolbarSelect has been deprecated but will still work in version 3.x. It is being replaced by "selectToolbarPlacement"="none". More info: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
}
// only give this warning message in newer browsers
if (Object.values) {
if (Object.values(STP).indexOf(this.options.selectToolbarPlacement) === -1) {
this.warnDep(
'Invalid option value for selectToolbarPlacement. Please check the documentation: https://github.com/gregnb/mui-datatables#options',
);
}
}
};
/*
* React currently does not support deep merge for defaultProps. Objects are overwritten
*/
mergeDefaultOptions(props) {
const defaultOptions = this.getDefaultOptions();
const theProps = Object.assign({}, props);
theProps.options = theProps.options || {};
this.updateOptions(defaultOptions, theProps);
}
validateOptions(options) {
if (options.serverSide && options.onTableChange === undefined) {
throw Error('onTableChange callback must be provided when using serverSide option');
}
if (options.expandableRows && options.renderExpandableRow === undefined) {
throw Error('renderExpandableRow must be provided when using expandableRows option');
}
if (options.rowsSelected && Array.isArray(options.rowsSelected) && options.rowsSelected.some(isNaN)) {
warnInfo('When using the rowsSelected option, must be provided an array of numbers only.');
}
}
setTableAction = action => {
if (typeof this.options.onTableChange === 'function') {
this.options.onTableChange(action, this.state);
}
};
setTableInit = action => {
if (typeof this.options.onTableInit === 'function') {
this.options.onTableInit(action, this.state);
}
};
getInitTableOptions() {
const optionNames = ['rowsPerPage', 'page', 'rowsSelected', 'rowsPerPageOptions'];
const optState = optionNames.reduce((acc, cur) => {
if (this.options[cur] !== undefined) {
acc[cur] = this.options[cur];
}
return acc;
}, {});
this.validateOptions(optState);
return optState;
}
setHeadCellRef = (index, pos, el) => {
this.draggableHeadCellRefs[index] = el;
this.resizeHeadCellRefs[pos] = el;
};
// must be arrow function on local field to refer to the correct instance when passed around
// assigning it as arrow function in the JSX would cause hard to track re-render errors
getTableContentRef = () => this.tableContent.current;
/*
* Build the source table data
*
* newColumns - columns from the options object.
* prevColumns - columns object saved onto ths state.
* newColumnOrder - columnOrder from the options object.
* prevColumnOrder - columnOrder object saved onto the state.
*/
buildColumns = (newColumns, prevColumns = [], newColumnOrder, prevColumnOrder = []) => {
let columnData = [];
let filterData = [];
let filterList = [];
let columnOrder = [];
newColumns.forEach((column, colIndex) => {
let columnOptions = {
display: 'true',
empty: false,
filter: true,
sort: true,
print: true,
searchable: true,
download: true,
viewColumns: true,
sortCompare: null,
sortThirdClickReset: false,
sortDescFirst: false,
};
columnOrder.push(colIndex);
const options = { ...column.options };
if (typeof column === 'object') {
if (options) {
if (options.display !== undefined) {
options.display = options.display.toString();
}
if (options.sortDirection === null || options.sortDirection) {
this.warnDep(
'The sortDirection column field has been deprecated. Please use the sortOrder option on the options object. More info: https://github.com/gregnb/mui-datatables/tree/master/docs/v2_to_v3_guide.md',
);
}
}
// remember stored version of display if not overwritten
if (
typeof options.display === 'undefined' &&
prevColumns[colIndex] &&
prevColumns[colIndex].name === column.name &&
prevColumns[colIndex].display
) {
options.display = prevColumns[colIndex].display;
}
columnOptions = {
name: column.name,
label: column.label ? column.label : column.name,
...columnOptions,
...options,
};
} else {
// remember stored version of display if not overwritten
if (prevColumns[colIndex] && prevColumns[colIndex].display) {
options.display = prevColumns[colIndex].display;
}
columnOptions = { ...columnOptions, ...options, name: column, label: column };
}
columnData.push(columnOptions);
filterData[colIndex] = [];
filterList[colIndex] = [];
});
if (Array.isArray(newColumnOrder)) {
columnOrder = newColumnOrder;
} else if (
Array.isArray(prevColumnOrder) &&
Array.isArray(newColumns) &&
Array.isArray(prevColumns) &&
newColumns.length === prevColumns.length
) {
columnOrder = prevColumnOrder;
}
return { columns: columnData, filterData, filterList, columnOrder };
};
transformData = (columns, data) => {
const { enableNestedDataAccess } = this.options;
const leaf = (obj, path) =>
(enableNestedDataAccess ? path.split(enableNestedDataAccess) : path.split()).reduce(
(value, el) => (value ? value[el] : undefined),
obj,
);
const transformedData = Array.isArray(data[0])
? data.map(row => {
let i = -1;
return columns.map(col => {
if (!col.empty) i++;
return col.empty ? undefined : row[i];
});
})
: data.map(row => columns.map(col => leaf(row, col.name)));
return transformedData;
};
setTableData(props, status, dataUpdated, callback = () => {}, fromConstructor = false) {
let tableData = [];
let { columns, filterData, filterList, columnOrder } = this.buildColumns(
props.columns,
this.state.columns,
this.options.columnOrder,
this.state.columnOrder,
);
let sortIndex = null;
let sortDirection = 'none';
let tableMeta;
let sortOrder;
if (this.options.sortOrder && this.options.sortOrder.direction && this.options.sortOrder.name) {
sortOrder = Object.assign({}, this.options.sortOrder);
} else {
sortOrder = Object.assign({}, this.state.sortOrder);
// if no sortOrder, check and see if there's a sortDirection on one of the columns (deprecation notice for this is given above)
if (!sortOrder.direction) {
props.columns.forEach((column, colIndex) => {
if (column.options && (column.options.sortDirection === 'asc' || column.options.sortDirection === 'desc')) {
sortOrder.name = column.name;
sortOrder.sortDirection = column.sortDirection;
}
});
}
}
const data = status === TABLE_LOAD.INITIAL ? this.transformData(columns, props.data) : props.data;
let searchText = status === TABLE_LOAD.INITIAL ? this.options.searchText : null;
if (typeof this.options.searchText === 'undefined' && typeof this.state.searchText !== 'undefined') {
searchText = this.state.searchText;
}
let rowsPerPage = this.state.rowsPerPage;
if (typeof this.options.rowsPerPage === 'number') {
rowsPerPage = this.options.rowsPerPage;
}
let page = this.state.page;
if (typeof this.options.page === 'number') {
page = this.options.page;
}
columns.forEach((column, colIndex) => {
for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
let value = status === TABLE_LOAD.INITIAL ? data[rowIndex][colIndex] : data[rowIndex].data[colIndex];
if (typeof tableData[rowIndex] === 'undefined') {
tableData.push({
index: status === TABLE_LOAD.INITIAL ? rowIndex : data[rowIndex].index,
data: status === TABLE_LOAD.INITIAL ? data[rowIndex] : data[rowIndex].data,
});
}
if (column.filter !== false) {
if (typeof column.customBodyRender === 'function') {
const rowData = tableData[rowIndex].data;
tableMeta = this.getTableMeta(rowIndex, colIndex, rowData, column, data, this.state, tableData);
const funcResult = column.customBodyRender(value, tableMeta);
if (React.isValidElement(funcResult) && funcResult.props.value) {
value = funcResult.props.value;
} else if (typeof funcResult === 'string') {
value = funcResult;
}
}
if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
// it's extremely rare but possible to create an object without a toString method, ex: var x = Object.create(null);
// so this check has to be made
value = value.toString ? value.toString() : '';
}
if (filterData[colIndex].indexOf(value) < 0 && !Array.isArray(value)) {
filterData[colIndex].push(value);
} else if (Array.isArray(value)) {
value.forEach(element => {
let elmVal;
if ((typeof element === 'object' && element !== null) || typeof element === 'function') {
elmVal = element.toString ? element.toString() : '';
} else {
elmVal = element;
}
if (filterData[colIndex].indexOf(elmVal) < 0) {
filterData[colIndex].push(elmVal);
}
});
}
}
}
if (column.filterOptions) {
if (Array.isArray(column.filterOptions)) {
filterData[colIndex] = cloneDeep(column.filterOptions);
this.warnDep(
'filterOptions must now be an object. see https://github.com/gregnb/mui-datatables/tree/master/examples/customize-filter example',
);
} else if (Array.isArray(column.filterOptions.names)) {
filterData[colIndex] = cloneDeep(column.filterOptions.names);
}
}
if (column.filterList) {
filterList[colIndex] = cloneDeep(column.filterList);
} else if (
this.state.filterList &&
this.state.filterList[colIndex] &&
this.state.filterList[colIndex].length > 0
) {
filterList[colIndex] = cloneDeep(this.state.filterList[colIndex]);
}
if (this.options.sortFilterList) {
const comparator = getCollatorComparator();
filterData[colIndex].sort(comparator);
}
if (column.name === sortOrder.name) {
sortDirection = sortOrder.direction;
sortIndex = colIndex;
}
});
let selectedRowsData = {
data: [],
lookup: {},
};
let expandedRowsData = {
data: [],
lookup: {},
};
if (TABLE_LOAD.INITIAL) {
// Multiple row selection customization
if (this.options.rowsSelected && this.options.rowsSelected.length && this.options.selectableRows === 'multiple') {
this.options.rowsSelected
.filter(selectedRowIndex => selectedRowIndex === 0 || (Number(selectedRowIndex) && selectedRowIndex > 0))
.forEach(row => {
let rowPos = row;
for (let cIndex = 0; cIndex < this.state.displayData.length; cIndex++) {
if (this.state.displayData[cIndex].dataIndex === row) {
rowPos = cIndex;
break;
}
}
selectedRowsData.data.push({ index: rowPos, dataIndex: row });
selectedRowsData.lookup[row] = true;
});
// Single row selection customization
} else if (
this.options.rowsSelected &&
this.options.rowsSelected.length === 1 &&
this.options.selectableRows === 'single'
) {
let rowPos = this.options.rowsSelected[0];
for (let cIndex = 0; cIndex < this.state.displayData.length; cIndex++) {
if (this.state.displayData[cIndex].dataIndex === this.options.rowsSelected[0]) {
rowPos = cIndex;
break;
}
}
selectedRowsData.data.push({ index: rowPos, dataIndex: this.options.rowsSelected[0] });
selectedRowsData.lookup[this.options.rowsSelected[0]] = true;
} else if (
this.options.rowsSelected &&
this.options.rowsSelected.length > 1 &&
this.options.selectableRows === 'single'
) {
console.error(
'Multiple values provided for selectableRows, but selectableRows set to "single". Either supply only a single value or use "multiple".',
);
} else if (typeof this.options.rowsSelected === 'undefined' && dataUpdated === false) {
if (this.state.selectedRows) {
selectedRowsData = Object.assign({}, this.state.selectedRows);
}
}
if (this.options.rowsExpanded && this.options.rowsExpanded.length && this.options.expandableRows) {
this.options.rowsExpanded.forEach(row => {
let rowPos = row;
for (let cIndex = 0; cIndex < this.state.displayData.length; cIndex++) {
if (this.state.displayData[cIndex].dataIndex === row) {
rowPos = cIndex;
break;
}
}
expandedRowsData.data.push({ index: rowPos, dataIndex: row });
expandedRowsData.lookup[row] = true;
});
} else if (typeof this.options.rowsExpanded === 'undefined' && dataUpdated === false && this.state.expandedRows) {
expandedRowsData = Object.assign({}, this.state.expandedRows);
}
}
if (!this.options.serverSide && sortIndex !== null) {
const sortedData = this.sortTable(tableData, sortIndex, sortDirection, columns[sortIndex].sortCompare);
tableData = sortedData.data;
}
/* set source data and display Data set source set */
let stateUpdates = {
columns: columns,
filterData: filterData,
filterList: filterList,
searchText: searchText,
selectedRows: selectedRowsData,
expandedRows: expandedRowsData,
count: this.options.count,
data: tableData,
sortOrder: sortOrder,
rowsPerPage,
page,
displayData: this.getDisplayData(columns, tableData, filterList, searchText, tableMeta, props),
columnOrder,
};
if (fromConstructor) {
this.state = Object.assign({}, this.state, stateUpdates);
} else {
this.setState(stateUpdates, callback);
}
}
/*
* Build the table data used to display to the user (ie: after filter/search applied)
*/
computeDisplayRow(
columns,
row,
rowIndex,
filterList,
searchText,
dataForTableMeta,
options,
props,
currentTableData,
) {
let isFiltered = false;
let isSearchFound = false;
let displayRow = [];
for (let index = 0; index < row.length; index++) {
let columnDisplay = row[index];
let columnValue = row[index];
let column = columns[index];
if (column.customBodyRenderLite) {
displayRow.push(column.customBodyRenderLite);
} else if (column.customBodyRender) {
const tableMeta = this.getTableMeta(
rowIndex,
index,
row,
column,
dataForTableMeta,
{
...this.state,
filterList: filterList,
searchText: searchText,
},
currentTableData,
);
const funcResult = column.customBodyRender(
columnValue,
tableMeta,
this.updateDataCol.bind(null, rowIndex, index),
);
columnDisplay = funcResult;
/* drill down to get the value of a cell */
columnValue =
typeof funcResult === 'string' || !funcResult
? funcResult
: funcResult.props && funcResult.props.value
? funcResult.props.value
: columnValue;
displayRow.push(columnDisplay);
} else {
displayRow.push(columnDisplay);
}
const columnVal = columnValue === null || columnValue === undefined ? '' : columnValue.toString();
const filterVal = filterList[index];
const caseSensitive = options.caseSensitive;
const filterType = column.filterType || options.filterType;
if (filterVal.length || filterType === 'custom') {
if (column.filterOptions && column.filterOptions.logic) {
if (column.filterOptions.logic(columnValue, filterVal, row)) isFiltered = true;
} else if (filterType === 'textField' && !this.hasSearchText(columnVal, filterVal, caseSensitive)) {
isFiltered = true;
} else if (
filterType !== 'textField' &&
Array.isArray(columnValue) === false &&
filterVal.indexOf(columnValue) < 0
) {
isFiltered = true;
} else if (filterType !== 'textField' && Array.isArray(columnValue)) {
//true if every filterVal exists in columnVal, false otherwise
const isFullMatch = filterVal.every(el => {
return columnValue.indexOf(el) >= 0;
});
//if it is not a fullMatch, filter row out
if (!isFullMatch) {
isFiltered = true;