class Tree {
constructor(json) {
this.nodes = [];
for (let i = 0; i < json.length; i++) {
this.nodes.push(new Node(json[i].name, json[i].parent));
}
for (let i = 0; i < this.nodes.length; i++) {
for (let j = 0; j < this.nodes.length; j++) {
if(this.nodes[j].parentName == this.nodes[i].name){
this.nodes[i].addChild(this.nodes[j]);
this.nodes[j].parentNode = this.nodes[i]}}}
}
buildLayout() {
this.assignLevel(this.nodes[0], 0)
this.assignPosition(this.nodes[0], 0)
return this;
}
assignLevel(node, level) {
node.level = level;
for (let child of node.children) {
this.assignLevel(child,level+1);
}
}
assignPosition(node, position) {
node.position = position;
if (node.children.length == 0) {
return position + 1;
}
for (let child of node.children) {
position = this.assignPosition(child, position);
}
return position;
}
render() {
const svg = d3.create('svg')
.attr('width', 600)
.attr('height', 800);
const linearScale = d3.scaleLinear()
.domain([0,4])
.range([0,400])
const g = svg.append('g')
.classed('nodeGroup', true)
.classed('label', true)
.attr('transform', 'translate(50, 50)')
g.selectAll('circle')
.data(this.nodes)
.join('circle')
.attr("cx", d => linearScale(d.level))
.attr("cy", d => linearScale(d.position))
.attr('r', 30)
g.selectAll('line')
.data(this.nodes)
.join('line')
.text(d => d.name)
g.selectAll('text')
.data(this.nodes)
.join('text')
.attr("x", d => linearScale(d.level))
.attr("y", d => linearScale(d.position))
.text(d => d.name)
return svg.node();
}
}