chart = {
const links = json.links.map(d => Object.create(d));
const nodes = json.nodes.map(d => Object.create(d));
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
svg
.append('rect')
.attr('width', '100%')
.attr('height', '100%')
.attr('fill', 'white')
.on('click', function() {
d3.selectAll('.link').style('opacity', '1');
d3.selectAll('.node').style('opacity', '1');
});
var container = svg.append('g');
svg.call(zoom(container));
var link = container
.append("g")
.attr("class", "links")
.selectAll("line");
var node = container
.append("g")
.attr("class", "nodes")
.selectAll("circle");
let toggle = 0;
var linkedByIndex = {};
for (let i = 0; i < nodes.length; i++) {
linkedByIndex[i + "," + i] = 1;
}
// Get the neighboring nodes and put them in linkedByIndex
json.links.forEach(function(d) {
linkedByIndex[d.source.index + ',' + d.target.index] = 1;
linkedByIndex[d.target.index + ',' + d.source.index] = 1;
});
// A function to test if two nodes are neighboring.
function neighboring(a, b) {
return linkedByIndex[a.index + ',' + b.index];
}
function connectedNodes() {
if (toggle == 0) {
let d = d3.select(this).node().__data__;
var neighbors = [];
node.style("opacity", function(o) {
neighboring(d, o) || neighboring(o, d) ? neighbors.push(o.id) : null;
return neighboring(d, o) || neighboring(o, d) ? 1 : 0.15;
});
link.style("opacity", function(o) {
return o.target == d || o.source == d ? 1 : 0.15;
});
var contents = [];
neighbors.forEach(function(item) {
contents.push("<li>" + item + "</li>");
});
console.log(contents);
return tooltip.html(
// style the contents of your tooltip here. This will replace the hover tooltip contents in tooltip below
"<h4>" + d.id + "</h4><ul>" + contents.join("") + "</ul>"
);
toggle = 1;
} else {
link.style("opacity", 1);
node.style("opacity", 1);
toggle = 0;
}
}
return Object.assign(svg.node(), {
update(nodes, links) {
link = link.data(links, function(d) {
return d.source.index + ", " + d.target.index;
});
link.exit().remove();
var linkEnter = link
.enter()
.append("line")
.attr('class', 'link')
.attr('stroke', 'gray');
link = linkEnter.merge(link);
node = node.data(nodes);
node.exit().remove();
var nodeEnter = node
.enter()
.append("circle")
.attr('r', function(d, i) {
return degreeSize(d.betweenness);
})
.attr("fill", color)
.attr('class', 'node')
.on("mouseover", (event, d) => tooltip_in(event, d))
.on("mouseout", tooltip_out)
.on('click', connectedNodes)
.call(drag(simulation));
node = nodeEnter.merge(node);
simulation.nodes(nodes).on("tick", ticked);
simulation.force("link").links(links);
simulation.alpha(1).restart();
function ticked() {
link
.attr("x1", function(d) {
return d.source.x;
})
.attr("y1", function(d) {
return d.source.y;
})
.attr("x2", function(d) {
return d.target.x;
})
.attr("y2", function(d) {
return d.target.y;
});
node
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
});
}
}
});
}