container = {
const svg = d3.select(DOM.svg(width, height));
const defs = svg.append("defs");
const view = svg.append("g")
.classed("view", true)
.attr("transform", `translate(${margin}, ${margin})`);
const nodes = view.selectAll("rect.node")
.data(graph.nodes)
.join("rect")
.attr("x", d => d.x0)
.attr("y", d => d.y0)
.attr("width", d => d.x1 - d.x0)
.attr("height", d => Math.max(1, d.y1 - d.y0))
.attr("fill", d => d.color)
.attr("opacity", 1);
nodes.append("title").text(d => `${d.name}\n${(d.value)}`);
view.selectAll("text.node")
.data(graph.nodes)
.join("text")
.attr("x", d => d.x1)
.attr("dx", 6)
.attr("y", d => (d.y1 + d.y0) / 2)
.attr("dy", "0.35em")
.attr("fill", "black")
.attr("text-anchor", "start")
.attr("font-size", 10)
.attr("font-family", "Helvetica, sans-serif")
.text(d => d.name)
.filter(d => d.x1 > width / 2)
.attr("x", d => d.x0)
.attr("dx", -6)
.attr("text-anchor", "end");
// Define the gray links.
const links = view.selectAll("path.link")
.data(graph.links)
.join("path")
.attr("d", d3WithSankey.sankeyLinkHorizontal())
.attr("stroke", "black")
.attr("stroke-opacity", 0.1)
.attr("stroke-width", d => Math.max(1, d.width))
.attr("fill", "none");
// Add hover effect on the links.
links.append("title").text(d => `${d.source.name} ${arrow} ${d.target.name}\n${(d.value)}`);
// Reference for the following code: https://observablehq.com/@jarrettmeyer/sankey-with-animated-gradients
// Define the default dash behavior for colored gradients.
function setDash(link) {
let el = view.select(`#${link.path.id}`);
let length = el.node().getTotalLength();
el.attr("stroke-dasharray", `${length} ${length}`)
.attr("stroke-dashoffset", length);
}
// Define the gray links
const grayLinks = view.selectAll("path.gray-link")
.data(graph.links)
.join("path")
.classed("gray-link", true)
.attr("id", d => d.path.id)
.attr("d", d3WithSankey.sankeyLinkHorizontal())
.attr("stroke", "black")
.attr("stroke-opacity", 0)
.attr("stroke-width", d => Math.max(1, d.width))
.attr("fill", "none")
.each(setDash);
//Link animation activated when mouse hovers on nodes
//Using nested function to continue animation beyond the selected node
function branchAnimate(evt, node) {
if (node === undefined) node = evt;
let links = view.selectAll("path.gray-link")
.filter((link) => {
return node.sourceLinks.indexOf(link) !== -1;
});
let nextNodes = [];
links.each((link) => {
nextNodes.push(link.target);
});
links.attr("stroke-opacity", 0.3)
.transition()
.duration(duration)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
.on("end", () => {
nextNodes.forEach((node) => {
branchAnimate(node);
});
});
}
function branchClear() {
grayLinks.transition();
grayLinks.attr("stroke-opactiy", 0)
.each(setDash);
}
nodes.on("mouseover", branchAnimate)
.on("mouseout", branchClear);
return svg
}