chart = {
const width = 928;
const height = 600;
const color = d3.scaleOrdinal(d3.schemeCategory10);
const links = this ? this.links : data.links.map((d) => ({ ...d }));
const nodes = this ? this.nodes : data.nodes.map((d) => ({ ...d }));
const simulation = d3
.forceSimulation(nodes)
.force(
"link",
d3.forceLink(links).id((d) => d.id)
)
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2))
.on("tick", ticked);
let bundling =
useEdgeBundling &&
edgeBundling(
{ nodes, links },
{
compatibility_threshold,
bundling_stiffness,
step_size
}
);
const line = d3
.line()
.x((d) => d.x)
.y((d) => d.y);
// **** /edge-bundling ****
// Create or reuse the SVG container.
const svg = (this ? d3.select(this) : d3.create("svg"))
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto;");
// Add a line for each link, and a circle for each node.
const link = svg
.selectAll("g#links")
.data([links])
.join("g")
.attr("id", "links")
.attr("stroke", "#999")
.attr("fill", "none")
.attr("stroke-opacity", 0.6)
.selectAll("path")
.data((d) => d)
.join("path")
.attr("stroke-width", (d) => Math.sqrt(d.value));
const node = svg
.selectAll("g#nodes")
.data([nodes])
.join("g")
.attr("id", "nodes")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data((d) => d)
.join("circle")
.attr("r", 5)
.attr("fill", (d) => color(d.group));
node
.selectAll("title")
.join("title")
.text((d) => d.id);
// Add a drag behavior.
node.call(
d3.drag().on("start", dragstarted).on("drag", dragged).on("end", dragended)
);
// Set the position attributes of links and nodes each time the simulation ticks.
function ticked() {
// The edge bundling plugin generates a path attribute in the links;
link.attr("d", (l) =>
line(useEdgeBundling && l.path ? l.path : [l.source, l.target])
);
node.attr("cx", (d) => d.x).attr("cy", (d) => d.y);
useEdgeBundling && bundling && bundling.update();
}
// Reheat the simulation when drag starts, and fix the subject position.
function dragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}
// Update the subject (dragged node) position during drag.
function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}
// Restore the target alpha so the simulation cools after dragging ends.
// Unfix the subject position now that it’s no longer being dragged.
function dragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
// When this cell is re-run, stop the previous simulation. (This doesn’t
// really matter since the target alpha is zero and the simulation will
// stop naturally, but it’s a good practice.)
invalidation.then(() => simulation.stop());
ticked();
svg.node().nodes = nodes;
svg.node().links = links;
return svg.node();
}