{
var margin = {top: 60, right: 20, bottom: 30, left: 50},
width = 700 - margin.left - margin.right,
height = 365 - margin.top - margin.bottom;
const svg = d3.select(DOM.svg(width, height));
let x = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([margin.left, width - margin.right])
let y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)]).nice()
.range([height - margin.bottom, margin.top])
let xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
let yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
let line = d3.line()
.defined(d => !isNaN(d.value))
.x(d => x(d.date))
.y(d => y(d.value))
let callout = (g, value) => {
if (!value) return g.style("display", "none");
g
.style("display", null)
.style("pointer-events", "none")
.style("font", "10px sans-serif");
const path = g.selectAll("path")
.data([null])
.join("path")
.attr("fill", "white")
.attr("stroke", "black");
const text = g.selectAll("text")
.data([null])
.join("text")
.call(text => text
.selectAll("tspan")
.data((value + "").split(/\n/))
.join("tspan")
.attr("x", 0)
.attr("y", (d, i) => `${i * 1.1}em`)
.style("font-weight", (_, i) => i ? null : "bold")
.text(d => d));
const {x, y, width: w, height: h} = text.node().getBBox();
text.attr("transform", `translate(${-w / 2},${15 - y})`);
path.attr("d", `M${-w / 2 - 10},5H-5l5,-5l5,5H${w / 2 + 10}v${h + 20}h-${w + 20}z`);
};
let bisect = d3.bisector(d => d.date).left;
let mx = {
const date = x.invert(mx);
const index = bisect(data, date, 1);
const a = data[index - 1];
const b = data[index];
return date - a.date > b.date - date ? a : b;
}
svg.append("g")
.call(xAxis);
svg.append("g")
.call(yAxis);
let path = svg.append("path")
.attr("d", line(data))
.attr("stroke", "steelblue")
.attr("stroke-width", "1.5")
.attr("class", "line")
.attr("fill", "none");
var totalLength = path.node().getTotalLength()
const tooltip = svg.append("g");
svg.on("touchmove mousemove", function() {
const {date, value} = bisect(d3.mouse(this)[0]);
tooltip
.attr("transform", `translate(${x(date)},${y(value)})`)
.call(callout, `${value.toLocaleString(undefined, {style: "currency", currency: "USD"})}
${date.toLocaleString(undefined, {month: "short", day: "numeric", year: "numeric"})}`);
});
svg.on("touchend mouseleave", () => tooltip.call(callout, null));
d3.select("#startLine").on("click", function() {
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(4000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
})
return svg.node();
}