function swatch(
color,
{
swatchSize = 15,
columnWidth = swatchSize + 90,
maxWidth = 600,
gap = 10,
fontFamily = "var(--sans-serif, sans-serif)",
fontSize = "10px",
fontFill = main.grey["900"]
} = {}
) {
const domain = color.domain();
const cols = Math.max(
Math.min(Math.floor(maxWidth / (columnWidth + gap)), domain.length),
1
);
const rows = Math.floor(domain.length / cols);
const width = Math.min(maxWidth, (columnWidth + gap) * cols);
const height = (swatchSize + gap) * rows;
const svg = DOM.svg(width, height);
const swatches = d3
.select(svg)
.selectAll("g")
.data(domain)
.join("g")
.attr("transform", (d, i) => {
const col = i % cols;
const row = Math.floor(i / cols);
return `translate(${col * (columnWidth + gap)},${
row * (swatchSize + gap)
})`;
});
swatches
.append("rect")
.attr("width", swatchSize)
.attr("height", swatchSize)
.attr("fill", (d) => color(d));
setTimeout(() => {
swatches
.append("text")
.style("font-family", fontFamily)
.style("font-size", fontSize)
.attr("dominant-baseline", "middle")
.attr("y", swatchSize / 2)
.attr("x", swatchSize + gap / 2)
.attr("dy", "0.15em")
.text((d) => d)
.call(wrap, columnWidth - (swatchSize + gap / 2));
});
return svg;
}