Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/frontend/packages/shared/src/forms.js
iris 3be4ec069c frontend: one time wording for the swarm UI and the dashboard, and no HTML strings in the dashboard's busy buttons
fmtAgo, fmtUntil and durationLabel move to @hive/shared/time.js. The swarm UI's util.ts is deleted and its importers (RelativeTime, ReviewRuns, BuildsPage) read the shared module directly. The dashboard's own copies are gone: its fmtAgeSecs (a third phrasing, used for two status lines) becomes the shared fmtAgo, and the dashboard util.js lost fmtAgo, fmtElapsed, epochSec and truncate, which nothing called. asyncBtn and the bulk action buttons mark themselves busy with markBusy: a spinner node before the label and aria-busy, in place of replacing the button's innerHTML with a string (and the label, so the button changed width and lost its name). The el() helper loses its html attribute.
2026-11-20 17:02:32 +01:00

131 lines
5 KiB
JavaScript

// Shared async-form primitives. Used by both the dashboard and the
// per-agent UI for any button/form that triggers a network action.
// Two pieces: `asyncBtn` (below) is the low-level per-button primitive;
// `bindAsyncForms` (further down) is the page-level `data-async` form
// submit interceptor built on top of it + the themed dialogs in
// `modal.js`.
//
// `asyncBtn(btn, fn)` — the single reusable component:
// 1. Guards double-click: returns immediately if `btn` is already
// disabled (prevents a second identical request from firing).
// 2. Puts a spinner before the label (`markBusy`) during the async
// operation; the label stays, so the button keeps its width.
// 3. Re-enables the button and takes the spinner away when `fn`
// resolves or rejects (via `finally`).
//
// Usage:
// btn.addEventListener('click', () => asyncBtn(btn, async () => {
// const resp = await fetch('/api/...');
// if (!resp.ok) throw new Error(await resp.text());
// // handle success
// }));
//
// Error handling: `asyncBtn` restores the button on any thrown error /
// rejected promise but does NOT surface the error — callers must catch
// and display it themselves (via `themedToast`, `alert`, a status span,
// etc.) inside `fn` without re-throwing. `fn` must not let errors escape
// unhandled: `asyncBtn` returns the `fn().finally(...)` promise so
// callers can optionally chain `.catch` or `await`, but does not add its
// own catch — an unhandled rejection from `fn` will propagate normally.
export function asyncBtn(btn, fn) {
if (btn.disabled) return; // double-click guard
btn.disabled = true;
const done = markBusy(btn);
return fn().finally(() => {
btn.disabled = false;
done();
});
}
// A spinner before the button's label, and `aria-busy`; the label stays, so the
// button does not change width and a screen reader still has its name. Built
// from nodes, not an HTML string. Returns the function that takes it away.
export function markBusy(btn) {
const spinner = document.createElement("span");
spinner.className = "spinner";
spinner.setAttribute("aria-hidden", "true");
spinner.textContent = "◐";
const gap = document.createTextNode(" ");
btn.prepend(spinner, gap);
btn.setAttribute("aria-busy", "true");
return () => {
spinner.remove();
gap.remove();
btn.removeAttribute("aria-busy");
};
}
// Page-level submit interceptor for `data-async` forms — the pattern every
// dashboard/agent action button uses (spawn, cancel, purge,
// rebuild, …). Without this a `data-async` form POSTs natively and the
// browser navigates to the bare `ok` response page. Each page that renders
// such forms must call this once at boot. `onSuccess` runs after a
// successful submit unless the form opts out with `data-no-refresh` (forms
// whose mutation arrives faster via an SSE event).
//
// Confirmation (`data-confirm`) is surfaced via the themed dialog in
// `modal.js` rather than native `confirm()`, and errors via `themedToast`
// rather than `alert()`, so every page gets the same in-theme experience.
import { themedConfirm, themedToast } from "./modal.js";
export function bindAsyncForms(onSuccess) {
document.addEventListener("submit", async (e) => {
const f = e.target;
if (!(f instanceof HTMLFormElement) || !f.hasAttribute("data-async"))
return;
e.preventDefault();
if (
f.dataset.confirm &&
!(await themedConfirm({ message: f.dataset.confirm }))
)
return;
const btn = f.querySelector(
'button[type="submit"], button:not([type]), .btn-inline',
);
// Inner action: POST, clear inputs, call onSuccess.
// Errors are surfaced via themedToast; the caller does not re-throw
// so asyncBtn's finally always runs (restoring the button).
const doSubmit = async () => {
let resp;
try {
resp = await fetch(f.action, {
method: f.method || "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(new FormData(f)),
redirect: "manual",
});
} catch (err) {
themedToast("action failed: " + err, { type: "error" });
return;
}
const ok =
resp.ok ||
resp.type === "opaqueredirect" ||
(resp.status >= 200 && resp.status < 400);
if (!ok) {
const text = await resp.text().catch(() => "");
themedToast(
"action failed: " + resp.status + (text ? "\n\n" + text : ""),
{ type: "error" },
);
return;
}
// Clear text inputs whose value was just submitted.
f.querySelectorAll(
'input[type="text"], input:not([type]), textarea',
).forEach((i) => {
i.value = "";
});
if (
!f.hasAttribute("data-no-refresh") &&
typeof onSuccess === "function"
) {
onSuccess();
}
};
// asyncBtn guards double-submit and shows a spinner while in-flight.
// When there is no submit button (unusual), fall through without a guard.
if (btn) asyncBtn(btn, doSubmit);
else await doSubmit();
});
}