function createSelectionForm(options, {searchable = true, multiple = true}) {
const searchBar = searchable ? html`<input type="text" id="searchBox" placeholder="Search..." style="margin-bottom: 10px; width: 100%;" autoComplete="off">` : "";
const selectAllBtn = multiple ? htl.html`<button type="button" style="margin-right: 5px;">Select All</button>` : "";
const deSelectAllBtn = multiple ? htl.html`<button type="button" style="margin-right: 5px;">Deselect All</button>` : "";
if (searchable) {
searchBar.addEventListener("input", (e) => {
e.preventDefault();
searchOptions();
});
}
if (multiple) {
selectAllBtn.addEventListener("click", (e) => {
e.preventDefault();
selectAll(true);
});
deSelectAllBtn.addEventListener("click", (e) => {
e.preventDefault();
selectAll(false);
});
}
const form = htl.html`
<form onchange="this.dispatchEvent(new CustomEvent('input', {bubbles: true}))" style="max-width: 300px;">
${searchBar}
${selectAllBtn}
${deSelectAllBtn}
<div style="height: 150px; overflow-y: scroll; border: 1px solid #ccc;" id="optionsList">
${options.map(option => html`
<div class="option-entry">
<input type="checkbox" id="${option}" name="option" value="${option}" checked>
<label for="${option}">${option}</label>
</div>`)}
</div>
</form>
`;
const searchOptions = () => {
const searchValue = form.querySelector('#searchBox').value.toLowerCase();
const optionEntries = form.querySelectorAll('.option-entry');
optionEntries.forEach(entry => {
const label = entry.querySelector('label').textContent.toLowerCase();
if (label.includes(searchValue)) {
entry.style.display = '';
} else {
entry.style.display = 'none';
}
});
};
const selectAll = (flag) => {
const checkboxes = form.querySelectorAll('#optionsList input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = flag;
});
form.dispatchEvent(new Event('input', { bubbles: true }));
};
return form;
}