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
| var treeData = [
{
"name": "Top Level",
"weight": -1,
"status" : -1,
"parent": "null",
"children": [
{
"name": "Level 2: A",
"weight": 2,
"status" : 1,
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"weight": 3,
"status" : 0,
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"weight": 4,
"status" : 0,
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"weight": 2,
"status" : 1,
"parent": "Top Level"
}
]
}
];
/************** Generate the tree diagram *****************/
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var i = 0;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var body = d3.select("body");
var svg = body.append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var root = treeData[0];
var clickedNode;
update(root);
function update(source) {
// compute the new tree layout.
var nodes = tree.nodes(source).reverse(),
links = tree.links(nodes);
// normalize for fixed-depth.
nodes.forEach(function(d) {
d.y = d.depth * 180;
});
// declare the nodes
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter the nodes.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")"; })
.on("click", function(d) {
var node = {
"name": "temp",
"weight": 2,
"status" : 1,
"parent": d
};
if(typeof d.children == "undefined") {
d.children = [node];
} else {
d.children.push(node);
}
update(d);
});
nodeEnter.append("circle")
.attr("class", "nodeCir")
.attr("r", 30)
.style("fill", function(d) { return d.status ? "#83AF9B" : "#AF4933"; });
nodeEnter.append("text")
.attr("text-anchor", "middle")
.html(function(d) { return d.name + "<br/>" + d.weight; });
// Declare the links
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter the links.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", diagonal);
} |