I've been working for a while to get the width and height of a label from a d3 node. I have an icon on the node that will toggle a subGraph. But I need the node's width and height to be set dynamically based on the size of the label. Once I get the width of the label I can then make room for the icon. Label sizes may change so I need to know the width. Here is what I have, I am using dagre-d3 to position and render the nodes:
nodes = [
{id: 1, shape: "diamond", label: "Start"}
]
for (var i = 0; i < nodes.length; i++) {
g.setNode(nodes[i].id, {
label: nodes[i].label
width: // I want to set the width here based on the width of the label
});
}
Been struggling with this any help is greatly appreciated. Happy to show more code if needed.
UPDATE:
Here is what I am doing to get the text of each node:
svgGroup.selectAll("tspan").each(function (object:any) {
object = parseInt(object, 10) // gives me the id of each node
var nodeObject = g.node(object); // get the full node
var length = this.getComputedTextLength();
for (var i = 0; i < nodes.length; i++) {
if (node[i].id === object) {
// add the node label width to the nodes array
nodes[i].labelWidth = length;
}
}
}
The above allows me to set the width of the node based on the label + toggle icon. The one problem I'm having is if a node has a sub graph I'm noticing that "svgGroup.selectAll("tspan")" is only getting the top level nodes. For example, my nodes look like this:
this.nodes = [
{id: 1, shape: "ellipse", label: "start",
subGraph: {
nodes = [
{id: 10, shape: "ellipse", label: "SubNode1"},
{id: 11, shape: "ellipse", label: "SubNode2"}
],
edges = [
{from: 10, to: 11, type: "vee", label: ""}
]
}
},
{id: 2, shape: "rect", label: "Square"}
]
The "svgGroup.selectAll" statement only gets the tspan for the top nodes with id 1 and id 2. Is there a way to get the tspan for the subGraph nodes of id 10 and id 11. Because id 10 or 11 could potentially have a subGraph nested within it, if thats the case I need to get the label width for those nodes as well.