This repository was archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 970
/
Copy pathsortableTable.js
593 lines (558 loc) · 19.7 KB
/
sortableTable.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
const React = require('react')
const Immutable = require('immutable')
const tableSort = require('tablesort')
const KeyCodes = require('../../../common/constants/keyCodes')
const {StyleSheet, css} = require('aphrodite/no-important')
const globalStyles = require('../styles/global')
// Utils
const cx = require('../../../../js/lib/classSet')
const eventUtil = require('../../../../js/lib/eventUtil')
tableSort.extend('number', (item) => {
return typeof item === 'number'
}, (a, b) => {
a = isNaN(a) ? 0 : a
b = isNaN(b) ? 0 : b
return b - a
})
class SortableTable extends React.Component {
constructor (props) {
super(props)
this.onClick = this.onClick.bind(this)
this.onContextMenu = this.onContextMenu.bind(this)
this.onKeyDown = this.onKeyDown.bind(this)
this.onTableDragStart = this.onTableDragStart.bind(this)
this.state = {
selection: Immutable.Set()
}
this.counter = 0
this.sortTable = null
}
componentDidMount () {
this.sortTable = tableSort(this.table)
return this.sortTable
}
componentDidUpdate (prevProps) {
if (this.props.rows &&
(!prevProps.rows ||
prevProps.rows.length !== this.props.rows.length)) {
this.clearSelection()
this.sortTable.refresh()
}
}
/**
* If you want multi-select to span multiple tables, you can
* provide a single React.Component as the state owner.
* NOTE: The state owner must have a state.selection property available.
* (ignored unless multi-select is specified)
*/
get stateOwner () {
return this.props.multiSelect
? this.props.stateOwner
? this.props.stateOwner
: this
: this
}
get nullSelection () {
return this.props.multiSelect
? this.stateOwner.state.selection.size === 0
: false
}
get multipleItemsSelected () {
return this.props.multiSelect
? this.stateOwner.state.selection.size > 1
: false
}
/**
* If multi-select spans multiple tables (ex: it has a state owner),
* tableID must be unique between all tables for which that state is bound.
* (ignored unless multi-select and state owner are specified)
*/
get tableID () {
return this.props.multiSelect && this.props.stateOwner
? this.props.tableID || 0
: 0
}
/**
* Creates a multi-table-safe index using the tableID.
*/
getGlobalIndex (index) {
return this.tableID + '-' + index
}
/**
* [CmdOrCtrl + click] selection can span multiple tables.
* (ignored unless multi-select is specified)
*/
processControlClick (index) {
const globalIndex = this.getGlobalIndex(index)
this.stateOwner.setState({
selection: this.stateOwner.state.selection.includes(globalIndex)
? this.stateOwner.state.selection.delete(globalIndex)
: this.stateOwner.state.selection.add(globalIndex)
})
}
/**
* Converts a data-row-index property to an HTML element's rowIndex within the
* table. rowIndex changes when the table is sorted.
* @param {number} index
*/
rowIndexToHTMLRowIndex (index) {
const element = this.table.querySelector(`tr[data-row-index="${index}"]`)
return element.rowIndex
}
/**
* Converts an HTML element's rowIndex within the
* table to its data-row-index property.
* @param {number} index
*/
htmlRowIndexToRowIndex (index) {
const element = this.table.rows[index]
return parseInt(element.getAttribute('data-row-index'))
}
/**
* [Shift + click] can only multi-select within the same table.
* @param {number} index - The rowIndex attribute of the row element
*/
processShiftClick (index) {
let newSelection = Immutable.Set()
this.stateOwner.state.selection.forEach((globalIndex) => {
const tableParts = globalIndex.split('-')
const tableID = parseInt(tableParts[0])
const rowIndex = this.rowIndexToHTMLRowIndex(parseInt(tableParts[1]))
if (tableID === this.tableID) {
let startIndex
let endIndex
if (rowIndex < index) {
startIndex = rowIndex
endIndex = index
} else if (rowIndex > index) {
startIndex = index
endIndex = rowIndex
} else {
return
}
for (let i = startIndex; i <= endIndex; ++i) {
newSelection = newSelection.add(this.getGlobalIndex(this.htmlRowIndexToRowIndex(i)))
}
}
})
this.stateOwner.setState({
selection: newSelection
})
}
/**
* Regular click (clear selection and toggle the value if already set).
* (ignored unless multi-select is specified)
*/
processClick (index) {
const globalIndex = this.getGlobalIndex(index)
this.stateOwner.setState({
selection: this.stateOwner.state.selection.includes(globalIndex)
? Immutable.Set()
: Immutable.Set().add(globalIndex)
})
}
/**
* Clear all selected items.
* (ignored unless multi-select is specified)
*/
clearSelection () {
this.stateOwner.setState({
selection: Immutable.Set()
})
}
/**
* Used by onClick to find the row that was clicked.
* (ignored unless multi-select is specified)
*/
getRowElement (e) {
// Work backwards until element is TR
let targetElement = e.target
while (targetElement) {
if (targetElement.tagName === 'TR') break
targetElement = targetElement.parentNode
}
return targetElement
}
/**
* Handle click, shift + click, and CmdOrCtrl + click
* (ignored unless multi-select is specified)
*/
onClick (e) {
const targetElement = this.getRowElement(e)
if (!targetElement) return
const clickedIndex = parseInt(targetElement.getAttribute('data-row-index'))
if (eventUtil.isForSecondaryAction(e)) {
this.processControlClick(clickedIndex)
} else if (e.shiftKey) {
this.processShiftClick(targetElement.rowIndex)
} else {
this.processClick(clickedIndex)
}
}
getSelectedRowObjects () {
const handlerInputs = []
this.stateOwner.state.selection.forEach((globalIndex) => {
const tableParts = globalIndex.split('-')
const tableID = parseInt(tableParts[0])
const rowIndex = parseInt(tableParts[1])
const handlerInput = this.props.totalRowObjects
? (typeof this.props.totalRowObjects[parseInt(tableID)][rowIndex].toJS === 'function'
? this.props.totalRowObjects[parseInt(tableID)][rowIndex].toJS()
: this.props.totalRowObjects[parseInt(tableID)][rowIndex])
: (this.props.rowObjects.size > 0 || this.props.rowObjects.length > 0)
? (typeof this.props.rowObjects.toJS === 'function'
? this.props.rowObjects.get(rowIndex).toJS()
: this.props.rowObjects[rowIndex])
: null
if (handlerInput) {
handlerInputs.push(handlerInput)
}
})
return handlerInputs
}
/**
* Handle right-click context menu for multiple selected items.
* (ignored unless multi-select is specified)
*/
onContextMenu (e) {
const handlerInputs = this.getSelectedRowObjects()
if (handlerInputs.length && this.hasContextMenu) {
if (handlerInputs.length === 1) {
this.props.onContextMenu(handlerInputs[0], this.props.contextMenuName, e)
} else {
this.props.onContextMenu(handlerInputs, this.props.contextMenuName, e)
}
}
}
/**
* Handle keydown
*/
onKeyDown (e) {
if (e.keyCode === KeyCodes.BACKSPACE && this.props.onDelete) {
const handlerInputs = this.getSelectedRowObjects()
if (handlerInputs) {
this.props.onDelete(handlerInputs)
}
}
}
/**
* Alternate drag start handler for when multiple items are selected.
* (ignored unless multi-select is specified AND multiple items are selected)
*/
onTableDragStart (e) {
// Set the ghost drag icon to default of SVG of multiple pages
// TODO: does this cause a memory leak if you continually drag items?
const dragImage = document.createElement('img')
dragImage.src = require('../../../../img/cursor_multi_copy_pages.svg')
e.dataTransfer.setDragImage(dragImage, 15, 30)
// Call the provided onDragStart handler with the list of selected objects
const thisArg = this.props.thisArg || this
const handlerInputs = this.getSelectedRowObjects()
this.props.onDragStart.call(thisArg, Immutable.fromJS(handlerInputs), e)
}
get hasClickHandler () {
return typeof this.props.onClick === 'function'
}
get hasColumnClassNames () {
return this.props.columnClassNames &&
this.props.columnClassNames.length === this.props.headings.length
}
get hasBodyClassNames () {
return this.props.bodyClassNames &&
this.props.bodyClassNames.length === this.props.rows.length
}
get hasContextMenu () {
return typeof this.props.onContextMenu === 'function' &&
typeof this.props.contextMenuName === 'string'
}
get isMultiDimensioned () {
return this.props.rows &&
Array.isArray(this.props.rows[0]) &&
(Array.isArray(this.props.rows[0][0]) || this.props.rows[0].length === 0) &&
this.entryMultiDimension
}
get entryMultiDimension () {
for (let i = 0; i < this.props.rows.length; i++) {
if (this.props.rows[i].length > 0) {
return this.props.rows[i]
}
}
return undefined
}
get sortingDisabled () {
if (typeof this.props.sortingDisabled === 'boolean') {
return this.props.sortingDisabled
}
return false
}
hasRowClassNames (bodyIndex) {
if (this.isMultiDimensioned) {
return this.props.rowClassNames &&
this.props.rowClassNames[bodyIndex].length === this.props.rows[bodyIndex].length
}
return this.props.rowClassNames &&
this.props.rowClassNames.length === this.props.rows.length
}
getTableAttributes () {
const tableAttributes = {}
if (this.props.multiSelect && this.multipleItemsSelected) {
if (typeof this.props.onDragStart === 'function') {
tableAttributes.onDragStart = this.onTableDragStart
tableAttributes.draggable = true
}
}
tableAttributes.tabIndex = 0
tableAttributes.onKeyDown = this.onKeyDown
return tableAttributes
}
getRowAttributes (row, index, bodyIndex) {
const rowAttributes = {}
let handlerInput
// Object bound to this row. Not passed to multi-select handlers.
if (this.isMultiDimensioned) {
// Object bound to this row. Not passed to multi-select handlers.
handlerInput = this.props.rowObjects[bodyIndex] &&
(this.props.rowObjects[bodyIndex].size > 0 || this.props.rowObjects[bodyIndex].length > 0)
? (typeof this.props.rowObjects[bodyIndex].toJS === 'function'
? this.props.rowObjects[bodyIndex].get(index).toJS()
: (typeof this.props.rowObjects[bodyIndex][index].toJS === 'function'
? this.props.rowObjects[bodyIndex][index].toJS()
: this.props.rowObjects[bodyIndex][index]))
: row
} else {
handlerInput = this.props.rowObjects &&
(this.props.rowObjects.size > 0 || this.props.rowObjects.length > 0)
? (typeof this.props.rowObjects.toJS === 'function'
? this.props.rowObjects.get(index).toJS()
: (typeof this.props.rowObjects[index].toJS === 'function'
? this.props.rowObjects[index].toJS()
: this.props.rowObjects[index]))
: row
}
// Allow parent control to optionally specify context
const thisArg = this.props.thisArg || this
// Optionally add class to each row for easy hover styling
if (this.props.addHoverClass) {
rowAttributes.className = 'rowHover'
}
// Bindings for multi-select-specific event handlers
if (this.props.multiSelect) {
// Table supports multi-select
rowAttributes.onClick = this.onClick
if (this.nullSelection && this.hasContextMenu) {
// If nothing is selected yet, offer a default per-item context menu
rowAttributes.onContextMenu = this.props.onContextMenu.bind(this, handlerInput, this.props.contextMenuName)
} else {
// If items are selected we must use the multiple item handler
rowAttributes.onContextMenu = this.onContextMenu
}
} else {
// Table does not support multi-select
if (this.hasContextMenu) {
rowAttributes.onContextMenu = this.props.onContextMenu.bind(this, handlerInput, this.props.contextMenuName)
}
if (this.hasClickHandler) {
rowAttributes.onClick = this.props.onClick.bind(thisArg, handlerInput)
}
}
// Bindings for row-specific event handlers
if (typeof this.props.onDoubleClick === 'function') {
rowAttributes.onDoubleClick = this.props.onDoubleClick.bind(thisArg, handlerInput)
}
// Only bind the ROW SPECIFIC onDragStart handler if:
// - one or no items are selected
// - onDragStart has a value
// When multiple items are selected, the drag
// handler is bound at the TABLE level.
if (!(this.props.multiSelect && this.multipleItemsSelected)) {
if (typeof this.props.onDragStart === 'function') {
rowAttributes.onDragStart = this.props.onDragStart.bind(thisArg, Immutable.fromJS(handlerInput))
rowAttributes.draggable = true
}
}
if (typeof this.props.onDragOver === 'function') {
rowAttributes.onDragOver = this.props.onDragOver.bind(thisArg, Immutable.fromJS(handlerInput))
}
if (typeof this.props.onDrop === 'function') {
rowAttributes.onDrop = this.props.onDrop.bind(thisArg, Immutable.fromJS(handlerInput))
}
return rowAttributes
}
generateTableRows (rows, bodyIndex) {
return rows.map((row, i) => {
const entry = row.map((item, j) => {
const value = typeof item === 'object' ? item.value : item
const html = typeof item === 'object' ? item.html : item
const cell = typeof item === 'object' ? item.cell : item
let hasColumnClassNames = (this.hasColumnClassNames ? this.props.columnClassNames[j] : '')
let customCellClassesStr = (this.props.customCellClasses ? this.props.customCellClasses : '')
return <td className={cx({
[hasColumnClassNames]: true,
[customCellClassesStr]: true,
[css(styles.table__tbody__tr__td, this.props.smallRow && styles.table__tbody__tr_smallRow__td)]: true
})}
data-sort={value} data-td-index={`${j}`}>
{
cell || (value === true ? '✕' : html)
}
</td>
})
const currentIndex = this.counter
this.counter ++
const rowAttributes = row.length
? this.getRowAttributes(row, i, bodyIndex)
: null
const classes = []
if (rowAttributes) classes.push(rowAttributes.className)
if (this.hasRowClassNames(bodyIndex)) {
if (this.isMultiDimensioned) {
classes.push(this.props.rowClassNames[bodyIndex][i])
} else {
classes.push(this.props.rowClassNames[i])
}
}
if (this.stateOwner.state.selection.includes(this.getGlobalIndex(currentIndex))) classes.push('selected')
return row.length
? <tr {...rowAttributes}
data-context-menu-disable={rowAttributes && rowAttributes.onContextMenu ? true : undefined}
data-table-id={this.tableID}
data-row-index={`${currentIndex}`}
className={cx({
[css(styles.table__tbody__tr, this.props.largeRow && styles.table__tbody__tr_largeRow)]: true,
[classes.join(' ')]: classes
})}>{entry}</tr>
: null
})
}
generateTableBody () {
this.counter = 0
if (this.isMultiDimensioned) {
return this.props.rows.map((rows, i) => {
const content = this.generateTableRows(rows, i)
return (content.length > 0)
? <tbody className={this.hasBodyClassNames ? this.props.bodyClassNames[i] : undefined} data-tbody-index={`${i}`}>
{content}
</tbody>
: null
})
} else {
return <tbody>{this.generateTableRows(this.props.rows)}</tbody>
}
}
render () {
if (!this.props.headings || !this.props.rows) {
return false
}
return <table
{...this.getTableAttributes()}
className={cx({
sort: !this.sortingDisabled,
sortableTable: true,
[this.props.tableClassNames]: !!this.props.tableClassNames,
[css(styles.table, this.props.fillAvailable && styles.table_fillAvailable)]: true
})}
ref={(node) => { this.table = node }}>
<thead>
<tr>
{this.props.headings.map((heading, j) => {
const firstRow = this.isMultiDimensioned ? this.entryMultiDimension[0] : this.props.rows[0]
const firstEntry = (firstRow && firstRow.length > 0)
? firstRow[j]
: undefined
let dataType = typeof firstEntry
if (dataType === 'object' && firstEntry.value) {
dataType = typeof firstEntry.value
}
const headerClasses = {
'sort-header': true,
'sort-default': this.sortingDisabled || heading === this.props.defaultHeading,
[css(styles.table__th)]: true
}
const isString = typeof heading === 'string'
const sortMethod = this.sortingDisabled ? 'none' : (dataType === 'number' ? 'number' : undefined)
if (isString) headerClasses['heading-' + heading] = true
return <th className={cx(headerClasses)}
data-sort-method={sortMethod}
data-sort-order={this.props.defaultHeadingSortOrder}
>
{
isString
? <div className={cx({
'th-inner': true,
[css(styles.table__th__inner, this.props.smallRow && styles.table__th__inner_smallRow)]: true,
[this.props.headerClassNames]: !!this.props.headerClassNames
})} data-l10n-id={heading} />
: heading
}
</th>
})}
</tr>
</thead>
{this.generateTableBody()}
</table>
}
}
const styles = StyleSheet.create({
// By default the width and margin are not specified.
// It can be specified by setting css to tableClassNames.
// See 'styles.devices__devicesList' on syncTab.js for example.
table: {
outline: 'none',
boxSizing: 'border-box',
cursor: 'default',
borderSpacing: 0,
// #10434: Enable border on the table by default
borderCollapse: 'collapse'
},
// Setting 'fillAvailable' maximizes the width of the table.
table_fillAvailable: {
width: '-webkit-fill-available'
},
table__th: {
background: `linear-gradient(to bottom, ${globalStyles.color.lightGray}, ${globalStyles.color.veryLightGray})`,
borderTop: `1px solid ${globalStyles.color.gray}`,
borderLeft: `1px solid ${globalStyles.color.braveOrange}`,
textAlign: 'left',
fontWeight: 300,
padding: '1ch',
whiteSpace: 'nowrap',
// Up/down arrow
':after': {
fontFamily: 'FontAwesome',
fontSize: '8pt',
marginLeft: '4px',
position: 'relative',
bottom: '2px'
},
':first-child': {
borderLeft: 'none'
}
},
table__th__inner: {
display: 'inline-block',
userSelect: 'none'
},
// See ledgerTable.js for an example
table__th__inner_smallRow: {
fontSize: '14px'
},
table__tbody__tr: {
height: '1rem'
},
// Add 'largeRow' to SortableTable to increase the height of tr.
table__tbody__tr_largeRow: {
height: '4rem'
},
table__tbody__tr__td: {
padding: '.5ch 1ch'
},
// Add 'smallRow' to SortableTable to decrease padding-top and padding-bottom of td.
table__tbody__tr_smallRow__td: {
paddingTop: '.3ch',
paddingBottom: '.3ch'
}
})
module.exports = SortableTable