/
D3TreeView.js
1157 lines (1021 loc) · 38.3 KB
/
D3TreeView.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
/*
D3 TreeView Widget
========================
@file : D3TreeView.js
@version : 2.3.0
@author : Ivo Sturm
@date : 9-1-2022
@copyright : First Consulting
@license : Apache 2
Documentation
========================
Add a collapsible, zoomable, drag- and droppable and clickable TreeView widget to your Mendix page.
Known bugs
========================
When collapsing and expanding quickly after eachother, the nodes circles do not come back.
Versions
========================
v1.1 - Fix for when context entity is updated, was not properly refreshing. Changed _cleanDomNode function not to clear the svg-tree container which holds the full TreeView + the added HTML Button Container div. See widget/template/D3TreeView.html for changes as well.
- Added Centralize On Click setting which defaults to No.
v1.2.1 - Minor fix for this._rightmostNode. Initial value was not set, giving NaN browser console errors.
v2.0.0 - Added support for Indented Horizontal TreeView.
- Added managing colors for expanded / collapsed parents and nodes without children
- Added showTopParent setting to cater for multiple topparents. If showTopParent = false, the Top Parent will not be shown.
v2.0.1 Added support for on click microflow of indented Tree View.
v2.2.0 - Removed deprecated usage of mx.ui
- Added generic log node
- Bugfix added missing on click support on parent node
- Added possibility to add a css class to a node so it can be styled
- Added nodeShapeRect attribute to being able to show nodes as rectangles in normal Tree View scenario
v2.3.0 - Added text positioning option in case of normal rectangle scenario
*/
// Required module list. Remove unnecessary modules, you can always get them back from the boilerplate.
define([
"dojo/_base/declare",
"mxui/widget/_WidgetBase",
"dijit/_TemplatedMixin",
"mxui/dom",
"dojo/dom",
"dojo/on",
"dojo/dom-style",
"dojo/_base/array",
"dojo/_base/lang",
"dojo/text!D3TreeView/widget/template/D3TreeView.html",
"D3TreeView/lib/d3-v3-min"
], function(declare, _WidgetBase, _TemplatedMixin, dom, dojoDom, on, dojoStyle, dojoArray, dojoLang, widgetTemplate) {
"use strict";
// d3 v3 is added to the window, so redefine it for programming convenience
var d3 = window.d3;
// Declare widget's prototype.
return declare("D3TreeView.widget.D3TreeView", [ _WidgetBase, _TemplatedMixin ], {
// _TemplatedMixin will create our dom node using this HTML template.
templateString: widgetTemplate,
// DOM elements
svgTree: null,
// Internal variables. Non-primitives created in the prototype are shared between all widget instances.
_handles: null,
_contextObj: null,
_progressID : null,
_totalNodes : 0,
_maxLabelLength : 0,
_rightmostNode: 0,
_selectedNode : null,
_draggingNode : null,
_panSpeed : 200,
_panBoundary : 20,
_i : 0,
_logNode: "D3 TreeView ",
// dojo.declare.constructor is called to construct the widget instance. Implement to initialize non-primitive properties.
constructor: function() {
this._handles = [];
this._root = null;
this._tree = null;
this._svgGroup = null;
this._dragListener = null;
this._zoomListener = null;
this._diagonal = null;
this._dragStarted = null;
this._nodes = null;
this._links = null;
this._panTimer = null;
this._treeData = [];
this._nodeObjects = [];
this._viewerMinHeight = 0;
this._viewerMinWidth = 0;
this._intialLoad = true;
},
// dijit._WidgetBase.postCreate is called after constructing the widget. Implement to do extra setup work.
postCreate: function() {
this._parentReferenceName = this.parentReference.substr(0, this.parentReference.indexOf('/'));
this._setupEvents();
},
// mxui.widget._WidgetBase.update is called when context is changed or initialized. Implement to re-render and / or fetch data.
update: function(obj, callback) {
this._contextObj = obj;
this._resetSubscriptions();
this._updateRendering(this._contextObj);
if (typeof callback !== "undefined") {
callback();
}
},
_drawChart: function(objs) {
if (objs){
// fill global array, so it can be used later on to store the changes
this._nodeObjects = objs;
// create objects with reference to parent
for (var j=0 ; j < objs.length ; j++){
var treeObj = {};
treeObj.name = objs[j].get(this.nameAttr);
treeObj.className = objs[j].get(this.classNameAttr);
treeObj.guid = objs[j].getGuid();
treeObj.parentGuid = objs[j].getReference(this._parentReferenceName);
// set children as empty array for now. In second loop fill based on parentGuid
treeObj.children = [];
this._treeData.push(treeObj);
}
// now set children based on parentGuids
for (var k=0 ; k < this._treeData.length ; k++){
if (this._treeData[k].parentGuid){
var parentObj = this._treeData.filter(dojoLang.hitch(this,function(e) {
return e.guid == this._treeData[k].parentGuid;
}));
// filter operation gives back a list, but since guid is unique we can take the first
if (parentObj[0] && parentObj[0].children){
parentObj[0].children.push(this._treeData[k]);
}
}
}
}
this._tree = d3.layout.tree();
// define a d3 diagonal projection for use by the node paths later on.
this._diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
// filter operation gives back a list, but since only one node should be the topparent with no parents itself, we can take the first
var treeData = this._treeData.filter(dojoLang.hitch(this,function(e) {
return e.parentGuid === "";
}))[0];
// if data fed to widget, setup the tree
if (treeData){
// call visit function to establish maxLabelLength
this._visit(treeData, dojoLang.hitch(this,function(d) {
this._totalNodes++;
this._maxLabelLength = Math.max(d.name.length, this._maxLabelLength);
}), function(d) {
return d.children && d.children.length > 0 ? d.children : null;
});
// make width a bit more concise, therefore take 80 % of maximum label as base of length for all links
this._maxLabelLength = 0.8 * this._maxLabelLength;
// Sort the tree initially in case the JSON isn't in a sorted order.
this._sortTree();
// define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
this._zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", dojoLang.hitch(this,function(){this._zoom();}));
// create svg element
var baseSvg;
// position svg element relative to buttons
if (this._buttonsBelow){
baseSvg = d3.select("#tree-container").insert("svg",":first-child");
} else {
baseSvg = d3.select("#tree-container").append("svg");
}
// attaching a class for styling and the zoomListener to svg element
baseSvg
.attr("width", this._viewerWidth)
.attr("height", this._viewerHeight)
.attr("class", "overlay")
.style("display","inherit") // needed to properly position buttons for collapse and expand above the SVG element itself
.style("background-color",this._backgroundColor)
.call(this._zoomListener);
// Append a group which holds all nodes to the full length and breadth of SVG to capture the zoom events.
this._svgGroup = baseSvg.append("g")
.attr("class", "svg-group")
.style("pointer-events", "all");
// Define the root
this._root = treeData;
if (!this.showTopParent){
// Mark root object as top parent to make it possible to not show it later on
this._root._topParent = true;
};
this._root.y0 = 0;
// add extra spacing horizontally based on length of text of rootelement
this._rootOffsetX = (this._root.name.length / 0.6) * 6;
// add extra spacing vertically for margin on top and bottom
this._rootOffsetY = 20;
if (this.verticalTreeView){
if (this.loggingEnabled){
console.log(this._logNode + 'indented treeview');
}
this._root.x0 = this._rootOffsetX;
} else {
if (this.loggingEnabled){
console.log(this._logNode + 'normal treeview');
}
this._root.x0 = this._viewerHeight / 2 + this._rootOffsetX;
}
// reposition root based on offsets
d3.select('g').transition()
.duration(this.duration)
.attr("transform", "translate(" + this._rootOffsetX + "," + this._rootOffsetY + ")");
// initialize layout of tree
this._expand(this._root);
}
this._hideProgress();
// once loaded, do not resize SVG element anymore, hence set this._initialLoad to false
this._intialLoad=false;
},
// rerender the interface.
_updateRendering: function(obj) {
// draw and attach event handlers only first time when this._tree is not populated yet
if (obj !== null && this._treeData.length === 0) {
this._showProgress();
this._loadTreeData();
} else if (obj !== null && this._treeData.length > 0){
// only redraw
this._expand(this._root);
}
},
// Reset subscriptions.
_resetSubscriptions: function () {
var _objectHandle = null;
// Release handles on previous object, if any.
if (this._handles) {
dojoArray.forEach(this._handles, function (handle, i) {
mx.data.unsubscribe(handle);
});
this._handles = [];
}
// When a mendix object exists create subscriptions.
if (this._contextObj) {
_objectHandle = this.subscribe({
guid: this._contextObj.getGuid(),
callback: dojoLang.hitch(this, function (guid) {
if (this.loggingEnabled){
console.log(this._logNode + "update on entity with guid: " + guid);
}
// reset _initialLoad, since it will trigger a resize of the widget based on the height it needs
this._intialLoad = true;
// empty stored treeData of previous version of context object
this._treeData = [];
this._showProgress();
this._cleanUpDomNode(this.svgTree,this._loadTreeData());
})
});
this._handles = [];
}
},
// HELPER FUNCTIONS
// A recursive helper function for performing some setup by walking through all nodes
_visit : function(parent, visitFn, childrenFn) {
if (!parent) return;
visitFn(parent);
var children = childrenFn(parent);
if (children) {
var count = children.length;
for (var i = 0; i < count; i++) {
this._visit(children[i], visitFn, childrenFn);
}
}
},
// Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.
_centerNode : function(source) {
var scale = this._zoomListener.scale();
var x = -source.y0;
var y = -source.x0;
x = x * scale + this._viewerWidth / 2;
y = y * scale + this._viewerHeight / 2;
d3.select('g').transition()
.duration(this.duration)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")");
this._zoomListener.scale(scale);
this._zoomListener.translate([x, y]);
},
// Toggle children function
_toggleChildren : function(d) {
if (d && d.children) {
d._children = d.children;
d.children = null;
} else if (d && d._children) {
d.children = d._children;
d._children = null;
}
return d;
},
// Toggle children on click.
_click : function(d) {
if (d3.event && d3.event.defaultPrevented) return; // click suppressed
d = this._toggleChildren(d);
if (d){
this._updateTreeView(d);
if (this.centralizeOnClick){
this._centerNode(d);
}
}
},
_updateTreeView : function(source){
// Compute the new height, function counts total children of root node and sets tree height accordingly.
// This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed
// This makes the layout more consistent.
var levelWidth = [1];
var childCount = function(level, n) {
if (n.children && n.children.length > 0) {
if (levelWidth.length <= level + 1) levelWidth.push(0);
levelWidth[level + 1] += n.children.length;
n.children.forEach(function(d) {
childCount(level + 1, d);
});
}
};
// walk through root to get the children per level and store this in levelWidth array
childCount(0, this._root);
// new height is based on the max of the number of children per level, so [1,4,8,2] => 8 children
var newHeight = d3.max(levelWidth) * this._verticalNodeDistance; // x pixels per line
this._tree = this._tree.size([newHeight, this._viewerWidth]);
if (this.verticalTreeView){
this._updateIndentedTree(source);
} else {
this._updateTree(source);
}
},
_updateTree : function(source) {
// Compute the new tree layout.
this._nodes = this._tree.nodes(this._root).reverse();
if (!this.showTopParent){
this._links = this._tree.links(this._nodes).filter(function(d){ return !d.source._topParent });
} else {
this._links = this._tree.links(this._nodes);
}
// Set widths between levels based on maxLabelLength.
this._nodes.forEach(dojoLang.hitch(this,function(d) {
d.y = (d.depth * (this._maxLabelLength * this._horizontalNodeDistance));
}));
// Update the nodes?
var node = this._svgGroup.selectAll("g.node")
.data(this._nodes, dojoLang.hitch(this,function(d) {
return d.id || (d.id = ++this._i);
}));
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.filter(function(d){ return !d._topParent })
.call(this._dragListener)
.attr("class", function(){
// v2.2.0 add class name to each node if fed from Studio Pro
return source.className ? "node " + source.className : 'node';
})
.attr("transform", function(d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.attr("id", function(d) {
return "node_" + d.guid;
})
.on('click', dojoLang.hitch(this,function(d) {
// block collapse & expand behavior when onClickMF is defined
if (!this.onClickMF){
this._click(d);
}
}));
// v2.2.0 user can choose between default circle or new rectangle
if (this.nodeShapeRect){
var barHeight = 20,
barWidth = this._maxLabelLength * 10;
this._appendRect(nodeEnter,barHeight,barWidth);
}
else {
nodeEnter.append("circle")
.attr('class', 'nodeCircle')
.attr("r", 0)
.style("fill", dojoLang.hitch(this, function(d) {
return this._color(d);
}))
.style("stroke", this.nodeStrokeColor)
.style("stroke-width", this.nodeStrokeWidth);
}
// v2.3.0: added extra check on node, if rectangle enabled to position text inside the rectangle
nodeEnter.append("text")
.attr("x", dojoLang.hitch(this,function(d){
if ((d.children || d._children) && !this.nodeShapeRect) {
return -10;
} else {
return 10;
}
}))
.attr("dy", ".35em")
.attr('class', 'nodeText')
.attr("text-anchor", dojoLang.hitch(this,function(d){
if ((d.children || d._children) && !this.nodeShapeRect) {
return "end";
} else {
return "start";
}
}))
.text(function(d) {
return d.name;
})
.style("fill-opacity", 0)
.style("font-size", this.fontSize + "px")
.style("font-color", this.fontColor + "px");
// ghost node to give us mouseover in a radius around it
nodeEnter.append("circle")
.attr('class', 'ghostCircle')
.attr("r", 3 * this.nodeRadius)
.attr("opacity", 0.2) // change this to zero to hide the target area
.style("fill", this.ghostNodeColor)
.attr('pointer-events', 'mouseover')
.on("mouseover", dojoLang.hitch(this,function(node) {
this._overCircle(node);
}))
.on("mouseout", dojoLang.hitch(this,function(node) {
this._outCircle(node);
}));
// Change the circle fill depending on whether it has children
node.select("circle.nodeCircle")
.attr("r", this.nodeRadius)
.style("fill", dojoLang.hitch(this, function(d) {
return this._color(d);
}))
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(this.duration)
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Fade the text in
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(this.duration)
.attr("transform", function(d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
nodeExit.select("circle")
.attr("r", 0);
nodeExit.select("text")
.style("fill-opacity", 0);
if (this.enableLinks){
// Update the links?
var link = this._svgGroup.selectAll("path.link")
.data(this._links, function(d) {
return d.target.id;
});
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.style("stroke", this.linkStrokeColor)
.attr("d", dojoLang.hitch(this,function(d) {
var o = {
x: source.x0,
y: source.y0
};
return this._diagonal({
source: o,
target: o
});
}));
// Transition links to their new position.
link.transition()
.duration(this.duration)
.attr("d", this._diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(this.duration)
.attr("d", dojoLang.hitch(this, function(d) {
var o = {
x: source.x,
y: source.y
};
return this._diagonal({
source: o,
target: o
});
}))
.remove();
}
// determine the maximum width of the SVG element by iterating through nodes and checking coordinates
this._maxWidth = 0;
this._nodes.forEach(dojoLang.hitch(this,function(d,i) {
d.x0 = d.x;
d.y0 = d.y;
if (this._viewerMinHeight === 0){
this._viewerMinHeight = d.x;
} else {
if (d.x < this._viewerMinHeight){
this._viewerMinHeight = d.x;
}
}
if (this._viewerMinWidth === 0){
this._viewerMinWidth = d.y;
} else {
if (d.y < this._viewerMinWidth){
this._viewerMinWidth = d.y;
}
}
if (d.x > this._viewerHeight){
this._viewerHeight = d.x;
}
if (d.y > this._maxWidth){
this._maxWidth = d.y;
this._rightmostNode = d.y;
}
}));
// update size of tree
this._tree
.size([this._viewerHeight + 2 * this._rootOffsetY,this._maxWidth + this._rootOffsetX]);
if (this._intialLoad){
// update size of svg group
d3.select("#tree-container svg")
.attr("width", this._rightmostNode + ((this._maxLabelLength * 20)))
.attr("height", this._viewerHeight + 2 * this._rootOffsetY);
}
if (this.loggingEnabled){
console.log(this._logNode + "calculated maxHeight based on tree: " + this._viewerHeight);
console.log(this._logNode + "calculated maxWidth based on tree: " + this._maxWidth);
console.log(this._logNode + "calculated minHeight based on tree: " + this._viewerMinHeight);
console.log(this._logNode + "calculated minWidth based on tree: " + this._viewerMinWidth);
}
},
_updateIndentedTree : function(source) {
var margin = {top: 30, right: 20, bottom: 30, left: 20},
width = this._viewerWidth,
barHeight = 20,
barWidth = this._maxLabelLength * 10;//(width - margin.left - margin.right) * 0.2;
var i = 0,
duration = 400;
// Compute the new tree layout.
this._nodes = this._tree.nodes(this._root);
if (!this.showTopParent){
this._links = this._tree.links(this._nodes).filter(function(d){ return !d.source._topParent });
} else {
this._links = this._tree.links(this._nodes);
}
var height = Math.max(500, this._nodes.length * barHeight + margin.top + margin.bottom);
d3.select("svg").transition()
.duration(duration)
.attr("height", height);
d3.select(self.frameElement).transition()
.duration(duration)
.style("height", height + "px");
// Compute the "layout". TODO https://github.com/d3/d3-hierarchy/issues/67
var index = -1;
this._nodes.forEach(function(n) {
n.x = ++index * barHeight;
n.y = n.depth * 20;
});
// Update the nodes?
var node = this._svgGroup.selectAll("g.node")
.data(this._nodes, function(d) { return d.id || (d.id = ++i); });
var nodeEnter = node.enter()
.append("g")
.filter(function(d){ return !d._topParent })
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.style("opacity", 0)
.call(this._dragListener)
.on('click', dojoLang.hitch(this,function(d) {
// block collapse & expand behavior when onClickMF is defined
if (!this.onClickMF){
this._click(d);
}
}));
// Enter any new nodes at the parent's previous position.
this._appendRect(nodeEnter,barHeight,barWidth)
.on('click', dojoLang.hitch(this,function(d) {
// block collapse & expand behavior when onClickMF is defined
if (!this.onClickMF){
this._click(d);
}
}));
nodeEnter.append("text")
.attr("dy", 3.5)
.attr("dx", 5.5)
//.text(function(d) { return d.data.name; })
.text(function(d) { return d.name; })
.on('click', dojoLang.hitch(this,function(d) {
// block collapse & expand behavior when onClickMF is defined
if (!this.onClickMF){
this._click(d);
}
}))
// Transition nodes to their new position.
node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.style("opacity", 1);
node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.style("opacity", 1)
.select("rect")
.style("fill", dojoLang.hitch(this,function(d){
return this._color(d);
}
))
// Transition exiting nodes to the parent's new position.
node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.style("opacity", 0)
.remove();
if (this.enableLinks){
// Update the links?
var link = this._svgGroup.selectAll("path.link")
.data(this._links, function(d) {
return d.target.id;
});
// Enter any new links at the parent's previous position.
link.enter()
.insert("path", "g")
.attr("class", "link")
.attr("d", dojoLang.hitch(this,function(d) {
var o = {x: source.x0, y: source.y0};
return this._diagonal({source: o, target: o});
}))
.style("stroke", this.linkStrokeColor)
.transition()
.duration(duration)
.attr("d", dojoLang.hitch(this,function(d) {return this._diagonal(d)}));
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", dojoLang.hitch(this,function(d) {return this._diagonal(d)}));
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", dojoLang.hitch(this,function(d) {
var o = {x: source.x, y: source.y};
return this._diagonal({source: o, target: o});
}))
.remove();
}
// Stash the old positions for transition.
this._nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
},
_appendRect : function (nodeEnter,barHeight,barWidth){
return nodeEnter.append("rect")
.attr("y", -barHeight / 2)
.attr("height", barHeight)
.attr("width", barWidth)
.style("fill", dojoLang.hitch(this,function(d){
return this._color(d);
}
))
.style("stroke", this.nodeStrokeColor)
.style("stroke-width", this.nodeStrokeWidth);
},
// color nodes based on whether it is collapsed and expanded and has children or not
_color : function(d){
return d.children ? this.parentExpandedColor : d._children ? this.parentCollapsedColor : this.childExpandedColor;
},
_endDrag : function(domNode) {
this._selectedNode = null;
d3.selectAll('.ghostCircle').attr('class', 'ghostCircle');
d3.select(domNode).attr('class', 'node');
// now restore the mouseover event or we won't be able to drag a 2nd time
d3.select(domNode).select('.ghostCircle').attr('pointer-events', '');
this._updateTempConnector();
if (this._draggingNode !== null) {
this._updateTreeView(this._root);
this._centerNode(this._draggingNode);
this._draggingNode = null;
}
},
// Helper functions for collapsing and expanding all nodes.
_collapse : function(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(dojoLang.hitch(this,function(i){this._collapse(i);}));
d.children = [];
}
if (d){
this._updateTreeView(d);
}
},
_expand : function(d) {
if (d._children) {
d.children = d._children;
d.children.forEach(dojoLang.hitch(this,function(i){this._expand(i);}));
}
if (d){
this._updateTreeView(d);
}
},
_initiateDrag : function(d, domNode) {
this._draggingNode = d;
d3.select(domNode).select('.ghostCircle').attr('pointer-events', 'none');
d3.selectAll('.ghostCircle').attr('class', 'ghostCircle show');
d3.select(domNode).attr('class', 'node activeDrag');
this._svgGroup.selectAll("g.node").sort(dojoLang.hitch(this,function(a, b) { // select the parent and sort the path's
if (a.id != this._draggingNode.id) return 1; // a is not the hovered element, send "a" to the back
else return -1; // a is the hovered element, bring "a" to the front
}));
// if nodes has children, remove the links and nodes
if (d.children && d.children.length > 1) {
// get all links connecting children of node being dragged
var links = this._tree.links(this._tree.nodes(d));
// remove those links from sight
this._svgGroup.selectAll("path.link")
.data(links, function(d) {
return d.target.id;
}).remove();
// remove child nodes as well
this._svgGroup.selectAll("g.node")
.data(this._tree.nodes(d), function(d) {
return d.id;
}).filter(dojoLang.hitch(this,function(d, i) {
if (d.id == this._draggingNode.id) {
return false;
}
return true;
})).remove();
}
// remove parent link
this._svgGroup.selectAll('path.link').filter(dojoLang.hitch(this,function(d, i) {
if (d.target.id == this._draggingNode.id) {
return true;
}
return false;
})).remove();
this._dragStarted = null;
},
_pan : function(domNode, direction) {
var translateX,
translateY;
var speed = this._panSpeed;
if (this._panTimer) {
clearTimeout(this._panTimer);
var translateCoords = d3.transform(this._svgGroup.attr("transform"));
if (direction == 'left' || direction == 'right') {
translateX = direction == 'left' ? translateCoords.translate[0] + speed : translateCoords.translate[0] - speed;
translateY = translateCoords.translate[1];
} else if (direction == 'up' || direction == 'down') {
translateX = translateCoords.translate[0];
translateY = direction == 'up' ? translateCoords.translate[1] + speed : translateCoords.translate[1] - speed;
}
var scale = this._zoomListener.scale();
this._svgGroup.transition().attr("transform", "translate(" + translateX + "," + translateY + ")scale(" + scale + ")");
d3.select(domNode).select('g.node').attr("transform", "translate(" + translateX + "," + translateY + ")");
this._zoomListener.scale(this._zoomListener.scale());
this._zoomListener.translate([translateX, translateY]);
this._panTimer = setTimeout(function() {
this._pan(domNode, speed, direction);
}, 50);
}
},
_zoom : function() {
if (this.zoomEnabled){
if (this._svgGroup){
this._svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
}
},
// sort the tree according to the node names
_sortTree : function() {
this._tree.sort(function(a, b) {
return b.name.toLowerCase() < a.name.toLowerCase() ? 1 : -1;
});
},
// define the drag listeners for drag/drop behaviour of nodes.
_setupEvents : function(){
// if drag and drop is disabled only call expand / collapse behavior
// a drag event is also triggered when clicking.
this._dragListener = d3.behavior.drag()
.on("dragstart", dojoLang.hitch(this,function(d) {
this._dragStarted = true;
d3.event.sourceEvent.stopPropagation();
if (this.onClickMF && d){
console.debug(this._logNode + 'child node clicked!');
this._execMF(d);
}
// v2.2.0: else means dragging and dropping, this we do not want enabled on parent node
else if (d == this._root) {
return;
}
}));
if (this.dragDropEnabled){
// DRAG AND DROP
// also add dragstart and dragend events
this._dragListener = this._dragListener
.on("drag", dojoLang.hitch(this,function(d) {
if (d == this._root) {
return;
}
if (this._dragStarted) {
var domNode = document.getElementById("node_" + d.guid);
this._initiateDrag(d, domNode);
}
// get coords of mouseEvent relative to svg container to allow for panning
var svgNode = document.getElementsByClassName('overlay')[0];
var relCoords = d3.mouse(svgNode);
if (relCoords[0] < this._panBoundary) {
this._panTimer = true;
this._pan(this, 'left');
} else if (relCoords[0] > (svgNode.width - this._panBoundary)) {
this._panTimer = true;
this._pan(this, 'right');
} else if (relCoords[1] < this._panBoundary) {
this._panTimer = true;
this._pan(this, 'up');
} else if (relCoords[1] > (svgNode.height - this._panBoundary)) {
this._panTimer = true;
this._pan(this, 'down');
} else {
try {
clearTimeout(this._panTimer);
} catch (e) {
}
}
d.x0 += d3.event.dy;
d.y0 += d3.event.dx;
var node = d3.select("node_" + d.guid);
node.attr("transform", "translate(" + d.y0 + "," + d.x0 + ")");
this._updateTempConnector();
})).on("dragend", dojoLang.hitch(this,function(d) {
if (d == this._root) {
return;
}
var domNode = document.getElementById("node_" + d.guid);
if (this._selectedNode) {
// now remove the element from the parent, and insert it into the new elements children
var index = this._draggingNode.parent.children.indexOf(this._draggingNode);
if (index > -1) {
this._draggingNode.parent.children.splice(index, 1);
}
if (typeof this._selectedNode.children !== 'undefined' || typeof this._selectedNode._children !== 'undefined') {
if (typeof this._selectedNode.children !== 'undefined') {
this._selectedNode.children.push(this._draggingNode);
} else {
this._selectedNode._children.push(this._draggingNode);
}
} else {
this._selectedNode.children = [];
this._selectedNode.children.push(this._draggingNode);
}
// Make sure that the node being added to is expanded so user can see added node is correctly moved
this._expand(this._selectedNode);
this._sortTree();
this._endDrag(domNode);
} else {
this._endDrag(domNode);
}
}));
// SAVE NODE CHANGES
on(this.svgBtnSaveNodes,"click", dojoLang.hitch(this,function(){
this._saveChanges(this._root);
}));
this.svgBtnSaveNodes.innerHTML += this._saveBtnText;
} else {
// if drag and drop disabled, do not show save button
this.svgBtnSaveNodes.style.display = "none";
}
if (this.collapseExpandAllEnabled){
// COLLAPSE ALL
this.svgBtnCollapseAll.innerHTML += this._collapeAllBtnText;
on(this.svgBtnCollapseAll,"click", dojoLang.hitch(this,function(){
this._collapse(this._root);
}));
// EXPAND ALL
this.svgBtnExpandAll.innerHTML += this._expandAllBtnText;
on(this.svgBtnExpandAll,"click", dojoLang.hitch(this,function(){
this._expand(this._root);
}));
} else {
// if collapse and expand all disabled, do not show buttons
this.svgBtnCollapseAll.style.display = "none";
this.svgBtnExpandAll.style.display = "none";
}
},
// Function to update the temporary connector indicating dragging affiliation
_updateTempConnector : function() {
var data = [];
if (this._draggingNode !== null && this._selectedNode !== null) {
// have to flip the source coordinates since we did this for the existing connectors on the original tree
data = [{
source: {
x: this._selectedNode.y0,
y: this._selectedNode.x0
},
target: {