import { SOURCES } from "./config"; import { norm } from "./format"; import type { TimelineEvent } from "./types"; // Wire up the top toolbar: a plain-text search plus per-service toggle pills. // Any change recomputes the visible subset and hands it to `render`, which // rebuilds the timeline (and its rail/context bar) from that list. export function setupFilter(all: TimelineEvent[], render: (list: TimelineEvent[]) => void): void { const search = document.querySelector("#search"); const filters = document.querySelector("#filters"); if (!search || !filters) { render(all); return; } // The toolbar is collapsed to a single icon by default; the toggle reveals // the search field and filter pills. const toolbar = document.querySelector("#toolbar"); const toggle = document.querySelector("#toolbar-toggle"); const setOpen = (open: boolean): void => { toolbar!.classList.toggle("open", open); toggle!.setAttribute("aria-expanded", String(open)); if (open) search.focus(); }; toggle?.addEventListener("click", (e) => { e.stopPropagation(); setOpen(!toolbar!.classList.contains("open")); }); // Dismiss the dropdown on an outside click or Escape. document.addEventListener("click", (e) => { if (toolbar!.classList.contains("open") && !toolbar!.contains(e.target as Node)) setOpen(false); }); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && toolbar!.classList.contains("open")) setOpen(false); }); // Pre-index each event's searchable text once; only offer pills for the // services that actually produced events. const present = new Set(all.map((e) => e.source)); const haystack = new Map( all.map((e) => [e, norm([e.title, e.note, e.meta, e.verb].filter(Boolean).join(" "))]), ); const active = new Set(); // empty ⇒ every service shown let query = ""; const apply = (): void => { const q = norm(query.trim()); render(all.filter((e) => (active.size === 0 || (e.source != null && active.has(e.source))) && (q === "" || haystack.get(e)!.includes(q)))); }; for (const { key, label, verb } of SOURCES) { if (!present.has(key)) continue; const pill = document.createElement("button"); pill.className = "filter-pill"; pill.type = "button"; pill.textContent = label; pill.dataset.source = key; pill.style.setProperty("--pill", `var(--verb-${verb})`); // track the verb colour live pill.setAttribute("aria-pressed", "false"); pill.addEventListener("click", () => { const on = active.has(key) ? (active.delete(key), false) : (active.add(key), true); pill.classList.toggle("active", on); pill.setAttribute("aria-pressed", String(on)); apply(); }); filters.appendChild(pill); } let debounce: number | undefined; search.addEventListener("input", () => { query = search.value; clearTimeout(debounce); debounce = window.setTimeout(apply, 160); }); render(all); // initial paint (unfiltered) }