forked from apache/superset
-
Notifications
You must be signed in to change notification settings - Fork 5
/
FilterableTable.jsx
483 lines (441 loc) · 14.5 KB
/
FilterableTable.jsx
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { List } from 'immutable';
import PropTypes from 'prop-types';
import JSONbig from 'json-bigint';
import React, { PureComponent } from 'react';
import JSONTree from 'react-json-tree';
import {
Column,
Grid,
ScrollSync,
SortDirection,
SortIndicator,
Table,
} from 'react-virtualized';
import { getMultipleTextDimensions } from '@superset-ui/dimension';
import { t } from '@superset-ui/translation';
import Button from '../Button';
import CopyToClipboard from '../CopyToClipboard';
import ModalTrigger from '../ModalTrigger';
import TooltipWrapper from '../TooltipWrapper';
function safeJsonObjectParse(data) {
// First perform a cheap proxy to avoid calling JSON.parse on data that is clearly not a
// JSON object or array
if (typeof data !== 'string' || ['{', '['].indexOf(data.substring(0, 1)) === -1) {
return null;
}
// We know `data` is a string starting with '{' or '[', so try to parse it as a valid object
try {
const jsonData = JSON.parse(data);
if (jsonData && typeof jsonData === 'object') {
return jsonData;
}
return null;
} catch (_) {
return null;
}
}
const SCROLL_BAR_HEIGHT = 15;
const GRID_POSITION_ADJUSTMENT = 4;
const JSON_TREE_THEME = {
scheme: 'monokai',
author: 'wimer hazenberg (http://www.monokai.nl)',
base00: '#272822',
base01: '#383830',
base02: '#49483e',
base03: '#75715e',
base04: '#a59f85',
base05: '#f8f8f2',
base06: '#f5f4f1',
base07: '#f9f8f5',
base08: '#f92672',
base09: '#fd971f',
base0A: '#f4bf75',
base0B: '#a6e22e',
base0C: '#a1efe4',
base0D: '#66d9ef',
base0E: '#ae81ff',
base0F: '#cc6633',
};
// when more than MAX_COLUMNS_FOR_TABLE are returned, switch from table to grid view
export const MAX_COLUMNS_FOR_TABLE = 50;
const propTypes = {
orderedColumnKeys: PropTypes.array.isRequired,
data: PropTypes.array.isRequired,
height: PropTypes.number.isRequired,
filterText: PropTypes.string,
headerHeight: PropTypes.number,
overscanColumnCount: PropTypes.number,
overscanRowCount: PropTypes.number,
rowHeight: PropTypes.number,
striped: PropTypes.bool,
expandedColumns: PropTypes.array,
};
const defaultProps = {
filterText: '',
headerHeight: 32,
overscanColumnCount: 10,
overscanRowCount: 10,
rowHeight: 32,
striped: true,
expandedColumns: [],
};
export default class FilterableTable extends PureComponent {
constructor(props) {
super(props);
this.list = List(this.formatTableData(props.data));
this.addJsonModal = this.addJsonModal.bind(this);
this.getCellContent = this.getCellContent.bind(this);
this.renderGridCell = this.renderGridCell.bind(this);
this.renderGridCellHeader = this.renderGridCellHeader.bind(this);
this.renderGrid = this.renderGrid.bind(this);
this.renderTableCell = this.renderTableCell.bind(this);
this.renderTableHeader = this.renderTableHeader.bind(this);
this.sortResults = this.sortResults.bind(this);
this.renderTable = this.renderTable.bind(this);
this.rowClassName = this.rowClassName.bind(this);
this.sort = this.sort.bind(this);
// columns that have complex type and were expanded into sub columns
this.complexColumns = props.orderedColumnKeys
.reduce((obj, key) => ({
...obj,
[key]: props.expandedColumns.some(name => name.startsWith(key + '.')),
}), {});
this.widthsForColumnsByKey = this.getWidthsForColumns();
this.totalTableWidth = props.orderedColumnKeys
.map(key => this.widthsForColumnsByKey[key])
.reduce((curr, next) => curr + next);
this.totalTableHeight = props.height;
this.state = {
sortBy: null,
sortDirection: SortDirection.ASC,
fitted: false,
};
this.container = React.createRef();
}
componentDidMount() {
this.fitTableToWidthIfNeeded();
}
getDatum(list, index) {
return list.get(index % list.size);
}
getWidthsForColumns() {
const PADDING = 40; // accounts for cell padding and width of sorting icon
const widthsByColumnKey = {};
const cellContent = [].concat(...this.props.orderedColumnKeys.map(key =>
this.list
.map(data => this.getCellContent({ cellData: data[key], columnKey: key }))
.push(key)
.toJS(),
));
const colWidths = getMultipleTextDimensions(
{
className: 'cell-text-for-measuring',
texts: cellContent,
},
).map(dimension => dimension.width);
this.props.orderedColumnKeys.forEach((key, index) => {
// we can't use Math.max(...colWidths.slice(...)) here since the number
// of elements might be bigger than the number of allowed arguments in a
// Javascript function
widthsByColumnKey[key] = colWidths.slice(
index * (this.list.size + 1),
(index + 1) * (this.list.size + 1),
).reduce((a, b) => Math.max(a, b)) + PADDING;
});
return widthsByColumnKey;
}
getCellContent({ cellData, columnKey }) {
if (cellData === null) {
return (
<i className="text-muted">
NULL
</i>
);
}
const content = String(cellData);
const firstCharacter = content.substring(0, 1);
let truncated;
if (firstCharacter === '[') {
truncated = '[…]';
} else if (firstCharacter === '{') {
truncated = '{…}';
} else {
truncated = '';
}
return this.complexColumns[columnKey] ? truncated : content;
}
formatTableData(data) {
const formattedData = data.map((row) => {
const newRow = {};
for (const k in row) {
const val = row[k];
if (['string', 'number'].indexOf(typeof (val)) >= 0) {
newRow[k] = val;
} else {
newRow[k] = val === null ? null : JSONbig.stringify(val);
}
}
return newRow;
});
return formattedData;
}
hasMatch(text, row) {
const values = [];
for (const key in row) {
if (row.hasOwnProperty(key)) {
const cellValue = row[key];
if (typeof cellValue === 'string') {
values.push(cellValue.toLowerCase());
} else if (cellValue !== null && typeof cellValue.toString === 'function') {
values.push(cellValue.toString());
}
}
}
const lowerCaseText = text.toLowerCase();
return values.some(v => v.includes(lowerCaseText));
}
rowClassName({ index }) {
let className = '';
if (this.props.striped) {
className = index % 2 === 0 ? 'even-row' : 'odd-row';
}
return className;
}
sort({ sortBy, sortDirection }) {
this.setState({ sortBy, sortDirection });
}
fitTableToWidthIfNeeded() {
const containerWidth = this.container.clientWidth;
if (this.totalTableWidth < containerWidth) {
// fit table width if content doesn't fill the width of the container
this.totalTableWidth = containerWidth;
}
this.setState({ fitted: true });
}
addJsonModal(node, jsonObject, jsonString) {
return (
<ModalTrigger
modalBody={<JSONTree data={jsonObject} theme={JSON_TREE_THEME} />}
modalFooter={<Button><CopyToClipboard shouldShowText={false} text={jsonString} /></Button>}
modalTitle={t('Cell Content')}
triggerNode={node}
/>
);
}
sortResults(sortBy, descending) {
return (a, b) => {
if (a[sortBy] === b[sortBy]) {
// equal items sort equally
return 0;
} else if (a[sortBy] === null) {
// nulls sort after anything else
return 1;
} else if (b[sortBy] === null) {
return -1;
} else if (descending) {
return a[sortBy] < b[sortBy] ? 1 : -1;
}
return a[sortBy] < b[sortBy] ? -1 : 1;
};
}
renderTableHeader({ dataKey, label, sortBy, sortDirection }) {
const className = this.props.expandedColumns.indexOf(label) > -1
? 'header-style-disabled'
: 'header-style';
return (
<TooltipWrapper label="header" tooltip={label}>
<div className={className}>
{label}
{sortBy === dataKey &&
<SortIndicator sortDirection={sortDirection} />
}
</div>
</TooltipWrapper>
);
}
renderGridCellHeader({ columnIndex, key, style }) {
const label = this.props.orderedColumnKeys[columnIndex];
const className = this.props.expandedColumns.indexOf(label) > -1
? 'header-style-disabled'
: 'header-style';
return (
<TooltipWrapper key={key} label="header" tooltip={label}>
<div
style={{ ...style, top: style.top - GRID_POSITION_ADJUSTMENT }}
className={`${className} grid-cell grid-header-cell`}
>
{label}
</div>
</TooltipWrapper>
);
}
renderGridCell({ columnIndex, key, rowIndex, style }) {
const columnKey = this.props.orderedColumnKeys[columnIndex];
const cellData = this.list.get(rowIndex)[columnKey];
const content = this.getCellContent({ cellData, columnKey });
const cellNode = (
<div
key={key}
style={{ ...style, top: style.top - GRID_POSITION_ADJUSTMENT }}
className={`grid-cell ${this.rowClassName({ index: rowIndex })}`}
>
{content}
</div>
);
const jsonObject = safeJsonObjectParse(cellData);
if (jsonObject) {
return this.addJsonModal(cellNode, jsonObject, cellData);
}
return cellNode;
}
renderGrid() {
const { orderedColumnKeys, overscanColumnCount, overscanRowCount, rowHeight } = this.props;
let { height } = this.props;
let totalTableHeight = height;
if (this.container && this.totalTableWidth > this.container.clientWidth) {
// exclude the height of the horizontal scroll bar from the height of the table
// and the height of the table container if the content overflows
height -= SCROLL_BAR_HEIGHT;
totalTableHeight -= SCROLL_BAR_HEIGHT;
}
const getColumnWidth = ({ index }) => this.widthsForColumnsByKey[orderedColumnKeys[index]];
// fix height of filterable table
return (
<ScrollSync>
{({ onScroll, scrollTop }) => (
<div
style={{ height }}
className="filterable-table-container Table"
ref={this.container}
>
<div className="LeftColumn">
<Grid
cellRenderer={this.renderGridCellHeader}
columnCount={orderedColumnKeys.length}
columnWidth={getColumnWidth}
height={rowHeight}
rowCount={1}
rowHeight={rowHeight}
scrollTop={scrollTop}
width={this.totalTableWidth}
/>
</div>
<div className="RightColumn">
<Grid
cellRenderer={this.renderGridCell}
columnCount={orderedColumnKeys.length}
columnWidth={getColumnWidth}
height={totalTableHeight - rowHeight}
onScroll={onScroll}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
rowCount={this.list.size}
rowHeight={rowHeight}
width={this.totalTableWidth}
/>
</div>
</div>
)}
</ScrollSync>
);
}
renderTableCell({ cellData, columnKey }) {
const cellNode = this.getCellContent({ cellData, columnKey });
const jsonObject = safeJsonObjectParse(cellData);
if (jsonObject) {
return this.addJsonModal(cellNode, jsonObject, cellData);
}
return cellNode;
}
renderTable() {
const { sortBy, sortDirection } = this.state;
const {
filterText,
headerHeight,
orderedColumnKeys,
overscanRowCount,
rowHeight,
} = this.props;
let sortedAndFilteredList = this.list;
// filter list
if (filterText) {
sortedAndFilteredList = this.list.filter(row => this.hasMatch(filterText, row));
}
// sort list
if (sortBy) {
sortedAndFilteredList = sortedAndFilteredList
.sort(this.sortResults(sortBy, sortDirection === SortDirection.DESC));
}
let { height } = this.props;
let totalTableHeight = height;
if (this.container && this.totalTableWidth > this.container.clientWidth) {
// exclude the height of the horizontal scroll bar from the height of the table
// and the height of the table container if the content overflows
height -= SCROLL_BAR_HEIGHT;
totalTableHeight -= SCROLL_BAR_HEIGHT;
}
const rowGetter = ({ index }) => this.getDatum(sortedAndFilteredList, index);
return (
<div
style={{ height }}
className="filterable-table-container"
ref={this.container}
>
{this.state.fitted &&
<Table
ref="Table"
headerHeight={headerHeight}
height={totalTableHeight}
overscanRowCount={overscanRowCount}
rowClassName={this.rowClassName}
rowHeight={rowHeight}
rowGetter={rowGetter}
rowCount={sortedAndFilteredList.size}
sort={this.sort}
sortBy={sortBy}
sortDirection={sortDirection}
width={this.totalTableWidth}
>
{orderedColumnKeys.map(columnKey => (
<Column
cellRenderer={({ cellData }) => this.renderTableCell({ cellData, columnKey })}
dataKey={columnKey}
disableSort={false}
headerRenderer={this.renderTableHeader}
width={this.widthsForColumnsByKey[columnKey]}
label={columnKey}
key={columnKey}
/>
))}
</Table>
}
</div>
);
}
render() {
if (this.props.orderedColumnKeys.length > MAX_COLUMNS_FOR_TABLE) {
return this.renderGrid();
}
return this.renderTable();
}
}
FilterableTable.propTypes = propTypes;
FilterableTable.defaultProps = defaultProps;