(() => { const baseUrl = document.currentScript.src; const toggle = document.querySelector(".search-toggle"); const dialog = document.querySelector(".site-search"); if (!toggle || !dialog || !window.siteSearchIndex) return; const input = dialog.querySelector("input"); const status = dialog.querySelector(".search-status"); const results = dialog.querySelector(".search-results"); const normalize = (text) => text.toLowerCase().normalize("NFKD").replace(/\p{M}/gu, ""); const records = window.siteSearchIndex.map((entry) => ({ entry, title: normalize(entry.title), text: normalize([entry.title, entry.type, entry.detail, entry.summary].join(" ")), })); function renderResults() { const terms = normalize(input.value).match(/[\p{L}\p{N}]+/gu) || []; results.replaceChildren(); if (!terms.length) { status.textContent = "Enter a keyword to search."; return; } const matches = records.filter(({text}) => terms.every((term) => text.includes(term))); const titleHits = (record) => terms.filter((term) => record.title.includes(term)).length; matches.sort((a, b) => titleHits(b) - titleHits(a)); status.textContent = matches.length ? `${matches.length} ${matches.length === 1 ? "result" : "results"}` : "No results. Try a different keyword."; const fragment = document.createDocumentFragment(); for (const {entry} of matches) { const item = document.createElement("li"); const link = document.createElement("a"); const label = document.createElement("small"); label.textContent = [entry.type, entry.detail].filter(Boolean).join(" ยท "); const title = document.createElement("strong"); title.textContent = entry.title; const summary = document.createElement("span"); summary.textContent = entry.summary; link.href = new URL(entry.url, baseUrl); link.append(label, title, summary); item.append(link); fragment.append(item); } results.append(fragment); } toggle.addEventListener("click", () => { dialog.showModal(); renderResults(); input.select(); }); input.addEventListener("input", renderResults); dialog.addEventListener("keydown", (event) => { if (event.key === "Escape") { event.preventDefault(); dialog.close(); } }); dialog.addEventListener("close", () => toggle.focus()); results.addEventListener("click", (event) => { if (event.target.closest("a")) dialog.close(); }); })();