forked from elastic/eui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_table.js
More file actions
643 lines (573 loc) Β· 18.3 KB
/
basic_table.js
File metadata and controls
643 lines (573 loc) Β· 18.3 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
import React, {
Component,
} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {
formatAuto, formatBoolean, formatDate, formatNumber, formatText, LEFT_ALIGNMENT, PropertySortType,
RIGHT_ALIGNMENT, SortDirection
} from '../../services';
import { isFunction } from '../../services/predicate';
import { get } from '../../services/objects';
import { EuiTable } from '../table/table';
import { EuiTableHeaderCellCheckbox } from '../table/table_header_cell_checkbox';
import { EuiCheckbox } from '../form/checkbox/checkbox';
import { EuiTableHeaderCell } from '../table/table_header_cell';
import { EuiTableHeader } from '../table/table_header';
import { EuiTableBody } from '../table/table_body';
import { EuiTableRowCellCheckbox } from '../table/table_row_cell_checkbox';
import { COLORS as BUTTON_ICON_COLORS } from '../button/button_icon/button_icon';
import { ICON_TYPES } from '../icon';
import { CollapsedItemActions } from './collapsed_item_actions';
import { ExpandedItemActions } from './expanded_item_actions';
import { EuiTableRowCell } from '../table/table_row_cell';
import { EuiTableRow } from '../table/table_row';
import { PaginationBar, PaginationType } from './pagination_bar';
import { EuiIcon } from '../icon/icon';
import { LoadingTableBody } from './loading_table_body';
const dataTypesProfiles = {
auto: {
align: LEFT_ALIGNMENT,
render: value => formatAuto(value)
},
string: {
align: LEFT_ALIGNMENT,
render: value => formatText(value)
},
number: {
align: RIGHT_ALIGNMENT,
render: value => formatNumber(value),
},
boolean: {
align: LEFT_ALIGNMENT,
render: value => formatBoolean(value),
},
date: {
align: LEFT_ALIGNMENT,
render: value => formatDate(value),
}
};
const DATA_TYPES = Object.keys(dataTypesProfiles);
const DefaultItemActionType = PropTypes.shape({
type: PropTypes.oneOf([ 'icon', 'button' ]), // default is 'button'
name: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired, // (item) => void,
available: PropTypes.func, // (item) => boolean;
enabled: PropTypes.func, // (item) => boolean;
icon: PropTypes.oneOfType([ // required when type is 'icon'
PropTypes.oneOf(ICON_TYPES),
PropTypes.func // (item) => oneOf(ICON_TYPES)
]),
color: PropTypes.oneOfType([
PropTypes.oneOf(BUTTON_ICON_COLORS),
PropTypes.func // (item) => oneOf(ICON_BUTTON_COLORS)
])
});
const CustomItemActionType = PropTypes.shape({
render: PropTypes.func.isRequired, // (item, enabled) => PropTypes.node;
available: PropTypes.func, // (item) => boolean;
enabled: PropTypes.func // (item) => boolean;
});
const SupportedItemActionType = PropTypes.oneOfType([
DefaultItemActionType,
CustomItemActionType
]);
const ActionsColumnType = PropTypes.shape({
actions: PropTypes.arrayOf(SupportedItemActionType).isRequired,
name: PropTypes.string,
description: PropTypes.string,
width: PropTypes.string
});
export const FieldDataColumnType = PropTypes.shape({
field: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
description: PropTypes.string,
dataType: PropTypes.oneOf(DATA_TYPES),
width: PropTypes.string,
sortable: PropTypes.bool,
align: PropTypes.oneOf([LEFT_ALIGNMENT, RIGHT_ALIGNMENT]),
truncateText: PropTypes.bool,
render: PropTypes.func // ((value, record) => PropTypes.node (also see [services/value_renderer] for basic implementations)
});
export const ComputedColumnType = PropTypes.shape({
render: PropTypes.func.isRequired, // (record) => PropTypes.node
name: PropTypes.string,
description: PropTypes.string,
width: PropTypes.string,
truncateText: PropTypes.bool
});
export const ColumnType = PropTypes.oneOfType([FieldDataColumnType, ComputedColumnType, ActionsColumnType]);
const ItemIdType = PropTypes.oneOfType([
PropTypes.string, // the name of the item id property
PropTypes.func // (item) => string
]);
export const SelectionType = PropTypes.shape({
itemId: ItemIdType.isRequired,
onSelectionChange: PropTypes.func, // (selection: Record[]) => void;,
selectable: PropTypes.func, // (item) => boolean;
selectableMessage: PropTypes.func // (selectable, item) => boolean;
});
const SortingType = PropTypes.shape({
sort: PropertySortType
});
const BasicTablePropTypes = {
items: PropTypes.array.isRequired,
columns: PropTypes.arrayOf(ColumnType).isRequired,
pagination: PaginationType,
sorting: SortingType,
selection: SelectionType,
onChange: PropTypes.func,
error: PropTypes.string,
loading: PropTypes.bool,
noItemsMessage: PropTypes.string,
className: PropTypes.string
};
export class EuiBasicTable extends Component {
static propTypes = BasicTablePropTypes;
static defaultProps = {
noItemsMessage: 'No items found'
};
constructor(props) {
super(props);
this.state = {
hoverRow: null,
selection: []
};
}
static buildCriteria(props) {
const criteria = {};
if (props.pagination) {
criteria.page = {
index: props.pagination.pageIndex,
size: props.pagination.pageSize
};
}
if (props.sorting) {
criteria.sort = props.sorting.sort;
}
return criteria;
}
itemId(item) {
const { selection } = this.props;
if (selection) {
if (isFunction(selection.itemId)) {
return selection.itemId(item);
}
return item[selection.itemId];
}
}
changeSelection(selection) {
if (!this.props.selection) {
return;
}
this.setState({ selection });
if (this.props.selection.onSelectionChange) {
this.props.selection.onSelectionChange(selection);
}
}
clearSelection() {
this.changeSelection([]);
}
onPageSizeChange(size) {
this.clearSelection();
const currentCriteria = EuiBasicTable.buildCriteria(this.props);
const criteria = {
...currentCriteria,
page: {
index: 0, // when page size changes, we take the user back to the first page
size
}
};
this.props.onChange(criteria);
}
onPageChange(index) {
this.clearSelection();
const currentCriteria = EuiBasicTable.buildCriteria(this.props);
const criteria = {
...currentCriteria,
page: {
...currentCriteria.page,
index
}
};
this.props.onChange(criteria);
}
onColumnSortChange(column) {
this.clearSelection();
const currentCriteria = EuiBasicTable.buildCriteria(this.props);
let direction = SortDirection.ASC;
if (currentCriteria && currentCriteria.sort && currentCriteria.sort.field === column.field) {
direction = SortDirection.reverse(currentCriteria.sort.direction);
}
const criteria = {
...currentCriteria,
// resetting the page if the criteria has one
page: !currentCriteria.page ? undefined : {
index: 0,
size: currentCriteria.page.size
},
sort: {
field: column.field,
direction
}
};
this.props.onChange(criteria);
}
onRowHover(row) {
this.setState({ hoverRow: row });
}
clearRowHover() {
this.setState({ hoverRow: null });
}
componentWillReceiveProps(nextProps) {
// Don't call changeSelection here or else we can get into an infinite loop:
// changeSelection calls props.onSelectionChanged on owner ->
// owner may react by changing props ->
// we receive new props, calling componentWillReceiveProps ->
// and we're in an infinite loop
if (!this.props.selection) {
return;
}
if (!nextProps.selection) {
this.setState({ selection: [] });
return;
}
this.setState(prevState => {
const selection = prevState.selection.filter(selectedItem => (
nextProps.items.findIndex(item => this.itemId(item) === this.itemId(selectedItem)) !== -1
));
return { selection };
});
}
render() {
const { className, loading } = this.props;
const classes = classNames(
'euiBasicTable',
{
'euiBasicTable-loading': loading
},
className
);
const table = this.renderTable();
const paginationBar = this.renderPaginationBar();
return (
<div className={classes}>
{table}
{paginationBar}
</div>
);
}
renderTable() {
const head = this.renderTableHead();
const body = this.renderTableBody();
return <EuiTable>{head}{body}</EuiTable>;
}
renderTableHead() {
const { items, columns, selection } = this.props;
const headers = [];
if (selection) {
const selectableItems = items.filter(item => (
!selection.selectable || selection.selectable(item)
));
const checked = this.state.selection &&
selectableItems.length > 0 &&
this.state.selection.length === selectableItems.length;
const disabled = selectableItems.length === 0;
const onChange = (event) => {
if (event.target.checked) {
this.changeSelection(selectableItems);
} else {
this.changeSelection([]);
}
};
headers.push(
<EuiTableHeaderCellCheckbox key="_selection_column_h" width="24px">
<EuiCheckbox
id="_selection_column-checkbox"
type="inList"
checked={checked}
disabled={disabled}
onChange={onChange}
data-test-subj="checkboxSelectAll"
/>
</EuiTableHeaderCellCheckbox>
);
}
columns.forEach((column, index) => {
// actions column
if (column.actions) {
headers.push(
<EuiTableHeaderCell
key={`_actions_h_${index}`}
align="right"
width={column.width}
>
{column.name}
</EuiTableHeaderCell>
);
return;
}
const align = this.resolveColumnAlign(column);
// computed column
if (!column.field) {
headers.push(
<EuiTableHeaderCell
key={`_computed_column_h_${index}`}
align={align}
width={column.width}
>
{column.name}
</EuiTableHeaderCell>
);
return;
}
// field data column
const sortDirection = this.resolveColumnSortDirection(column);
const onSort = this.resolveColumnOnSort(column);
const isSorted = !!sortDirection;
const isSortAscending = SortDirection.isAsc(sortDirection);
headers.push(
<EuiTableHeaderCell
key={`_data_h_${column.field}_${index}`}
align={align}
isSorted={isSorted}
isSortAscending={isSortAscending}
onSort={onSort}
width={column.width}
>
{column.name}
</EuiTableHeaderCell>
);
});
return <EuiTableHeader>{headers}</EuiTableHeader>;
}
renderTableBody() {
if (this.props.error) {
return this.renderErrorBody(this.props.error);
}
const { items } = this.props;
if (items.length === 0) {
return this.renderEmptyBody();
}
const rows = items.map((item, index) => {
return this.renderItemRow(item, index);
});
if (this.props.loading) {
return <LoadingTableBody>{rows}</LoadingTableBody>;
}
return <EuiTableBody>{rows}</EuiTableBody>;
}
renderErrorBody(error) {
const colSpan = this.props.columns.length + (this.props.selection ? 1 : 0);
return (
<EuiTableBody>
<EuiTableRow>
<EuiTableRowCell align="center" colSpan={colSpan}>
<EuiIcon type="minusInCircle" color="danger"/> {error}
</EuiTableRowCell>
</EuiTableRow>
</EuiTableBody>
);
}
renderEmptyBody() {
const colSpan = this.props.columns.length + (this.props.selection ? 1 : 0);
return (
<EuiTableBody>
<EuiTableRow>
<EuiTableRowCell align="center" colSpan={colSpan}>
<div>{ this.props.noItemsMessage }</div>
</EuiTableRowCell>
</EuiTableRow>
</EuiTableBody>
);
}
renderItemRow(item, rowIndex) {
const { columns, selection } = this.props;
const cells = [];
const itemId = selection ? this.itemId(item) : rowIndex;
const selected = !selection ? false : this.state.selection && !!this.state.selection.find(selectedRecord => (
this.itemId(selectedRecord) === itemId
));
if (selection) {
cells.push(this.renderItemSelectionCell(itemId, item, selected));
}
columns.forEach((column, columnIndex) => {
if (column.actions) {
cells.push(this.renderItemActionsCell(itemId, item, column, columnIndex, rowIndex));
} else if (column.field) {
cells.push(this.renderItemFieldDataCell(itemId, item, column, columnIndex));
} else {
cells.push(this.renderItemComputedCell(itemId, item, column, columnIndex));
}
});
const onMouseOver = () => this.onRowHover(rowIndex);
const onMouseOut = () => this.clearRowHover();
return (
<EuiTableRow
key={`row_${rowIndex}_${itemId}`}
isSelected={selected}
onMouseOver={onMouseOver}
onMouseOut={onMouseOut}
>
{cells}
</EuiTableRow>
);
}
renderItemSelectionCell(itemId, item, selected) {
const { selection } = this.props;
const key = `_selection_column_${itemId}`;
const checked = selected;
const disabled = selection.selectable && !selection.selectable(item);
const title = selection.selectableMessage && selection.selectableMessage(!disabled, item);
const onChange = (event) => {
if (event.target.checked) {
this.changeSelection([...this.state.selection, item]);
} else {
this.changeSelection(this.state.selection.reduce((selection, selectedItem) => {
if (this.itemId(selectedItem) !== itemId) {
selection.push(selectedItem);
}
return selection;
}, []));
}
};
return (
<EuiTableRowCellCheckbox key={key}>
<EuiCheckbox
id={`${key}-checkbox`}
type="inList"
disabled={disabled}
checked={checked}
onChange={onChange}
title={title}
data-test-subj={`checkboxSelectRow-${itemId}`}
/>
</EuiTableRowCellCheckbox>
);
}
renderItemActionsCell(itemId, item, column, columnIndex, rowIndex) {
const visible = this.state.hoverRow === rowIndex;
const actionEnabled = (action) =>
this.state.selection.length === 0 && (!action.enabled || action.enabled(item));
let actualActions = column.actions;
if (column.actions.length > 1) {
// if we have more than 1 action, we don't show them all in the cell, instead we
// put them all in a popover tool. This effectively means we can only have a maximum
// of one tool per row (it's either and normal action, or it's a popover that shows multiple actions)
//
// here we create a single custom action that triggers the popover with all the configured actions
actualActions = [
{
name: 'Actions',
render: (item) => {
return (
<CollapsedItemActions
actions={column.actions}
visible={visible}
itemId={itemId}
item={item}
actionEnabled={actionEnabled}
/>
);
}
}
];
}
const tools = (
<ExpandedItemActions
actions={actualActions}
visible={visible}
itemId={itemId}
item={item}
actionEnabled={actionEnabled}
/>
);
const key = `record_actions_${itemId}_${columnIndex}`;
return (
<EuiTableRowCell key={key} align="right" textOnly={false}>
{tools}
</EuiTableRowCell>
);
}
renderItemFieldDataCell(itemId, item, column, columnIndex) {
const key = `_data_column_${column.field}_${itemId}_${columnIndex}`;
const align = this.resolveColumnAlign(column);
const textOnly = !column.render;
const value = get(item, column.field);
const contentRenderer = this.resolveContentRenderer(column);
const content = contentRenderer(value, item);
return (
<EuiTableRowCell key={key} align={align} truncateText={column.truncateText} textOnly={textOnly}>
{content}
</EuiTableRowCell>
);
}
renderItemComputedCell(itemId, item, column, columnIndex) {
const key = `_computed_column_${itemId}_${columnIndex}`;
const align = this.resolveColumnAlign(column);
const contentRenderer = this.resolveContentRenderer(column);
const content = contentRenderer(item);
return (
<EuiTableRowCell key={key} align={align} truncateText={column.truncateText} textOnly={false}>
{content}
</EuiTableRowCell>
);
}
resolveColumnAlign(column) {
if (column.align) {
return column.align;
}
const dataType = column.dataType || 'auto';
const profile = dataTypesProfiles[dataType];
if (!profile) {
throw new Error(`Unknown dataType [${dataType}]. The supported data types are [${DATA_TYPES.join(', ')}]`);
}
return profile.align;
}
resolveColumnSortDirection(column) {
const { sorting } = this.props;
if (!sorting || !sorting.sort || !column.sortable) {
return;
}
if (sorting.sort.field === column.field) {
return sorting.sort.direction;
}
}
resolveColumnOnSort(column) {
if (column.sortable) {
if (!this.props.onChange) {
throw new Error(`BasicTable is configured to be sortable on column [${column.field}] but
[onChange] is not configured. This callback must be implemented to handle the sort requests`);
}
return () => this.onColumnSortChange(column);
}
}
resolveContentRenderer(column) {
if (column.render) {
return column.render;
}
const dataType = column.dataType || 'auto';
const profile = dataTypesProfiles[dataType];
if (!profile) {
throw new Error(`Unknown dataType [${dataType}]. The supported data types are [${DATA_TYPES.join(', ')}]`);
}
return profile.render;
}
renderPaginationBar() {
const { error, pagination, onChange } = this.props;
if (!error && pagination) {
if (!onChange) {
throw new Error(`The Basic Table is configured with pagination but [onChange] is
not configured. This callback must be implemented to handle pagination changes`);
}
return (
<PaginationBar
pagination={pagination}
onPageSizeChange={this.onPageSizeChange.bind(this)}
onPageChange={this.onPageChange.bind(this)}
/>
);
}
}
}