forked from sendgrid/react-table
-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-table.js
3645 lines (3227 loc) · 123 KB
/
react-table.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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(factory((global.ReactTable = {}),global.React));
}(this, (function (exports,React) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if ('object' !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (typeof undefined === 'function' && typeof undefined.amd === 'object' && undefined.amd) {
// register as 'classnames', consistent with npm package name
undefined('classnames', [], function () {
return classNames;
});
} else {
window.classNames = classNames;
}
}());
});
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
//
var _ = {
get: get$1,
set: set$1,
takeRight: takeRight,
last: last,
orderBy: orderBy,
range: range,
remove: remove,
clone: clone,
getFirstDefined: getFirstDefined,
sum: sum,
makeTemplateComponent: makeTemplateComponent,
groupBy: groupBy,
isArray: isArray,
splitProps: splitProps,
compactObject: compactObject,
isSortingDesc: isSortingDesc,
normalizeComponent: normalizeComponent,
asPx: asPx
};
function get$1(obj, path, def) {
if (!path) {
return obj;
}
var pathObj = makePathArray(path);
var val = void 0;
try {
val = pathObj.reduce(function (current, pathPart) {
return current[pathPart];
}, obj);
} catch (e) {
// continue regardless of error
}
return typeof val !== 'undefined' ? val : def;
}
function set$1() {
var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var path = arguments[1];
var value = arguments[2];
var keys = makePathArray(path);
var keyPart = void 0;
var cursor = obj;
while ((keyPart = keys.shift()) && keys.length) {
if (!cursor[keyPart]) {
cursor[keyPart] = {};
}
cursor = cursor[keyPart];
}
cursor[keyPart] = value;
return obj;
}
function takeRight(arr, n) {
var start = n > arr.length ? 0 : arr.length - n;
return arr.slice(start);
}
function last(arr) {
return arr[arr.length - 1];
}
function range(n) {
var arr = [];
for (var i = 0; i < n; i += 1) {
arr.push(n);
}
return arr;
}
function orderBy(arr, funcs, dirs, indexKey) {
return arr.sort(function (rowA, rowB) {
for (var i = 0; i < funcs.length; i += 1) {
var comp = funcs[i];
var desc = dirs[i] === false || dirs[i] === 'desc';
var sortInt = comp(rowA, rowB);
if (sortInt) {
return desc ? -sortInt : sortInt;
}
}
// Use the row index for tie breakers
return dirs[0] ? rowA[indexKey] - rowB[indexKey] : rowB[indexKey] - rowA[indexKey];
});
}
function remove(a, b) {
return a.filter(function (o, i) {
var r = b(o);
if (r) {
a.splice(i, 1);
return true;
}
return false;
});
}
function clone(a) {
try {
return JSON.parse(JSON.stringify(a, function (key, value) {
if (typeof value === 'function') {
return value.toString();
}
return value;
}));
} catch (e) {
return a;
}
}
function getFirstDefined() {
for (var i = 0; i < arguments.length; i += 1) {
if (typeof (arguments.length <= i ? undefined : arguments[i]) !== 'undefined') {
return arguments.length <= i ? undefined : arguments[i];
}
}
}
function sum(arr) {
return arr.reduce(function (a, b) {
return a + b;
}, 0);
}
function makeTemplateComponent(compClass, displayName) {
if (!displayName) {
throw new Error('No displayName found for template component:', compClass);
}
var cmp = function cmp(_ref) {
var children = _ref.children,
className = _ref.className,
rest = objectWithoutProperties(_ref, ['children', 'className']);
return React__default.createElement(
'div',
_extends({ className: classnames(compClass, className) }, rest),
children
);
};
cmp.displayName = displayName;
return cmp;
}
function groupBy(xs, key) {
return xs.reduce(function (rv, x, i) {
var resKey = typeof key === 'function' ? key(x, i) : x[key];
rv[resKey] = isArray(rv[resKey]) ? rv[resKey] : [];
rv[resKey].push(x);
return rv;
}, {});
}
function asPx(value) {
value = Number(value);
return Number.isNaN(value) ? null : value + 'px';
}
function isArray(a) {
return Array.isArray(a);
}
// ########################################################################
// Non-exported Helpers
// ########################################################################
function makePathArray(obj) {
return flattenDeep(obj).join('.').replace(/\[/g, '.').replace(/\]/g, '').split('.');
}
function flattenDeep(arr) {
var newArr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
if (!isArray(arr)) {
newArr.push(arr);
} else {
for (var i = 0; i < arr.length; i += 1) {
flattenDeep(arr[i], newArr);
}
}
return newArr;
}
function splitProps(_ref2) {
var className = _ref2.className,
style = _ref2.style,
rest = objectWithoutProperties(_ref2, ['className', 'style']);
return {
className: className,
style: style,
rest: rest || {}
};
}
function compactObject(obj) {
var newObj = {};
if (obj) {
Object.keys(obj).map(function (key) {
if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] !== undefined && typeof obj[key] !== 'undefined') {
newObj[key] = obj[key];
}
return true;
});
}
return newObj;
}
function isSortingDesc(d) {
return !!(d.sort === 'desc' || d.desc === true || d.asc === false);
}
function normalizeComponent(Comp) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var fallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Comp;
return typeof Comp === 'function' ? Object.getPrototypeOf(Comp).isReactComponent ? React__default.createElement(Comp, params) : Comp(params) : fallback;
}
var Lifecycle = (function (Base) {
return function (_Base) {
inherits(_class, _Base);
function _class() {
classCallCheck(this, _class);
return possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
}
createClass(_class, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.setStateWithData(this.getDataModel(this.getResolvedState()));
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.fireFetchData();
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps, nextState) {
var oldState = this.getResolvedState();
var newState = this.getResolvedState(nextProps, nextState);
// Do a deep compare of new and old `defaultOption` and
// if they are different reset `option = defaultOption`
var defaultableOptions = ['sorted', 'filtered', 'resized', 'expanded'];
defaultableOptions.forEach(function (x) {
var defaultName = 'default' + (x.charAt(0).toUpperCase() + x.slice(1));
if (JSON.stringify(oldState[defaultName]) !== JSON.stringify(newState[defaultName])) {
newState[x] = newState[defaultName];
}
});
// If they change these table options, we need to reset defaults
// or else we could get into a state where the user has changed the UI
// and then disabled the ability to change it back.
// e.g. If `filterable` has changed, set `filtered = defaultFiltered`
var resettableOptions = ['sortable', 'filterable', 'resizable'];
resettableOptions.forEach(function (x) {
if (oldState[x] !== newState[x]) {
var baseName = x.replace('able', '');
var optionName = baseName + 'ed';
var defaultName = 'default' + (optionName.charAt(0).toUpperCase() + optionName.slice(1));
newState[optionName] = newState[defaultName];
}
});
// Props that trigger a data update
if (oldState.data !== newState.data || oldState.columns !== newState.columns || oldState.pivotBy !== newState.pivotBy || oldState.sorted !== newState.sorted || oldState.filtered !== newState.filtered) {
this.setStateWithData(this.getDataModel(newState));
}
}
}, {
key: 'setStateWithData',
value: function setStateWithData(newState, cb) {
var _this2 = this;
var oldState = this.getResolvedState();
var newResolvedState = this.getResolvedState({}, newState);
var freezeWhenExpanded = newResolvedState.freezeWhenExpanded;
// Default to unfrozen state
newResolvedState.frozen = false;
// If freezeWhenExpanded is set, check for frozen conditions
if (freezeWhenExpanded) {
// if any rows are expanded, freeze the existing data and sorting
var keys = Object.keys(newResolvedState.expanded);
for (var i = 0; i < keys.length; i += 1) {
if (newResolvedState.expanded[keys[i]]) {
newResolvedState.frozen = true;
break;
}
}
}
// If the data isn't frozen and either the data or
// sorting model has changed, update the data
if (oldState.frozen && !newResolvedState.frozen || oldState.sorted !== newResolvedState.sorted || oldState.filtered !== newResolvedState.filtered || oldState.showFilters !== newResolvedState.showFilters || !newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData) {
// Handle collapseOnsortedChange & collapseOnDataChange
if (oldState.sorted !== newResolvedState.sorted && this.props.collapseOnSortingChange || oldState.filtered !== newResolvedState.filtered || oldState.showFilters !== newResolvedState.showFilters || oldState.sortedData && !newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData && this.props.collapseOnDataChange) {
newResolvedState.expanded = {};
}
Object.assign(newResolvedState, this.getSortedData(newResolvedState));
}
// Set page to 0 if filters change
if (oldState.filtered !== newResolvedState.filtered) {
newResolvedState.page = 0;
}
// Calculate pageSize all the time
if (newResolvedState.sortedData) {
newResolvedState.pages = newResolvedState.manual ? newResolvedState.pages : Math.ceil(newResolvedState.sortedData.length / newResolvedState.pageSize);
newResolvedState.page = Math.max(newResolvedState.page >= newResolvedState.pages ? newResolvedState.pages - 1 : newResolvedState.page, 0);
}
return this.setState(newResolvedState, function () {
if (cb) {
cb();
}
if (oldState.page !== newResolvedState.page || oldState.pageSize !== newResolvedState.pageSize || oldState.sorted !== newResolvedState.sorted || oldState.filtered !== newResolvedState.filtered) {
_this2.fireFetchData();
}
});
}
}]);
return _class;
}(Base);
});
var Methods = (function (Base) {
return function (_Base) {
inherits(_class, _Base);
function _class() {
classCallCheck(this, _class);
return possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
}
createClass(_class, [{
key: 'getResolvedState',
value: function getResolvedState(props, state) {
var resolvedState = _extends({}, _.compactObject(this.state), _.compactObject(this.props), _.compactObject(state), _.compactObject(props));
return resolvedState;
}
}, {
key: 'getDataModel',
value: function getDataModel(newState) {
var _this2 = this;
var columns = newState.columns,
_newState$pivotBy = newState.pivotBy,
pivotBy = _newState$pivotBy === undefined ? [] : _newState$pivotBy,
data = newState.data,
pivotIDKey = newState.pivotIDKey,
pivotValKey = newState.pivotValKey,
subRowsKey = newState.subRowsKey,
aggregatedKey = newState.aggregatedKey,
nestingLevelKey = newState.nestingLevelKey,
originalKey = newState.originalKey,
indexKey = newState.indexKey,
groupedByPivotKey = newState.groupedByPivotKey,
SubComponent = newState.SubComponent;
// Determine Header Groups
var hasHeaderGroups = false;
columns.forEach(function (column) {
if (column.columns) {
hasHeaderGroups = true;
}
});
var columnsWithExpander = [].concat(toConsumableArray(columns));
var expanderColumn = columns.find(function (col) {
return col.expander || col.columns && col.columns.some(function (col2) {
return col2.expander;
});
});
// The actual expander might be in the columns field of a group column
if (expanderColumn && !expanderColumn.expander) {
expanderColumn = expanderColumn.columns.find(function (col) {
return col.expander;
});
}
// If we have SubComponent's we need to make sure we have an expander column
if (SubComponent && !expanderColumn) {
expanderColumn = { expander: true };
columnsWithExpander = [expanderColumn].concat(toConsumableArray(columnsWithExpander));
}
var makeDecoratedColumn = function makeDecoratedColumn(column, parentColumn) {
var dcol = void 0;
if (column.expander) {
dcol = _extends({}, _this2.props.column, _this2.props.expanderDefaults, column);
} else {
dcol = _extends({}, _this2.props.column, column);
}
// Ensure minWidth is not greater than maxWidth if set
if (dcol.maxWidth < dcol.minWidth) {
dcol.minWidth = dcol.maxWidth;
}
if (parentColumn) {
dcol.parentColumn = parentColumn;
}
// First check for string accessor
if (typeof dcol.accessor === 'string') {
dcol.id = dcol.id || dcol.accessor;
var accessorString = dcol.accessor;
dcol.accessor = function (row) {
return _.get(row, accessorString);
};
return dcol;
}
// Fall back to functional accessor (but require an ID)
if (dcol.accessor && !dcol.id) {
console.warn(dcol);
throw new Error('A column id is required if using a non-string accessor for column above.');
}
// Fall back to an undefined accessor
if (!dcol.accessor) {
dcol.accessor = function () {
return undefined;
};
}
return dcol;
};
var allDecoratedColumns = [];
// Decorate the columns
var decorateAndAddToAll = function decorateAndAddToAll(column, parentColumn) {
var decoratedColumn = makeDecoratedColumn(column, parentColumn);
allDecoratedColumns.push(decoratedColumn);
return decoratedColumn;
};
var decoratedColumns = columnsWithExpander.map(function (column) {
if (column.columns) {
return _extends({}, column, {
columns: column.columns.map(function (d) {
return decorateAndAddToAll(d, column);
})
});
}
return decorateAndAddToAll(column);
});
// Build the visible columns, headers and flat column list
var visibleColumns = decoratedColumns.slice();
var allVisibleColumns = [];
visibleColumns = visibleColumns.map(function (column) {
if (column.columns) {
var visibleSubColumns = column.columns.filter(function (d) {
return pivotBy.indexOf(d.id) > -1 ? false : _.getFirstDefined(d.show, true);
});
return _extends({}, column, {
columns: visibleSubColumns
});
}
return column;
});
visibleColumns = visibleColumns.filter(function (column) {
return column.columns ? column.columns.length : pivotBy.indexOf(column.id) > -1 ? false : _.getFirstDefined(column.show, true);
});
// Find any custom pivot location
var pivotIndex = visibleColumns.findIndex(function (col) {
return col.pivot;
});
// Handle Pivot Columns
if (pivotBy.length) {
// Retrieve the pivot columns in the correct pivot order
var pivotColumns = [];
pivotBy.forEach(function (pivotID) {
var found = allDecoratedColumns.find(function (d) {
return d.id === pivotID;
});
if (found) {
pivotColumns.push(found);
}
});
var PivotParentColumn = pivotColumns.reduce(function (prev, current) {
return prev && prev === current.parentColumn && current.parentColumn;
}, pivotColumns[0].parentColumn);
var PivotGroupHeader = hasHeaderGroups && PivotParentColumn.Header;
PivotGroupHeader = PivotGroupHeader || function () {
return React__default.createElement(
'strong',
null,
'Pivoted'
);
};
var pivotColumnGroup = {
Header: PivotGroupHeader,
columns: pivotColumns.map(function (col) {
return _extends({}, _this2.props.pivotDefaults, col, {
pivoted: true
});
})
};
// Place the pivotColumns back into the visibleColumns
if (pivotIndex >= 0) {
pivotColumnGroup = _extends({}, visibleColumns[pivotIndex], pivotColumnGroup);
visibleColumns.splice(pivotIndex, 1, pivotColumnGroup);
} else {
visibleColumns.unshift(pivotColumnGroup);
}
}
// Build Header Groups
var headerGroups = [];
var currentSpan = [];
// A convenience function to add a header and reset the currentSpan
var addHeader = function addHeader(columns, column) {
headerGroups.push(_extends({}, _this2.props.column, column, {
columns: columns
}));
currentSpan = [];
};
// Build flast list of allVisibleColumns and HeaderGroups
visibleColumns.forEach(function (column) {
if (column.columns) {
allVisibleColumns = allVisibleColumns.concat(column.columns);
if (currentSpan.length > 0) {
addHeader(currentSpan);
}
addHeader(column.columns, column);
return;
}
allVisibleColumns.push(column);
currentSpan.push(column);
});
if (hasHeaderGroups && currentSpan.length > 0) {
addHeader(currentSpan);
}
// Access the data
var accessRow = function accessRow(d, i) {
var _row;
var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var row = (_row = {}, defineProperty(_row, originalKey, d), defineProperty(_row, indexKey, i), defineProperty(_row, subRowsKey, d[subRowsKey]), defineProperty(_row, nestingLevelKey, level), _row);
allDecoratedColumns.forEach(function (column) {
if (column.expander) return;
row[column.id] = column.accessor(d);
});
if (row[subRowsKey]) {
row[subRowsKey] = row[subRowsKey].map(function (d, i) {
return accessRow(d, i, level + 1);
});
}
return row;
};
var resolvedData = data.map(function (d, i) {
return accessRow(d, i);
});
// TODO: Make it possible to fabricate nested rows without pivoting
var aggregatingColumns = allVisibleColumns.filter(function (d) {
return !d.expander && d.aggregate;
});
// If pivoting, recursively group the data
var aggregate = function aggregate(rows) {
var aggregationValues = {};
aggregatingColumns.forEach(function (column) {
var values = rows.map(function (d) {
return d[column.id];
});
aggregationValues[column.id] = column.aggregate(values, rows);
});
return aggregationValues;
};
if (pivotBy.length) {
var groupRecursively = function groupRecursively(rows, keys) {
var i = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
// This is the last level, just return the rows
if (i === keys.length) {
return rows;
}
// Group the rows together for this level
var groupedRows = Object.entries(_.groupBy(rows, keys[i])).map(function (_ref) {
var _ref3;
var _ref2 = slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
return _ref3 = {}, defineProperty(_ref3, pivotIDKey, keys[i]), defineProperty(_ref3, pivotValKey, key), defineProperty(_ref3, keys[i], key), defineProperty(_ref3, subRowsKey, value), defineProperty(_ref3, nestingLevelKey, i), defineProperty(_ref3, groupedByPivotKey, true), _ref3;
});
// Recurse into the subRows
groupedRows = groupedRows.map(function (rowGroup) {
var _babelHelpers$extends;
var subRows = groupRecursively(rowGroup[subRowsKey], keys, i + 1);
return _extends({}, rowGroup, (_babelHelpers$extends = {}, defineProperty(_babelHelpers$extends, subRowsKey, subRows), defineProperty(_babelHelpers$extends, aggregatedKey, true), _babelHelpers$extends), aggregate(subRows));
});
return groupedRows;
};
resolvedData = groupRecursively(resolvedData, pivotBy);
}
return _extends({}, newState, {
resolvedData: resolvedData,
allVisibleColumns: allVisibleColumns,
headerGroups: headerGroups,
allDecoratedColumns: allDecoratedColumns,
hasHeaderGroups: hasHeaderGroups
});
}
}, {
key: 'getSortedData',
value: function getSortedData(resolvedState) {
var manual = resolvedState.manual,
sorted = resolvedState.sorted,
filtered = resolvedState.filtered,
defaultFilterMethod = resolvedState.defaultFilterMethod,
resolvedData = resolvedState.resolvedData,
allVisibleColumns = resolvedState.allVisibleColumns,
allDecoratedColumns = resolvedState.allDecoratedColumns;
var sortMethodsByColumnID = {};
allDecoratedColumns.filter(function (col) {
return col.sortMethod;
}).forEach(function (col) {
sortMethodsByColumnID[col.id] = col.sortMethod;
});
// Resolve the data from either manual data or sorted data
return {
sortedData: manual ? resolvedData : this.sortData(this.filterData(resolvedData, filtered, defaultFilterMethod, allVisibleColumns), sorted, sortMethodsByColumnID)
};
}
}, {
key: 'fireFetchData',
value: function fireFetchData() {
this.props.onFetchData(this.getResolvedState(), this);
}
}, {
key: 'getPropOrState',
value: function getPropOrState(key) {
return _.getFirstDefined(this.props[key], this.state[key]);
}
}, {
key: 'getStateOrProp',
value: function getStateOrProp(key) {
return _.getFirstDefined(this.state[key], this.props[key]);
}
}, {
key: 'filterData',
value: function filterData(data, filtered, defaultFilterMethod, allVisibleColumns) {
var _this3 = this;
var filteredData = data;
if (filtered.length) {
filteredData = filtered.reduce(function (filteredSoFar, nextFilter) {
var column = allVisibleColumns.find(function (x) {
return x.id === nextFilter.id;
});
// Don't filter hidden columns or columns that have had their filters disabled
if (!column || column.filterable === false) {
return filteredSoFar;
}
var filterMethod = column.filterMethod || defaultFilterMethod;
// If 'filterAll' is set to true, pass the entire dataset to the filter method
if (column.filterAll) {
return filterMethod(nextFilter, filteredSoFar, column);
}
return filteredSoFar.filter(function (row) {
return filterMethod(nextFilter, row, column);
});
}, filteredData);
// Apply the filter to the subrows if we are pivoting, and then
// filter any rows without subcolumns because it would be strange to show
filteredData = filteredData.map(function (row) {
if (!row[_this3.props.subRowsKey]) {
return row;
}
return _extends({}, row, defineProperty({}, _this3.props.subRowsKey, _this3.filterData(row[_this3.props.subRowsKey], filtered, defaultFilterMethod, allVisibleColumns)));
}).filter(function (row) {
if (!row[_this3.props.subRowsKey]) {
return true;
}
return row[_this3.props.subRowsKey].length > 0;
});
}
return filteredData;
}
}, {
key: 'sortData',
value: function sortData(data, sorted) {
var _this4 = this;
var sortMethodsByColumnID = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!sorted.length) {
return data;
}
var sortedData = (this.props.orderByMethod || _.orderBy)(data, sorted.map(function (sort) {
// Support custom sorting methods for each column
if (sortMethodsByColumnID[sort.id]) {
return function (a, b) {
return sortMethodsByColumnID[sort.id](a[sort.id], b[sort.id], sort.desc);
};
}
return function (a, b) {
return _this4.props.defaultSortMethod(a[sort.id], b[sort.id], sort.desc);
};
}), sorted.map(function (d) {
return !d.desc;
}), this.props.indexKey);
sortedData.forEach(function (row) {
if (!row[_this4.props.subRowsKey]) {
return;
}
row[_this4.props.subRowsKey] = _this4.sortData(row[_this4.props.subRowsKey], sorted, sortMethodsByColumnID);
});
return sortedData;
}
}, {
key: 'getMinRows',
value: function getMinRows() {
return _.getFirstDefined(this.props.minRows, this.getStateOrProp('pageSize'));
}
// User actions
}, {
key: 'onPageChange',
value: function onPageChange(page) {
var _props = this.props,
onPageChange = _props.onPageChange,
collapseOnPageChange = _props.collapseOnPageChange;
var newState = { page: page };
if (collapseOnPageChange) {