Public
Edited
Jan 5, 2023
1 fork
Importers
Insert cell
# Utils

Some utility functions used across my modules.
Insert cell
function get_bbox(svg, nm) {
let ssvg = svg.node();
document.body.append(ssvg)
const mbox = ssvg.querySelector(`[name="${nm}"]`).getBBox()
ssvg.remove()
return mbox;
}
Insert cell
function get_text_length(svg, nm) {
let ssvg = svg.node();
document.body.append(ssvg)
let txtspan = ssvg.querySelector(`[name="${nm}"]`)
// let lth = txtspan.node().getComputedTextLength()
ssvg.remove()
return 0 // lth;
}
Insert cell
// ARGS:
// - txt (text object to be tested/change)
// - maxwidth (max width in pixels)
// - fsz (font size)
// - txtnm (name of text object)
// - svg
// function wrap_text(txt, maxwidth, fsz = 14, txtnm = "", svg = null) {
function wrap_text(txt, maxwidth, fsz , txtnm ,svg ) {

//let ww = t._groups[0][0].getBBox().width;
//let hh = t._groups[0][0].getBBox().height;
let word;
let words = txt.text().split(/\s+/).reverse()
let xx = txt.text()
let line = [],
lineHeight = 1.1, // ems
y = txt.attr("y"),
x = txt.attr("x"),
lineno = 0,
tspan = txt.text(null)
.append("tspan")
.attr("name", `TXT_${xx}`)
.attr("x", x)
.style("font-size", `${fsz}pt`)
.attr("y", y)
// nxtline
while(word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
let bx = get_bbox(svg, `TXT_${xx}`)
let hh = bx.height / (lineno + 1);

if (bx.width > maxwidth) {
lineno += 1;
line.pop();
tspan.text(line.join(" "));
line = [word];
let addy = parseInt(y) + (hh*lineno)
tspan = txt.append("tspan")
.attr("x", x)
.attr("y", addy)
.style("font-size", `${fsz}pt`)
.text(word);
}
}
lineno = 0;
}
Insert cell
function get_padded_range(yext, pad = 0.25, ctype = "line") {
let range = yext[1] - yext[0]
let rangepad = range * .25
// console.log(`Range: [${yext[0]}, ${yext[1]}] (${range}) | Rangepad: ${rangepad}`)
let ymm = (yext[0] >= 0 && yext[0] - range < 0 ? 0 : yext[0] - rangepad)
if(ctype == "bar") {
ymm = (yext[0] < 0 ? yext[0] - (range * .05) : 0)
}
return [ymm, yext[1] + rangepad];
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more