function wrap(
text,
width,
dyAdjust,
lineHeightEms,
lineHeightSquishFactor,
splitOnHyphen,
centreVertically
) {
if (!lineHeightEms) lineHeightEms = 1.05;
if (!lineHeightSquishFactor) lineHeightSquishFactor = 1;
if (splitOnHyphen == null) splitOnHyphen = true;
if (centreVertically == null) centreVertically = true;
text.each(function () {
var text = d3.select(this),
x = text.attr("x"),
y = text.attr("y");
var words = [];
text
.text()
.split(/\s+/)
.forEach(function (w) {
if (splitOnHyphen) {
var subWords = w.split("-");
for (var i = 0; i < subWords.length - 1; i++)
words.push(subWords[i] + "-");
words.push(subWords[subWords.length - 1] + " ");
} else {
words.push(w + " ");
}
});
text.text(null);
var tspan = text.append("tspan");
var line = "";
var prevLine = "";
var nWordsInLine = 0;
for (var i = 0; i < words.length; i++) {
var word = words[i];
prevLine = line;
line = line + word;
++nWordsInLine;
tspan.text(line.trim());
if (tspan.node().getComputedTextLength() > width && nWordsInLine > 1) {
tspan.text(prevLine.trim());
prevLine = "";
line = word;
nWordsInLine = 1;
tspan = text.append("tspan").text(word.trim());
}
}
var tspans = text.selectAll("tspan");
var h = lineHeightEms;
if (tspans.size() > 2)
for (var i = 0; i < tspans.size(); i++) h *= lineHeightSquishFactor;
tspans.each(function (d, i) {
var dy = i * h + dyAdjust;
if (centreVertically) dy -= ((tspans.size() - 1) * h) / 2;
d3.select(this)
.attr("y", y)
.attr("x", x)
.attr("dy", dy + "em");
});
});
}