tooltip = g => {
const formatTime = d3.utcFormat("%-I:%M %p");
const tooltip = g.append("g")
.style("font", "10px sans-serif");
const path = tooltip.append("path")
.attr("fill", "white");
const text = tooltip.append("text");
const line1 = text.append("tspan")
.attr("x", 0)
.attr("y", 0)
.style("font-weight", "bold");
const line2 = text.append("tspan")
.attr("x", 0)
.attr("y", "1.1em");
const line3 = text.append("tspan")
.attr("x", 0)
.attr("y", "2.2em");
g.append("g")
.attr("fill", "none")
.attr("pointer-events", "all")
.selectAll("path")
.data(stops)
.join("path")
.attr("d", (d, i) => voronoi.renderCell(i))
.on("mouseout", () => tooltip.style("display", "none"))
.on("mouseover", (event, d) => {
tooltip.style("display", null);
line1.text(`${d.train.number}${d.train.direction}`);
line2.text(d.stop.station.name);
line3.text(formatTime(d.stop.time));
path.attr("stroke", colors[d.train.type]);
const box = text.node().getBBox();
path.attr("d", `
M${box.x - 10},${box.y - 10}
H${box.width / 2 - 5}l5,-5l5,5
H${box.width + 10}
v${box.height + 20}
h-${box.width + 20}
z
`);
tooltip.attr("transform", `translate(${
x(d.stop.station.distance) - box.width / 2},${
y(d.stop.time) + 28
})`);
});
}