// 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 } 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, SearchSequencer, filterSearchResults, resolveRunTarget, searchControlsSummary, searchFailureText, searchPanelBody, searchPanelProgress, searchQuerySendable, searchResultKindLabel, searchRow, searchTarget, sortSearchResults, } from "../search.js"; export function createSearchView(rt) { const { state, repo, searchHost } = rt; 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: the previous results show immediately, and a non-blank query is // refreshed so the list is not stale. if (searchQuerySendable(state.searchQuery)) { 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. A blank/whitespace query clears the results locally and sends * nothing; otherwise the previous results stay visible, the request is marked in * flight and the send 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)) { 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)) { 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, and — when the query is non-blank — a fresh server * request is sent with the new kind. A sort change never sends a request. */ function setSearchKind(kind) { state.searchKind = kind; refreshSearch(); if (searchQuerySendable(state.searchQuery)) 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) { try { const reply = await repo.search(sent.query, state.searchKind); 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.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 = state.searchKind; const sortSelect = document.getElementById("searchSort"); if (sortSelect) sortSelect.value = state.searchSort; const summary = document.getElementById("searchSummary"); if (summary) summary.textContent = searchControlsSummary(state.searchKind, 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 = state.searchKind; 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, state.searchKind), 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) 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(state.searchKind, 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, 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 shown = sortSearchResults( filterSearchResults(state.searchResults, state.searchKind), state.searchSort, ); const nodes = []; if (searchPanelProgress(state)) { nodes.push(h("div", { class: "search-progress", role: "progressbar", "aria-label": "Searching" })); } const body = searchPanelBody(state, shown, state.searchKind); 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 })); } area.replaceChildren(...nodes); } /** 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, state.searchQuery); const target = searchTarget(hit); const artifactHit = hit?.kind === "artifact" && hit.artifact ? hit.artifact : null; const element = h("div", { class: `search-row${target ? " clickable" : " readonly"}${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 { element.append(h("span", { class: "search-kind muted", text: searchResultKindLabel(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; // An artifact hit opens the artifact, not the run/visit that recorded it: media // in the viewer, anything else in a tab. Nothing to show means no navigation. if (hit?.kind === "artifact" && hit.artifact?.url) { const artifact = hit.artifact; const resolved = resolveArtifactUrl(state.url, artifact.url); if (!resolved) return; closeSearch(); const kind = artifactKind(artifact.content_type, artifact.name); if (kind === ArtifactKind.Image || kind === ArtifactKind.Video) { rt.views.dialogs.openArtifactViewer( [ { url: artifact.url, name: artifact.name, content_type: artifact.content_type, run_id: artifact.run_id, }, ], 0, ); } else { window.open(resolved, "_blank", "noopener,noreferrer"); } 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) { 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, }; }