chart = {
const links = data.links;
const nodes = data.nodes;
const forceLink = d3.forceLink(links)
.id(d => d.id)
.distance(link => {
const scale = d3.scaleSqrt()
.domain([0, 11])
.range([30, 70]);
return scale(link.distance);
})
.strength(link => 1 / Math.min(link.source.count, link.target.count));
const simulation = d3.forceSimulation(nodes)
.force("link", forceLink)
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.call(d3.zoom()
.scaleExtent([1 / 2, 4])
.on("zoom", zoomed));
const container = svg.append("g");
svg.on("click", (e) => {
if (e.target === svg.node()) {
link.style("stroke-opacity", 0.6);
node.style("opacity", 0.8);
text.attr("display", "block");
}
});
function zoomed({transform}) {
container.attr("transform", transform);
}
const link = container.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line")
.attr("stroke-width", linkWidth);
const node = container.append("g")
.attr("opacity", 0.8)
.attr("stroke", "#fff")
.attr("stroke-width", 2)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", nodeSize)
.attr("fill", color)
.call(drag(simulation));
node.append("title")
.text(d => d.id);
const text = container.append("g")
.attr("class", "labels")
.selectAll("g")
.data(nodes)
.enter().append("g");
text.append("text")
.attr("fill", "black")
.attr("stroke", "#fff")
.attr("stroke-width", 3)
.attr("paint-order", "stroke fill")
.attr("pointer-events", "none")
.attr("text-anchor", "middle")
.attr("dy", labeldY)
.style("font-family", "sans-serif")
.style("font-size", labelSize)
.text(function(d) { return d.id; })
node.on("click", (_, d) => {
var _nodes = [d]
link.style('stroke-opacity', function(l) {
if (d === l.source) {
_nodes.push(l.target);
return 1.0;
} else if (d === l.target) {
_nodes.push(l.source);
return 1.0;
}
else return 0.3;
});
node.style("opacity", function(n) {
return _nodes.indexOf(n) !== -1 ? 0.8 : 0.3;
});
text.attr("display", function(t) {
return _nodes.indexOf(t) !== -1 ? "block": "none";
});
});
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
text
.attr("transform", d => `translate(${d.x}, ${d.y})`);
});
invalidation.then(() => simulation.stop());
return svg.node();
}