Skip to content

Instantly share code, notes, and snippets.

@robert-moore
Last active August 8, 2017 22:08
Show Gist options
  • Save robert-moore/ad3b0e8c2d73924b83e7b0f0aca0025c to your computer and use it in GitHub Desktop.
Save robert-moore/ad3b0e8c2d73924b83e7b0f0aca0025c to your computer and use it in GitHub Desktop.
function wrap(d) {
var allowedWidth = (x(d.x + d.dx) - x(d.x))*0.85;
var self = d3.select(this),
textLength = self.node().getComputedTextLength(),
text = self.text();
while (textLength > allowedWidth && text.length > 0) {
text = text.slice(0, -1);
self.text(text + '...');
textLength = self.node().getComputedTextLength();
}
}
function wrap(allowedWidth, val) {
var valuePadding = val ? 0.15 : 0;
return function(d) {
var pad = 1 - (valuePadding * (d.col == 2 ? 2 : 1));
var self = d3.select(this),
textLength = self.node().getComputedTextLength(),
text = self.text();
while (textLength > (allowedWidth * pad * 0.80) && text.length > 0) {
text = text.slice(0, -1);
self.text(text + '...');
textLength = self.node().getComputedTextLength();
}
};
}
svg.selectAll('g.item text.label')
.text(function(d) { return d.name })
.each(wrap(itemWidth, false));
function wrap(text, width, height, verticalAlign) {
text.each(function() {
var words = text.text().split(/\s+/).reverse(),
word,
totalHeight,
line = [],
lastLine,
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
x = text.attr("x"),
dy = text.attr("dy"),
tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", "1em");
while (word = words.pop()) { // while there are still words take off the next
line.push(word); // add the word
tspan.text(line.join(" ")); // modify the tspan to match the line
if (tspan.node().getComputedTextLength() > width) { // if the next word won't fit on the line
line.pop(); //pull it off
if(line.length == 0) {lineNumber--};
tspan.text(line.join(" ")); // recreate the line without the word
line = [word]; // assign the last word that wouldn't fit to the new line and then assing to new tspan
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + 1 + "em").text(word);
}
}
totalHeight = text.node().getBBox().height;
while(totalHeight > height) {
globalText = text;
text.selectAll("tspan").last().remove();
totalHeight = text.node().getBBox().height;
}
// add ellipsis if over length
lastLine = text.selectAll("tspan").last();
lastLine.each( wrapLineClosure(width) );
totalHeight = text.node().getBBox().height;
if(verticalAlign) {
text.attr("transform", "translate(0, " + ((height - totalHeight) / 2) + ")");
}
});
}
d3.selectall('p').text(function(d) { return d}).each(wrap)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment