web: run history list, filter and sort (R1/R2)

Day-grouped run list with sticky day headers (Today / Yesterday / d MMM
yyyy / Unknown date), a usage roll-up block, the app's row hierarchy and
a bounded filter/sort menu — mirroring RunHistoryScreen.kt, ListFilter.kt
and ListSort.kt. New pure helpers live in src/runs.js with focused unit
tests; app.js keeps the wiring and sets server strings with textContent.

R1 done, R2 partial: no per-row "needs you" mark exists in the Android
app; its wording is deferred to R15 (separate attention surface).
This commit is contained in:
2026-10-19 02:50:51 +01:00
parent 4721b8af10
commit 849a184561
6 changed files with 1601 additions and 48 deletions
+343 -39
View File
@@ -4,6 +4,26 @@
import { PipelinesClient } from "./client.js";
import { PipelinesRepository } from "./repository.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
import {
RUN_STATES,
RUN_TIME_RANGES,
RUN_SORTS,
DEFAULT_RUN_SORT,
runStateOf,
runIdentity,
versionLabel,
progressText,
metaText,
formatDuration,
localDayKey,
filterRuns,
groupRunsByDay,
runComparator,
pipelineFilterOptions,
runListEntries,
defaultRunFilters,
runFiltersActiveCount,
} from "./runs.js";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
@@ -45,10 +65,20 @@ const state = {
selectedRunId: null,
loading: false,
error: "",
runFilters: defaultRunFilters(),
runSort: DEFAULT_RUN_SORT,
openMenu: null,
};
let runPoll = null;
// One shared live clock for the runs list: it ticks only while a shown run is
// executing, and each running row reads its elapsed from it rather than starting
// a timer of its own. Elapsed is derived from the server's start timestamp, so
// it stays correct after a reconnect; a finished history never ticks.
let listClock = null;
let listNow = Date.now();
// ---------------------------------------------------------------------------
// DOM helpers
// ---------------------------------------------------------------------------
@@ -181,6 +211,8 @@ function renderContent() {
}
nodes.push(split);
content.replaceChildren(...nodes);
if (state.view === "runs") refreshListClock();
else stopListClock();
}
function tabButton(view, label) {
@@ -265,52 +297,294 @@ function renderPipelineDetail() {
}
function renderRunList() {
const list = h("div", { class: "list" });
if (state.usage) {
list.append(
h(
"div",
{ class: "usage" },
h("span", { text: `${state.usage.total} total` }),
h("span", { class: "ok", text: `${state.usage.succeeded} succeeded` }),
h("span", { class: "bad", text: `${state.usage.failed} failed` }),
h("span", { class: "warn", text: `${state.usage.active} active` }),
),
);
}
const pane = h("div", { class: "list runs" });
pane.append(renderRunToolbar());
const scroll = h("div", { class: "run-scroll" });
if (state.loading && !state.runs.length) {
list.append(h("div", { class: "muted pad", text: "Loading…" }));
return list;
scroll.append(h("div", { class: "muted pad", text: "Loading…" }));
pane.append(scroll);
return pane;
}
if (!state.runs.length) {
list.append(h("div", { class: "muted pad", text: "No runs." }));
return list;
const filters = state.runFilters;
const today = localDayKey(new Date());
const filtered = filterRuns(state.runs, filters, today);
const groups = groupRunsByDay(filtered, today, undefined, runComparator(state.runSort));
const entries = runListEntries(
state.usage,
state.runs.length === 0,
filtered.length === 0 && state.runs.length > 0,
groups,
"",
);
for (const entry of entries) {
switch (entry.kind) {
case "usage":
scroll.append(renderUsage(entry.usage));
break;
case "empty":
scroll.append(renderEmptyState(entry));
break;
case "day":
scroll.append(h("div", { class: "day-header", text: entry.label }));
break;
case "run":
scroll.append(renderRunRow(entry.run));
break;
case "error":
scroll.append(h("div", { class: "run-list-error", text: entry.message }));
break;
}
}
for (const r of state.runs) {
list.append(
pane.append(scroll);
return pane;
}
function renderUsage(usage) {
const metrics = h("div", { class: "metrics" });
metrics.append(metric("Total", String(usage.total ?? 0), "total"));
if ((usage.average_seconds ?? 0) > 0) {
metrics.append(metric("Average", formatDuration(usage.average_seconds), "average"));
}
metrics.append(metric("Succeeded", String(usage.succeeded ?? 0), "succeeded"));
metrics.append(metric("Failed", String(usage.failed ?? 0), "failed"));
metrics.append(metric("Canceled", String(usage.canceled ?? 0), "canceled"));
metrics.append(metric("Interrupted", String(usage.interrupted ?? 0), "interrupted"));
metrics.append(metric("Active", String(usage.active ?? 0), "active"));
return metrics;
}
function metric(label, value, cls) {
return h(
"div",
{ class: `metric metric-${cls}` },
h("span", { class: "metric-value", text: value }),
h("span", { class: "metric-label", text: label }),
);
}
function renderEmptyState(entry) {
const wrap = h("div", { class: "empty-state" }, h("span", { text: entry.message }));
if (entry.actionLabel) {
wrap.append(h("button", { class: "ghost", text: entry.actionLabel, onclick: clearRunFilters }));
}
return wrap;
}
/**
* One run row, in the app's exact hierarchy: status chip (+ spinner while
* executing); primary line = stored title else pipeline name, carrying the
* version chip when there is no title; the pipeline name + version chip on a
* second line only when a title exists; the progress line; the meta line; and
* the diagnostic line, in the error colour only on a failure. Every
* server-provided string is set with textContent.
*/
function renderRunRow(run) {
const status = runStateOf(run.status);
const identity = runIdentity(run.title, run.name);
const row = h("button", {
class: `row run-row${state.selectedRunId === run.id ? " selected" : ""}`,
onclick: () => selectRun(run.id),
});
const head = h("span", { class: "run-row-head" });
head.append(h("span", { class: `chip chip-${status}`, text: status }));
if (run.executing) head.append(h("span", { class: "spinner", "aria-hidden": "true" }));
head.append(h("span", { class: "run-row-title", text: identity.label }));
if (identity.pipeline == null) head.append(versionChip(run.version));
row.append(head);
if (identity.pipeline != null) {
row.append(
h(
"button",
{
class: `row${state.selectedRunId === r.id ? " selected" : ""}`,
onclick: () => selectRun(r.id),
},
h(
"span",
{ class: "row-head" },
h("span", { class: "row-title", text: r.title || r.name || `run ${r.id}` }),
h("span", { class: statusClass(r.status), text: r.status || "unknown" }),
),
h(
"span",
{ class: "row-meta" },
`#${r.id} · ${fmtTime(r.created_at)} · `,
isExecuting(r) ? h("em", { text: fmtDuration(r.created_at, "") }) : fmtDuration(r.created_at, r.finished_at),
),
r.diagnostic ? h("span", { class: "row-diag", text: r.diagnostic }) : null,
"span",
{ class: "run-row-pipeline" },
h("span", { class: "run-row-pipeline-name", text: identity.pipeline }),
versionChip(run.version),
),
);
}
return list;
row.append(h("span", { class: "run-row-progress", text: progressText(run) }));
row.append(
h("span", {
class: "run-row-meta",
"data-run-id": String(run.id),
text: metaText(run, listNow),
}),
);
if (String(run.diagnostic ?? "").trim()) {
row.append(
h("span", {
class: `run-row-diag${status === "failed" ? " error" : ""}`,
text: run.diagnostic,
}),
);
}
return row;
}
function versionChip(version) {
return h("span", { class: "version-chip", text: versionLabel(version) });
}
function renderRunToolbar() {
const activeCount = runFiltersActiveCount(state.runFilters);
const filterLabel = activeCount > 0 ? `Filter (${activeCount})` : "Filter";
const sortLabel = (RUN_SORTS.find((s) => s.value === state.runSort) ?? RUN_SORTS[0]).label;
const toolbar = h("div", { class: "run-toolbar" });
toolbar.append(
h(
"div",
{ class: "menu-anchor" },
h("button", {
id: "runFilterBtn",
class: `ghost filter-btn${activeCount > 0 ? " active" : ""}`,
title: activeCount > 0 ? `${activeCount} active filter${activeCount === 1 ? "" : "s"}` : "Filter runs",
text: filterLabel,
"data-active-count": String(activeCount),
onclick: () => toggleMenu("filter"),
}),
state.openMenu === "filter" ? renderFilterMenu() : null,
),
h(
"div",
{ class: "menu-anchor" },
h("button", {
id: "runSortBtn",
class: "ghost sort-btn",
title: "Sort runs",
text: `Sort: ${sortLabel}`,
onclick: () => toggleMenu("sort"),
}),
state.openMenu === "sort" ? renderSortMenu() : null,
),
h("span", { class: "spacer" }),
);
return toolbar;
}
function renderFilterMenu() {
const filters = state.runFilters;
const menu = h("div", { class: "menu filter-menu", id: "runFilterMenu" });
menu.append(h("div", { class: "menu-section", text: "Status" }));
for (const status of RUN_STATES) {
menu.append(
filterCheck(status, filters.statuses.has(status), () => toggleStatusFilter(status), {
"data-status": status,
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(h("div", { class: "menu-section", text: "Pipeline" }));
menu.append(
filterCheck("Any pipeline", filters.pipelineId == null, () => setPipelineFilter(null), {
"data-pipeline": "any",
}),
);
for (const option of pipelineFilterOptions(state.runs)) {
menu.append(
filterCheck(option.name, filters.pipelineId === option.id, () => setPipelineFilter(option.id), {
"data-pipeline": String(option.id),
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(h("div", { class: "menu-section", text: "Time range" }));
for (const range of RUN_TIME_RANGES) {
menu.append(
filterCheck(range.label, filters.timeRange === range.value, () => setTimeRangeFilter(range.value), {
"data-time": range.value,
}),
);
}
menu.append(
h(
"div",
{ class: "menu-actions" },
h("button", { class: "ghost", text: "Clear filters", onclick: clearRunFilters }),
h("button", { class: "ghost", text: "Done", onclick: closeMenu }),
),
);
return menu;
}
function filterCheck(label, checked, onclick, data = {}) {
return h(
"label",
{ class: "filter-check" },
h("input", {
type: "checkbox",
checked: checked ? "checked" : null,
onchange: onclick,
...data,
}),
h("span", { text: label }),
);
}
function renderSortMenu() {
const menu = h("div", { class: "menu sort-menu", id: "runSortMenu" });
for (const option of RUN_SORTS) {
menu.append(
h("button", {
class: `menu-item${state.runSort === option.value ? " selected" : ""}`,
text: option.label,
onclick: () => {
state.runSort = option.value;
closeMenu();
},
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(
h("button", {
class: "menu-item",
text: "Reset",
onclick: () => {
state.runSort = DEFAULT_RUN_SORT;
closeMenu();
},
}),
);
return menu;
}
function toggleStatusFilter(status) {
const next = new Set(state.runFilters.statuses);
if (next.has(status)) next.delete(status);
else next.add(status);
state.runFilters = { ...state.runFilters, statuses: next };
renderContent();
}
function setPipelineFilter(pipelineId) {
state.runFilters = { ...state.runFilters, pipelineId };
closeMenu();
}
function setTimeRangeFilter(timeRange) {
state.runFilters = { ...state.runFilters, timeRange };
closeMenu();
}
function clearRunFilters() {
state.runFilters = defaultRunFilters();
closeMenu();
}
function toggleMenu(name) {
state.openMenu = state.openMenu === name ? null : name;
renderContent();
}
function closeMenu() {
state.openMenu = null;
renderContent();
}
function renderRunDetail() {
@@ -509,6 +783,35 @@ function stopRunPoll() {
}
}
/**
* (Re)start the shared runs-list clock: it ticks once a second only while a
* shown run is executing, updating each running row's meta line in place (never
* a full re-render, so an open filter/sort menu is not torn down). The elapsed
* value is derived from the run's server start timestamp, so it survives a
* reconnect.
*/
function refreshListClock() {
stopListClock();
listNow = Date.now();
if (state.view === "runs" && state.runs.some((run) => run.executing)) {
listClock = setInterval(() => {
listNow = Date.now();
for (const node of document.querySelectorAll(".run-row-meta[data-run-id]")) {
const id = Number(node.getAttribute("data-run-id"));
const run = state.runs.find((candidate) => candidate.id === id);
if (run && run.executing) node.textContent = metaText(run, listNow);
}
}, 1000);
}
}
function stopListClock() {
if (listClock) {
clearInterval(listClock);
listClock = null;
}
}
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
@@ -523,6 +826,7 @@ client.addEventListener("state", (event) => {
}
if (next.kind !== "connected" && previousKind === "connected") {
stopRunPoll();
stopListClock();
}
render();
});
+512
View File
@@ -0,0 +1,512 @@
// Pure, DOM-free helpers for the runs history list: the status vocabulary, run
// identity, progress/meta wording, filtering, sorting and day grouping.
//
// This mirrors the Android app exactly — ui/screens/RunHistoryScreen.kt,
// screens/ListFilter.kt, screens/ListSort.kt, ui/RunIdentity.kt and ui/Format.kt
// — so the browser list reads the same words in the same order as the app. It is
// deliberately DOM-free: every rule here is unit-testable under `node --test`
// with no browser and no server. app.js keeps the wiring.
//
// Every server-provided string is only ever compared or rendered, never parsed
// as markup; the caller sets it with textContent.
// ---------------------------------------------------------------------------
// Status vocabulary
// ---------------------------------------------------------------------------
/**
* The server's own run vocabulary, in the filter's display order
* (internal/pipeline/runs.go: queued/running/waiting/succeeded/failed/canceled/
* interrupted). The app-only `active` usage bucket, the stage-outcome words
* (`blocked`/`skipped`) and the `unknown` fallback are deliberately not offered
* as run-status filters, mirroring RUN_STATUS_FILTERS.
*/
export const RUN_STATES = [
"queued",
"running",
"waiting",
"succeeded",
"failed",
"canceled",
"interrupted",
];
/**
* Maps a server status or outcome word to its canonical display state, accepting
* the server's vocabulary only (the steps/outcomes synonyms resolve onto the same
* states so one chip set renders list, detail and timeline). Mirrors
* runStateOf: blank or unrecognised input is the safe `unknown` fallback.
*/
export function runStateOf(status) {
switch (String(status ?? "").trim().toLowerCase()) {
case "running":
return "running";
case "queued":
return "queued";
case "waiting":
return "waiting";
case "active":
return "active";
case "succeeded":
case "success":
case "completed":
case "done":
return "succeeded";
case "failed":
case "error":
return "failed";
case "canceled":
case "cancelled":
return "canceled";
case "interrupted":
return "interrupted";
case "blocked":
return "blocked";
case "skipped":
return "skipped";
default:
return "unknown";
}
}
// ---------------------------------------------------------------------------
// Identity, wording and time formatting
// ---------------------------------------------------------------------------
/**
* The runs list's two identity lines: `label` is the run's primary line and
* `pipeline` is the pipeline the run belongs to, shown as a second line only
* when the label is a stored title. A run with no title falls back to the
* pipeline name as its only line — never a title followed by an empty one.
* Mirrors ui/RunIdentity.kt runIdentity.
*/
export function runIdentity(title, name) {
const stored = String(title ?? "").trim();
return stored
? { label: stored, pipeline: String(name ?? "") }
: { label: String(name ?? ""), pipeline: null };
}
/** The version chip label, e.g. `v5` (mirrors RunHistoryScreen.VersionChip). */
export function versionLabel(version) {
return `v${version}`;
}
/**
* A visit count in the app's one singular/plural spelling (`1 visit` /
* `n visits`), mirroring ui/Format.kt visitCount so the same run is never
* described inconsistently.
*/
export function visitCount(count, adjective) {
const n = Number(count) || 0;
return `${n} ${adjective} ${n === 1 ? "visit" : "visits"}`;
}
/** Parses an RFC3339 timestamp to epoch millis, or null when blank/unparseable. */
export function parseInstant(text) {
if (text == null) return null;
const value = String(text).trim();
if (!value) return null;
const ms = Date.parse(value);
return Number.isNaN(ms) ? null : ms;
}
/**
* Non-negative whole seconds between two RFC3339 timestamps, or null when either
* is blank/unparseable or the end precedes the start. Mirrors Format.durationSeconds
* (truncating toward zero), so a sort key and the printed duration never disagree.
*/
export function durationSeconds(start, end) {
const from = parseInstant(start);
const to = parseInstant(end);
if (from == null || to == null) return null;
const seconds = Math.trunc((to - from) / 1000);
return seconds >= 0 ? seconds : null;
}
/**
* Non-negative whole seconds from a [start] RFC3339 timestamp to [nowMillis], or
* null when [start] is blank/unparseable. A future start (clock skew) reads as 0,
* never a negative. Mirrors Format.secondsSince.
*/
export function secondsSince(start, nowMillis) {
const from = parseInstant(start);
if (from == null) return null;
return Math.max(0, Math.trunc((nowMillis - from) / 1000));
}
/**
* Human duration for a whole number of seconds: `Ns`, `Nm Ss`, `Hh Mm`. Mirrors
* Format.formatDuration (a negative total renders as `0s`).
*/
export function formatDuration(totalSeconds) {
const seconds = Math.max(0, Math.trunc(Number(totalSeconds) || 0));
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
}
/**
* An RFC3339 timestamp as the app's one human, local rendering (`d MMM HH:mm`,
* e.g. `17 Oct 21:26`), or null when blank/unparseable so a caller omits the
* value rather than printing a blank. [options] may carry a `zone` (IANA name)
* and `locale` for deterministic tests; both default to the runtime's.
*/
export function formatLocalTimestamp(instant, options = {}) {
const ms = parseInstant(instant);
if (ms == null) return null;
return formatInZone(ms, options, (parts) => `${parts.day} ${parts.month} ${parts.hour}:${parts.minute}`);
}
/** The run's calendar day (`YYYY-MM-DD`) in [zone], or null when unparseable. */
export function localDayKey(value, zone) {
const ms = value instanceof Date ? value.getTime() : parseInstant(value);
if (ms == null || !Number.isFinite(ms)) return null;
try {
const fmt = new Intl.DateTimeFormat("en-CA", {
year: "numeric",
month: "2-digit",
day: "2-digit",
timeZone: zone,
});
return fmt.format(new Date(ms));
} catch {
return null;
}
}
/**
* The day header for a run: `Today`, `Yesterday`, `d MMM yyyy`, or `Unknown date`
* for a blank/unparseable timestamp. [today] may be a day-key string or a Date.
* Mirrors RunHistoryScreen.dayLabel.
*/
export function dayLabel(createdAt, today, zone) {
const key = localDayKey(createdAt, zone);
if (key == null) return "Unknown date";
const todayKey = typeof today === "string" ? today : localDayKey(today, zone);
if (todayKey == null) return "Unknown date";
if (key === todayKey) return "Today";
if (key === addDays(todayKey, -1)) return "Yesterday";
return formatDayKey(key);
}
/**
* The runs list's meta line: `run {id} · {local d MMM HH:mm} · {duration}` for a
* finished run, and `run {id} · {live elapsed}` for an executing one (elapsed
* computed from its server start timestamp against [nowMillis]). Mirrors
* RunHistoryScreen.metaText.
*/
export function metaText(run, nowMillis, options = {}) {
const parts = [`run ${run.id}`];
if (run.executing) {
const elapsed = secondsSince(run.created_at, nowMillis);
if (elapsed != null) parts.push(formatDuration(elapsed));
} else {
const stamp = formatLocalTimestamp(run.created_at, options);
if (stamp != null) parts.push(stamp);
const duration = durationSeconds(run.created_at, run.finished_at);
if (duration != null) parts.push(formatDuration(duration));
}
return parts.join(" · ");
}
/**
* Progress from the fields a summary actually has: an optional resource-wait
* line, completed visits, then the current stage. Mirrors
* RunHistoryScreen.progressText.
*/
export function progressText(run) {
const parts = [];
if (run.resource_wait != null) {
parts.push(`Waiting for resource ${String(run.resource_wait.resource ?? "")}`);
}
parts.push(visitCount(run.completed_steps, "completed"));
const stage = String(run.current_stage ?? "").trim();
if (stage) parts.push(`stage ${stage}`);
return parts.join(" · ");
}
// ---------------------------------------------------------------------------
// Filters
// ---------------------------------------------------------------------------
/** The run-list time windows offered by the filter control. */
export const RUN_TIME_RANGES = [
{ value: "any_time", label: "Any time" },
{ value: "today", label: "Today" },
{ value: "last_7_days", label: "Last 7 days" },
{ value: "last_30_days", label: "Last 30 days" },
];
export const DEFAULT_TIME_RANGE = "any_time";
/** The runs-list filters, each defaulting to "no narrowing". */
export function defaultRunFilters() {
return { statuses: new Set(), pipelineId: null, timeRange: DEFAULT_TIME_RANGE };
}
/** The number of active facets (one per status/pipeline/time choice). */
export function runFiltersActiveCount(filters) {
return (
(filters.statuses && filters.statuses.size > 0 ? 1 : 0) +
(filters.pipelineId != null ? 1 : 0) +
(filters.timeRange && filters.timeRange !== DEFAULT_TIME_RANGE ? 1 : 0)
);
}
/** True when [run] is in [statuses]; an empty set means "any status". */
export function runMatchesStatuses(run, statuses) {
if (!statuses || statuses.size === 0) return true;
return statuses.has(runStateOf(run.status));
}
/** True when [run] belongs to [pipelineId]; null means "any pipeline". */
export function runMatchesPipeline(run, pipelineId) {
return pipelineId == null || run.pipeline_id === pipelineId;
}
/**
* True when [run] falls inside [range] relative to [today]. A blank/unparseable
* timestamp and a future-dated run never match a finite window; `any_time`
* matches everything. The window is inclusive calendar days ending today.
*/
export function runMatchesTimeRange(run, range, today, zone) {
if (!range || range === DEFAULT_TIME_RANGE) return true;
const key = localDayKey(run.created_at, zone);
if (key == null) return false;
const todayKey = typeof today === "string" ? today : localDayKey(today, zone);
if (todayKey == null) return false;
if (key > todayKey) return false;
switch (range) {
case "today":
return key === todayKey;
case "last_7_days":
return key >= addDays(todayKey, -6);
case "last_30_days":
return key >= addDays(todayKey, -29);
default:
return true;
}
}
/** Every run facet combined with AND. */
export function runMatchesFilters(run, filters, today, zone) {
return (
runMatchesStatuses(run, filters.statuses) &&
runMatchesPipeline(run, filters.pipelineId) &&
runMatchesTimeRange(run, filters.timeRange, today, zone)
);
}
/** Narrows [runs] by [filters]; the default filters change nothing. */
export function filterRuns(runs, filters, today, zone) {
if (runFiltersActiveCount(filters) === 0) return runs;
return (runs ?? []).filter((run) => runMatchesFilters(run, filters, today, zone));
}
/** One selectable pipeline in the run filter, named from its runs. */
export function pipelineFilterOptions(runs) {
const names = new Map();
for (const run of runs ?? []) {
const current = names.get(run.pipeline_id);
if (current == null || current.trim() === "") names.set(run.pipeline_id, run.name ?? "");
}
return [...names.entries()]
.map(([id, name]) => ({ id, name: name.trim() === "" ? `Pipeline ${id}` : name }))
.sort((a, b) => caseInsensitiveCompare(a.name, b.name) || a.id - b.id);
}
// ---------------------------------------------------------------------------
// Sort
// ---------------------------------------------------------------------------
/** The run-list orderings offered by the sort control. */
export const RUN_SORTS = [
{ value: "newest_first", label: "Newest first" },
{ value: "oldest_first", label: "Oldest first" },
{ value: "longest_duration", label: "Longest duration" },
{ value: "shortest_duration", label: "Shortest duration" },
{ value: "pipeline_name", label: "Pipeline name" },
{ value: "status", label: "Status" },
];
export const DEFAULT_RUN_SORT = "newest_first";
/**
* The pure comparator for [sort]. Every case ends in an explicit id tie-break
* (`id` is unique) so runs that compare equal on the primary key always order
* the same way. A blank/unparseable timestamp and a run with no recorded
* duration (still executing) sort last regardless of direction and never crash.
* Mirrors ListSort.runComparator.
*/
export function runComparator(sort) {
switch (sort) {
case "oldest_first":
return (a, b) =>
ascending(instantOr(a.created_at, Infinity), instantOr(b.created_at, Infinity)) ||
ascending(a.id, b.id);
case "longest_duration":
return (a, b) => {
const da = durationSeconds(a.created_at, a.finished_at);
const db = durationSeconds(b.created_at, b.finished_at);
return (
ascending(da == null ? 1 : 0, db == null ? 1 : 0) ||
descending(da ?? -Infinity, db ?? -Infinity) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id)
);
};
case "shortest_duration":
return (a, b) => {
const da = durationSeconds(a.created_at, a.finished_at);
const db = durationSeconds(b.created_at, b.finished_at);
return (
ascending(da == null ? 1 : 0, db == null ? 1 : 0) ||
ascending(da ?? Infinity, db ?? Infinity) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id)
);
};
case "pipeline_name":
return (a, b) =>
caseInsensitiveCompare(a.name, b.name) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id);
case "status":
return (a, b) =>
caseInsensitiveCompare(a.status, b.status) ||
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id);
case "newest_first":
default:
return (a, b) =>
descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) ||
descending(a.id, b.id);
}
}
/** Orders [runs] by [sort], returning a new array. */
export function sortRuns(runs, sort) {
return [...(runs ?? [])].sort(runComparator(sort));
}
// ---------------------------------------------------------------------------
// Day grouping and the list's slots
// ---------------------------------------------------------------------------
/**
* Groups runs by calendar day in [zone], preserving the order [order] puts them
* in and the order within a day. A blank/unparseable timestamp gets a safe
* "Unknown date" group. Mirrors RunHistoryScreen.groupRunsByDay.
*/
export function groupRunsByDay(runs, today, zone, order = runComparator(DEFAULT_RUN_SORT)) {
const groups = new Map();
for (const run of [...(runs ?? [])].sort(order)) {
const label = dayLabel(run.created_at, today, zone);
if (!groups.has(label)) groups.set(label, []);
groups.get(label).push(run);
}
return [...groups.entries()].map(([label, list]) => ({ label, runs: list }));
}
export const NO_RUNS_MESSAGE = "No runs have been recorded yet.";
export const NO_MATCH_MESSAGE = "No runs match the current filters.";
export const CLEAR_FILTERS_LABEL = "Clear filters";
/**
* The runs list's slots in layout order: the usage block when there is one, then
* either the single empty line (nothing recorded, or nothing matching the
* filters) or the day groups, then the inline error row. Pure and single-sourced
* with the renderer, so its size is exactly the list's entry count. Mirrors
* RunHistoryScreen.runListEntries.
*/
export function runListEntries(usage, nothingRecorded, nothingMatched, groups, error) {
const entries = [];
if (usage != null) entries.push({ kind: "usage", key: "usage", usage });
if (nothingRecorded) {
entries.push({ kind: "empty", key: "runs-empty", message: NO_RUNS_MESSAGE, actionLabel: null });
} else if (nothingMatched) {
entries.push({
kind: "empty",
key: "runs-filtered-empty",
message: NO_MATCH_MESSAGE,
actionLabel: CLEAR_FILTERS_LABEL,
});
} else {
for (const group of groups ?? []) {
entries.push({ kind: "day", key: `day-${group.label}`, label: group.label });
for (const run of group.runs) entries.push({ kind: "run", key: `run-${run.id}`, run });
}
}
if (error) entries.push({ kind: "error", key: "runs-error", message: error });
return entries;
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
/** Ascending compare of two numbers/strings, safe on the -Infinity sentinels. */
function ascending(x, y) {
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
/** Descending compare: the larger value sorts first. */
function descending(x, y) {
return ascending(y, x);
}
function instantOr(iso, fallback) {
const ms = parseInstant(iso);
return ms == null ? fallback : ms;
}
function caseInsensitiveCompare(a, b) {
const left = String(a ?? "").toLowerCase();
const right = String(b ?? "").toLowerCase();
if (left < right) return -1;
if (left > right) return 1;
return 0;
}
/** `dayKey` shifted by [days] calendar days (keys are `YYYY-MM-DD`). */
function addDays(dayKey, days) {
const [year, month, day] = dayKey.split("-").map(Number);
const shifted = new Date(Date.UTC(year, month - 1, day) + days * 86400000);
return `${shifted.getUTCFullYear()}-${pad2(shifted.getUTCMonth() + 1)}-${pad2(shifted.getUTCDate())}`;
}
function pad2(value) {
return String(value).padStart(2, "0");
}
function formatDayKey(dayKey) {
const [year, month, day] = dayKey.split("-").map(Number);
const parts = zoneParts(Date.UTC(year, month - 1, day), "UTC", "en-GB");
return `${parts.day} ${parts.month} ${parts.year}`;
}
function formatInZone(ms, options, assemble) {
const parts = zoneParts(ms, options.zone, options.locale);
return parts ? assemble(parts) : null;
}
/** The named parts of `ms` in [zone], or null when the zone is unusable. */
function zoneParts(ms, zone, locale) {
try {
const fmt = new Intl.DateTimeFormat(locale ?? "en-GB", {
day: "numeric",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
timeZone: zone,
});
return Object.fromEntries(fmt.formatToParts(new Date(ms)).map((part) => [part.type, part.value]));
} catch {
return null;
}
}