// Omni-search: the shell's Search control, kind/sort controls, rows and result // routing. Debounce/staleness/ordering/empty-state decisions are pure in // search.js; this module owns the DOM and the route hand-off. import { h, openArtifactInBrowser } from "../dom.js"; import { describeError } from "../format.js"; import { resolveArtifactUrl } from "../serverUrl.js"; import { ArtifactKind, artifactKind } from "../artifacts.js"; import { DEFAULT_SEARCH_KIND, DEFAULT_SEARCH_SORT, SEARCH_DEBOUNCE_MS, SEARCH_KINDS, SEARCH_SORTS, parseSearchQuery, SearchSequencer, filterSearchResults, resolveRunTarget, searchControlsSummary, searchFailureText, searchPanelBody, searchPanelProgress, searchQuerySendable, searchResultKindLabel, searchRow, searchTarget, sortSearchResults, } from "../search.js"; export function createSearchView(rt) { const { state, repo, searchHost } = rt; const parsedSearch = () => parseSearchQuery(state.searchQuery, state.searchKind); let searchTimer = null; let searchEdit = null; // The last search is resumed on the next open (the field, kind, sort and the // selected row). Persisted so it also survives a reload. const SEARCH_STORAGE_KEY = "pipelines.web.search.v1"; function saveSearchState() { try { localStorage.setItem( SEARCH_STORAGE_KEY, JSON.stringify({ query: state.searchQuery, kind: state.searchKind, sort: state.searchSort, activeIndex: state.searchActiveIndex, }), ); } catch { // Storage may be unavailable; the in-memory state still resumes in this page. } } function restoreSearchState() { if (state.searchQuery !== "") return; try { const saved = JSON.parse(localStorage.getItem(SEARCH_STORAGE_KEY) || "null"); if (!saved || typeof saved.query !== "string") return; state.searchQuery = saved.query; if (SEARCH_KINDS.some((k) => k.value === saved.kind)) state.searchKind = saved.kind; if (SEARCH_SORTS.some((k) => k.value === saved.sort)) state.searchSort = saved.sort; state.searchActiveIndex = Number.isInteger(saved.activeIndex) ? Math.max(0, saved.activeIndex) : 0; } catch { // A corrupt value simply starts empty. } } // Where focus goes when the panel closes: the rail or dock Search control that // opened it, so Escape/Close never drops the operator on . let searchTriggerId = null; const renderHeader = (...args) => rt.renderHeader(...args); const renderContent = (...args) => rt.renderContent(...args); const selectPipeline = (...args) => rt.selectPipeline(...args); const selectRun = (...args) => rt.selectRun(...args); const openStagePane = (...args) => rt.views.runDetail.openStagePane(...args); // Omni-search (S1/S2) // --------------------------------------------------------------------------- /** Open the search field and ask for focus; the current view is left alone. */ function openSearch() { if (state.searchOpen) return; const trigger = document.activeElement; searchTriggerId = trigger && trigger.id ? trigger.id : null; restoreSearchState(); state.searchOpen = true; state.searchError = ""; state.searchFocusPending = true; renderHeader(); renderSearch(); // Resume: show previous results immediately, then refresh text or kind-only // searches so the list is not stale. if (searchQuerySendable(state.searchQuery, parsedSearch().kind)) { state.searchLoading = true; const sent = state.searchSequencer.begin(state.searchSequencer.edit(state.searchQuery)); if (sent) runSearch(sent); refreshSearch(); } } /** * Close and clear the search: the pending debounce is dropped, an in-flight reply * is invalidated by recording a fresh edit, and the query, results, error and * loading flag are reset. The view, the selection and the loaded data are * deliberately untouched, so closing restores exactly the state that was on * screen before the search opened. */ function closeSearch() { cancelSearchDebounce(); saveSearchState(); // Recording an empty edit advances the sequencer, so a reply for a request // still in flight can no longer be accepted. state.searchSequencer.edit(""); state.searchOpen = false; state.searchLoading = false; state.searchFocusPending = false; renderHeader(); renderSearch(); const trigger = searchTriggerId ? document.getElementById(searchTriggerId) : null; searchTriggerId = null; if (trigger && trigger.getClientRects().length > 0) trigger.focus(); } /** Keep the keyboard-selected row visible in the results list. */ function scrollActiveSearchRow() { document.querySelector("#searchResults .search-row.active")?.scrollIntoView({ block: "nearest" }); } function cancelSearchDebounce() { if (searchTimer) { clearTimeout(searchTimer); searchTimer = null; } searchEdit = null; } /** * A keystroke. Blank text without a kind clears locally and sends nothing; * kind-only searches browse recent items. Previous results stay visible while * loading; sending is debounced `SEARCH_DEBOUNCE_MS` from the last keystroke. * Recording the edit is itself enough to drop any older reply still in flight. */ function onSearchInput(value) { state.searchQuery = value; state.searchError = ""; cancelSearchDebounce(); if (!searchQuerySendable(value, parsedSearch().kind)) { state.searchSequencer.edit(""); state.searchResults = []; state.searchLoading = false; state.searchLoaded = false; refreshSearch(); return; } state.searchLoading = true; searchEdit = state.searchSequencer.edit(value); refreshSearch(); searchTimer = setTimeout(() => { searchTimer = null; const sent = state.searchSequencer.begin(searchEdit); if (sent) runSearch(sent); }, SEARCH_DEBOUNCE_MS); } /** Send the current query at once (Enter, or a kind change), skipping the debounce. */ function sendSearchNow() { const query = state.searchQuery; cancelSearchDebounce(); if (!searchQuerySendable(query, parsedSearch().kind)) { state.searchSequencer.edit(""); state.searchResults = []; state.searchLoading = false; state.searchError = ""; state.searchLoaded = false; refreshSearch(); return; } const sent = state.searchSequencer.begin(state.searchSequencer.edit(query)); if (sent) runSearch(sent); } /** * A kind-filter change: the in-hand filter is re-applied immediately so the list * always matches the control. Text or a valid kind sends a fresh server request; * clearing both stays local. A sort change never sends a request. */ function setSearchKind(kind) { state.searchQuery = parsedSearch().query; const input = document.getElementById("searchInput"); if (input) input.value = state.searchQuery; state.searchKind = kind; sendSearchNow(); } function setSearchSort(sort) { state.searchSort = sort; refreshSearch(); } /** * Run one query and apply the reply only if it is still the newest edit. A reply * without a `search_results` payload (an older server's pong) or a rejection * naming an unknown command reports the app's "cannot search" sentence; any other * failure carries the server's own text. A stale reply is dropped entirely. */ async function runSearch(sent) { const parsed = parseSearchQuery(sent.query, state.searchKind); try { const reply = await repo.search(parsed.query.trim() ? parsed.query : "", parsed.kind); if (!state.searchSequencer.accepts(sent.token)) return; if (reply == null) { state.searchLoading = false; state.searchLoaded = true; state.searchError = searchFailureText(null); refreshSearch(); return; } state.searchResults = Array.isArray(reply.results) ? reply.results : []; state.searchTruncated = Boolean(reply.truncated); state.searchActiveIndex = 0; state.searchLoading = false; state.searchError = ""; state.searchLoaded = true; refreshSearch(); } catch (error) { if (!state.searchSequencer.accepts(sent.token)) return; state.searchLoading = false; state.searchLoaded = true; state.searchError = searchFailureText(error); refreshSearch(); } } /** * Re-render the search panel's controls and results in place. Only the results * area, the summary and the select values are touched, so a keystroke never * rebuilds (and so never blurs) the query field. */ function refreshSearch() { const kindSelect = document.getElementById("searchKind"); if (kindSelect) kindSelect.value = parsedSearch().kind; const sortSelect = document.getElementById("searchSort"); if (sortSelect) sortSelect.value = state.searchSort; const summary = document.getElementById("searchSummary"); if (summary) summary.textContent = searchControlsSummary(parsedSearch().kind, state.searchSort); const area = document.getElementById("searchResults"); if (area) fillSearchResults(area); } /** * The full-width search panel: the controls row (kind select, sort select, the * one-line summary and the Clear filter reset) and a bounded scrolling result * area. Rendered only while the search is open; the panel is one flat list, with * no per-kind grouping headers, matching the app. */ function renderSearch() { if (!state.searchOpen) { searchHost.replaceChildren(); return; } const kindSelect = h( "select", { id: "searchKind", class: "search-select", "aria-label": "Filter results", onchange: (event) => setSearchKind(event.target.value), }, ...SEARCH_KINDS.map((option) => h("option", { value: option.value, text: option.label })), ); kindSelect.value = parsedSearch().kind; const sortSelect = h( "select", { id: "searchSort", class: "search-select", "aria-label": "Sort results in hand", onchange: (event) => setSearchSort(event.target.value), }, ...SEARCH_SORTS.map((option) => h("option", { value: option.value, text: option.label })), ); sortSelect.value = state.searchSort; const fieldRow = h( "div", { class: "search-field-row" }, h("input", { id: "searchInput", class: "search-input", type: "text", placeholder: "Search pipelines, runs and artifacts", value: state.searchQuery, spellcheck: "false", autocomplete: "off", "aria-label": "Search", oninput: (event) => onSearchInput(event.target.value), onkeydown: (event) => { const shown = sortSearchResults( filterSearchResults(state.searchResults, parsedSearch().kind), state.searchSort, ); if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); if (!shown.length) return; const delta = event.key === "ArrowDown" ? 1 : -1; state.searchActiveIndex = (state.searchActiveIndex + delta + shown.length) % shown.length; refreshSearch(); scrollActiveSearchRow(); return; } if (event.key === "Enter") { event.preventDefault(); if (shown.length && !state.searchLoading && !state.searchError) { routeSearchResult(shown[state.searchActiveIndex] ?? shown[0]); } else sendSearchNow(); } }, }), h("button", { id: "searchClose", class: "ghost search-close", type: "button", text: "Close search", onclick: () => closeSearch(), }), ); const controls = h( "div", { class: "search-controls" }, h("label", { class: "search-field" }, h("span", { class: "search-field-label", text: "Kind" }), kindSelect), h("label", { class: "search-field" }, h("span", { class: "search-field-label", text: "Sort" }), sortSelect), h("span", { id: "searchSummary", class: "search-summary muted", text: searchControlsSummary(parsedSearch().kind, state.searchSort), }), h("button", { id: "searchClearFilter", class: "ghost search-clear", type: "button", text: "Clear filter", onclick: () => setSearchKind(DEFAULT_SEARCH_KIND), }), ); const area = h("div", { id: "searchResults", class: "search-results", "aria-live": "polite" }); fillSearchResults(area); const panel = h( "div", { id: "searchPanel", class: "search-panel", role: "dialog", "aria-modal": "true", "aria-label": "Search" }, h("div", { class: "search-modal", role: "search" }, fieldRow, controls, h("p", { class: "muted", text: "Filter with t:pipeline or type:artifact (pipeline, run, step, field, artifact, version). Type alone lists recent items. Last type wins; choosing Kind replaces it. Quote tokens to search literally." }), area), ); // A spotlight: clicking the dimmed backdrop closes it (the modal itself stops). panel.addEventListener("click", (event) => { if (event.target === panel) closeSearch(); }); panel.querySelector(".search-modal")?.addEventListener("click", (event) => event.stopPropagation()); searchHost.replaceChildren(panel); if (state.searchFocusPending) { document.getElementById("searchInput")?.focus(); state.searchFocusPending = false; } } /** * Fill the results area from the current state. A first load with nothing yet * shows the spinner and `Searching…`; a refresh that retained results shows a thin * progress bar above them; an error takes precedence over the results; otherwise * the filtered and sorted rows, or the empty-state line. */ function fillSearchResults(area) { const parsed = parsedSearch(); const shown = sortSearchResults( filterSearchResults(state.searchResults, parsed.kind), state.searchSort, ); const nodes = []; const panelState = { query: parsed.query, loading: state.searchLoading, loaded: state.searchLoaded, error: state.searchError, results: state.searchResults, truncated: state.searchTruncated, }; if (searchPanelProgress(panelState)) { nodes.push(h("div", { class: "search-progress", role: "progressbar", "aria-label": "Searching" })); } const body = searchPanelBody(panelState, shown, parsed.kind); if (body.kind === "error") { nodes.push(h("div", { class: "search-error", text: body.message })); } else if (body.kind === "results") { state.searchActiveIndex = Math.min(Math.max(0, state.searchActiveIndex), shown.length - 1); shown.forEach((hit, index) => { const row = renderSearchResultRow(hit); if (index === state.searchActiveIndex) { row.classList.add("active"); row.setAttribute("aria-selected", "true"); } nodes.push(row); }); } else if (body.kind === "searching") { nodes.push( h( "div", { class: "search-searching muted" }, h("span", { class: "spinner", "aria-hidden": "true" }), h("span", { text: "Searching…" }), ), ); } else if (body.kind === "empty") { nodes.push(h("div", { class: "search-empty muted", text: body.message })); } if (body.kind === "results" && !state.searchLoading && parsed.kind && !parsed.query.trim()) { nodes.push(h("div", { class: "search-summary muted", text: state.searchTruncated ? "Recent items · limited by the server's result or scan cap." : "Recent items", })); } area.replaceChildren(...nodes); } /** The inline glyph for a non-artifact search result's kind. */ function searchKindGlyph(kind) { const ns = "http://www.w3.org/2000/svg"; const svg = document.createElementNS(ns, "svg"); svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true"); svg.setAttribute("focusable", "false"); const paths = { pipeline: "M7 12h5V6h4M12 12v6h4", version: "M12 3l9 5-9 5-9-5 9-5ZM3 12l9 5 9-5", run: "M8 5l11 7-11 7V5Z", step: "M5 12h10M13 8l4 4-4 4", field: "M5 7h14M5 12h14M5 17h9", unknown: "M12 8v8M8 12h8", }; const path = document.createElementNS(ns, "path"); path.setAttribute("d", paths[kind] ?? paths.unknown); path.setAttribute("fill", "none"); path.setAttribute("stroke", "currentColor"); path.setAttribute("stroke-width", "1.8"); path.setAttribute("stroke-linecap", "round"); path.setAttribute("stroke-linejoin", "round"); svg.append(path); if (kind === "pipeline") { for (const [cx, cy] of [[4, 12], [19, 6], [19, 18]]) { const dot = document.createElementNS(ns, "circle"); dot.setAttribute("cx", String(cx)); dot.setAttribute("cy", String(cy)); dot.setAttribute("r", "2"); dot.setAttribute("fill", "currentColor"); svg.append(dot); } } return svg; } /** The fixed-size leading tile for a non-artifact result: a kind glyph only. */ function searchKindTile(hit) { const label = searchResultKindLabel(hit); const tile = h("span", { class: "search-type search-type-kind", title: label, "aria-label": label, }); tile.append(searchKindGlyph(String(hit?.kind ?? "unknown"))); return tile; } /** The short caption on a non-image artifact's type tile. */ function artifactTypeBadge(kind, artifact) { const name = String(artifact?.name ?? "").toLowerCase(); const mime = String(artifact?.content_type ?? "").split(";")[0].trim().toLowerCase(); const ext = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : ""; if (kind === ArtifactKind.Document) { if (mime === "text/markdown" || ext === "md" || ext === "markdown") return "MD"; if (mime === "text/plain" || ext === "txt") return "TXT"; return "DOC"; } if (kind === ArtifactKind.Spreadsheet) { if (ext === "csv") return "CSV"; if (ext === "tsv") return "TSV"; if (ext === "xlsx" || ext === "xls") return "XLSX"; return "SHEET"; } if (kind === ArtifactKind.Code) return ext ? ext.toUpperCase().slice(0, 5) : "CODE"; switch (kind) { case ArtifactKind.Image: return "IMG"; case ArtifactKind.Video: return "VID"; case ArtifactKind.Audio: return "AUD"; case ArtifactKind.Pdf: return "PDF"; case ArtifactKind.Json: return "JSON"; case ArtifactKind.Archive: return "ZIP"; case ArtifactKind.Spreadsheet: return "SHEET"; case ArtifactKind.Log: return "LOG"; case ArtifactKind.Code: return "CODE"; case ArtifactKind.Document: return "DOC"; default: return "FILE"; } } /** Leave the search panel and open a run, for an artifact row's own action. */ async function openRunFromSearch(runId) { closeSearch(); state.error = ""; state.view = "runs"; await selectRun(runId); } /** * One result row: the artifact itself when it is an image (a thumbnail), a type * tile otherwise, the title and — for a text match — the server snippet with the * first case-insensitive query occurrence emphasised. A known payload is * clickable and routes to its destination; an unknown/absent payload is rendered * read-only and is never clickable. Every server string is set as text. */ function renderSearchResultRow(hit) { const row = searchRow(hit, parsedSearch().query); const target = searchTarget(hit); const artifactHit = hit?.kind === "artifact" && hit.artifact ? hit.artifact : null; const element = h("div", { class: `search-row${target ? " clickable" : " readonly"} search-row-with-icon${artifactHit ? " search-row-artifact" : ""}`, "data-kind": String(hit?.kind ?? ""), }); if (target) { const route = () => routeSearchResult(hit); element.setAttribute("role", "button"); element.setAttribute("tabindex", "0"); if (target.kind === "pipeline") { element.setAttribute("data-target", `pipeline:${target.pipelineId}:v${target.version}`); } else if (target.matchedField) { element.setAttribute("data-target", `run:${target.runId}:${target.sequence}:${target.matchedField}`); } else { element.setAttribute("data-target", `run:${target.runId}${target.sequence ? `:${target.sequence}` : ""}`); } element.addEventListener("click", route); element.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); route(); } }); } if (artifactHit) { const kind = artifactKind(artifactHit.content_type, artifactHit.name); const resolved = artifactHit.url ? resolveArtifactUrl(state.url, artifactHit.url) : ""; if (kind === ArtifactKind.Image && resolved) { const thumb = h("img", { class: "search-thumb", src: resolved, alt: "", loading: "lazy", "aria-hidden": "true", }); element.append(thumb); element.setAttribute("aria-label", `Image artifact ${searchRow(hit, state.searchQuery).title}`); } else { element.append( h("span", { class: "search-type", text: artifactTypeBadge(kind, artifactHit), title: searchResultKindLabel(hit), "aria-label": searchResultKindLabel(hit), }), ); } } else { // Every row leads with the same fixed-size tile; kinds are symbols, never // words like "PIPELINE" that make one row look different from another. element.append(searchKindTile(hit)); } const main = h("div", { class: "search-row-main" }); main.append(h("div", { class: "search-row-title", text: row.title })); if (row.snippet != null) { const line = h("div", { class: "search-row-snippet muted" }); for (const span of row.snippet) { if (span.matched) { line.append(h("strong", { class: "search-match" }, h("u", {}, span.text))); } else { line.append(document.createTextNode(span.text)); } } main.append(line); } else if (row.secondary) { main.append(h("div", { class: "search-row-secondary muted", text: row.secondary })); } if (artifactHit && Number(artifactHit.run_id) > 0) { const runButton = h("button", { class: "search-open-run", type: "button", text: `Open run #${Number(artifactHit.run_id)}`, }); // A row action must not also trigger the row's own artifact navigation. runButton.addEventListener("click", (event) => { event.stopPropagation(); openRunFromSearch(Number(artifactHit.run_id)); }); runButton.addEventListener("keydown", (event) => event.stopPropagation()); main.append(runButton); } element.append(main); return element; } /** * Route one selected result through the page's existing navigation, exactly as * the app does. The search is closed and cleared first, so every selection leaves * the panel; a known payload then opens the pipeline detail (at the result * version, 0 = latest), the run detail, the run-detail tab holding a text match, * or the recorded visit's stage pane (the artifact route is that same pane). A * visit that cannot be located falls back to the plain run detail. An unknown * result has no target and never navigates. */ async function routeSearchResult(hit) { const target = searchTarget(hit); if (!target) return; // All artifact types open in the browser. In-app preview is an explicit // gallery action, never an unexpected navigation away from the installed app. if (hit?.kind === "artifact" && hit.artifact?.url) { const artifact = hit.artifact; const resolved = resolveArtifactUrl(state.url, artifact.url); if (!resolved) return; closeSearch(); openArtifactInBrowser(resolved); return; } closeSearch(); state.error = ""; if (target.kind === "pipeline") { state.view = "pipelines"; state.selectedRunId = null; await selectPipeline({ id: target.pipelineId, version: target.version }); return; } state.view = "runs"; await selectRun(target.runId); if (!state.runDetail) return; const resolved = resolveRunTarget(target, target.runId, state.runDetail.steps ?? []); if (resolved.tab === "input" || resolved.tab === "output") { // Input and Output are run Summary sections now, so a field hit opens the // Summary with the matching section expanded rather than a dead tab. state.runTab = "summary"; state.runSections = new Set([...state.runSections, `summary-${resolved.tab}`]); renderContent(); } else if (resolved.tab) { state.runTab = resolved.tab; renderContent(); } else if (resolved.stageKey != null) { openStagePane(resolved.stageKey, resolved.visitIndex); } } // Ctrl+/ (Cmd+/ on macOS) is the Spotlight shortcut: toggle from anywhere. document.addEventListener("keydown", (event) => { if (!(event.ctrlKey || event.metaKey) || event.key !== "/") return; event.preventDefault(); if (state.searchOpen) closeSearch(); else openSearch(); }); return { openSearch, closeSearch, renderSearch, onSearchInput, sendSearchNow, }; }