bars = () => {
const x = d3.scaleLinear().domain([0, d3.sum(barsData, d => d.days)]);
const color = threshold => palette[thresholds.indexOf(threshold)];
const colorText = threshold => paletteText[thresholds.indexOf(threshold)];
const wrapper = d3.create("div").attr("class", "bars");
const svg = wrapper.append("svg").style("display", "table").style("margin", "0 auto")
const g = svg.append("g");
const rect = g.selectAll("rect")
.data(barsData)
.join("rect")
.attr("fill", d => color(d.threshold))
.attr("stroke", d => colorText(d.threshold));
const label = g.selectAll(".label")
.data(barsData)
.join("text")
.attr("class", "label")
.attr("y", d => -6 - ((d.word_count - 1) * 16))
.html(d => d.html);
label.selectAll("tspan")
.attr("x", 0)
.attr("dy", (_, i) => i * 16);
const value = g.selectAll(".value")
.data(barsData)
.join("text")
.attr("class", "value")
.attr("fill", d => colorText(d.threshold))
.attr("x", 4);
return Object.assign(wrapper.node(), {
resize(width) {
const margin = { left: 1, right: 1, top: 40, bottom: 1 };
const chartwidth = Math.min(width, 400) - margin.left - margin.right;
const chartheight = 32;
x.range([0, chartwidth]);
const first = barsData.findIndex(d => x(d.days) > 80);
barsData.forEach((d, i) => {
d.first = i === first;
return d;
});
wrapper.style("width", `${Math.min(640, width)}px`)
svg
.attr("width", chartwidth + margin.left + margin.right)
.attr("height", chartheight + margin.top + margin.bottom);
g
.attr("transform", `translate(${[margin.left, margin.top]})`);
rect
.attr("height", chartheight)
.attr("width", d => x(d.days))
.attr("x", (_, i) => x(d3.sum(barsData.slice(0, i), d0 => d0.days)));
label
.attr("opacity", d => x(d.days) > maxWidth ? 1 : 0)
.attr("transform", (d, i) => {
if (x(d.days) > maxWidth) {
return `translate(${x(d3.sum(barsData.slice(0, i), d0 => d0.days))})`;
}
else {
return "translate(0)";
}
});
value
.attr("opacity", d => x(d.days) > maxWidth ? 1 : 0)
.attr("transform", (d, i) => {
if (x(d.days) > maxWidth) {
return `translate(${x(d3.sum(barsData.slice(0, i), d0 => d0.days))})`;
}
else {
return "translate(0)"
}
})
.attr("y", chartheight / 2 + 6)
.text(d => `${d.days}${d.first ? " days" : ""}`);
}
})
}