-
Notifications
You must be signed in to change notification settings - Fork 6
/
simpleTree.js
568 lines (523 loc) · 20.3 KB
/
simpleTree.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
/* ============================================================================
MIT LICENSE
Copyright (c) 2019 eScience-Center, University of Tübingen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
============================================================================ */
;(function($){
$.fn.simpleTree = function(options, data) {
// ============================================================================
if(this.length > 1) {
this.each(function() {
$(this).simpleTree(options, data);
});
return this;
}
// ========================================================================
//
// PUBLIC METHODS
//
// ========================================================================
// ------------------------------------------------------------------------
// set the selected node
this.getSelectedNode = function(
) {
// ------------------------------------------------------------------------
return _selectedNode;
}
// ------------------------------------------------------------------------
// sets the selected node
this.setSelectedNode = function(
node,
fireEvent = true
) {
// ------------------------------------------------------------------------
if(node === _selectedNode)
return;
this.clearSelection(false);
this.expandTo(node);
node.domLabel.addClass(_options.css.selected);
_selectedNode = node;
if(fireEvent)
this.trigger('simpleTree:change', [ _selectedNode ]);
return this;
}
// ------------------------------------------------------------------------
// clears the selected node, if any
this.clearSelection = function(
fireEvent = true
) {
// ------------------------------------------------------------------------
if(!_selectedNode)
return this;
_selectedNode.domLabel.removeClass(_options.css.selected);
_selectedNode = undefined;
if(fireEvent)
this.trigger('simpleTree:change', [ _selectedNode ]);
return this;
}
// ------------------------------------------------------------------------
// get total node count
this.getNodeCount = function(
) {
// ------------------------------------------------------------------------
return _nodeCount;
}
// ------------------------------------------------------------------------
// expand all nodes
this.expandAll = function(
) {
// ------------------------------------------------------------------------
return this.traverseTree((node) => {
if(node.children.length > 0 && !node.expanded)
this.toggleSubtree(node);
});
}
// ------------------------------------------------------------------------
// collapse all nodes
this.collapseAll = function(
) {
// ------------------------------------------------------------------------
return this.traverseTree((node) => {
if(node.children.length > 0 && node.expanded)
this.toggleSubtree(node);
});
}
// ------------------------------------------------------------------------
// traverse all tree nodes
this.traverseTree = function(
callback,
startNode = undefined
) {
// ------------------------------------------------------------------------
if(startNode === undefined)
startNode = { children: _treeData };
startNode.children.forEach(childNode => {
callback(childNode);
if(childNode.children.length > 0)
this.traverseTree(callback, childNode);
});
return this;
}
// ------------------------------------------------------------------------
// expands/collapses node with children
this.toggleSubtree = function(
node
) {
// ------------------------------------------------------------------------
if(node.children.length === 0) {
console.warn('Invoked toggleSubtree on node with no children');
return this;
}
if(node.expanded)
node.domChildren.hide();
else {
// expand ancestor nodes if needed
if(node.parent && !node.parent.expanded)
this.toggleSubtree(node.parent);
if(node.domChildren.children().length > 0)
node.domChildren.show();
else
node.children.forEach(child => _renderNode(child));
}
node.expanded = !node.expanded;
node.domContainer
.find('.' + _options.css.toggle)
.first()
.text(_options.symbols[node.expanded ? 'expanded' : 'collapsed']);
return this;
}
// ------------------------------------------------------------------------
// retrieves node object from node value
this.getNodeFromValue = function(
value
) {
// ------------------------------------------------------------------------
return _nodeValueMap[value];
}
// ------------------------------------------------------------------------
// ensures node is visible; only works if node is shown - see expandTo()
this.scrollTo = function(
node
) {
// ------------------------------------------------------------------------
let nt = node.domContainer.offset().top,
nh = node.domContainer.height(),
dt = this.offset().top,
dh = this.height();
if(nt < dt || nt + nh > dt + dh) {
this.animate({
scrollTop: nt - dt - dh / 2 // scroll to middle of the tree
});
}
}
// ------------------------------------------------------------------------
// expand the ancestry of the given node
this.expandTo = function(
node
) {
// ------------------------------------------------------------------------
if(node.parent && !node.parent.expanded)
this.toggleSubtree(node.parent);
return this;
}
// ------------------------------------------------------------------------
// node is visible if the whole ancestry is visible and expanded and the
// node itself is not hidden
this.isNodeVisible = function(
node
) {
// ------------------------------------------------------------------------
// the DOM container must exist
if(!node.domContainer)
return false;
// the container must not be hidden
if(node.domContainer.hasClass('hidden'))
return false;
// if there's no parent, we're fine
if(!node.parent)
return true;
if(!node.parent.expanded)
return false;
return this.isNodeVisible(node.parent);
}
// ------------------------------------------------------------------------
// shows the node in the DOM
this.showNode = function(
node
) {
// ------------------------------------------------------------------------
if(node.domContainer)
node.domContainer.removeClass('hidden');
if(node.domChildren)
node.domChildren.removeClass('hidden');
return this;
}
// ------------------------------------------------------------------------
// hides the node in the DOM
this.hideNode = function(
node
) {
// ------------------------------------------------------------------------
if(node.domContainer)
node.domContainer.addClass('hidden');
if(node.domChildren)
node.domChildren.addClass('hidden');
return this;
}
// ------------------------------------------------------------------------
// toggles node visibility in the DOM
this.toggleNodeVisibility = function(
node
) {
// ------------------------------------------------------------------------
return this.isNodeVisible(node)
? this.hideNode(node)
: this.showNode(node);
}
// ========================================================================
//
// PRIVATE VARIABLES
//
// ========================================================================
var _self = this;
var _selectedNode;
var _lastSearchTerm;
var _nodeValueMap;
var _options;
var _treeData;
var _nodeCount;
// Default options, can be overriden when initializing the jQuery object
var _defaults = {
// Optionally provide here the jQuery element that you use as the
// search box for filtering the tree. simplTree then takes control
// over the provided box, handling user input
searchBox: undefined,
// Search starts after at least 3 characters are entered in the
// search box
searchMinInputLength: 3,
// Number of pixels to indent each additional nesting level
indentSize: 25,
// Show child count badges?
childCountShow: true,
// Symbols for expanded and collapsed nodes that have child nodes
symbols: {
collapsed: '▶',
expanded: '▼'
},
// these are the CSS class names used on various occasions.
// If you change these names, you also need to provide
// the corresponding CSS class. See simpleTree.css
css: {
childrenContainer: 'simpleTree-childrenContainer',
childCountBadge: 'simpleTree-childCountBadge badge badge-pill badge-secondary',
highlight: 'simpleTree-highlight',
indent: 'simpleTree-indent',
label: 'simpleTree-label',
mainContainer: 'simpleTree-mainContainer',
nodeContainer: 'simpleTree-nodeContainer',
selected: 'simpleTree-selected',
toggle: 'simpleTree-toggle'
}
};
// ========================================================================
//
// PRIVATE FUNCTIONS
//
// ========================================================================
// ------------------------------------------------------------------------
var _nodeClicked = function(
node
) {
// ------------------------------------------------------------------------
if(node === _selectedNode)
_self.clearSelection(true);
else
_self.setSelectedNode(node);
}
// ------------------------------------------------------------------------
var _htmlEncode = function(
text
) {
// ------------------------------------------------------------------------
return $('<textarea/>').text(text).html();
}
// ------------------------------------------------------------------------
var _renderNodeLabelText = function(
node
) {
// ------------------------------------------------------------------------
if(!node.domLabel)
return;
if(!_lastSearchTerm)
node.domLabel.text(node.label);
else {
let remaining = node.label;
let label = '';
while(remaining !== '') {
let pos = remaining.toUpperCase().indexOf(_lastSearchTerm);
if(pos === -1) {
label += _htmlEncode(remaining);
break;
}
else {
label += (
_htmlEncode(remaining.substr(0, pos))
+ "<span class='" + _options.css.highlight + "'>"
+ _htmlEncode(remaining.substr(pos, _lastSearchTerm.length))
+ "</span>"
);
remaining = remaining.substr(pos + _lastSearchTerm.length);
}
}
node.domLabel.html(label);
}
}
// ------------------------------------------------------------------------
var _renderNode = function(
node
) {
// ------------------------------------------------------------------------
let div = $('<div/>').addClass(_options.css.nodeContainer);
div.append($('<div/>').addClass(_options.css.indent).css({
width: (node.children.length > 0 ? node.indent : (node.indent + 1)) * _options.indentSize
}));
if(node.children.length > 0) {
node.domToggle = $('<div/>')
.css({ width: _options.indentSize })
.addClass(_options.css.toggle)
.text(node.expanded ? _options.symbols.expanded : _options.symbols.collapsed);
node.domToggle.on('click', () => {
if(!node.domToggle.hasClass('disabled'))
_self.toggleSubtree(node)
});
div.append(node.domToggle);
}
node.domLabel = $('<div/>').addClass(_options.css.label)
.on('click', () => _nodeClicked(node));
_renderNodeLabelText(node);
div.append(node.domLabel);
if(node.children.length > 0 && _options.childCountShow) {
div.append($('<span/>')
.addClass(_options.css.childCountBadge)
.text(node.children.length)
);
}
div.data('node', node);
if(node.parent) {
if(!node.parent.domChildren)
_renderNode(node.parent);
node.parent.domChildren.append(div);
}
else
_self.append(div);
node.domContainer = div;
if(node.children.length > 0)
node.domChildren = $('<div/>').addClass(_options.css.childrenContainer).insertAfter(div);
if(node.expanded)
node.children.forEach(child => _renderNode(child));
}
// ------------------------------------------------------------------------
var _setSearchInfo = function(
node
) {
// ------------------------------------------------------------------------
if(!node.upperLabel)
node.upperLabel = node.label.toUpperCase();
if(node.searchInfo) {
node.searchInfo.prevMatched = node.searchInfo.matches;
node.searchInfo.matches = _lastSearchTerm === '' || node.upperLabel.includes(_lastSearchTerm);
}
else {
node.searchInfo = {
matches: _lastSearchTerm === '' || node.upperLabel.includes(_lastSearchTerm),
expandedBefore: !!node.expanded
};
}
node.searchInfo.anyChildMatches = false;
node.children.forEach(child => {
if(_setSearchInfo(child))
node.searchInfo.anyChildMatches = true;
});
return node.searchInfo.matches || node.searchInfo.anyChildMatches;
}
// ------------------------------------------------------------------------
var _setSearchVisibility = function(
node
) {
// ------------------------------------------------------------------------
if((node.searchInfo.matches || node.searchInfo.anyChildMatches)
&& !_self.isNodeVisible(node)
) {
_self.showNode(node);
}
if(node.searchInfo.anyChildMatches
&& !node.expanded
) {
_self.toggleSubtree(node);
}
if(!node.searchInfo.matches
&& !node.searchInfo.anyChildMatches
&& _self.isNodeVisible(node)
) {
_self.hideNode(node);
}
_renderNodeLabelText(node);
node.children.forEach(child => _setSearchVisibility(child));
if(node.children.length > 0 && node.domToggle) {
if(!node.searchInfo.anyChildMatches)
node.domToggle.addClass('disabled');
else
node.domToggle.removeClass('disabled');
}
}
// ------------------------------------------------------------------------
var _restoreNodeAfterSearch = function(
node
) {
// ------------------------------------------------------------------------
if(node.searchInfo) {
if(!_self.isNodeVisible(node))
_self.showNode(node);
if(node.children.length > 0) {
node.domToggle && node.domToggle.removeClass('disabled');
if((node.searchInfo.expandedBefore && !node.expanded)
|| (!node.searchInfo.expandedBefore && node.expanded)
) {
_self.toggleSubtree(node);
}
}
let hasMatched = node.searchInfo.matches;
delete node.searchInfo;
if(hasMatched)
_renderNodeLabelText(node);
node.children.forEach(child => _restoreNodeAfterSearch(child));
}
}
// ------------------------------------------------------------------------
var _performSearch = function(
searchTerm
) {
// ------------------------------------------------------------------------
if(_lastSearchTerm === searchTerm)
return;
_self.hide();
_lastSearchTerm = searchTerm;
if(_lastSearchTerm === '') {
// restore previous
_treeData.forEach(node => _restoreNodeAfterSearch(node));
_self.removeClass('countHidden');
// restore selection
if(_selectedNode)
_self.expandTo(_selectedNode).scrollTo(_selectedNode);
}
else {
_treeData.forEach(node => {
_setSearchInfo(node);
_setSearchVisibility(node);
});
_self.addClass('countHidden');
}
_self.show();
}
// ------------------------------------------------------------------------
var _installSearch = function(
) {
// ------------------------------------------------------------------------
let box = _options.searchBox;
box && box.bind('keyup focus', function() {
let v = String(box.val()).trim().toUpperCase();
_performSearch(v.length >= _options.searchMinInputLength ? v : '');
});
}
// ------------------------------------------------------------------------
var _initialize = function(
options,
data
) {
// ------------------------------------------------------------------------
_options = $.extend(true, _defaults, options);
_nodeValueMap = {};
_nodeCount = 0;
// augment data object with essential info for processing
(function traverseData(nodeArray, indent = 0, parent = undefined) {
nodeArray.sort((a, b) => {
return a.label.localeCompare(b.label);
}).forEach((node, index) => {
_nodeCount++;
node.index = index;
node.indent = indent;
node.parent = parent;
_nodeValueMap[node.value] = node;
if(!$.isArray(node.children))
node.children = [];
traverseData(node.children, indent + 1, node);
});
})(data);
_treeData = data;
_selectedNode = undefined;
_lastSearchTerm = '';
_self.data('simpleTree', _self);
_self.empty();
_treeData.forEach(node => _renderNode(node));
_self.addClass(_options.css.mainContainer);
_installSearch();
}
_initialize(options, data);
return this;
// ============================================================================
}
})(jQuery);