Published
Edited
Oct 22, 2020
Importers
Insert cell
Insert cell
selected
Insert cell
viewof selected = swatchesInput({
color: d3.scaleOrdinal(
["blueberries", "oranges", "apples"],
d3.schemeCategory10
)
})
Insert cell
Insert cell
function swatchesInput({
color,
format = x => x,
swatchSize = 15,
swatchWidth = swatchSize,
swatchHeight = swatchSize,
marginLeft = 0
}) {
const id = DOM.uid().id;
const domain = color.domain();
const form = html`<form class="swatches-${id}" style="display: flex; align-items: center; min-height: 33px; margin-left: ${+marginLeft}px; font: 10px sans-serif;">
<style>

.${id} label {
display: inline-flex;
align-items: center;
margin-right: 1em;
}

.${id} label span.swatch {
display: inline-flex;
}

.${id} label span.swatch::before {
content: "";
width: ${+swatchWidth}px;
height: ${+swatchHeight}px;
margin-right: 0.5em;
background: var(--color);
}

.${id} input[type="checkbox"] ~ label {
cursor: pointer;
}

.${id} input[type="checkbox"]:checked ~ label .label-text {
font-weight: bold;
}

</style>
${domain.map(
d => html`<div class="${id}">
<input hidden type="checkbox" id="input-${d}" name="input-${d}">
<label for="input-${d}">
<span class="swatch" style="--color: ${color(d)}"></span>
<span class="label-text">${document.createTextNode(format(d))}</span>
</label>
</div>`
)}
</form>`;

form.oninput = () => {
const toggled = Array.from(form.elements).map(el => el.checked);
form.value = domain.filter((v, i) => toggled[i]);
};

form.oninput();

return form;
}
Insert cell
d3 = require("d3-scale@2", "d3-scale-chromatic@2")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more