Skip to content

Commit 7366ef3

Browse files
authored
Refactor SVG text wrapping functions and add new ones
1 parent bfa9903 commit 7366ef3

1 file changed

Lines changed: 40 additions & 7 deletions

File tree

utils/allFunction.js

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ function wrapSVGText(text, maxCharsPerLine = 25, lineHeight = 16) {
1818
).join("");
1919
}
2020

21-
function wrapSVGTextCentered(text, maxCharsPerLine = 25, lineHeight = 16, svgHeight = 400, svgWidth = 600) {
21+
function wrapSVGTextLeft(text, maxCharsPerLine = 25, lineHeight = 16, xPos = 40) {
2222
const words = text.split(" ");
2323
const lines = [];
2424
let line = "";
@@ -33,22 +33,55 @@ function wrapSVGTextCentered(text, maxCharsPerLine = 25, lineHeight = 16, svgHei
3333
}
3434
if (line) lines.push(line.trim());
3535

36-
const totalHeight = lines.length * lineHeight;
37-
const startY = (svgHeight - totalHeight) / 2;
38-
3936
return lines.map((l, i) =>
40-
`<tspan x="${svgWidth / 2}" dy="${i === 0 ? startY : lineHeight}" text-anchor="middle">${l}</tspan>`
37+
`<tspan x="${xPos}" dy="${i === 0 ? 0 : lineHeight}" text-anchor="start">${l}</tspan>`
4138
).join("");
4239
}
4340

4441

45-
4642
function capitalize(str = "") {
4743
str = str.toLowerCase()
4844
return str.charAt(0).toUpperCase() + str.slice(1);
4945
}
5046

47+
function escapeXML(str = "") {
48+
return String(str)
49+
.replace(/&/g, "&amp;")
50+
.replace(/</g, "&lt;")
51+
.replace(/>/g, "&gt;");
52+
}
53+
54+
function svgMultiline(text, lineHeight = 18) {
55+
return escapeXML(text)
56+
.split('\n')
57+
.map((line, i) => `<tspan x="0" dy="${i === 0 ? 0 : lineHeight}">${line}</tspan>`)
58+
.join('');
59+
}
60+
61+
function wrapSVGTextCenter(text, x, y, maxCharsPerLine = 30, lineHeight = 18) {
62+
const words = text.split(" ");
63+
const lines = [];
64+
let line = "";
65+
66+
for (const w of words) {
67+
if ((line + w).length > maxCharsPerLine) {
68+
lines.push(line.trim());
69+
line = w + " ";
70+
} else {
71+
line += w + " ";
72+
}
73+
}
74+
if (line) lines.push(line.trim());
75+
76+
const totalHeight = (lines.length - 1) * lineHeight;
77+
const startY = y - totalHeight / 2;
78+
return lines
79+
.map((l, i) =>
80+
`<tspan x="${x}" y="${startY + i * lineHeight}" text-anchor="middle">${l}</tspan>`
81+
)
82+
.join("");
83+
}
5184

5285

53-
module.exports = { wrapSVGText, wrapSVGTextCentered, capitalize };
5486

87+
module.exports = { wrapSVGText, capitalize, wrapSVGTextLeft, escapeXML, svgMultiline, wrapSVGTextCenter };

0 commit comments

Comments
 (0)