Repository navigation
Expand file tree
/
Copy pathreact_smart_table.js
More file actions
766 lines (695 loc) · 28.7 KB
/
Copy pathreact_smart_table.js
File metadata and controls
766 lines (695 loc) · 28.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
/*
Datatable - Extrapolate columns from data
Datatable - Colums are sortables (js or SQL)
Datatable - Header stay visible (stick on screen limited by area)
Datatable - Rows can use custom component
Datatable - Cell can use custom component (blank cells are grayed by default)
Datatable - Visibles Columns are selectables via dropdown select
Datatable - Data is paginable for sql paginated data,
Datatable - Record count is always visible
Datatable - Pagination is shown
*/
// css
/*
table [fixed size]
- thead
- - tr [fixed height]
- - - td [fixed width]
- tbody
- - tr
- - - td
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) { // AMD
define(['react'], factory);
} else if (typeof exports === 'object') { // Node, CommonJS-like
module.exports = factory(require('react'));
} else { // Browser globals (root is window)
root.ReactSmartTable = factory(root.React);
}
}(this, function(React) {
"use strict";
var exports = {};
function detectScrollbarWidthHeight() {
var div = document.createElement("div");
div.style.overflow = "scroll";
div.style.visibility = "hidden";
div.style.position = 'relative';
div.style.width = '100px';
div.style.height = '100px';
document.body.appendChild(div);
var d = {
width: div.offsetWidth - div.clientWidth,
height: div.offsetHeight - div.clientHeight
};
document.body.removeChild(div);
return d;
}
function clamp(val, min, max) {
return Math.max(min, Math.min(max, val))
}
// Inequality function map for the filtering
var operators = {
"<": function(x, y) {
return x < y;
},
"<=": function(x, y) {
return x <= y;
},
">": function(x, y) {
return x > y;
},
">=": function(x, y) {
return x >= y;
},
"==": function(x, y) {
return x == y;
},
"!=": function(x, y) {
return x != y;
}
};
var exampleColumn = {
dataKey: "id",
label: "Id",
width: 60,
isVisible: true,
cellRenderer: function(cellData, rowData, rowIndex, column, columnIndex) {
return cellData;
},
headerRenderer: function(column, columnIndex) {
if ('label' in column)
return column.label;
else
return column.dataKey;
}
};
var T = React.createClass({
displayName: "Table",
getDefaultProps: function() {
return {
width: 'auto', // css rules -> width will expand horizontally to the parent border
height: 'auto', // css rules -> height will expand vertically to the content
// if set to 'fill' the height will adjust to stick to the bottom of the window
// minus offsetBottom
headerHeight: 30, // height of the header
filterHeight:30,
rowHeight: 30, // height of a row
footerHeight: 15,
footerPresent: true,
filterPresent: true,
items: [],
fixedColumns: [],
columns: [],
offsetBottom: 5, // pixel offset to the page bottom when fill is active
autoGenerateColumns: false, // generate columns from the first item
defaultColumnWidth: 80,
defaultSortColumn:null,
defaultSortOrderAscending:false,
// generate columns from the data
autoColumnsGetter: function() {
if (this.items.length == 0) return [];
var columnsField = Object.keys(this.items[0]);
var columns = [];
for (var i = 0; i < columnsField.length; i++) {
columns.push({
dataKey: columnsField[i]
});
}
return columns;
},
defaultCellClassGetter: function(cellData, rowData, rowIndex, column, columnIndex) {
if (cellData == undefined)
return "rst_empty";
},
defaultCellRenderer: function(cellData, rowData, rowIndex, column, columnIndex) {
return cellData;
},
defaultHeaderRenderer: function(column, columnIndex) {
if ('label' in column)
return column.label;
else
return column.dataKey;
},
sortIconGetter: function(column, isAscending) {
var ascOrDesc = (isAscending) ? "glyphicon glyphicon-triangle-top" : "glyphicon glyphicon-triangle-bottom";
return React.DOM.span({
style: {
position: "absolute",
right: 5,
verticalAlign: "center"
},
className: ascOrDesc
});
}
};
},
getInitialState: function() {
return {
scrollTop: 0,
scrollLeft: 0,
sortOrderAscending: this.props.defaultSortOrderAscending,
sortColumn: this.props.defaultSortColumn,
visibleColumns: [],
visibleFixedColumns: [],
filterTexts: {}
};
},
componentWillMount: function() {
this.SB = detectScrollbarWidthHeight();
this.initColumnState(this.props);
},
componentWillReceiveProps: function(nextProps) {
this.initColumnState(nextProps);
},
componentDidMount: function() {
this.updateSize();
$(window).on('resize', this.onWindowResize);
},
componentWillUnmount:function() {
$(window).off('resize', this.onWindowResize);
},
onWindowResize: function() {
clearTimeout(this._updateTimer);
this._updateTimer = setTimeout(this.updateSize, 16);
},
updateSize: function() {
var container = ("findDOMNode" in React) ? React.findDOMNode(this) :
this.getDOMNode();
// console.log(rect);
// console.log("W:" + container.offsetWidth+" vs "+container.clientWidth+" vs "+rect.width);
// console.log("H:" + container.offsetHeight+" vs "+container.clientHeight+" vs "+rect.height);
var w = this.props.width;
var h = this.props.height;
w = container.clientWidth;
if (h == "fill") {
// rect is a DOMRect object with four properties: left, top, right, bottom
var rect = container.getBoundingClientRect();
//compute available space from the window and the table upper position
h = window.innerHeight - rect.top - this.props.offsetBottom;
//console.log('fill',h);
} else {
h = container.clientHeight;
}
//console.log("updateSize w: "+w+" h: "+h);
this.setState({
width: w,
height: h
});
},
initColumnState: function(props) {
//console.log("initColumnState");
var fixedColumns = [];
var columns = [];
var keys = {};
for (var i = 0, len = props.fixedColumns.length; i < len; i++) {
var column = props.fixedColumns[i];
keys[column.dataKey] = true;
fixedColumns.push(column);
}
for (var i = 0, len = props.columns.length; i < len; i++) {
var column = props.columns[i];
if (!(column.dataKey in keys)) {
keys[column.dataKey] = true;
columns.push(column);
}
}
var generatedColumns = (props.autoGenerateColumns) ? props.autoColumnsGetter() : [];
for (var i = 0, len = generatedColumns.length; i < len; i++) {
var column = generatedColumns[i];
if (!(column.dataKey in keys)) {
keys[column.dataKey] = true;
columns.push(column);
}
}
this.setState({
visibleFixedColumns: fixedColumns,
visibleColumns: columns
});
},
computeColumnExtents: function(columns) {
var extents = [0],
val = 0;
for (var i = 0, len = columns.length; i < len; i++) {
val += ("width" in columns[i]) ? columns[i].width : this.props.defaultColumnWidth;
extents.push(val);
}
return extents;
},
computeRowExtents: function(items) {
var extents = [0],
val = 0;
for (var i = 0, len = items.length; i < len; i++) {
val += this.props.rowHeight;
extents.push(val);
}
return extents;
},
getVisibleSlice: function(extents, minVal, maxVal) {
var i = 1,
len = extents.length - 1;
if (len < 1) {
return {
begin: 0,
end: 0
};
}
while (i < len && extents[i] < minVal) {
i++;
}
var begin = i - 1;
while (i < len && extents[i] < maxVal) {
i++;
}
var end = i;
return {
begin: begin,
end: end
};
},
onSortColumn: function(column) {
return function(event) {
var newSortOrder = (this.state.sortColumn != column) ? true : (!this.state.sortOrderAscending);
this.setState({
sortColumn: column,
sortOrderAscending: newSortOrder
});
}.bind(this);
},
onFilterTextChange: function(column) {
return function(newValue) {
this.state.filterTexts[column.dataKey] = newValue;
// Mutation without setState so we need to call forceUpdate().
this.forceUpdate();
}.bind(this);
},
onRightBodyScroll: function(e) {
if ((e.target.scrollLeft != this.state.scrollLeft) ||
(e.target.scrollTop != this.state.scrollTop)) {
this.setState({
scrollTop: e.target.scrollTop,
scrollLeft: e.target.scrollLeft
}, function() {
if ("left_body" in this.refs) {
this.refs.left_body.getDOMNode().scrollTop = this.state.scrollTop;
}
if ("right_header" in this.refs) {
this.refs.right_header.getDOMNode().scrollLeft = this.state.scrollLeft;
}
//force focus on body
this.refs.right_body.getDOMNode().focus();
}.bind(this));
}
},
renderHeader: function(colSlice, columns, extents) {
var headerHeight = this.props.headerHeight;
if(this.props.filterPresent) headerHeight += this.props.filterHeight;
var titles = [];
var filters = [];
for (var i = colSlice.begin; i < colSlice.end; i++) {
var column = columns[i];
// Generate title
var cellElem = ('headerRenderer' in column) ?
column.headerRenderer(column, i) :
this.props.defaultHeaderRenderer(column, i);
var style = {
left: extents[i],
width: extents[i + 1] - extents[i],
height: headerHeight
};
// ... with sort icon
var icon = null;
if (this.state.sortColumn != null && this.state.sortColumn == column.dataKey) {
icon = this.props.sortIconGetter(column, this.state.sortOrderAscending);
}
cellElem = React.DOM.div({
className: "rst_th_wrapper",
onClick: this.onSortColumn(column.dataKey)
}, cellElem, icon);
var filter = null;
if(this.props.filterPresent) {
// Make search filter
var valueLink = {
value: (column.dataKey in this.state.filterTexts) ? this.state.filterTexts[column.dataKey] : "",
requestChange: this.onFilterTextChange(column)
};
filter = React.DOM.input({
type: "text",
valueLink: valueLink,
style: {
display: 'block',
width: '100%',
marginTop: 2
}
});
}
titles.push(React.DOM.div({
style: style,
key: i,
className: "rst_th"
}, cellElem, filter));
}
var style = {
top: 0,
height: headerHeight
};
return React.DOM.div({
style: style,
className: "rst_tr"
}, titles);
},
renderBody: function(colSlice, rowSlice, columns, columnsExtents, items, rowsExtents) {
var rows = [];
for (var j = rowSlice.begin; j < rowSlice.end; j++) {
var rowData = items[j];
var cells = [];
for (var i = colSlice.begin; i < colSlice.end; i++) {
var column = columns[i];
var style = {
left: columnsExtents[i],
width: columnsExtents[i + 1] - columnsExtents[i],
height: this.props.rowHeight
};
var className = "rst_td";
var cellElem = null;
var cellData = undefined;
if (column.dataKey in rowData) {
cellData = rowData[column.dataKey];
if (cellData !== null && cellData !== undefined){
cellElem = ('cellRenderer' in column) ?
column.cellRenderer(cellData, rowData, j, column, i) :
this.props.defaultCellRenderer(cellData, rowData, j, column, i);
}
}
var customClass = ('cellClassGetter' in column) ?
column.cellClassGetter(cellData, rowData, j, column, i) :
this.props.defaultCellClassGetter(cellData, rowData, j, column, i);
className += " " + customClass;
cells.push(React.DOM.div({
style: style,
key: i,
className: className
}, cellElem));
}
var style = {
top: rowsExtents[j],
height: this.props.rowHeight
};
rows.push(React.DOM.div({
style: style,
key: j,
className: "rst_tr"
}, cells));
}
return rows;
},
getFilteredItems: function() {
var filters = [];
var allColumns = this.state.visibleFixedColumns.concat(this.state.visibleColumns);
var operandRegex = /^((?:(?:[<>!]=?)|==))\s?([-]?\d+(?:\.\d+)?)$/;
allColumns.forEach(function(column) {
if (column.dataKey in this.state.filterTexts) {
var filterText = this.state.filterTexts[column.dataKey];
if (filterText.length > 0) {
var operandMatch = operandRegex.exec(filterText);
if (operandMatch && operandMatch.length == 3) {
filters[column.dataKey] = function(match) {
return function(x) {
if (x === null || x === undefined) return false;
return operators[match[1]](x, match[2]);
};
}(operandMatch);
} else {
if (filterText.indexOf("!=") == 0) {
filterText = filterText.substring(2);
filters[column.dataKey] = function(x) {
if (x === null || x === undefined) return true;
return (x.toString().toLowerCase().indexOf(filterText.toLowerCase()) == -1);
};
} else {
filters[column.dataKey] = function(x) {
if (x === null || x === undefined) return false;
return (x.toString().toLowerCase().indexOf(filterText.toLowerCase()) > -1);
};
}
}
}
}
}, this);
// filter the items
var filterFunc = function(item) {
for (var key in filters) {
if (key in item) {
if(!filters[key](item[key])) return false;
}else{
if(!filters[key](undefined)) return false;
}
}
return true;
}
return this.props.items.filter(filterFunc);
},
render: function() {
// kind of a hack so that we can get the table size at the beginning
// according to sizing config and the viewport
if (!("height" in this.state))
return React.DOM.div({
className: "rst_table",
style: {
width: this.props.width,
height: this.props.height
}
});
// filter the items
var items = this.getFilteredItems();
// sort the items
if(this.state.sortColumn) {
var sortedColumn = this.state.sortColumn;
var order = this.state.sortOrderAscending ? 1 : -1;
var key = sortedColumn; //this.state.sortColumn.dataKey;
items.sort(function(x, y) {
return (x[key] === y[key]) ? 0 : (x[key] > y[key] ? order : -order);
});
}
//recompute extents
// TODO optimize this madness
var rowsExtents = this.computeRowExtents(items);
var fixedColumnsExtents = this.computeColumnExtents(this.state.visibleFixedColumns);
var columnsExtents = this.computeColumnExtents(this.state.visibleColumns);
// outer size == viewport size
var width = this.state.width;
var height = this.state.height;
var leftWidth = fixedColumnsExtents[fixedColumnsExtents.length - 1];
var innerRightWidth = columnsExtents[columnsExtents.length - 1];
var headerHeight = this.props.headerHeight;
if(this.props.filterPresent) headerHeight += this.props.filterHeight;
var footerHeight = (this.props.footerPresent) ? this.props.footerHeight : 0;
var innerHeight = rowsExtents[rowsExtents.length - 1];
if (innerHeight == 0)
innerHeight = 1;
// handle case where height is set by its content
// TODO better support of scrollbar
if (this.props.height == "auto")
height = innerHeight + headerHeight + this.SB.height;
// handle case where width is bigger than its content
if (width > innerRightWidth + leftWidth + this.SB.width)
width = innerRightWidth + leftWidth + this.SB.width;
var outerRightWidth = width - leftWidth;
var rightHeaderWidth = outerRightWidth;
var bodyHeight = height - headerHeight - footerHeight;
var leftBodyHeight = bodyHeight;
// account for scrollbar
var verticalBarVisible = innerHeight > bodyHeight;
var horizontalBarVisible = innerRightWidth > outerRightWidth;
if (verticalBarVisible)
rightHeaderWidth -= this.SB.width;
if (horizontalBarVisible)
leftBodyHeight -= this.SB.height;
// right body decal
var scrollLeft = this.state.scrollLeft;
var scrollTop = this.state.scrollTop;
var rowSlice = this.getVisibleSlice(rowsExtents, scrollTop, scrollTop + height);
var grids = [];
var columns = this.state.visibleFixedColumns;
// compute left header cells and left body cells
if (columns.length > 0) {
var colSlice = {
begin: 0,
end: columns.length
};
var headerCells = this.renderHeader(colSlice, columns, fixedColumnsExtents);
var bodyCells = this.renderBody(colSlice, rowSlice, columns, fixedColumnsExtents, items, rowsExtents);
var header =
React.DOM.div({
key: "left_header",
ref: "left_header",
style: {
position: "absolute",
left: 0,
top: 0,
width: leftWidth,
height: headerHeight
},
className: "rst_left"
}, React.DOM.div({
style: {
position: "relative",
width: leftWidth,
height: headerHeight
},
className: "rst_thead"
}, headerCells));
var body =
React.DOM.div({
key: "left_body",
ref: "left_body",
style: {
position: "absolute",
left: 0,
top: headerHeight,
width: leftWidth,
height: leftBodyHeight,
overflowY: "hidden"
},
className: "rst_left"
}, React.DOM.div({
style: {
position: "relative",
width: leftWidth,
height: innerHeight
},
className: "rst_tbody"
}, bodyCells));
grids.push(header);
grids.push(body);
}
//var rightColumns = this.getAllColumns();
columns = this.state.visibleColumns;
// compute right header cells and right body cells
if (columns.length > 0) {
var colSlice = this.getVisibleSlice(columnsExtents, scrollLeft, scrollLeft + rightHeaderWidth);
var headerCells = this.renderHeader(colSlice, columns, columnsExtents);
var bodyCells = this.renderBody(colSlice, rowSlice, columns, columnsExtents, items, rowsExtents);
var header =
React.DOM.div({
key: "right_header",
ref: "right_header",
style: {
position: "absolute",
left: leftWidth,
top: 0,
width: rightHeaderWidth,
height: headerHeight,
overflowX: "hidden"
}
}, React.DOM.div({
style: {
position: "relative",
width: innerRightWidth,
height: headerHeight
},
className: "rst_thead"
}, headerCells));
var body =
React.DOM.div({
key: "right_body",
ref: "right_body",
tabIndex: 0, // needed to force focus :s
style: {
position: "absolute",
left: leftWidth,
top: headerHeight,
width: outerRightWidth,
height: bodyHeight,
overflowX: "auto",
overflowY: "auto"
},
className: "rst_tbody_container",
onScroll: this.onRightBodyScroll
}, React.DOM.div({
style: {
position: "relative",
width: innerRightWidth,
height: innerHeight
},
className: "rst_tbody"
}, bodyCells));
grids.push(header);
grids.push(body);
}
if (footerHeight > 0) {
var footer =
React.DOM.div({
key: "footer",
ref: "footer",
style: {
position: "absolute",
left: 0,
top: headerHeight + bodyHeight,
width: width,
height: footerHeight,
overflow: "hidden",
backgroundColor: "#EEE",
borderTop: "1px solid #CCC",
fontSize: "10px",
padding: "1px",
}
},
"Download ",
React.DOM.a({
onClick: this.downloadJSON,
download: "code.json"
}, "JSON"),
" - ",
React.DOM.a({
onClick: this.downloadCSV,
download: "code.csv"
}, "CSV")
);
grids.push(footer);
}
var containizer = React.DOM.div({
style: {
position: 'relative',
width: width,
height: height
}
}, grids);
var table_elem = React.DOM.div({
key: "table",
className: "rst_table",
style: {
position: 'relative',
width: this.props.width,
height: (this.props.height == 'fill') ? "auto" : this.props.height
}
}, containizer);
return table_elem;
},
downloadJSON: function(plop) {
var data = this.getFilteredItems();
var blob = new Blob([JSON.stringify(data)], {
type: "application/json;charset=utf-8"
});
saveAs(blob, "table_data.json");
},
downloadCSV: function(plop) {
var items = this.getFilteredItems();
var data = Object.keys(items[0]).join(";") + "\n"; // CSV Header
for (var row_id in items) {
var row = items[row_id];
var values = [];
for (var key in row) {
values.push(row[key]);
}
data = data.concat(values.join(";")) + "\n"; // CSV row
}
var blob = new Blob([data], {
type: "application/json;charset=utf-8"
});
saveAs(blob, "table_data.csv");
}
});
var Table = exports.Table = React.createFactory(T);
return exports;
}));