| 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 |
6x
6x
6x
6x
6x
6x
6x
6x
6x
6x
1x
1x
1x
1x
1x
1x
1x
8x
8x
8x
8x
1x
1x
1x
1x
1x
1x
1x
8x
8x
8x
8x
1x
8x
30x
30x
8x
8x
8x
8x
8x
8x
18x
18x
8x
18x
1x
8x
27x
81x
81x
27x
8x
2x
8x
8x
8x
1x
8x
1x
1x
| import React from 'react';
import PropTypes from 'prop-types';
import LoadStatus from '../utilities/load-status.jsx';
import SearchBar from '../form/pieces/search-bar.jsx';
class DataTable extends React.Component {
constructor(props) {
super(props);
this.state = {
// Table sorting && searching states
sortOrder: this.props.defaultSortOrder,
searchFilter: null, // Handles display changes
searchQuery: null, // Handles display changes
dataSearchForm: { // Handles search form changes
filter: this.props.searchCategory instanceof Array ? (this.props.searchCategory[0] || null) : this.props.searchCategory,
query: null
},
// Pagination states
page: this.props.page,
pageCount: this.props.pageCount || Math.ceil((this.props.totalSize || this.props.data.length) / this.props.sizePerPage),
pageSet: [1],
totalSize: this.props.totalSize || this.props.data.length,
sizePerPage: this.props.sizePerPage,
// Table data states
tableData: this.props.data,
headerData: this.props.headers
};
this.setPaginatorList = this.setPaginatorList.bind(this);
this.returnPaginatedData = this.returnPaginatedData.bind(this);
this.onChangePageSize = this.onChangePageSize.bind(this);
this.onPageChange = this.onPageChange.bind(this);
this.onSortChange = this.onSortChange.bind(this);
this.onSearchSubmit = this.onSearchSubmit.bind(this);
this.onSearchCategoryChange = this.onSearchCategoryChange.bind(this);
this.returnFilteredData = this.returnFilteredData.bind(this);
}
componentDidMount() {
this.setHeaderList();
this.setPaginatorList();
}
componentWillReceiveProps(nextProps) {
this.setState({
tableData: nextProps.data,
page: nextProps.page,
pageCount: nextProps.pageCount || (nextProps.data.length / nextProps.sizePerPage),
totalSize: nextProps.totalSize || nextProps.data.length,
sizePerPage: nextProps.sizePerPage
}, () => {
this.setHeaderList();
this.setPaginatorList();
});
}
// Sets the sort order for all of the dataset
setHeaderList() {
let headers = this.state.headerData.length > 0 ? this.state.headerData.map(header => {
if (this.props.sorts && !header.sortOrder) {
header.sortOrder = this.state.sortOrder || 'asc';
}
return header;
}) : [];
this.state.tableData.forEach(datum => {
let keys = Object.keys(datum).filter(key => {
let matched = false;
for (let h = 0; h < headers.length; h++) {
if (headers[h].id === key) {
matched = true;
break;
}
}
return !matched;
});
keys = keys.map(key => {
return {
id: key,
content: key,
sortOrder: this.state.sortOrder || 'asc'
};
});
headers = headers.concat(keys).filter(header => {
let ignored = false;
for (let id = 0; id < this.props.ignoreData.length; id++) {
if (this.props.ignoreData[id] === header.id) {
ignored = true;
break;
}
}
return !ignored;
});
});
this.setState({ headerData: headers });
}
// Sets the pagination page list display data
setPaginatorList() {
const pageSet = [];
const currentPage = this.state.page;
let minSetCount = 1;
let maxSetCount = this.state.pageCount;
Iif (this.state.pageCount > 5) {
switch (true) {
case (currentPage <= maxSetCount - 5):
minSetCount = currentPage;
break;
case (currentPage > maxSetCount - 5):
minSetCount = maxSetCount - 5;
break;
default: break;
}
maxSetCount = minSetCount + 4;
}
for (let i = minSetCount; i <= maxSetCount; i++) { pageSet.push(i); }
this.setState({ pageSet });
}
// Sets the size shown per page, setting the state to that.
onChangePageSize(sizePerPage) {
if (this.props.onPageSizeChange) {
this.props.onPageSizeChange(sizePerPage);
} else {
this.setState({
page: 1,
sizePerPage: sizePerPage,
pageCount: Math.ceil(this.state.totalSize / sizePerPage)
}, this.setPaginatorList);
}
}
// Handles setting the current page when the page is called to change.
onPageChange(page) {
if (this.props.onPageChange) {
this.props.onPageChange(page);
} else {
let pageSet = this.state.pageSet;
if (page > this.state.page) {
if ((page === pageSet[3] || page === pageSet[4]) && (pageSet.indexOf(this.state.pageCount) < 0)) {
pageSet.push(pageSet[4] + 1);
pageSet.shift();
if (page === pageSet[4]) {
pageSet.push(pageSet[4] + 1);
pageSet.shift();
}
} else if (page === this.state.pageCount && this.state.pageCount > 5) {
pageSet = [];
for (let i = this.state.pageCount - 4; i <= this.state.pageCount; i++) { pageSet.push(i); }
}
} else {
if ((page === pageSet[1] || page === pageSet[0]) && (pageSet.indexOf(1) < 0)) {
pageSet.unshift(pageSet[0] - 1);
pageSet.pop();
if (page === pageSet[0]) {
pageSet.unshift(pageSet[0] - 1);
pageSet.pop();
}
} else if (page === 1 && this.state.pageCount > 5) {
pageSet = [];
for (let i = 1; i <= 5; i++) { pageSet.push(i); }
}
}
this.setState({ page: page, pageSet: pageSet });
}
}
// Handles displaying data associated with a page
returnPaginatedData() {
const data = this.returnFilteredData();
const min = (this.state.page - 1) * this.state.sizePerPage;
const max = (this.state.page * this.state.sizePerPage) >= this.state.totalSize ? this.state.totalSize : this.state.page * this.state.sizePerPage;
return this.props.remote ? data : data.slice(min, max);
}
// Upon clicking a header sort button, change sort order of that column
onSortChange(columnIndex) {
Eif (this.props.sorts) {
Iif (this.props.onSortChange) {
// Sends the user back the data id to be sorted && the current sort state
this.props.onSortChange(headers[columnIndex].id, headers[columnIndex].sortOrder);
} else {
// Sets this.state.headerData sort
const formerSortOrder = this.state.headerData[columnIndex].sortOrder;
const headers = this.state.headerData;
headers[columnIndex].sortOrder = formerSortOrder === 'asc' ? 'desc' : 'asc';
// Sets this.state.tableData sort
const data = this.state.tableData;
data.sort((a, b) => {
const aSorter = a[headers[columnIndex].id] === null || a[headers[columnIndex].id] === undefined ? '' : a[headers[columnIndex].id];
const bSorter = b[headers[columnIndex].id] === null || b[headers[columnIndex].id] === undefined ? '' : b[headers[columnIndex].id];
Eif (typeof aSorter === 'string' || typeof bSorter === 'string') {
return headers[columnIndex].sortOrder === 'asc' ? aSorter.localeCompare(`${bSorter}`) : bSorter.localeCompare(`${aSorter}`);
}
return headers[columnIndex].sortOrder === 'asc' ? aSorter - bSorter : bSorter - aSorter;
});
this.setState({ headerData: headers, tableData: data, page: 1 }, this.setPaginatorList);
}
}
}
// If there are multiple categories to search by, this sets the next chosen category
onSearchCategoryChange(e) {
const dataSearchForm = this.state.dataSearchForm;
dataSearchForm.filter = e.currentTarget.value === 'all' ? null : e.currentTarget.value;
this.setState({ dataSearchForm });
}
// Searches / Filters and returns X data to display
onSearchSubmit(query = null, filter = this.state.dataSearchForm.filter) {
if (this.props.onSearchSubmit) {
this.props.onSearchSubmit(query, filter);
} else {
const currentSearchParams = this.state.dataSearchForm;
currentSearchParams.filter = filter;
currentSearchParams.query = query;
this.setState({
dataSearchForm: currentSearchParams,
searchFilter: filter,
searchQuery: query
}, () => {
const dataSize = query ? this.returnFilteredData().length : (this.props.totalSize || this.props.data.length);
this.setState({
page: 1,
totalSize: dataSize,
pageCount: Math.ceil(dataSize / this.state.sizePerPage)
}, this.setPaginatorList);
});
}
}
returnFilteredData() {
return this.state.tableData.filter(dataset => {
// Filters the data based on search parameters
Iif (this.state.searchQuery) {
if (this.state.searchFilter) {
return `${dataset[this.state.searchFilter]}`.toLowerCase().includes(this.state.searchQuery.toLowerCase());
} else {
let hasRelevantContent = false;
const keys = Object.keys(dataset);
for (let k = 0; k < keys.length; k++) {
if (`${dataset[keys[k]]}`.toLowerCase().includes(this.state.searchQuery.toLowerCase())) {
hasRelevantContent = true;
break;
}
}
return hasRelevantContent;
}
}
return dataset;
});
}
// Renders the page. What else?
render() {
const filteredData = this.returnPaginatedData();
const striped = this.props.striped ? ' table-striped' : '';
const condensed = this.props.condensed ? ' table-condensed' : '';
const bordered = this.props.bordered ? ' table-bordered' : '';
const hovers = this.props.hovers ? ' table-hover' : '';
const columnStyles = filteredData.length > 0 && this.state.headerData.length > 0 ? (
<colgroup>
{this.state.headerData.map((column, c) => {
const width = typeof column === 'string' || Object.keys(column).indexOf('width') < 0 ? this.props.defaultColumnWidth : column.width;
return <col key={c} style={{ width: width, minWidth: width }} />;
})}
</colgroup>
) : null;
const headers = filteredData.length > 0 && this.state.headerData.length > 0 ? (
<thead>
<tr>
{this.state.headerData.map((header, h) => {
/*
this.props.headers expects
{
id: 'dataId',
content: 'Header Text',
width: '100px',
format: (cellData, rowData, rowId) => {},
sortOrder: 'asc' || 'desc'
}
*/
return (
<th
key={h}
onClick={() => { Eif (this.props.sorts && !header.noSort) { this.onSortChange(h); } }}
>
{typeof header === 'string' ? header : header.content}
{this.props.sorts && !header.noSort && (typeof header === 'string' || header.content) ? ' ' : ''}
{this.props.sorts && !header.noSort ? (
<small>
<i className={`fa ${header.sortOrder === 'asc' ? 'fa-sort-amount-asc' : 'fa-sort-amount-desc'} text-muted`} />
</small>
) : null}
</th>
);
})}
</tr>
</thead>
) : null;
const content = filteredData.length > 0 ? filteredData.map((dataset, ds) => {
const cells = this.state.headerData.length !== 0 ? this.state.headerData.map((header, h) => {
const cellDatum = dataset[header.id] || null;
return <td key={h}>{header.format ? header.format(cellDatum, this.state.tableData[ds], ds) : cellDatum}</td>;
}) : Object.keys(dataset).map((datum, d) => {
return <td key={d}>{dataset[datum]}</td>;
});
return <tr key={ds}>{cells}</tr>;
}) : <tr className="datatable-no-data text-center"><td><p>{this.props.noDataMessage}</p></td></tr>;
const searchFilter = this.props.search && this.props.searchCategory instanceof Array && this.props.searchCategory.length > 1 ? (
<div className="col-xs-12 col-sm-4">
<select
id={`${this.props.id}-datatable-searchbar-select`}
name={`${this.props.id}-datatable-searchbar-select`}
className="form-control"
onChange={this.onSearchCategoryChange}
value={this.state.dataSearchForm.filter || 'all'}
disabled={this.state.loading}
>
{this.props.searchCategory.map((category, c) => {
return (
<option key={c} value={category}>
{category}
</option>
);
})}
{this.props.hideSearchAny ? '' : (
<option key={this.props.searchCategory.length} value="all">*</option>
)}
</select>
</div>
) : null;
const searchbar = !this.props.search ? '' : (
<div className={`col-xs-12${this.props.searchCategory instanceof Array && this.props.searchCategory.length > 1 ? '' : ' col-sm-offset-4'} col-sm-8`}>
<SearchBar
id={`${this.props.id}-datatable-searchbar`}
placeholder={this.props.searchPlaceholder}
searchHandler={this.onSearchSubmit}
disabled={this.state.loading}
/>
</div>
);
const pageCount = !this.props.pagination || this.props.hideSizePerPage ? '' : (
<select
className="form-control input-sm datatable-data-per-page-selector"
onChange={e => { this.onChangePageSize(e.currentTarget.value); }}
>
{this.props.sizePerPageList.map((size, s) => {
return (<option key={s} value={size}>{size}</option>);
})}
</select>
);
const pageList = !this.props.pagination ? '' : (
<ul className="pagination datatable-pagination">
{this.state.pageSet.indexOf(1) < 0 ? (
<li className="paginate_button previous">
<a onClick={() => { this.onPageChange(1); }}><<</a>
</li>
) : null}
{this.state.page !== 1 ? (
<li className="paginate_button previous">
<a onClick={() => { this.onPageChange(this.state.page - 1); }}><</a>
</li>
) : null}
{this.state.pageSet.map((pageNum, pn) => {
return (
<li key={pn} className={`paginate_button${this.state.page === pageNum ? ' active' : ''}`}>
<a onClick={() => { if (this.state.page !== pageNum) { this.onPageChange(pageNum); } }}>{pageNum}</a>
</li>
);
})}
{this.state.page !== this.state.pageCount ? (
<li className="paginate_button next">
<a onClick={() => { this.onPageChange(this.state.page + 1); }}>></a>
</li>
) : null}
{this.state.pageSet.indexOf(this.state.pageCount) < 0 ? (
<li className="paginate_button next">
<a onClick={() => { this.onPageChange(this.state.pageCount); }}>>></a>
</li>
) : null}
</ul>
);
return (
<div>
{this.props.search ? (
<div className="datatable-searchbar-container row">
{searchFilter}
{searchbar}
</div>
) : null}
<div className="row">
<div className="col-sm-12">
<div className="datatable-container">
<table id={this.props.id} className={`datatable table${striped}${condensed}${bordered}${hovers}`}>
{columnStyles}
{headers}
<tbody>{content}</tbody>
</table>
</div>
</div>
</div>
{this.props.pagination ? (
<div className="row">
<div className="col-xs-4 col-sm-2">
{pageCount}
</div>
<div className="col-xs-8 col-sm-10 text-right">
{pageList}
</div>
</div>
) : null}
{!this.props.loading ? null : (
<div className="load-status-container text-center align-middle">
<LoadStatus size="4em" color={this.props.loadColor} spins />
</div>
)}
</div>
);
}
}
DataTable.propTypes = {
// Props regarding markup && styling
id: PropTypes.string,
loading: PropTypes.bool,
loadColor: PropTypes.string,
defaultColumnWidth: PropTypes.string,
striped: PropTypes.bool,
condensed: PropTypes.bool,
bordered: PropTypes.bool,
hovers: PropTypes.bool,
noDataMessage: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]),
searchPlaceholder: PropTypes.string,
searchCategory: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array
]),
hideSearchAny: PropTypes.bool,
// Props regarding data handling
headers: PropTypes.array,
data: PropTypes.array,
defaultSortOrder: PropTypes.string,
search: PropTypes.bool,
ignoreData: PropTypes.array,
sorts: PropTypes.bool,
onSortChange: PropTypes.func,
// Props regarding pagination || remote data handling
pagination: PropTypes.bool,
sizePerPage: PropTypes.number,
totalSize: PropTypes.number,
page: PropTypes.number,
pageCount: PropTypes.number,
onPageChange: PropTypes.func,
sizePerPageList: PropTypes.array,
hideSizePerPage: PropTypes.bool,
onPageSizeChange: PropTypes.func,
remote: PropTypes.bool,
onSearchSubmit: PropTypes.func
};
DataTable.defaultProps = {
// Props regarding markup && styling
id: '',
loading: false,
loadColor: '#BBBBBB',
defaultColumnWidth: 'auto',
striped: false,
condensed: false,
bordered: false,
hovers: false,
noDataMessage: 'No Data Loaded',
searchPlaceholder: 'Search the table',
searchCategory: [],
hideSearchAny: false,
// Props regarding data handling
headers: [],
data: [],
defaultSortOrder: 'asc',
search: false,
ignoreData: [],
sorts: false,
// Props regarding pagination || remote data handling
pagination: false,
sizePerPage: 20,
totalSize: 0,
page: 1,
pageCount: 0,
sizePerPageList: [5, 10, 20, 50, 100],
hideSizePerPage: false,
remote: false
};
export default DataTable;
|