@@ -0,0 +1,49 @@
1+// The header search suggests projects and topics as you type, from /search.json, with the first one selected:
2+// Enter opens the selected one, the arrows move, Escape closes. Not on /projects, where the list filters as you type.
3+const input = document.querySelector("header input[name=q]"), box = document.getElementById("suggest");
4+let index, items = [], at = 0;
5+const load = () => index ??= fetch("/search.json", { cache: "no-cache" }).then(r => r.json());
6+
7+function draw() {
8+ box.replaceChildren(...items.map((it, i) => {
9+ const a = Object.assign(document.createElement("a"), { href: it.href, id: "suggest-" + i, role: "option" });
10+ a.ariaSelected = i === at;
11+ a.append(Object.assign(document.createElement("b"), { textContent: it.label }), Object.assign(document.createElement("span"), { textContent: it.note }));
12+ return a;
13+ }));
14+ box.hidden = !items.length;
15+ input.ariaExpanded = !box.hidden;
16+ input.setAttribute("aria-activedescendant", items.length ? "suggest-" + at : "");
17+}
18+
19+async function suggest() {
20+ const q = input.value.trim().toLowerCase(), { projects, topics } = await load();
21+ const starts = p => !p.n.toLowerCase().startsWith(q);
22+ items = !q ? [] : [
23+ ...projects.filter(p => p.n.toLowerCase().includes(q)).sort((a, b) => starts(a) - starts(b)).slice(0, 6)
24+ .map(p => ({ label: p.n, note: p.d, href: `/projects/${p.n}/` })),
25+ ...topics.filter(t => t.includes(q)).slice(0, 3)
26+ .map(t => ({ label: t, note: `topic · ${projects.filter(p => p.t?.includes(t)).length} projects`, href: `/projects/?q=${encodeURIComponent(t)}` })),
27+ ];
28+ at = 0;
29+ draw();
30+}
31+
32+if (input && box && location.pathname !== "/projects/") {
33+ input.setAttribute("role", "combobox");
34+ input.setAttribute("aria-controls", "suggest");
35+ input.setAttribute("aria-autocomplete", "list");
36+ input.autocomplete = "off";
37+ input.addEventListener("focus", load, { once: true });
38+ input.addEventListener("input", suggest);
39+ input.addEventListener("keydown", e => {
40+ if (box.hidden) return;
41+ if (e.key === "ArrowDown" || e.key === "ArrowUp") at = (at + (e.key === "ArrowDown" ? 1 : items.length - 1)) % items.length, draw();
42+ else if (e.key === "Enter") location.href = items[at].href;
43+ else if (e.key === "Escape") items = [], draw();
44+ else return;
45+ e.preventDefault();
46+ });
47+ input.addEventListener("blur", () => { items = [], draw(); });
48+ box.addEventListener("mousedown", e => e.preventDefault()); // keep focus, so the click lands on the link
49+}