createTooltip = () => {
const tooltip = d3.create("svg:g")
.attr("id", "tooltip")
.attr("visibility", "hidden");
let tooltipWidth = 200;
const tooltipHeight = 32;
const shadowOffset = 9;
const shadow = tooltip.append("rect")
.attr("id", "tooltip-shadow")
.attr("x", shadowOffset)
.attr("y", shadowOffset)
.attr("height", tooltipHeight)
const background = tooltip.append("rect")
.attr("id", "tooltip-background")
.attr("height", tooltipHeight)
.attr("fill", "gray")
const markSideLength = 12;
const markMargin = {
top: (tooltipHeight - markSideLength) / 2,
right: 7,
left: shadowOffset
};
const mark = tooltip.append("rect")
.attr("id", "tooltip-mark")
.attr("x", markMargin.left)
.attr("y", markMargin.top)
.attr("width", markSideLength)
.attr("height", markSideLength)
const textOffset = {
x: markMargin.left + markSideLength + markMargin.right,
y: tooltipHeight / 2
};
const text = tooltip.append("text")
.attr("dx", textOffset.x)
.attr("dy", textOffset.y);
tooltip.show = (country, participation, color) => {
mark.attr("fill", color);
text.text(`${country.properties.name}: `);
text.append("tspan")
.attr("id", "participation")
.text(`${format(participation.percentage)} (${participation.count})`);
const textWidth = Math.ceil(text.node().getBBox().width);
tooltipWidth = textOffset.x + textWidth + markMargin.right;
background.attr("width", tooltipWidth);
shadow.attr("width", tooltipWidth);
tooltip.attr("visibility", "visible");
};
tooltip.move = (x, y) => {
const dx = x - (tooltipWidth / 2);
const dy = y - tooltipHeight - (shadowOffset * 2);
tooltip.attr("transform", `translate(${dx},${dy})`);
};
tooltip.hide = () => {
tooltip.attr("visibility", "hidden");
};
return tooltip;
}