function FacetedSearch(data, { attribs, filterData = filterDataJS } = {}) {
if (!data || data.length < 0) {
throw Error("Please provide an array of objects");
}
const filtersContainer = html`<div id="filters"></div>`;
const target = html`
${filtersContainer}
`;
const filters = new Map();
target.value = data;
target.value.filters = filters;
function redraw() {
filtersContainer.innerHTML = "";
filtersContainer.appendChild(
html`<div >Selected ${target?.value.length} of ${data.length}
${Array.from(filters.values()).map(({ attr, ele }) => {
return html`
<div>${ele}</div>
`;
})}
</div>`
);
}
async function updateAndRedraw() {
let before;
if (debug) {
before = performance.now();
}
const focused = document.activeElement;
target.value = await filterData(data, filters);
debug && console.log(`Finished filtering ${performance.now() - before}`);
target.value.filters = filters;
target.dispatchEvent(new Event("input", { bubbles: true }));
redraw();
console.log("Trying to return the focus to", focused, document.activeElement);
focused.focus && focused.focus()
}
attribs = attribs || Object.keys(data[0]);
for (let attr of attribs) {
if (isNaN(data[0][attr])) {
addSearchCheckboxes({
attr,
filters,
data,
updateAndRedraw,
target
});
} else {
addRange({ attr, filters, data, updateAndRedraw, target });
}
}
redraw();
return target;
}