web: add omni-search results and routing (S1/S2)

This commit is contained in:
2026-10-19 04:27:59 +01:00
parent 9555bfe58f
commit 26eaec2531
9 changed files with 2003 additions and 10 deletions
+437 -8
View File
@@ -133,6 +133,25 @@ import {
runChangesHeader,
runChangesNote,
} from "./changes.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";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
@@ -209,6 +228,19 @@ const state = {
runSections: new Set(),
runStagePane: null,
runStageSections: new Set(),
// Omni-search (S1/S2): the field/panel state, kept beside the view it never
// changes, plus the pure debounce/stale-token sequencer. Opening or closing the
// search leaves state.view, the selection and the loaded data untouched.
searchOpen: false,
searchQuery: "",
searchKind: DEFAULT_SEARCH_KIND,
searchSort: DEFAULT_SEARCH_SORT,
searchResults: [],
searchLoading: false,
searchError: "",
searchLoaded: false,
searchFocusPending: false,
searchSequencer: new SearchSequencer(),
};
let runPoll = null;
@@ -256,11 +288,20 @@ function isExecuting(run) {
// ---------------------------------------------------------------------------
const header = h("header", { class: "topbar" });
// The full-width omni-search panel sits directly under the top bar (and so under
// the search control that lives in it), above the connection banner so it can
// never be mistaken for a status strip.
const searchHost = h("div", { id: "searchHost", class: "search-host" });
// The persistent connection banner sits in normal document flow directly under
// the header (never fixed/overlaying), so it can never cover the content.
const connBanner = h("div", { id: "connBanner", class: "conn-banner", hidden: true });
const content = h("main", { id: "content" });
document.body.append(header, connBanner, content);
document.body.append(header, searchHost, connBanner, content);
// The pending debounce timer and the edit it belongs to. Both are dropped the
// moment the query is sent, cleared or superseded.
let searchTimer = null;
let searchEdit = null;
/** Whether the URL field currently holds a usable endpoint for Reconnect. */
function endpointConfigured() {
@@ -270,6 +311,7 @@ function endpointConfigured() {
function renderHeader() {
const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() });
const controls = [
...searchHeaderControls(),
h("input", {
id: "url",
type: "text",
@@ -300,6 +342,58 @@ function renderHeader() {
h("div", { class: "brand" }, h("strong", { text: "Pipelines" }), h("span", { class: "muted", text: "web spike" })),
h("div", { class: "connbar" }, ...controls),
);
// Autofocus the field only for the render that opened it, so a later
// connection-state re-render never steals the operator's focus.
if (state.searchOpen && state.searchFocusPending) {
document.getElementById("searchInput")?.focus();
state.searchFocusPending = false;
}
}
/**
* The top bar's search control: the Search button while closed, and the query
* field with its Close control while open. The field's value is always read back
* from `state.searchQuery`, so a re-render can never desync the two.
*/
function searchHeaderControls() {
if (!state.searchOpen) {
return [
h("button", {
id: "searchToggle",
class: "ghost search-toggle",
type: "button",
title: "Search",
text: "Search",
onclick: openSearch,
}),
];
}
return [
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) => {
if (event.key === "Enter") {
event.preventDefault();
sendSearchNow();
}
},
}),
h("button", {
id: "searchClose",
class: "ghost search-close",
type: "button",
text: "Close search",
onclick: closeSearch,
}),
];
}
/**
@@ -330,6 +424,7 @@ function connectionLabel() {
function render() {
renderHeader();
renderBanner();
renderSearch();
renderContent();
}
@@ -2249,6 +2344,337 @@ function kvMono(key, value) {
);
}
// ---------------------------------------------------------------------------
// Omni-search (S1/S2)
// ---------------------------------------------------------------------------
/** Open the search field and ask for focus; the current view is left alone. */
function openSearch() {
if (state.searchOpen) return;
state.searchOpen = true;
state.searchError = "";
state.searchFocusPending = true;
renderHeader();
renderSearch();
}
/**
* 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();
// 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.searchQuery = "";
state.searchResults = [];
state.searchLoading = false;
state.searchError = "";
state.searchLoaded = false;
state.searchFocusPending = false;
renderHeader();
renderSearch();
}
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.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 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);
searchHost.replaceChildren(h("div", { id: "searchPanel", class: "search-panel" }, controls, area));
}
/**
* 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") {
for (const hit of shown) nodes.push(renderSearchResultRow(hit));
} 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);
}
/**
* One result row: a compact kind label (the accessibility counterpart of the
* app's type glyph), 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 element = h("div", {
class: `search-row${target ? " clickable" : " readonly"}`,
"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();
}
});
}
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 }));
}
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;
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);
}
}
// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------
@@ -2543,16 +2969,19 @@ client.addEventListener("state", (event) => {
// The stage pane is a modal dialog: Escape closes it (a stacked overlay — the
// artifact viewer or the diff viewer, when either is above — owns Escape first).
// Registered once; it is a no-op when no pane is open.
// Once no pane is open, Escape closes the omni-search field. Registered once;
// every branch is a no-op when nothing relevant is open.
document.addEventListener("keydown", (event) => {
if (
event.key === "Escape" &&
state.runStagePane &&
!document.querySelector(".artifact-viewer") &&
!document.querySelector(".change-viewer")
) {
if (event.key !== "Escape") return;
if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return;
if (state.runStagePane) {
event.preventDefault();
closeStagePane();
return;
}
if (state.searchOpen) {
event.preventDefault();
closeSearch();
}
});