function SpaceTree(
data,
{
path,
id = Array.isArray(data) ? (d) => d.id : null,
parentId = Array.isArray(data) ? (d) => d.parentId : null,
children,
tree = d3.tree,
sort,
label,
title,
link,
linkTarget = "_blank",
width = 640,
height,
margin = { top: 10, right: 150, bottom: 10, left: 20 },
r = 3,
padding = 1,
fill = "#999",
fillOpacity,
stroke = "#555",
strokeWidth = 1.5,
strokeOpacity = 0.4,
strokeLinejoin,
strokeLinecap,
halo = "#fff",
haloWidth = 3,
curve = d3.curveBumpX,
thumbSize = 25,
transitionDuration = 1000,
highlight = "#ca2c92",
value = null,
onClick = null
} = {}
) {
// If id and parentId options are specified, or the path option, use d3.stratify
// to convert tabular data to a hierarchy; otherwise we assume that the data is
// specified as an object {children} with nested objects (a.k.a. the “flare.json”
// format), and use d3.hierarchy.
const root =
path != null
? d3.stratify().path(path)(data)
: id != null || parentId != null
? d3.stratify().id(id).parentId(parentId)(data)
: d3.hierarchy(data, children);
value = value || root;
// Sort the nodes.
if (sort != null) root.sort(sort);
// Compute labels and titles.
const descendants = root.descendants();
const diagonal = d3
.link(curve)
.x((d) => d.y)
.y((d) => d.x);
// Initially collapse everything beyond depth 1
descendants.forEach((d, i) => {
d.id = i;
d._children = d.children;
if (d.depth) d.children = null;
});
let dx, //vertical
dy; //horizontal
let heightFit = false;
const layout = tree();
// horizontal
dy = (width - margin.left - margin.right) / (root.height + padding);
if (!height) {
heightFit = false;
height = thumbSize * root.leaves().length + margin.top + margin.bottom;
// vertical
dx = thumbSize;
layout.nodeSize([dx, dy]);
} else {
heightFit = true;
// vertical
dx = (height - margin.top - margin.bottom) / root.leaves().length;
// height = thumbSize * root.leaves().length + 1;
layout.nodeSize([dx, dy]);
// layout.size([
// height - margin.top - margin.bottom,
// width - margin.left - margin.right
// ]);
}
layout(root);
let maxX, minX;
if (height) {
// Center the tree if we have fixed height
// Tree boundaries
minX = Infinity;
maxX = -minX; // y coordinates go down on svg, so max is negative (up)
root.each((d) => {
if (d.x > maxX) maxX = d.x;
if (d.x < minX) minX = d.x;
});
}
// Default positions to come back to when collapsing
root.x0 = dy / 2;
root.y0 = 0;
// Use the required curve
if (typeof curve !== "function") throw new Error(`Unsupported curve`);
const svg = d3
.create("svg")
.attr("viewBox", [
-margin.left,
-margin.top,
width - margin.left - margin.right,
height - margin.top - margin.bottom
])
.style("font", "10px sans-serif")
.style("user-select", "none");
svg.append("defs").html(`
<style>
.highlight circle { fill:${highlight} }
.highlight circle { fill:${highlight} }
.highlight text { fill:${highlight} }
.leaf circle { fill:${highlight} }
.leaf circle { fill:${highlight} }
.leaf text { fill:${highlight} }
path.highlight { stroke:${highlight} }
<style>`);
const gLink = svg
.append("g")
.attr("fill", "none")
.attr("stroke", stroke)
.attr("stroke-opacity", strokeOpacity)
.attr("stroke-linecap", strokeLinecap)
.attr("stroke-linejoin", strokeLinejoin)
.attr("stroke-width", strokeWidth);
const gNode = svg
.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");
function removeThumb(source) {
return svg
.selectAll("image.thumb")
.filter((d) => d === source)
.transition()
.duration(transitionDuration / 5)
.attr("opacity", 0);
}
function addThumb(nodeIds) {
// console.log("add Thumbs", nodeIds);
return svg
.selectAll("image.thumb")
.filter(
(d) => typeof nodeIds?.includes === "function" && nodeIds.includes(d.id)
)
.transition()
.duration(transitionDuration / 5)
.attr("opacity", 1);
}
// ******* Internal Click Event ***************
async function _onClick(event, d, triggerEvent = true) {
// ***** EVENT Triggering
value = d;
// Trigger an input event change with the current subtree
if (triggerEvent)
svg.node().dispatchEvent(new Event("input", { bubbles: true }));
// Call the onClick user function
if (triggerEvent && onClick && typeof onClick === "function") onClick(d);
try {
// Start the animation
// Then trim
const trimmingNodes = trim(d);
// Wait for trimming to finish
await update(d, trimmingNodes).end();
// Add the thumb for the trimming nodes;
await addThumb(trimmingNodes).end();
// Remove the thumb of the source
await removeThumb(d).end();
// Then expand
expand(d);
await update(d, trimmingNodes).end();
// Finally add the thumb for the collapsed node
addThumb([d.id]);
} catch (e) {
console.log("Error running animation", e);
}
}
function update(source, trimmingNodes = []) {
value = source;
const duration =
d3.event && d3.event.altKey
? transitionDuration * 10
: (transitionDuration * 2) / 5;
const nodes = root.descendants().reverse();
const links = root.links();
if (heightFit) {
dx = (height - margin.top - margin.bottom) / root.leaves().length;
layout.nodeSize([dx, dy]);
}
// Compute the new tree layout.
layout(root);
let left = root;
let right = root;
root.eachBefore((node) => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});
let _height = heightFit ? height : right.x - left.x + dx * 2;
// let _height = height || right.x - left.x + dx * 2;
let transition = svg
.transition()
.duration(duration)
// .attr("viewBox", [-margin.left, left.x - margin.top, width, _height])
.attr("viewBox", [
(-dy * padding) / 2,
heightFit ? -_height / 2 : left.x - dx,
width - margin.left - margin.right,
_height
])
.attr("width", width)
.attr("height", _height)
// .attr("style", "max-width: 100%; height: auto; height: intrinsic;")
.tween(
"resize",
window.ResizeObserver ? null : () => () => svg.dispatch("toggle")
);
const context = {
gNode,
transition,
nodes,
source,
update,
r,
stroke,
fill,
label,
halo,
haloWidth,
links,
diagonal,
gLink,
thumbSize,
curve,
root,
_onClick,
trimmingNodes
};
const node = updateNodes(context);
const link = updateLinks(context);
updatePath({ node, link, root, source });
// Stash the old positions for transition.
root.eachBefore((d) => {
d.x0 = d.x;
d.y0 = d.y;
});
return transition;
}
update(root);
// Set initial value
svg.node().value = root;
// Update the display whenever the value changes
Object.defineProperty(svg.node(), "value", {
get() {
return value;
},
set(v) {
_onClick(null, v, false);
}
});
return svg.node();
}