chart = {
const width = 1200;
const root = filteredHierarchyData;
const maxDepth = d3.max(root.descendants(), (d) => d.depth);
const marginLeft = Math.max(40, (maxDepth + 1) * 10);
const marginRight = Math.max(10, (maxDepth + 1) * 10);
const marginTop = Math.max(10, (maxDepth + 1) * 10);
const marginBottom = Math.max(10, (maxDepth + 1) * 10);
const dx = 20;
const dy = (width - marginRight - marginLeft) / (1 + root.height);
const treeLayout = d3.tree().nodeSize([dx, dy]);
const maxCount = d3.max(root.descendants(), (d) => d.value) || 1;
const colorScale = d3.scaleOrdinal(d3.schemeTableau10).domain([0, maxCount]);
const diagonal = d3
.linkHorizontal()
.x((d) => d.y)
.y((d) => d.x);
const svg = d3
.create("svg")
.attr("width", width)
.attr("viewBox", [-marginLeft, -marginTop, width, dx])
.style("max-width", "100%")
.style("height", "auto")
.style("font", "15px sans-serif");
const gLink = svg
.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5);
const gNode = svg
.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");
// Update function for rendering and transitioning the tree
function update(event, source) {
const duration = event?.altKey ? 2500 : 250; // Hold alt key to slow down transitions
const nodes = root.descendants().reverse();
const links = root.links();
// Compute the new tree layout
treeLayout(root);
let left = root;
let right = root;
root.eachBefore((node) => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});
const height = right.x - left.x + marginTop + marginBottom;
const transition = svg
.transition()
.duration(duration)
.attr("viewBox", [-marginLeft, left.x - marginTop, width, height])
.tween(
"resize",
window.ResizeObserver ? null : () => () => svg.dispatch("toggle")
);
// Update the nodes
const node = gNode.selectAll("g").data(nodes, (d) => d.id);
// Enter new nodes at the parent's previous position
const nodeEnter = node
.enter()
.append("g")
.attr("transform", (d) => `translate(${source.y0},${source.x0})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0)
.on("click", (event, d) => {
if (d.children) {
// Collapse: store children in _children before nullifying
d._children = d.children;
d.children = null;
} else if (d._children) {
// Expand: restore children from _children
d.children = d._children;
d._children = null;
} else {
// Handle leaf nodes (no children to toggle)
return;
}
update(event, d);
});
// Add tooltip functionality
nodeEnter.append("title").text((d) => {
const path = d
.ancestors()
.reverse()
.map((n) => n.data.name)
.join(" → ");
return `${path}\nCount: ${d.value || 1}`;
});
// Define a scaling function for circle sizes
const maxCount = d3.max(root.descendants(), (d) => d.value) || 1;
const sizeScale = d3.scaleSqrt().domain([0, maxCount]).range([5, 50]); // Minimum radius = 5, Maximum radius = 50
nodeEnter
.append("circle")
.attr("r", (d) => {
const scaledSize = sizeScale(d.value || 1);
return Math.min(scaledSize, 50);
}) // Cap the radius
.attr("fill", (d) => colorScale(d.value)) // Color collapsed vs expanded nodes
.attr("stroke-width", 10);
nodeEnter
.append("text")
.attr("dy", "0.31em")
.attr("x", (d) => (d._children ? -6 : 6))
.attr("text-anchor", (d) => (d._children ? "end" : "start"))
.text((d) => d.data.name)
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.attr("stroke", "white")
.attr("paint-order", "stroke");
// Transition nodes to their new position
const nodeUpdate = node
.merge(nodeEnter)
.transition(transition)
.attr("transform", (d) => `translate(${d.y},${d.x})`)
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);
// Transition exiting nodes to the parent's new position
const nodeExit = node
.exit()
.transition(transition)
.remove()
.attr("transform", (d) => `translate(${source.y},${source.x})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0);
// Update the links
const link = gLink.selectAll("path").data(links, (d) => d.target.id);
// Enter new links at the parent's previous position
const linkEnter = link
.enter()
.append("path")
.attr("d", (d) => {
const o = { x: source.x0, y: source.y0 };
return diagonal({ source: o, target: o });
});
// Transition links to their new position
link.merge(linkEnter).transition(transition).attr("d", diagonal);
// Transition exiting links to the parent's new position
link
.exit()
.transition(transition)
.remove()
.attr("d", (d) => {
const o = { x: source.x, y: source.y };
return diagonal({ source: o, target: o });
});
// Stash the old positions for transition
root.eachBefore((d) => {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Initialize the tree
root.x0 = dx / 2;
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = i;
if (d.depth >= 1) {
d._children = d.children; // Store children in _children
d.children = null; // Collapse nodes beyond Battalion level initially
}
});
update(null, root);
return svg.node();
// Add color legend
const legend = svg
.append("g")
.attr("transform", `translate(${width - 150}, 20)`) // Position legend in top-right corner
.selectAll(".legend")
.data(colorScale.domain())
.join("g")
.attr("class", "legend")
.attr("transform", (d, i) => `translate(0, ${i * 20})`);
legend
.append("rect")
.attr("width", 18)
.attr("height", 18)
.attr("fill", (d) => colorScale(d));
legend
.append("text")
.attr("x", 24)
.attr("y", 9)
.attr("dy", "0.35em")
.text((d) => `Level ${d}`);
return svg.node();
}