title: Sunburst Diagram Intelligent Text Wrapping
body: <p>I have a zoomable sunburst diagram based on the great d3 "coffee wheel" example:</p>
  
  <p><img src="https://i.stack.imgur.com/xVm07.png" alt="enter image description here"></p>
  
  <p>In that example there is simple text wrapping code that searches for a space in a label and wraps the text at the first space character:</p>
  
  <pre><code>var textEnter = text.enter().append("text")
    .style("fill-opacity", 1)
    .style("fill", function(d) {
        return brightness(d3.rgb(colour(d))) &lt; 125 ? "#eee" : "#000";
    })
    .attr("text-anchor", function(d) {
        return x(d.x + d.dx / 2) &gt; Math.PI ? "end" : "start";
    })
    .attr("dy", ".2em")
    .attr("transform", function(d) {
        var multiline = (d.name || "").split(" ").length &gt; 1,
        angle = x(d.x + d.dx / 2) * 180 / Math.PI - 90,
        rotate = angle + (multiline ? -.5 : 0);
        return "rotate(" + rotate + ")translate(" + (y(d.y) + padding) +
                ")rotate(" + (angle &gt; 90 ? -180 : 0) + ")";
        })
    .on("click", click);
  
  textEnter.append("tspan")
    .attr("x", 0)
    .text(function(d) {
        return d.depth ? d.name.split(" ")[0] : "";
    });
  
  textEnter.append("tspan")
    .attr("x", 0)
    .attr("dy", "1em")
    .text(function(d) {
        return d.depth ? d.name.split(" ")[1] || "" : "";
    });
  </code></pre>
  
  <p>This code works fine, but it is very basic, especially if the whole label would have fitted on one line in the available sunbust segment (eiether because the particular label is short or the available space is large enough as the sunburst is zoom'ed). In densely packed sunbursts wrapping the labels unnecesarily causes the diagram to look messy/cluttered.</p>
  
  <ol>
  <li><p>I would like to make the text processing more intelligent and compare the length of the label with the available space (noting that the "width" of a segment changes depending on the depth of segments visible when zoom'ed).</p></li>
  <li><p>Also if the available space for the label is known then the text wrapping could be more intelligent eg if the label contains more than two words code can decide whether it is better to  break at first space or second.</p></li>
  </ol>
  
  <p>If anyone has already solved this problem and has some example, greatly appreciated if it can be shared. Alternatively if anyone has any ideas about how the length of a label can be compared to the changing available space?</p>