export function installSearchableSelects(win) { const doc = win.document; const controls = /* @__PURE__ */ new WeakMap(); let nextId = 0; let active; const fold = (text) => text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLocaleLowerCase(); const copy = (en, fr) => doc.documentElement.lang.startsWith("fr") ? fr : en; function reveal(popup, node) { const box = popup.getBoundingClientRect(); const row = node.getBoundingClientRect(); const top = box.top + popup.clientTop; const bottom = top + popup.clientHeight; if (row.top < top) popup.scrollTop -= top - row.top; else if (row.bottom > bottom) popup.scrollTop += row.bottom - bottom; } function place(popup, anchor, limit) { const rect = anchor.getBoundingClientRect(); const viewport = win.visualViewport; const left = (viewport?.offsetLeft || 0) + 8; const top = (viewport?.offsetTop || 0) + 8; const right = left + (viewport?.width || win.innerWidth) - 16; const bottom = top + (viewport?.height || win.innerHeight) - 16; const below = Math.max(0, bottom - rect.bottom - 4); const above = Math.max(0, rect.top - top - 4); const upward = below < Math.min(220, limit) && above > below; popup.style.boxSizing = "border-box"; popup.style.width = Math.max(0, Math.min(Math.max(rect.width, 240), right - left)) + "px"; popup.style.maxHeight = Math.max(0, Math.min(limit, upward ? above : below)) + "px"; popup.style.left = Math.max(left, Math.min(rect.left, right - popup.offsetWidth)) + "px"; popup.style.top = Math.max(top, upward ? rect.top - popup.offsetHeight - 4 : rect.bottom + 4) + "px"; } function enhance(select) { if (controls.has(select)) return controls.get(select).sync(); const wrapper = doc.createElement("span"); wrapper.className = "dm-select"; const trigger = doc.createElement("button"); trigger.type = "button"; trigger.className = "dm-select-trigger"; trigger.setAttribute("translate", "no"); trigger.setAttribute("aria-haspopup", "listbox"); trigger.setAttribute("aria-expanded", "false"); const popup = doc.createElement("div"); popup.className = "dm-select-popup"; popup.tabIndex = -1; popup.setAttribute("popover", "manual"); const search = doc.createElement("input"); search.type = "search"; search.autocomplete = "off"; search.setAttribute("role", "combobox"); search.setAttribute("aria-autocomplete", "list"); search.setAttribute("aria-expanded", "false"); const list = doc.createElement("div"); list.id = `dm-select-options-${++nextId}`; list.setAttribute("role", "listbox"); search.setAttribute("aria-controls", list.id); trigger.setAttribute("aria-controls", list.id); const empty = doc.createElement("p"); empty.setAttribute("role", "status"); popup.append(search, list, empty); select.after(wrapper); wrapper.append(trigger, popup); select.classList.add("dm-select-native"); select.tabIndex = -1; select.setAttribute("aria-hidden", "true"); let rows = []; let index = -1; let opened = false; function name() { return select.getAttribute("aria-label") || [...select.labels || []].map((label) => { const clone = label.cloneNode(true); clone.querySelectorAll("select, .dm-select, input, button").forEach((node) => node.remove()); return clone.textContent.trim(); }).join(" ") || select.name || copy("choose an option", "choisir une option"); } function sync() { trigger.textContent = [...select.selectedOptions].map((option) => option.label).join(", ") || copy("choose an option", "choisir une option"); trigger.disabled = select.matches(":disabled"); wrapper.hidden = select.hidden; trigger.setAttribute("aria-label", `${name()}: ${trigger.textContent}`); trigger.setAttribute("aria-required", String(select.required)); if (opened) render(); } function highlight(value) { index = value; rows.forEach((row, i) => row.node.classList.toggle("dm-select-active", i === index)); if (rows[index]) { search.setAttribute("aria-activedescendant", rows[index].node.id); reveal(popup, rows[index].node); } else search.removeAttribute("aria-activedescendant"); } function render() { list.replaceChildren(); rows = []; const query = fold(search.value.trim()); list.setAttribute("aria-label", name()); list.setAttribute("aria-multiselectable", String(select.multiple)); for (const option of select.options) { const group = option.parentElement; if (option.hidden || group.hidden || !fold(`${group.label || ""} ${option.label}`).includes(query)) continue; const node = doc.createElement("div"); node.id = `${list.id}-${option.index}`; node.setAttribute("role", "option"); node.setAttribute("translate", "no"); node.setAttribute("aria-selected", String(option.selected)); const disabled = option.disabled || group.tagName === "OPTGROUP" && group.disabled; node.setAttribute("aria-disabled", String(disabled)); node.textContent = group.tagName === "OPTGROUP" ? `${group.label} \u2014 ${option.label}` : option.label; list.append(node); if (!disabled) { rows.push({ node, option }); node.addEventListener("pointerdown", (event) => event.preventDefault()); node.addEventListener("click", (event) => { event.preventDefault(); choose(option); }); } } empty.textContent = copy("no results", "aucun r\xE9sultat"); empty.hidden = !!list.children.length; highlight(Math.max(0, rows.findIndex((row) => row.option.selected))); } function position() { if (!opened) return; place(popup, trigger, 360); } function close(focus = false) { if (!opened) return; opened = false; popup.hidePopover(); trigger.setAttribute("aria-expanded", "false"); search.setAttribute("aria-expanded", "false"); if (active?.select === select) active = null; if (focus && trigger.isConnected) trigger.focus(); } function open() { if (trigger.disabled) return; active?.close(); search.value = ""; search.placeholder = copy("search options", "rechercher des options"); search.setAttribute("aria-label", `${search.placeholder}: ${name()}`); sync(); popup.showPopover(); opened = true; active = { select, close, position, owns: (node) => wrapper.contains(node) }; trigger.setAttribute("aria-expanded", "true"); search.setAttribute("aria-expanded", "true"); render(); position(); if (rows[index]) reveal(popup, rows[index].node); popup.focus({ preventScroll: true }); } function choose(option) { if (select.multiple) option.selected = !option.selected; else select.selectedIndex = option.index; select.dispatchEvent(new win.Event("input", { bubbles: true })); select.dispatchEvent(new win.Event("change", { bubbles: true })); sync(); if (!select.multiple) close(true); else popup.focus({ preventScroll: true }); } trigger.addEventListener("click", () => opened ? close() : open()); trigger.addEventListener("keydown", (event) => { if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); open(); } }); popup.addEventListener("keydown", (event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); close(true); } else if (event.key === "Tab" && event.target === search) close(true); else if (event.key === "Enter") { event.preventDefault(); if (rows[index]) choose(rows[index].option); } else if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); highlight(rows.length ? (index + (event.key === "ArrowDown" ? 1 : -1) + rows.length) % rows.length : -1); } }); search.addEventListener("input", () => { render(); position(); }); select.addEventListener("change", sync); select.addEventListener("invalid", (event) => { event.preventDefault(); trigger.setAttribute("aria-invalid", "true"); trigger.focus(); open(); }); select.addEventListener("input", () => trigger.removeAttribute("aria-invalid")); select.form?.addEventListener("reset", () => win.setTimeout(sync)); for (const property of ["value", "selectedIndex", "disabled", "required", "multiple"]) { const descriptor = Object.getOwnPropertyDescriptor(win.HTMLSelectElement.prototype, property); Object.defineProperty(select, property, { configurable: true, get() { return descriptor.get.call(this); }, set(value) { descriptor.set.call(this, value); sync(); } }); } controls.set(select, { sync }); sync(); } function enhanceSuggestions(input) { if (controls.has(input) || !input.list) return; const datalist = input.list; if (!input.hasAttribute("aria-label") && !input.hasAttribute("aria-labelledby")) { const label = [...input.labels].map((element) => { const clone = element.cloneNode(true); clone.querySelectorAll("input, datalist, .dm-select").forEach((node) => node.remove()); return clone.textContent.trim(); }).join(" "); if (label) input.setAttribute("aria-label", label); } input.removeAttribute("list"); input.autocomplete = "off"; const popup = doc.createElement("div"); popup.className = "dm-select dm-select-popup"; popup.setAttribute("popover", "manual"); const list = doc.createElement("div"); list.id = `dm-select-options-${++nextId}`; list.setAttribute("role", "listbox"); popup.append(list); input.after(popup); input.setAttribute("role", "combobox"); input.setAttribute("aria-autocomplete", "list"); input.setAttribute("aria-controls", list.id); input.setAttribute("aria-expanded", "false"); let opened = false; let rows = []; let index = -1; const highlight = (value) => { index = value; rows.forEach((row, i) => row.node.classList.toggle("dm-select-active", i === index)); if (rows[index]) { input.setAttribute("aria-activedescendant", rows[index].node.id); reveal(popup, rows[index].node); } else input.removeAttribute("aria-activedescendant"); }; const close = () => { if (!opened) return; opened = false; popup.hidePopover(); input.setAttribute("aria-expanded", "false"); input.removeAttribute("aria-activedescendant"); if (active?.select === input) active = null; }; const position = () => { if (!opened) return; place(popup, input, 300); }; const choose = (option) => { if (option.create) { const event = new win.CustomEvent("dm-create-option", { bubbles: true, cancelable: true, detail: { value: option.value } }); if (!input.dispatchEvent(event)) return; const added = doc.createElement("option"); added.value = option.value; added.setAttribute("translate", "no"); datalist.append(added); } input.value = option.value; close(); input.dispatchEvent(new win.Event("input", { bubbles: true })); input.dispatchEvent(new win.Event("change", { bubbles: true })); close(); }; const open = () => { if (input.disabled || input.readOnly) return; if (!opened) { active?.close(); popup.showPopover(); opened = true; active = { select: input, close, position, owns: (node) => node === input || popup.contains(node) }; input.setAttribute("aria-expanded", "true"); } list.replaceChildren(); rows = []; for (const option of datalist.options) { if (option.disabled || !fold(option.value + " " + option.label).includes(fold(input.value.trim()))) continue; const node = doc.createElement("div"); node.id = `${list.id}-${rows.length}`; node.setAttribute("role", "option"); node.setAttribute("aria-selected", String(input.value === option.value)); node.setAttribute("translate", "no"); node.textContent = option.label || option.value; node.addEventListener("pointerdown", (event) => event.preventDefault()); node.addEventListener("click", (event) => { event.preventDefault(); choose(option); }); list.append(node); rows.push({ node, option }); } const value = input.value.trim(); if (input.hasAttribute("data-create-option") && value && (!input.maxLength || input.maxLength < 0 || value.length <= input.maxLength) && ![...datalist.options].some((option) => fold(option.value) === fold(value))) { const option = { value, create: true }; const node = doc.createElement("div"); node.id = `${list.id}-${rows.length}`; node.setAttribute("role", "option"); node.setAttribute("aria-selected", "false"); node.setAttribute("translate", "no"); node.textContent = `${copy("add category", "ajouter la cat\xE9gorie")} \u201C${value}\u201D`; node.addEventListener("pointerdown", (event) => event.preventDefault()); node.addEventListener("click", (event) => { event.preventDefault(); choose(option); }); list.append(node); rows.push({ node, option }); } if (!rows.length) { const empty = doc.createElement("p"); empty.setAttribute("role", "status"); empty.textContent = copy("no results", "aucun r\xE9sultat"); list.append(empty); } highlight(-1); position(); }; controls.set(input, { sync() { } }); input.addEventListener("focus", open); input.addEventListener("click", () => { if (!opened) open(); }); input.addEventListener("input", open); input.addEventListener("keydown", (event) => { if (event.key === "Escape" && opened) { event.preventDefault(); event.stopPropagation(); close(); } else if (event.key === "Tab") close(); else if (event.key === "Enter" && opened && rows[index]) { event.preventDefault(); choose(rows[index].option); } else if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); if (!opened) open(); highlight(rows.length ? (index + (event.key === "ArrowDown" ? 1 : -1) + rows.length) % rows.length : -1); } }); } const scan = (node) => { if (node.nodeType !== 1) return; if (node.matches("select")) enhance(node); node.querySelectorAll("select").forEach(enhance); if (node.matches("input[list]")) enhanceSuggestions(node); node.querySelectorAll("input[list]").forEach(enhanceSuggestions); }; scan(doc.documentElement); new win.MutationObserver((records) => { for (const record of records) { const select = record.target.closest?.("select"); if (select) enhance(select); if (record.type === "childList") record.addedNodes.forEach(scan); if (record.type === "attributes" && record.target.matches("fieldset")) scan(record.target); } if (active && !active.select.isConnected) active.close(); }).observe(doc.documentElement, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["disabled", "hidden", "label", "selected", "required", "aria-label"] }); doc.addEventListener("pointerdown", (event) => { if (active && !active.owns(event.target)) active.close(); }); doc.addEventListener("focusin", (event) => { if (active && !active.owns(event.target)) active.close(); }); doc.addEventListener("click", (event) => { const label = event.target.closest("label"); if (label?.control?.matches("select") && !event.target.closest(".dm-select")) { event.preventDefault(); label.control.nextElementSibling?.querySelector("button")?.focus(); } }); win.addEventListener("resize", () => active?.position()); win.visualViewport?.addEventListener("resize", () => active?.position()); win.visualViewport?.addEventListener("scroll", () => active?.position()); doc.addEventListener("scroll", (event) => { if (active && !active.owns(event.target)) active.position(); }, true); }