-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathjstreegrid.js
executable file
·1377 lines (1264 loc) · 52 KB
/
jstreegrid.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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* http://github.com/deitch/jstree-grid
*
* This plugin handles adding a grid to a tree to display additional data
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Works only with jstree version >= 3.3.0
*
* $Date: 2017-04-19 $
* $Revision: 3.8.2 $
*/
/*jslint nomen:true */
/*jshint unused:vars */
/*global console, navigator, document, jQuery, define, localStorage */
/* AMD support added by jochenberger per https://github.com/deitch/jstree-grid/pull/49
*
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery', 'jstree'], factory);
} else if(typeof module !== 'undefined' && module.exports) {
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var BLANKRE = /^\s*$/g,
IDREGEX = /[\\:&!^|()\[\]<>@*'+~#";,= \/${}%]/g, escapeId = function (id) {
return (id||"").replace(IDREGEX,'\\$&');
}, NODE_DATA_ATTR = "data-jstreegrid", COL_DATA_ATTR = "data-jstreegrid-column",
SEARCHCLASS = "jstree-search",
SPECIAL_TITLE = "_DATA_", LEVELINDENT = 24, styled = false,
MINCOLWIDTH = 10,
generateCellId = function (tree,id) {
return("jstree_"+tree+"_grid_"+escapeId(id)+"_col");
},
getIds = function (nodes) {
return $.makeArray(nodes.map(function(){return this.id;}));
},
findDataCell = function (uniq, ids, col, scope) {
if (scope == undefined) { scope = $(); };
if (ids === null || ids === undefined || ids.length === 0) {
return scope;
}
var ret = $(), columns = [].concat(col), cellId;
if (typeof (ids) === "string") {
cellId = generateCellId(uniq,ids);
ret = columns.map(function (col) {
return "#"+cellId+col;
}).join(", ");
} else {
ret = []
ids.forEach(function (elm,i) {
var cellId = generateCellId(uniq,elm);
ret = ret.concat(columns.map(function (col) {
return "#"+cellId+col;
}));
});
ret = ret.join(", ");
}
return columns.length ==1 ? scope.find(ret) : $(ret);
},
isClickedSep = false, toResize = null, oldMouseX = 0, newMouseX = 0,
/*jslint regexp:true */
htmlstripre = /<\/?[^>]+>/gi,
/*jslint regexp:false */
getIndent = function(node,tree) {
var div, i, li, width;
// did we already save it for this tree?
tree._gridSettings = tree._gridSettings || {};
if (tree._gridSettings.indent > 0) {
width = tree._gridSettings.indent;
} else {
// create a new div on the DOM but not visible on the page
div = $("<div></div>");
i = node.prev("i");
li = i.parent();
// add to that div all of the classes on the tree root
div.addClass(tree.get_node("#",true).attr("class"));
// move the li to the temporary div root
li.appendTo(div);
// attach to the body quickly
div.appendTo($("body"));
// get the width
width = i.width() || LEVELINDENT;
// detach the li from the new div and destroy the new div
li.detach();
div.remove();
// save it for the future
tree._gridSettings.indent = width;
}
return(width);
},
copyData = function (fromtree,from,totree,to,recurse) {
var i, j;
to.data = $.extend(true, {}, from.data);
if (from && from.children_d && recurse) {
for(i = 0, j = from.children_d.length; i < j; i++) {
copyData(fromtree,fromtree.get_node(from.children_d[i]),totree,totree.get_node(to.children_d[i]),recurse);
}
}
},
findLastClosedNode = function (tree,id) {
// first get our node
var ret, node = tree.get_node(id), children = node.children;
// is it closed?
if (!children || children.length <= 0 || !node.state.opened) {
ret = id;
} else {
ret = findLastClosedNode(tree,children[children.length-1]);
}
return(ret);
},
renderAWidth = function(node,tree) {
var depth, width,
fullWidth = parseInt(tree.settings.grid.columns[0].width,10) + parseInt(tree._gridSettings.treeWidthDiff,10);
// need to use a selector in jquery 1.4.4+
depth = tree.get_node(node).parents.length;
width = fullWidth - depth*getIndent(node,tree);
// the following line is no longer needed, since we are doing this inside a <td>
//a.css({"vertical-align": "top", "overflow":"hidden"});
return(fullWidth);
},
renderATitle = function(node,t,tree) {
var a = node.hasClass("jstree-anchor") ? node : node.children("[class~='jstree-anchor']"), title, col = tree.settings.grid.columns[0];
// get the title
title = "";
if (col.title) {
if (col.title === SPECIAL_TITLE) {
title = tree.get_text(t);
} else if (t.attr(col.title)) {
title = t.attr(col.title);
}
}
// strip out HTML
title = title.replace(htmlstripre, '');
if (title) {
a.attr("title",title);
}
},
getCellData = function (value,data) {
var val;
// get the contents of the cell - value could be a string or a function
if (value !== undefined && value !== null) {
if (typeof(value) === "function") {
val = value(data);
} else if (data.data !== null && data.data !== undefined && data.data[value] !== undefined) {
val = data.data[value];
} else {
val = "";
}
} else {
val = "";
}
return val;
};
$.jstree.defaults.grid = {
width: 'auto'
};
$.jstree.plugins.grid = function(options,parent) {
this._initialize = function () {
if (!this._initialized) {
var s = this.settings.grid || {}, styles, container = this.element, i,
gs = this._gridSettings = {
columns : s.columns || [],
treeClass : "jstree-grid-col-0",
context: s.contextmenu || false,
columnWidth : s.columnWidth,
defaultConf : {"*display":"inline","*+display":"inline"},
isThemeroller : !!this._data.themeroller,
treeWidthDiff : 0,
resizable : s.resizable,
draggable : s.draggable,
stateful: s.stateful,
headerAsTitle: s.headerAsTitle || false,
indent: 0,
sortOrder: 'text',
sortAsc: true,
caseInsensitive: s.caseInsensitive,
fixedHeader: s.fixedHeader !== false,
width: s.width,
height: s.height,
gridcontextmenu : s.gridcontextmenu,
treecol: 0,
gridcols: []
}, cols = gs.columns, treecol = 0, columnSearch = false;
if(gs.gridcontextmenu === true) {
gs.gridcontextmenu = function (grid,tree,node,val,col,t,target) {
return {
"edit": {
label: "Edit",
"action": function (data) {
var obj = t.get_node(node);
grid._edit(obj,col,target);
}
}
}
}
} else if (gs.gridcontextmenu === false) {
gs.gridcontextmenu = false;
}
// find which column our tree shuld go in
for (var i = 0, len = s.columns.length;i<len;i++) {
if (s.columns[i].tree) {
// save which column it was
treecol = i;
gs.treecol = treecol;
} else {
gs.gridcols.push(i);
}
}
// set a unique ID for this table
this.uniq = Math.ceil(Math.random()*1000);
this.rootid = container.attr("id");
var msie = /msie/.test(navigator.userAgent.toLowerCase());
if (msie) {
var version = parseFloat(navigator.appVersion.split("MSIE")[1]);
if (version < 8) {
gs.defaultConf.display = "inline";
gs.defaultConf.zoom = "1";
}
}
// set up the classes we need
if (!styled) {
styled = true;
styles = [
'.jstree-grid-cell {vertical-align: top; overflow:hidden;margin-left:0;position:relative;width: 100%;padding-left:7px;white-space: nowrap;-ms-scroll-limit: 0 0 0 0;}',
'.jstree-grid-cell span {margin-right:0px;margin-right:0px;*display:inline;*+display:inline;white-space: nowrap;}',
'.jstree-grid-separator {position:absolute; top:0; right:0; height:24px; margin-left: -2px; border-width: 0 2px 0 0; *display:inline; *+display:inline; margin-right:0px;width:0px;}',
'.jstree-grid-header-cell {overflow: hidden; white-space: nowrap;padding: 1px 3px 2px 5px; cursor: default;}',
'.jstree-grid-header-themeroller {border: 0; padding: 1px 3px;}',
'.jstree-grid-header-regular {position:relative; background-color: #EBF3FD; z-index: 1;}',
'.jstree-grid-hidden {display: none;}',
'.jstree-grid-resizable-separator {cursor: col-resize; width: 2px;}',
'.jstree-grid-separator-regular {border-color: #d0d0d0; border-style: solid;}',
'.jstree-grid-cell-themeroller {border: none !important; background: transparent !important;}',
'.jstree-grid-wrapper {table-layout: fixed; width: 100%; overflow: auto; position: relative;}',
'.jstree-grid-midwrapper {display: table-row;}',
'.jstree-grid-width-auto {width:auto;display:block;}',
'.jstree-grid-column {display: table-cell; overflow: hidden;-ms-scroll-limit: 0 0 0 0;}',
'.jstree-grid-ellipsis {text-overflow: ellipsis;}',
'.jstree-grid-col-0 {width: 100%;}'
];
$('<style type="text/css">'+styles.join("\n")+'</style>').appendTo("head");
}
this.gridWrapper = $("<div></div>").addClass("jstree-grid-wrapper").insertAfter(container);
this.midWrapper = $("<div></div>").addClass("jstree-grid-midwrapper").appendTo(this.gridWrapper);
// set the wrapper width
if (s.width) {
this.gridWrapper.width(s.width);
}
if (s.height) {
this.gridWrapper.height(s.height);
}
// create the data columns
for (var i = 0, len = cols.length;i<len;i++) {
// create the column
$("<div></div>").addClass("jstree-default jstree-grid-column jstree-grid-column-"+i+" jstree-grid-column-root-"+this.rootid).appendTo(this.midWrapper);
}
this.midWrapper.children("div:eq("+treecol+")").append(container);
container.addClass("jstree-grid-cell");
//move header with scroll
if (gs.fixedHeader) {
this.gridWrapper.scroll(function() {
$(this).find('.jstree-grid-header').css('top', $(this).scrollTop());
});
}
// copy original sort function
var defaultSort = $.proxy(this.settings.sort, this);
// override sort function
this.settings.sort = function (a, b) {
var bigger, colrefs = this.colrefs;
if (gs.sortOrder==='text') {
var caseInsensitiveSort = this.get_text(a).toLowerCase().localeCompare(this.get_text(b).toLowerCase());
bigger = gs.caseInsensitive ? (caseInsensitiveSort === 1) : (defaultSort(a, b) === 1);
} else {
// gs.sortOrder just refers to the unique random name for this column
// we need to get the correct value
var nodeA = this.get_node(a), nodeB = this.get_node(b),
value = colrefs[gs.sortOrder].value,
valueA = typeof(value) === 'function' ? value(nodeA) : nodeA.data[value],
valueB = typeof(value) === 'function' ? value(nodeB) : nodeB.data[value];
if(typeof(valueA) && typeof(valueB) !== 'undefined') {
bigger = gs.caseInsensitive ? valueA.toLowerCase() > valueB.toLowerCase(): valueA > valueB ;
}
}
if (!gs.sortAsc)
bigger = !bigger;
return bigger ? 1 : -1;
};
// sortable columns when jQuery UI is available
if (gs.draggable) {
if (!$.ui || !$.ui.sortable) {
console.warn('[jstree-grid] draggable option requires jQuery UI');
} else {
var from, to;
$(this.midWrapper).sortable({
axis: "x",
handle: ".jstree-grid-header",
cancel: ".jstree-grid-separator",
start: function (event, ui) {
from = ui.item.index();
},
stop: function (event, ui) {
to = ui.item.index();
gs.columns.splice(to, 0, gs.columns.splice(from, 1)[0]);
}
});
}
}
//public function. validate searchObject keys, set columnSearch flag, calls jstree search and reset columnSearch flag
this.searchColumn = function (searchObj) {
var validatedSearchObj = {};
if(typeof searchObj == 'object') {
for(var columnIndex in searchObj) {
if(searchObj.hasOwnProperty(columnIndex)) {
// keys should be the index of a column. This means the following:
// only integers and smaller than the number of columns and bigger or equal to 0
// (possilbe idea for in the future: ability to set key as a more human readable term like the column header and then map it here to an index)
if (columnIndex % 1 === 0 && columnIndex < cols.length && columnIndex >= 0) {
validatedSearchObj[columnIndex] = searchObj[columnIndex];
}
}
}
}
columnSearch = validatedSearchObj;
if(Object.keys(validatedSearchObj).length !== 0){
//the search string doesn't matter. we'll use the search string in the columnSearch object!
this.search('someValue');
} else { // nothing to search so reset jstree's search by passing an empty string
this.search('');
}
columnSearch = false;
}
// set default search for each column with no user defined search function (used when doing a columnSearch)
for (var i = 0, len = cols.length; i<len; i++) {
var column = cols[i];
if (typeof(column.search_callback) !== "function") {
// no search callback so set default function
column.search_callback = function (str, columnValue, node, column) {
var f = new $.vakata.search(str, true, { caseSensitive : searchSettings.case_sensitive, fuzzy : searchSettings.fuzzy });
return f.search(columnValue).isMatch;
};
}
}
// if there was no overridden search_callback, we will provide it
// it will use the default per-node search algorithm, augmented by searching our data nodes
var searchSettings = this.settings.search;
var omniSearchCallback = searchSettings.search_callback;
if(!omniSearchCallback){
omniSearchCallback = function (str,node) {
var i, f = new $.vakata.search(str, true, { caseSensitive : searchSettings.case_sensitive, fuzzy : searchSettings.fuzzy }),
matched = f.search(node.text).isMatch,
col;
// only bother looking in each cell if it was not yet matched
if (!matched) {
for (var i = 0, len = cols.length;i<len;i++) {
if (treecol === i) {
continue;
}
col = cols[i];
var cellData = getCellData(col.value,node) ;
if ( ( cellData == null ) || ( cellData == '' ) ) {
continue ;
}
matched = f.search(cellData).isMatch;
if (matched) {
break;
}
}
}
return matched;
}
}
searchSettings.search_callback = function (str,node) {
var matched = false;
if(columnSearch){
//using logical AND for column searches (more options in the future)
for(var columnIndex in columnSearch) {
if(columnSearch.hasOwnProperty(columnIndex)) {
var searchValue = columnSearch[columnIndex];
if(searchValue == ''){
continue;
}
var col = cols[columnIndex];
if(treecol == columnIndex){
matched = col.search_callback(searchValue, node.text, node, col)
} else {
matched = col.search_callback(searchValue, getCellData(col.value,node), node, col)
}
if(!matched){
break; //found one that didn't match
}
}
}
container.trigger("columnSearch_grid.jstree");
} else {
matched = omniSearchCallback(str, node);
container.trigger("omniSearch_grid.jstree");
}
return matched;
};
this._initialized = true;
}
};
this.init = function (el,options) {
parent.init.call(this,el,options);
this._initialize();
};
this.bind = function () {
parent.bind.call(this);
this._initialize();
this.element
.on("move_node.jstree create_node.jstree clean_node.jstree change_node.jstree", $.proxy(function (e, data) {
var target = this.get_node(data || "#", true);
var id = _guid();
this._detachColumns(id);
this._prepare_grid(target);
this._reattachColumns(id);
}, this))
.on("delete_node.jstree",$.proxy(function (e,data) {
if (data.node.id !== undefined) {
var grid = this.gridWrapper, removeNodes = [data.node.id], i;
// add children to remove list
if (data.node && data.node.children_d) {
removeNodes = removeNodes.concat(data.node.children_d);
}
findDataCell(this.uniq,removeNodes,this._gridSettings.gridcols).remove();
}
}, this))
.on("show_node.jstree", $.proxy(function (e, data) {
this._hideOrShowTree(data.node, false);
}, this))
.on("hide_node.jstree", $.proxy(function (e, data) {
this._hideOrShowTree(data.node, true);
}, this))
.on("close_node.jstree",$.proxy(function (e,data) {
this._hide_grid(data.node);
}, this))
.on("open_node.jstree",$.proxy(function (e,data) {
}, this))
.on("load_node.jstree",$.proxy(function (e,data) {
}, this))
.on("loaded.jstree", $.proxy(function (e) {
this._prepare_headers();
this.element.trigger("loaded_grid.jstree");
}, this))
.on("ready.jstree",$.proxy(function (e,data) {
// find the line-height of the first known node
var anchorHeight = this.element.find("[class~='jstree-anchor']:first").outerHeight(), q,
cls = this.element.attr("class") || "";
$('<style type="text/css">div.jstree-grid-cell-root-'+this.rootid+' {line-height: '+anchorHeight+'px; height: '+anchorHeight+'px;}</style>').appendTo("head");
// add container classes to the wrapper - EXCEPT those that are added by jstree, i.e. "jstree" and "jstree-*"
q = cls.split(/\s+/).map(function(i){
var match = i.match(/^jstree(-|$)/);
return (match ? "" : i);
});
this.gridWrapper.addClass(q.join(" "));
},this))
.on("move_node.jstree",$.proxy(function(e,data){
var node = data.new_instance.element;
//renderAWidth(node,this);
// check all the children, because we could drag a tree over
node.find("li > a").each($.proxy(function(i,elm){
//renderAWidth($(elm),this);
},this));
},this))
.on("hover_node.jstree",$.proxy(function(node,selected,event){
var id = selected.node.id;
if (this._hover_node !== null && this._hover_node !== undefined) {
findDataCell(this.uniq,this._hover_node,this._gridSettings.gridcols).removeClass("jstree-hovered");
}
this._hover_node = id;
findDataCell(this.uniq,id,this._gridSettings.gridcols).addClass("jstree-hovered");
},this))
.on("dehover_node.jstree",$.proxy(function(node,selected,event){
var id = selected.node.id;
this._hover_node = null;
findDataCell(this.uniq,id,this._gridSettings.gridcols).removeClass("jstree-hovered");
},this))
.on("select_node.jstree",$.proxy(function(node,selected,event){
var id = selected.node.id;
findDataCell(this.uniq,id,this._gridSettings.gridcols).addClass("jstree-clicked");
this.get_node(selected.node.id,true).children("div.jstree-grid-cell").addClass("jstree-clicked");
},this))
.on("deselect_node.jstree",$.proxy(function(node,selected,event){
var id = selected.node.id;
findDataCell(this.uniq,id,this._gridSettings.gridcols).removeClass("jstree-clicked");
},this))
.on("deselect_all.jstree",$.proxy(function(node,selected,event){
// get all of the ids that were unselected
var ids = selected.node || [], i;
findDataCell(this.uniq,ids,this._gridSettings.gridcols).removeClass("jstree-clicked");
},this))
.on("search.jstree", $.proxy(function (e, data) {
// search sometimes filters, so we need to hide all of the appropriate grid cells as well, and show only the matches
var grid = this.gridWrapper, that = this, nodesToShow, startTime = new Date().getTime(),
ids = getIds(data.nodes.filter(".jstree-node")), endTime;
this.holdingCells = {};
if (data.nodes.length) {
var id = _guid();
// save the cells we will hide
var cells = grid.find('div.jstree-grid-cell-regular');
this._detachColumns(id);
if(this._data.search.som) {
// create the list of nodes we want to look at
if(this._data.search.smc) {
nodesToShow = data.nodes.add(data.nodes.find('.jstree-node'));
}
nodesToShow = (nodesToShow || data.nodes).add(data.nodes.parentsUntil(".jstree"));
// hide all of the grid cells
cells.hide();
// show only those that match
nodesToShow.filter(".jstree-node").each(function (i,node) {
var id = node.id;
if (id) {
that._prepare_grid(node);
for (var i = 0, len = that._gridSettings.gridcols.length; i < len; i++) {
if (i === that._gridSettings.treecol) { continue; }
findDataCell(that.uniq, id, that._gridSettings.gridcols[i], $(that._domManipulation.columns[i])).show();
}
}
});
}
for (var i = 0, len = this._gridSettings.gridcols.length; i < len; i++) {
if (i === this._gridSettings.treecol) { continue; }
findDataCell(that.uniq, ids, this._gridSettings.gridcols[i], $(this._domManipulation.columns[i])).addClass(SEARCHCLASS);
}
this._reattachColumns(id);
endTime = new Date().getTime();
this.element.trigger("search-complete.jstree-grid", [{time:endTime-startTime}]);
}
return true;
}, this))
.on("clear_search.jstree", $.proxy(function (e, data) {
// search has been cleared, so we need to show all rows
var grid = this.gridWrapper, ids = getIds(data.nodes.filter(".jstree-node"));
grid.find('div.jstree-grid-cell').show();
findDataCell(this.uniq,ids,this._gridSettings.gridcols).removeClass(SEARCHCLASS);
return true;
}, this))
.on("copy_node.jstree", function (e, data) {
var newtree = data.new_instance, oldtree = data.old_instance, obj = newtree.get_node(data.node,true);
copyData(oldtree, data.original, newtree, data.node, true);
newtree._detachColumns(obj.id);
newtree._prepare_grid(obj);
newtree._reattachColumns(obj.id);
return true;
})
.on("show_ellipsis.jstree", $.proxy(function (e, data) {
this.gridWrapper.find(".jstree-grid-cell").add(".jstree-grid-header", this.gridWrapper).addClass("jstree-grid-ellipsis");
return true;
}, this))
.on("hide_ellipsis.jstree", $.proxy(function (e, data) {
this.gridWrapper.find(".jstree-grid-cell").add(".jstree-grid-header", this.gridWrapper).removeClass("jstree-grid-ellipsis");
return true;
}, this))
.on("enable_node.jstree", $.proxy(function (e, data) {
var id = data.node.id;
findDataCell(this.uniq,id,this._gridSettings.gridcols).removeClass("jstree-disabled");
this.get_node(data.node.id,true).children("div.jstree-grid-cell").removeClass("jstree-disabled");
}, this))
.on("disable_node.jstree", $.proxy(function (e, data) {
var id = data.node.id;
findDataCell(this.uniq,id,this._gridSettings.gridcols).addClass("jstree-disabled");
this.get_node(data.node.id,true).children("div.jstree-grid-cell").addClass("jstree-disabled");
}, this))
;
if (this._gridSettings.isThemeroller) {
this.element
.on("select_node.jstree",$.proxy(function(e,data){
data.rslt.obj.children("[class~='jstree-anchor']").nextAll("div").addClass("ui-state-active");
},this))
.on("deselect_node.jstree deselect_all.jstree",$.proxy(function(e,data){
data.rslt.obj.children("[class~='jstree-anchor']").nextAll("div").removeClass("ui-state-active");
},this))
.on("hover_node.jstree",$.proxy(function(e,data){
data.rslt.obj.children("[class~='jstree-anchor']").nextAll("div").addClass("ui-state-hover");
},this))
.on("dehover_node.jstree",$.proxy(function(e,data){
data.rslt.obj.children("[class~='jstree-anchor']").nextAll("div").removeClass("ui-state-hover");
},this));
}
if (this._gridSettings.stateful) {
this.element
.on("resize_column.jstree-grid",$.proxy(function(e,col,width){
localStorage['jstree-root-'+this.rootid+'-column-'+col] = width;
},this));
}
};
// tear down the tree entirely
this.teardown = function() {
var gw = this.gridWrapper, container = this.element, gridparent = gw.parent();
container.detach();
gw.remove();
gridparent.append(container);
parent.teardown.call(this);
};
// clean the grid in case of redraw or refresh entire tree
this._clean_grid = function (target,id) {
var grid = this.gridWrapper;
if (target) {
findDataCell(this.uniq,id,this._gridSettings.gridcols).remove();
} else {
// get all of the `div` children in all of the `td` in dataRow except for :first (that is the tree itself) and remove
grid.find("div.jstree-grid-cell-regular").remove();
}
};
// prepare the headers
this._prepare_headers = function() {
var header, i, col, _this = this, gs = this._gridSettings,cols = gs.columns || [], width, defaultWidth = gs.columnWidth, resizable = gs.resizable || false,
cl, ccl, val, name, last, tr = gs.isThemeroller, classAdd = (tr?"themeroller":"regular"), puller,
hasHeaders = false, gridparent = this.gridparent, rootid = this.rootid,
conf = gs.defaultConf, coluuid,
borPadWidth = 0, totalWidth = 0;
// save the original parent so we can reparent on destroy
this.parent = gridparent;
// save the references to columns by unique ID
this.colrefs = {};
// create the headers
for (var i = 0, len = cols.length;i<len;i++) {
//col = $("<col/>");
//col.appendTo(colgroup);
cl = cols[i].headerClass || "";
ccl = cols[i].columnClass || "";
val = cols[i].header || "";
headerTitle = cols[i].headerTitle || "";
do {
coluuid = String(Math.floor(Math.random()*10000));
} while(this.colrefs[coluuid] !== undefined);
// create a unique name for this column
name = cols[i].value ? coluuid : "text";
this.colrefs[name] = cols[i];
if (val) {hasHeaders = true;}
if(gs.stateful && localStorage['jstree-root-'+rootid+'-column-'+i])
width = localStorage['jstree-root-'+rootid+'-column-'+i];
else
width = cols[i].width || defaultWidth;
var minWidth = cols[i].minWidth || width;
var maxWidth = cols[i].maxWidth || width;
// we only deal with borders if width is not auto and not percentages
borPadWidth = tr ? 1+6 : 2+8; // account for the borders and padding
if (width !== 'auto' && typeof(width) !== "string") {
width -= borPadWidth;
}
col = this.midWrapper.children("div.jstree-grid-column-"+i);
last = $("<div></div>").css(conf).addClass("jstree-grid-div-"+this.uniq+"-"+i+" "+(tr?"ui-widget-header ":"")+" jstree-grid-header jstree-grid-header-cell jstree-grid-header-"+classAdd+" "+cl+" "+ccl).html(val);
last.addClass((tr?"ui-widget-header ":"")+"jstree-grid-header jstree-grid-header-"+classAdd);
if (this.settings.core.themes.ellipsis === true){
last.addClass('jstree-grid-ellipsis');
}
// add title and strip out HTML
var title = gs.headerAsTitle && !headerTitle ? val : (headerTitle ? headerTitle : "");
title = title.replace(htmlstripre, '');
if (title) {
last.attr("title",title);
}
last.prependTo(col);
last.attr(COL_DATA_ATTR, name);
totalWidth += last.outerWidth();
puller = $("<div class='jstree-grid-separator jstree-grid-separator-"+classAdd+(tr ? " ui-widget-header" : "")+(resizable? " jstree-grid-resizable-separator":"")+"'> </div>").appendTo(last);
col.width(width);
col.css("min-width", minWidth);
col.css("max-width", maxWidth);
}
last.addClass((tr?"ui-widget-header ":"")+"jstree-grid-header jstree-grid-header-last jstree-grid-header-"+classAdd);
// if there is no width given for the last column, do it via automatic
if (cols[cols.length-1].width === undefined) {
totalWidth -= width;
col.css({width:"auto"});
last.addClass("jstree-grid-width-auto").next(".jstree-grid-separator").remove();
}
if (hasHeaders) {
// save the offset of the div from the body
//gs.divOffset = header.parent().offset().left;
gs.header = header;
} else {
$("div.jstree-grid-header").hide();
}
if (!this.bound && resizable) {
this.bound = true;
$(document).mouseup(function () {
var ref, cols, width, headers, currentTree, colNum;
if (isClickedSep) {
colNum = toResize.prevAll(".jstree-grid-column").length;
currentTree = toResize.closest(".jstree-grid-wrapper").find(".jstree");
ref = $.jstree.reference(currentTree);
cols = ref.settings.grid.columns;
headers = toResize.parent().children("div.jstree-grid-column");
if (isNaN(colNum) || colNum < 0) { ref._gridSettings.treeWidthDiff = currentTree.find("ins:eq(0)").width() + currentTree.find("[class~='jstree-anchor']:eq(0)").width() - ref._gridSettings.columns[0].width; }
width = ref._gridSettings.columns[colNum].width = parseFloat(toResize.css("width"));
isClickedSep = false;
toResize = null;
currentTree.trigger("resize_column.jstree-grid", [colNum,width]);
}
}).mousemove(function (e) {
if (isClickedSep) {
newMouseX = e.pageX;
var diff = newMouseX - oldMouseX,
oldPrevHeaderInner,
oldPrevColWidth, newPrevColWidth;
if (diff !== 0){
oldPrevHeaderInner = toResize.width();
oldPrevColWidth = parseFloat(toResize.css("width"));
// handle a Chrome issue with columns set to auto
// thanks to Brabus https://github.com/side-by-side
if (!oldPrevColWidth) {oldPrevColWidth = toResize.innerWidth();}
// make sure that diff cannot be beyond the left/right limits
diff = diff < 0 ? Math.max(diff,-oldPrevHeaderInner) : diff;
newPrevColWidth = oldPrevColWidth+diff;
// only do this if we are not shrinking past 0 on left - and limit it to that amount
if ((diff > 0 || oldPrevHeaderInner > 0) && newPrevColWidth > MINCOLWIDTH) {
toResize.width(newPrevColWidth+"px");
toResize.css("min-width",newPrevColWidth+"px");
toResize.css("max-width",newPrevColWidth+"px");
oldMouseX = newMouseX;
}
}
}
});
this.gridWrapper.on("selectstart", ".jstree-grid-resizable-separator", function () {
return false;
}).on("mousedown", ".jstree-grid-resizable-separator", function (e) {
isClickedSep = true;
oldMouseX = e.pageX;
toResize = $(this).closest("div.jstree-grid-column");
// the max rightmost position we will allow is the right-most of the wrapper minus a buffer (10)
return false;
})
.on("dblclick", ".jstree-grid-resizable-separator", function (e) {
var clickedSep = $(this), col = clickedSep.closest("div.jstree-grid-column"),
oldPrevColWidth = parseFloat(col.css("width")), newWidth = 0, diff,
colNum = col.prevAll(".jstree-grid-column").length,
oldPrevHeaderInner = col.width(), newPrevColWidth;
//find largest width
col.find(".jstree-grid-cell").each(function() {
var item = $(this), width;
item.css("position", "absolute");
item.css("width", "auto");
width = item.outerWidth();
item.css("position", "relative");
if (width>newWidth) {
newWidth = width;
}
});
diff = newWidth-oldPrevColWidth;
// make sure that diff cannot be beyond the left limits
diff = diff < 0 ? Math.max(diff,-oldPrevHeaderInner) : diff;
newPrevColWidth = (oldPrevColWidth+diff)+"px";
col.width(newPrevColWidth);
col.css("min-width",newPrevColWidth);
col.css("max-width",newPrevColWidth);
$(this).closest(".jstree-grid-wrapper").find(".jstree").trigger("resize_column.jstree-grid",[colNum,newPrevColWidth]);
})
.on("click", ".jstree-grid-separator", function (e) {
// don't sort after resize
e.stopPropagation();
});
}
this.gridWrapper.on("click", ".jstree-grid-header-cell", function (e) {
if (!_this.sort) {
return;
}
// get column
var name = $(this).attr(COL_DATA_ATTR);
// sort order
var symbol;
if (gs.sortOrder === name && gs.sortAsc === true) {
gs.sortAsc = false;
symbol = "↓";
} else {
gs.sortOrder = name;
gs.sortAsc = true;
symbol = "↑";
}
// add sort arrow
$(this.closest('.jstree-grid-wrapper')).find(".jstree-grid-sort-icon").remove();
$("<span></span>").addClass("jstree-grid-sort-icon").appendTo($(this)).html(symbol);
// sort by column
var rootNode = _this.get_node('#');
_this.sort(rootNode, true);
_this.redraw_node(rootNode, true);
});
};
this._domManipulation = null; // We'll store the column nodes in this object and an id for the grid-node that started the manipulation { id: "id of the node that started the manipulation", columns: { Key-Value-Pair col-No: Column }}
function _guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
/*
* Trys to detach the tree columns on massive dom manipulations
*/
this._detachColumns = function (id) {
// if the columns are not detached, then detach them
if (this._domManipulation == null) {
var cols = this._gridSettings.columns || [], treecol = this._gridSettings.treecol, mw = this.midWrapper;
this._domManipulation = { id: id, oldActiveElement: document.activeElement, columns: {} };
for (var i = 0, len = cols.length; i < len; i++) {
//if (treecol === i) {
// continue;
//}
this._domManipulation.columns[i] = mw.children(".jstree-grid-column-" + i)[0];
this._domManipulation.columns[i].parentNode.removeChild(this._domManipulation.columns[i]);
}
}
return this._domManipulation;
}
this._reattachColumns = function (id) {
if (this._domManipulation == null) { return false; }
if (this._domManipulation.id === id) {
var cols = this._gridSettings.columns || [], treecol = this._gridSettings.treecol, mw = this.midWrapper;
for (var i = 0, len = cols.length; i < len; i++) {
//if (treecol === i) {
// continue;
//}
mw[0].appendChild(this._domManipulation.columns[i]);
}
if (this._domManipulation.oldActiveElement !== document.activeElement) { $(this._domManipulation.oldActiveElement).focus(); }
this._domManipulation = null;
}
return true;
}
/*
* Override open_node to detach the columns before redrawing child-nodes, and do reattach them afterwarts
*/
this.open_node = function (obj, callback, animation) {
var isArray = $.isArray(obj);
var node = null;
if (!isArray) {
node = this.get_node(obj);
if (node.id === "#") { return; } // wtf??? we ar in the root and do not need a open!
}
var id = isArray ? _guid() : node.id;
this._detachColumns(id);
var ret = parent.open_node.call(this, obj, callback, animation);
this._reattachColumns(id);
return ret;
}
/*
* Override redraw_node to correctly insert the grid
*/
this.redraw_node = function (obj, deep, is_callback, force_render) {
var id = $.isArray(obj) ? _guid() : this.get_node(obj).id;
// we detach the columns once
this._detachColumns(id);
// first allow the parent to redraw the node
obj = parent.redraw_node.call(this, obj, deep, is_callback, force_render);
// next prepare the grid for a redrawn node - but only if ths node is not hidden (search does that)
if (obj) {
this._prepare_grid(obj);
}
// don't forget to reattach
this._reattachColumns(id);
return obj;
};
this.refresh = function () {
this._clean_grid();
return parent.refresh.apply(this,arguments);
};
/*
* Override set_id to update cell attributes
*/
this.set_id = function (obj, id) {
var old, uniq = this.uniq;
if(obj) {
old = obj.id;
}
var result = parent.set_id.apply(this,arguments);
if(result) {
if (old !== undefined) {
var grid = this.gridWrapper, oldNodes = [old], i;
// get children
if (obj && obj.children_d) {
oldNodes = oldNodes.concat(obj.children_d);
}
// update id in children
findDataCell(uniq,oldNodes,this._gridSettings.gridcols)
.attr(NODE_DATA_ATTR, obj.id)
.removeClass(generateCellId(uniq,old))
.addClass(generateCellId(uniq,obj.id))
.each(function(i,node) {
$(node).attr('id', generateCellId(uniq,obj.id)+(i+1));
});
}
}
return result;
};
this._hideOrShowTree = function(node, hide) {
//Hides or shows a tree
this._detachColumns(node.id);
// show cells in each detachted column
this._hideOrShowNode(node, hide, this._gridSettings.columns || [], this._gridSettings.treecol);
this._reattachColumns(node.id);
}
this._hideOrShowNode = function(node, hide, cols, treecol) {
//Hides or shows a node with recursive calls to all open child-nodes
for (var i = 0, len = cols.length; i < len; i++) {
if (i === treecol) { continue; }
var cells = findDataCell(this.uniq, node.id, i, $(this._domManipulation.columns[i]));
if (hide) {
cells.addClass("jstree-grid-hidden");
} else {
cells.removeClass("jstree-grid-hidden");
}
}
if (node.state.opened && node.children) {
for (var i = 0, len = node.children.length; i < len; i++) {
this._hideOrShowNode(this.get_node(node.children[i]), hide, cols, treecol);
}