function textwrap(
chart,
width = 500,
selector = "text",
lineHeightEms = 1.05,
lineHeightSquishFactor = 1,
splitOnHyphen = true,
centreVertically = true
) {
const text = d3.select(chart).selectAll("text");
text.each(function () {
const text = d3.select(this);
const x = text.attr("x");
const y = text.attr("y");
const textStyle = text.attr("style");
console.log(text.text());
const words = [];
text
.text()
.split(/\s+/)
.forEach(function (w) {
if (splitOnHyphen) {
const 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);
text.attr("style", textStyle);
text.attr("dy", "1em");
let tspan = text.append("tspan").attr("style", textStyle);
let line = "";
let prevLine = "";
let nWordsInLine = 0;
for (var i = 0; i < words.length; i++) {
let 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");
tspan.attr("style", textStyle);
tspan.text(word.trim());
}
}
const tspans = text.selectAll("tspan");
let h = lineHeightEms;
if (tspans.size() > 2)
for (var i = 0; i < tspans.size(); i++) h *= lineHeightSquishFactor;
tspans.each(function (d, i) {
let dy = i * h;
d3.select(this)
.attr("y", y)
.attr("x", x)
.attr("dy", dy + "em");
});
});
}