SwatchInput = async (colors, { value, label, multiple = false } = {}) => {
let indexes = [];
const node = html`<div style="padding-top: 0.5rem; padding-bottom: 0.5rem;">
${colors.map((color, idx) => {
const c = color.toString();
let onclick = () => set(node, idx);
let style = `position: relative; appearance: none; border: none; outline: none; display: inline-block; width: 40px; height: 40px; background-color: ${c}; border: 1px solid rgba(0,0,0,.12); border-radius: 4px; margin-right: 2px;`;
return html`<button onclick=${onclick} style="${style}">
<div style="color: ${isWhiteText(c) ? "white" : "black"}">${icon(
"checkmark"
)}</div>
</button>`;
})}
</div>`;
Object.defineProperty(node, "value", {
get() {
return value;
},
set(v) {
const index = +v;
const c = colors[index];
if (multiple) {
if (value === undefined) {
value = [];
}
if (v !== undefined) {
if (indexes.includes(v)) {
indexes = indexes.filter((vv) => vv !== v);
} else {
indexes.push(v);
}
}
value = indexes.map((idx) => colors[idx]);
} else {
value = c;
indexes = [v];
}
restyle();
}
});
if (multiple) {
if (value === undefined) {
value = [];
indexes = [];
} else {
indexes = value.map((v) => colors.findIndex((c) => c.equals(v)));
}
set(node);
} else {
let initIndex = value ? colors.findIndex((c) => c.equals(value)) : 0;
set(node, initIndex);
}
function restyle(newIndex) {
const btns = node.querySelectorAll("button");
btns.forEach((btn, idx) => {
let checked = indexes.includes(idx);
let ch = btn.getElementsByTagName("div")[0];
if (checked) {
btn.style.boxShadow = "0 0 0 2px rgba(0,0,0,1)";
btn.style.zIndex = "10";
ch.style.display = "block";
} else {
btn.style.boxShadow = "";
btn.style.zIndex = "";
ch.style.display = "none";
}
});
}
restyle();
return node;
}