-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrollableTable.js
644 lines (467 loc) · 20.7 KB
/
scrollableTable.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
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
var scrollableTable = function(id, wrapperId, enableLogging=false) {
var logging = enableLogging
var root = this
var lastRowId = 0
var enabledSingleSelect = true
var metadata = {}
this.enableLogging = function(enabled = true) {
logging = enabled
}
/** ########### Metadata Functions ########### */
var resetMetadata = function(data = {}, columnNames = "", eventType = "", subtreePropertyName="") {
metadata = {
data: JSON.parse( JSON.stringify(data) ),
rowInfo: [],
eventType: eventType,
columnNames: columnNames,
subtreePropertyName: subtreePropertyName,
filter: [],
selectedRows: []
}
}
var initiallyPrepareMetaData = function(data, metadataRowInfo, parentId, level, nestedIds) {
$.each(data, function(index) {
var rowId = id+'_rowId_'+ (++lastRowId)
var parentRowId = id+'_rowId_'+parentId
var _ids = []
nestedIds.forEach((_i) => _ids.push(_i))
_ids.push(lastRowId)
replaceUndefinedThroughEmptyStringInDataEntry(data[index])
rowInfo = {
rowId: rowId,
id: lastRowId,
parentId: parentId,
parentRowId: parentRowId,
level: level,
displayed: true,
nestedIds: _ids,
expanded: false,
isSelected: false,
dataEntry: data[index],
rowInfoSubtree: [],
tableRow: null
}
metadataRowInfo.push(rowInfo)
if (metadata.subtreePropertyName.length > 0 &&
data[index][metadata.subtreePropertyName] !== undefined) {
var dataSubtree = data[index][metadata.subtreePropertyName]
var rowInfoSubtree = rowInfo.rowInfoSubtree
initiallyPrepareMetaData(dataSubtree, rowInfoSubtree, lastRowId, level+1, _ids)
}
})
}
function replaceUndefinedThroughEmptyStringInDataEntry(data) {
metadata.columnNames.forEach(cName => {
if (data[cName] === undefined) data[cName] = ''
})
}
/** ########### END Metadata Functions ########### */
/** ########### HTML Widget Functions ########### */
var createHtmlWidget = function() {
resetMetadata()
$('<section>').addClass("scrollableTableSection").append(
$('<div>').attr('id', id+'_scrollableTableContainer').addClass("scrollableTableContainer").append(
$('<table>').attr('id', id).addClass("scrollableTable").append(
$('<thead>').attr("id", id+"_scrollableTableHeader"), $('<tbody>') )
)).prependTo('#'+wrapperId);
$(document).keydown(function(e) {
if (e.key === "ArrowUp") {
selectPreviousRow()
if (!(isSelectedRowCloseToTop())) e.view.event.preventDefault()
}
else if (e.key === "ArrowDown") {
selectNextRow()
if (!(isSelectedRowCloseToBottom())) e.view.event.preventDefault()
}
else if (e.key === "ArrowRight") openCurrentRow()
else if (e.key === "ArrowLeft") closeCurrentRow()
})
}
this.setTableHeight = function(height) {
if ($.isFunction(height)) {
$('#'+id+'_scrollableTableContainer').height( height() )
// add listener for window resize events
$( window ).resize(function() {
$('.scrollableTableContainer').height( height )
})
} else {
$('#'+id+'_scrollableTableContainer').height( height )
}
}
/** ########### END HTML Widget Functions ########### */
/** ########### SCROLL FUNCTIONS ########### */
var isSelectedRowCloseToTop = function() {
if( metadata.selectedRows.length == 1) {
var rowId = metadata.selectedRows[0].rowId
if (($('#'+rowId).offset().top - $('#'+id+'_scrollableTableContainer').offset().top) < 50) return true
}
return false
}
var isSelectedRowCloseToBottom = function() {
if( metadata.selectedRows.length == 1) {
var rowId = metadata.selectedRows[0].rowId
var height = $('#'+id+'_scrollableTableContainer').height()
if ((height - $('#'+rowId).offset().top) < 50) return true
}
return false
}
/** ########### END SCROLL FUNCTIONS ########### */
/** ########### SELECTION OF ROWS ########### */
var showPointer = function() {
if (enabledSingleSelect) {
$('#'+id+' > tbody').css('cursor','pointer')
}
else {
$('#'+id+' > tbody').css('cursor','auto')
}
}
this.enableSingleSelect = function(enabled=true) {
enabledSingleSelect = enabled
if (!enabledSingleSelect) clearAllSelectedRows()
showPointer()
}
var clearAllSelectedRows = function() {
metadata.selectedRows.forEach( (rowInfo) => {
rowInfo.isSelected = false
showRowSelection(rowInfo)
})
metadata.selectedRows = []
}
var chickHandlerForSelectRow = function(rowInfo) {
if (enabledSingleSelect) {
var isSelected = rowInfo.isSelected
clearAllSelectedRows()
rowInfo.isSelected = !isSelected
if (rowInfo.isSelected) metadata.selectedRows.push(rowInfo)
showRowSelection(rowInfo)
if (rowInfo.isSelected) $(document).trigger( metadata.eventType, {rowId: rowInfo.rowId, data: rowInfo.dataEntry} )
else $(document).trigger( metadata.eventType, null )
if (logging) console.log("Selected Row id: "+rowInfo.rowId)
}
}
var showRowSelection = function(rowInfo) {
if (rowInfo.isSelected) {
$('#'+rowInfo.rowId).addClass("scrollableTableSelectedRow")
}
else {
$('#'+rowInfo.rowId).removeClass("scrollableTableSelectedRow")
}
}
var selectPreviousRow = function() {
// if (metadata.selectedRows.length == 1) {
var rowInfo = metadata.selectedRows[0]
var firstRow = $('#'+id+' > tbody > tr:first')
if (rowInfo.rowId != firstRow.attr('id')) {
var prevTR = $('#'+rowInfo.rowId).prev()
clearAllSelectedRows()
// click on row
prevTR.click()
}
// }
}
var selectNextRow = function() {
var rowInfo = metadata.selectedRows[0]
var lastRow = $('#'+id+' > tbody > tr:last')
if (rowInfo.rowId != lastRow.attr('id')) {
var nextTR = $('#'+rowInfo.rowId).next()
clearAllSelectedRows()
// click on row
nextTR.click()
}
}
/** ########### END SELECTION OF ROWS ########### */
/** ########### Collapse and Expand Functions ########### */
this.collapseTree = function() {
metadata.rowInfo.forEach( (rowInfo) => {
if (rowInfo.rowInfoSubtree.length > 0 && rowInfo.expanded) {
collapseSubtree(rowInfo.rowInfoSubtree)
}
})
}
var expandAllSubtrees = function(rowInfoArray) {
rowInfoArray.forEach( (rowInfo) => {
if (rowInfo.rowInfoSubtree.length > 0 && !rowInfo.expanded) {
rowInfo.expanded = true
createSubtree(rowInfo.rowInfoSubtree, rowInfo.tableRow)
expandAllSubtrees(rowInfo.rowInfoSubtree)
// refresh existing parent node
showTreeIcon(rowInfo)
}
})
}
this.expandTree = function() {
if (logging) console.log("expandTree")
expandAllSubtrees(metadata.rowInfo)
}
/** ########### End Collapse and Expand Functions ########### */
/** ########### CREATE TABLE FUNCTIONS ########### */
this.setTableHeader = function(names) {
// clear first
$('#'+id+' > thead').empty()
$('#'+id+' > thead').css('cursor', 'pointer')
// create headlines
var trElem = $('<tr>');
$.each(names, function(index, value) {
// Set header
trElem.append(
$('<th>')
.append($('<div>').text(value))
.click(() => {root.sortByColumnIndex(index)})
)
});
trElem.appendTo('#'+id+'_scrollableTableHeader')
}
/**
* let the browser calculate the width of the columns and then set this width to the div containers
*
* This function needs to be called after changing content of the table in order to adjust the header columns width
*/
var adjustHeaderSize = function() {
// set size to 0
$('#'+id+' > thead > tr').children('th').each(function () {
var divElem = $(this).children().first()
$(this).append( $('<span>').text(divElem.text()) )
divElem.width( 0 )
})
// Adjust size
$('#'+id+' > thead > tr').children('th').each(function () {
var div = $(this).children().first()
div.width( $(this).width() )
div.css('background-position-x', $(this).width()-15)
$(this).width( $(this).width() )
})
// remove text from th
// this is only needed so that the browser can calculate the original width
$('#'+id+' > thead > tr > th').children('span').remove()
$('#'+id+'_scrollableTableHeader > tr > th > div').addClass('scrollableTableHeaderBackground')
}
this.setTableContent = function(data, eventType, columnNames, subtreePropertyName="") {
if (subtreePropertyName === undefined) subtreePropertyName = ""
isTreeTable = subtreePropertyName != ""
resetMetadata(data, columnNames, eventType, subtreePropertyName)
initiallyPrepareMetaData(metadata.data, metadata.rowInfo, 0, 1, [])
root.refreshTableContent()
}
this.refreshTableContent = function() {
$('#'+id+' > tbody').empty()
createSubtree(metadata.rowInfo)
showPointer()
adjustHeaderSize()
}
/**
* creates the TR elements in the table, sets the style and adds all handlers
* @param {*} rowInfoArray list of meta info about the subtree elements as list
* @param {*} lastEnteredTR last TR element after which all new elements will be entered
*/
var createSubtree = function(rowInfoArray, lastEnteredTR=null) {
rowInfoArray.forEach((rowInfo) => {
// Create TR
rowInfo.tableRow = $('<tr>')
// add attributes
rowInfo.tableRow.attr('id', rowInfo.rowId)
rowInfo.tableRow.attr('level', rowInfo.level)
rowInfo.tableRow.attr('parentId', rowInfo.parentRowId)
rowInfo.tableRow.attr('findStr', rowInfo.dataEntry.findStr)
setTableRowVisibility(rowInfo)
// Create TDs (Columns)
// fill up cells
metadata.columnNames.forEach( (cName) => {
rowInfo.tableRow.append( $('<td>').text( rowInfo.dataEntry[cName] ))
})
// define click handler for selection
rowInfo.tableRow.click(() => { chickHandlerForSelectRow(rowInfo) })
// define click handler for expand / collapse tree
rowInfo.tableRow.click((event) => { clickHandlerForExpandAndCollapse(rowInfo, event) })
if (lastEnteredTR == null) rowInfo.tableRow.appendTo('#'+id)
else rowInfo.tableRow.insertAfter(lastEnteredTR)
showTreeIcon(rowInfo)
// display selected rows
// needs to be placed after attaching the TR element
showRowSelection(rowInfo)
lastEnteredTR = rowInfo.tableRow
// enter subtree
if (rowInfo.rowInfoSubtree.length > 0 && rowInfo.expanded) {
lastEnteredTR = createSubtree(rowInfo.rowInfoSubtree, lastEnteredTR)
}
})
return lastEnteredTR
}
var setTableRowVisibility = function(rowInfo) {
if (rowInfo.displayed) rowInfo.tableRow.css('display', '')
else rowInfo.tableRow.css('display', 'none')
}
/**
* Click handler which is called for expanding and collapsing a subtree
* @param {*} rowInfo
* @param {*} event
*/
var clickHandlerForExpandAndCollapse = function(rowInfo, event) {
const distIcon = (rowInfo.level-1)*16
var firstTD = rowInfo.tableRow.children().first()
var cursorPos = event.clientX - firstTD.offset().left - distIcon
var clickedOnIcon = (cursorPos < 16 && cursorPos >= 0)
if (clickedOnIcon) {
if (logging) console.log("Clicked on expand/collapse icon, id: "+rowInfo.rowId)
if (rowInfo.expanded) {
// collapse subtree
collapseSubtree(rowInfo.rowInfoSubtree)
} else {
// expand subtree
createSubtree(rowInfo.rowInfoSubtree, rowInfo.tableRow)
}
// store meta info about row
rowInfo.expanded = !rowInfo.expanded
showTreeIcon(rowInfo)
}
}
/**
* closes a subtree after clicking on the icon
* @param {*} rowInfoArray
*/
var collapseSubtree = function(rowInfoArray) {
rowInfoArray.forEach((rowInfo) => {
// start collapsing from bottom to top
if (rowInfo.rowInfoSubtree.length > 0) {
collapseSubtree(rowInfo.rowInfoSubtree)
rowInfo.expanded = false
}
$('#'+rowInfo.rowId).remove()
})
}
var showTreeIcon = function(rowInfo) {
// calc distance for collapse and expand icon
const distText = rowInfo.level*16
const distIcon = (rowInfo.level-1)*16
var firstTD = rowInfo.tableRow.children().first()
firstTD.attr('style', 'padding-left: '+distText+'px; ')
if (rowInfo.rowInfoSubtree.length > 0) {
firstTD.css('padding-left', distText)
firstTD.css('background-position-x', distIcon)
if (rowInfo.expanded) {
firstTD.removeClass("scrollableTableCollapsed")
firstTD.addClass("scrollableTableExpanded")
}
else {
firstTD.removeClass("scrollableTableExpanded")
firstTD.addClass("scrollableTableCollapsed")
}
}
}
this.clearTableContent = function(clearHead=false) {
lastSelectedRow = ""
resetMetadata()
if (clearHead) $('#'+id+' > thead').empty()
$('#'+id+' > tbody').empty()
}
/** ########### END CREATE TABLE FUNCTIONS ########### */
var getCellValueFromTable = function(row, column) {
return row.children().eq(column).text()
}
/** ########### SORT FUNCTIONS ########### */
this.sortByColumnName = function(columnName) {
var columnButton = $('#'+id+' > thead > tr > th:contains("'+columnName+'")')
var index = columnButton.parent().children().index(columnButton)
// error message
if (index == -1) {
var validNames = []
$('#'+id+' > thead > tr > th > div').each((i, div) => validNames.push(div.innerText))
console.log("'%s' is no valid column name. Valid names are: %s", columnName, JSON.stringify(validNames))
}
root.sortByColumnIndex(index)
}
this.sortByColumnIndex = function(columnIndex) {
var startMilli = performance.now()
var columnButton = $('#'+id+' > thead > tr > th').eq(columnIndex)
// swop sort directions
var sortDir = columnButton.attr('sortDir')
$('#'+id+' > thead > tr > th').removeAttr('sortDir');
if (sortDir === undefined) sortDir = 1
else sortDir = sortDir * -1
columnButton.attr('sortDir', sortDir)
// reset and set sort icons
$('#'+id+' > thead > tr > th > div').css('background-image', "url('css/unsorted-icon.png')")
if (sortDir == -1) columnButton.children('div').css('background-image', "url('css/dasc-icon.png')")
else columnButton.children('div').css('background-image', "url('css/asc-icon.png')")
if (logging) console.log("sort by column (Name: %s, Index: %d, direction: %d)", columnButton.text(), columnIndex, sortDir)
// actual sort function
sortSubtreeByColumn(metadata.rowInfo, metadata.columnNames[columnIndex], sortDir)
// remove all flags
$('#'+id+' > tbody > tr').removeAttr('subtreeSorted');
root.refreshTableContent()
if (logging) console.log("Sorting and redrawing the table took %d milli seconds.", (performance.now() - startMilli))
}
this.getSortInfo = function() {
var columnButton = $('#'+id+' > thead > tr > th[sortDir]')
var index = columnButton.parent().children().index(columnButton)
return {
isSorted: index > -1,
buttonObject: columnButton,
buttonText: columnButton.text(),
columnIndex: index,
sortDir: columnButton.attr('sortDir')
}
}
var defaultCompareFunction = function(a,b) {
return a.localeCompare(b, undefined, {usage: 'sort', numeric: true, sensitivity: 'base'})
}
var compareFunction = defaultCompareFunction
this.setCompareFunctionForSorting = function(f) {
compareFunction = f
}
var sortSubtreeByColumn = function(rowInfoArray, columnName, sortDir) {
rowInfoArray.sort( function(a,b) {
if (a.rowInfoSubtree.length > 0) {
sortSubtreeByColumn(a.rowInfoSubtree, columnName, sortDir)
}
return compareFunction(a.dataEntry[columnName].toString(), b.dataEntry[columnName]) * sortDir
})
root.refreshTableContent()
}
/** ########### END SORT FUNCTIONS ########### */
/** ########### FILTER FUNCTIONS ########### */
this.clearFilter = function() {
filter("")
}
this.filter = function(searchString) {
var startMilli = performance.now()
if (logging) console.log("Filter table: %s", JSON.stringify(searchString) )
metadata.filter = searchString.split(' ').filter(Boolean) // remove empty strings
filterMetadata(metadata.rowInfo)
if (logging) console.log("Filtering and redrawing the table took %d milli seconds.", (performance.now() - startMilli))
}
/**
* sets visibility in metadata and updates UI
* @param {*} rowInfoArray
* @returns if a child node is visible
*/
var filterMetadata = function(rowInfoArray) {
var anyVisible = false
rowInfoArray.forEach( (rowInfo) => {
// check if search strings are contained
rowInfo.displayed = containsRowSearchString(rowInfo)
// if node in subtree is visible then make parent visible as well
if (rowInfo.rowInfoSubtree.length > 0) rowInfo.displayed |= filterMetadata(rowInfo.rowInfoSubtree)
// check if one node is visible to return info for parent node
anyVisible |= rowInfo.displayed
// change visibility
setTableRowVisibility(rowInfo)
})
return anyVisible
}
var containsRowSearchString = function(rowInfo) {
for(var cIndex in metadata.columnNames) {
var cName = metadata.columnNames[cIndex]
if (rowInfo.dataEntry[cName] !== undefined) {
var text = rowInfo.dataEntry[cName].toString().toLowerCase()
if (metadata.filter.length == 0) return true
for(var sIndex in metadata.filter) {
var sStr = metadata.filter[sIndex]
if (text.indexOf(sStr) > -1) return true
}
}
}
return false
}
/** ########### END FILTER FUNCTIONS ########### */
createHtmlWidget()
}