feat(#2443): asyncBtn — shared reusable component, replace ad-hoc disable/spinner patterns
add `asyncBtn(btn, fn)` to `@hive/shared/forms.js` as the single reusable component for async button actions: 1. double-click guard: returns immediately if btn is already disabled 2. saves btn.innerHTML, replaces with spinner while in-flight 3. restores btn on resolve or reject via finally wire it into all ad-hoc disable/spinner/restore patterns: - common.js: bindAsyncForms uses asyncBtn internally - core.js: 'clear perms' button - permissions.js: clearStaleAgent - schedules.js: saveSchedule submit, editSchedule submit - app.js: buildAnswerForm, buildInboxMarkAllRow fireScheduleNow in schedules.js is left with its existing childNode save/restore because it shows a custom result flash on the button content after a successful fire-now (the auto-restore of asyncBtn would overwrite it); the surrounding themedConfirm dialog already acts as a natural double-click barrier before the fetch. saveAll in permissions.js is also left as-is: it uses a custom 'queued ✓' success label + a 900ms delay before re-fetch; the btn.dataset.busy flag is its own double-submit guard.
This commit is contained in:
parent
6d281e4606
commit
4b45c5cd3d
7 changed files with 143 additions and 119 deletions
|
|
@ -3,6 +3,7 @@
|
||||||
// actions (send / login/* / dashboard rebuild).
|
// actions (send / login/* / dashboard rebuild).
|
||||||
|
|
||||||
import { create as termCreate, linkify as termLinkify } from '@hive/shared/terminal.js';
|
import { create as termCreate, linkify as termLinkify } from '@hive/shared/terminal.js';
|
||||||
|
import { asyncBtn } from '@hive/shared/forms.js';
|
||||||
import { marked } from 'marked';
|
import { marked } from 'marked';
|
||||||
import DOMPurify from 'dompurify';
|
import DOMPurify from 'dompurify';
|
||||||
|
|
||||||
|
|
@ -1051,29 +1052,28 @@ window.marked = marked;
|
||||||
const ta = el('textarea', { rows: '2', placeholder: 'answer as operator…' });
|
const ta = el('textarea', { rows: '2', placeholder: 'answer as operator…' });
|
||||||
const btn = el('button', { type: 'button' }, 'send answer');
|
const btn = el('button', { type: 'button' }, 'send answer');
|
||||||
const status = el('span', { class: 'answer-status' });
|
const status = el('span', { class: 'answer-status' });
|
||||||
btn.addEventListener('click', async () => {
|
btn.addEventListener('click', () => {
|
||||||
const answer = ta.value.trim();
|
const answer = ta.value.trim();
|
||||||
if (!answer) { status.textContent = 'answer required'; return; }
|
if (!answer) { status.textContent = 'answer required'; return; }
|
||||||
if (!dashboardBase) { status.textContent = 'dashboard url unknown'; return; }
|
if (!dashboardBase) { status.textContent = 'dashboard url unknown'; return; }
|
||||||
btn.disabled = true;
|
|
||||||
status.textContent = 'sending…';
|
status.textContent = 'sending…';
|
||||||
try {
|
asyncBtn(btn, async () => {
|
||||||
const resp = await fetch(dashboardBase + 'api/answer-question/' + id, {
|
try {
|
||||||
method: 'POST',
|
const resp = await fetch(dashboardBase + 'api/answer-question/' + id, {
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
method: 'POST',
|
||||||
body: 'answer=' + encodeURIComponent(answer),
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
});
|
body: 'answer=' + encodeURIComponent(answer),
|
||||||
if (resp.ok) {
|
});
|
||||||
status.textContent = 'answered ✓';
|
if (resp.ok) {
|
||||||
refreshLooseEnds();
|
status.textContent = 'answered ✓';
|
||||||
} else {
|
refreshLooseEnds();
|
||||||
status.textContent = 'failed: ' + (await resp.text());
|
} else {
|
||||||
btn.disabled = false;
|
status.textContent = 'failed: ' + (await resp.text());
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
status.textContent = 'failed: ' + err;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
});
|
||||||
status.textContent = 'failed: ' + err;
|
|
||||||
btn.disabled = false;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
wrap.append(ta, btn, status);
|
wrap.append(ta, btn, status);
|
||||||
return wrap;
|
return wrap;
|
||||||
|
|
@ -1094,38 +1094,31 @@ window.marked = marked;
|
||||||
+ 'history shown here is the most-recent-N regardless of state, '
|
+ 'history shown here is the most-recent-N regardless of state, '
|
||||||
+ 'so the list itself stays visible.',
|
+ 'so the list itself stays visible.',
|
||||||
}, '✓ mark all read');
|
}, '✓ mark all read');
|
||||||
btn.addEventListener('click', async () => {
|
btn.addEventListener('click', () => {
|
||||||
if (!dashboardBase) {
|
if (!dashboardBase) { status.textContent = 'dashboard url unknown'; return; }
|
||||||
status.textContent = 'dashboard url unknown';
|
if (!label) { status.textContent = 'agent label unknown'; return; }
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!label) {
|
|
||||||
status.textContent = 'agent label unknown';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!window.confirm(
|
if (!window.confirm(
|
||||||
`mark every queued message for ${label} as read? `
|
`mark every queued message for ${label} as read? `
|
||||||
+ `the message history shown stays; only the unread queue is drained.`
|
+ `the message history shown stays; only the unread queue is drained.`
|
||||||
)) return;
|
)) return;
|
||||||
btn.disabled = true;
|
|
||||||
status.textContent = 'clearing…';
|
status.textContent = 'clearing…';
|
||||||
try {
|
asyncBtn(btn, async () => {
|
||||||
const resp = await fetch(
|
try {
|
||||||
dashboardBase + 'api/agent/' + encodeURIComponent(label) + '/mark-all-read',
|
const resp = await fetch(
|
||||||
{ method: 'POST' });
|
dashboardBase + 'api/agent/' + encodeURIComponent(label) + '/mark-all-read',
|
||||||
if (resp.ok) {
|
{ method: 'POST' });
|
||||||
const data = await resp.json().catch(() => ({}));
|
if (resp.ok) {
|
||||||
const n = Number(data.marked) || 0;
|
const data = await resp.json().catch(() => ({}));
|
||||||
status.textContent = '✓ marked ' + n + ' as read';
|
const n = Number(data.marked) || 0;
|
||||||
if (typeof onCleared === 'function') onCleared();
|
status.textContent = '✓ marked ' + n + ' as read';
|
||||||
} else {
|
if (typeof onCleared === 'function') onCleared();
|
||||||
status.textContent = 'failed: http ' + resp.status;
|
} else {
|
||||||
btn.disabled = false;
|
status.textContent = 'failed: http ' + resp.status;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
status.textContent = 'failed: ' + err;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
});
|
||||||
status.textContent = 'failed: ' + err;
|
|
||||||
btn.disabled = false;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
return el('div', { class: 'inbox-mark-all-row' }, btn, status);
|
return el('div', { class: 'inbox-mark-all-row' }, btn, status);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
// infrastructure for the side panel.
|
// infrastructure for the side panel.
|
||||||
|
|
||||||
import { linkify as termLinkify } from '@hive/shared/terminal.js';
|
import { linkify as termLinkify } from '@hive/shared/terminal.js';
|
||||||
|
import { asyncBtn } from '@hive/shared/forms.js';
|
||||||
import DOMPurify from 'dompurify';
|
import DOMPurify from 'dompurify';
|
||||||
// Themed dialog/toast helpers (modal.js imports `el` back from here — a safe
|
// Themed dialog/toast helpers (modal.js imports `el` back from here — a safe
|
||||||
// deferred cycle: neither side uses the other at module-init time, only inside
|
// deferred cycle: neither side uses the other at module-init time, only inside
|
||||||
|
|
@ -80,9 +81,10 @@ export function bindAsyncForms(onSuccess) {
|
||||||
input.value = ans;
|
input.value = ans;
|
||||||
}
|
}
|
||||||
const btn = f.querySelector('button[type="submit"], button:not([type]), .btn-inline');
|
const btn = f.querySelector('button[type="submit"], button:not([type]), .btn-inline');
|
||||||
const original = btn ? btn.innerHTML : '';
|
// Inner action: POST, clear inputs, call onSuccess.
|
||||||
if (btn) { btn.disabled = true; btn.innerHTML = '<span class="spinner">◐</span>'; }
|
// Errors are surfaced via themedToast; the caller does not re-throw
|
||||||
try {
|
// so asyncBtn's finally always runs (restoring the button).
|
||||||
|
const doSubmit = async () => {
|
||||||
const resp = await fetch(f.action, {
|
const resp = await fetch(f.action, {
|
||||||
method: f.method || 'POST',
|
method: f.method || 'POST',
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
|
@ -94,21 +96,18 @@ export function bindAsyncForms(onSuccess) {
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
const text = await resp.text().catch(() => '');
|
const text = await resp.text().catch(() => '');
|
||||||
themedToast('action failed: ' + resp.status + (text ? '\n\n' + text : ''), { type: 'error' });
|
themedToast('action failed: ' + resp.status + (text ? '\n\n' + text : ''), { type: 'error' });
|
||||||
if (btn) { btn.disabled = false; btn.innerHTML = original; }
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Re-enable the button — the refresh rebuilds most lists but skips
|
|
||||||
// forms that didn't change, so without this the spinner sticks.
|
|
||||||
if (btn) { btn.disabled = false; btn.innerHTML = original; }
|
|
||||||
// Clear text inputs whose value was just submitted.
|
// Clear text inputs whose value was just submitted.
|
||||||
f.querySelectorAll('input[type="text"], input:not([type]), textarea').forEach((i) => { i.value = ''; });
|
f.querySelectorAll('input[type="text"], input:not([type]), textarea').forEach((i) => { i.value = ''; });
|
||||||
if (!f.hasAttribute('data-no-refresh') && typeof onSuccess === 'function') {
|
if (!f.hasAttribute('data-no-refresh') && typeof onSuccess === 'function') {
|
||||||
onSuccess();
|
onSuccess();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
};
|
||||||
themedToast('action failed: ' + err, { type: 'error' });
|
// asyncBtn guards double-submit and shows a spinner while in-flight.
|
||||||
if (btn) { btn.disabled = false; btn.innerHTML = original; }
|
// When there is no submit button (unusual), fall through without a guard.
|
||||||
}
|
if (btn) asyncBtn(btn, doSubmit);
|
||||||
|
else await doSubmit();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@
|
||||||
// own copy of the tombstones state.
|
// own copy of the tombstones state.
|
||||||
|
|
||||||
import { $, el, form, openStream, initServerWarnings, bindAsyncForms } from './common.js';
|
import { $, el, form, openStream, initServerWarnings, bindAsyncForms } from './common.js';
|
||||||
|
import { asyncBtn } from '@hive/shared/forms.js';
|
||||||
import { createTabStrip } from '@hive/shared/tabs.js';
|
import { createTabStrip } from '@hive/shared/tabs.js';
|
||||||
|
|
||||||
// ─── derived state (own copies; this bundle has its own runtime) ──────────
|
// ─── derived state (own copies; this bundle has its own runtime) ──────────
|
||||||
|
|
@ -104,8 +105,7 @@ function renderStalePerms(root, ghosts) {
|
||||||
class: 'btn btn-destroy',
|
class: 'btn btn-destroy',
|
||||||
title: 'remove explicit capability and tool-group entries for ' + name,
|
title: 'remove explicit capability and tool-group entries for ' + name,
|
||||||
}, '✕ clear perms');
|
}, '✕ clear perms');
|
||||||
btn.addEventListener('click', async () => {
|
btn.addEventListener('click', () => asyncBtn(btn, async () => {
|
||||||
btn.disabled = true;
|
|
||||||
errP.hidden = true;
|
errP.hidden = true;
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/permissions/' + encodeURIComponent(name), { method: 'DELETE' });
|
const resp = await fetch('/api/permissions/' + encodeURIComponent(name), { method: 'DELETE' });
|
||||||
|
|
@ -113,17 +113,15 @@ function renderStalePerms(root, ghosts) {
|
||||||
const msg = await resp.text().catch(() => String(resp.status));
|
const msg = await resp.text().catch(() => String(resp.status));
|
||||||
errP.textContent = 'failed to clear perms for ' + name + ': ' + msg;
|
errP.textContent = 'failed to clear perms for ' + name + ': ' + msg;
|
||||||
errP.hidden = false;
|
errP.hidden = false;
|
||||||
btn.disabled = false;
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
errP.textContent = 'failed to clear perms for ' + name + ': ' + err;
|
errP.textContent = 'failed to clear perms for ' + name + ': ' + err;
|
||||||
errP.hidden = false;
|
errP.hidden = false;
|
||||||
btn.disabled = false;
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await fetchAndRenderStalePerms();
|
await fetchAndRenderStalePerms();
|
||||||
});
|
}));
|
||||||
li.append(btn);
|
li.append(btn);
|
||||||
ul.append(li);
|
ul.append(li);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@
|
||||||
|
|
||||||
import { $, el } from './common.js';
|
import { $, el } from './common.js';
|
||||||
import { containersState } from './state.js';
|
import { containersState } from './state.js';
|
||||||
|
import { asyncBtn } from '@hive/shared/forms.js';
|
||||||
|
|
||||||
// ── SSE re-render guards ────────────────────────────────────────────
|
// ── SSE re-render guards ────────────────────────────────────────────
|
||||||
// Skip the live re-render when the operator has unsaved edits in that
|
// Skip the live re-render when the operator has unsaved edits in that
|
||||||
|
|
@ -325,27 +326,28 @@ function updateSaveBar() {
|
||||||
// agent isn't in the live container list. Re-fetches both tables after
|
// agent isn't in the live container list. Re-fetches both tables after
|
||||||
// the delete so the row disappears immediately.
|
// the delete so the row disappears immediately.
|
||||||
async function clearStaleAgent(name, sectionRoot) {
|
async function clearStaleAgent(name, sectionRoot) {
|
||||||
// Disable the row's remove button while the request is in flight to
|
|
||||||
// prevent a double-submit.
|
|
||||||
const btn = sectionRoot
|
const btn = sectionRoot
|
||||||
? sectionRoot.querySelector(`[data-agent="${CSS.escape(name)}"] .perm-remove-btn`)
|
? sectionRoot.querySelector(`[data-agent="${CSS.escape(name)}"] .perm-remove-btn`)
|
||||||
: null;
|
: null;
|
||||||
if (btn) btn.disabled = true;
|
const doDelete = async () => {
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/permissions/' + encodeURIComponent(name), { method: 'DELETE' });
|
const resp = await fetch('/api/permissions/' + encodeURIComponent(name), { method: 'DELETE' });
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
const text = await resp.text().catch(() => resp.status);
|
const text = await resp.text().catch(() => resp.status);
|
||||||
setSaveNote('failed to remove ' + name + ': ' + text, true);
|
setSaveNote('failed to remove ' + name + ': ' + text, true);
|
||||||
if (btn) btn.disabled = false;
|
return;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setSaveNote('failed to remove ' + name + ': ' + err, true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
// Re-fetch both sections so the stale row disappears.
|
||||||
setSaveNote('failed to remove ' + name + ': ' + err, true);
|
await Promise.all([fetchAndRenderCapabilities(), fetchAndRenderToolGroups()]);
|
||||||
if (btn) btn.disabled = false;
|
};
|
||||||
return;
|
// asyncBtn guards double-submit; fall through without guard when there
|
||||||
}
|
// is no button (e.g. called programmatically without a DOM context).
|
||||||
// Re-fetch both sections so the stale row disappears.
|
if (btn) asyncBtn(btn, doDelete);
|
||||||
await Promise.all([fetchAndRenderCapabilities(), fetchAndRenderToolGroups()]);
|
else await doDelete();
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearSaveStatus() {
|
function clearSaveStatus() {
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import { $, el, appendLinkified } from './common.js';
|
||||||
import { themedConfirm, themedToast } from './modal.js';
|
import { themedConfirm, themedToast } from './modal.js';
|
||||||
import { paintAtomic, epochSec, fmtAgo, fmtDuration } from './util.js';
|
import { paintAtomic, epochSec, fmtAgo, fmtDuration } from './util.js';
|
||||||
import { containersState } from './state.js';
|
import { containersState } from './state.js';
|
||||||
|
import { asyncBtn } from '@hive/shared/forms.js';
|
||||||
|
|
||||||
export async function refreshReminders() {
|
export async function refreshReminders() {
|
||||||
const liveRoot = $('reminders-section');
|
const liveRoot = $('reminders-section');
|
||||||
|
|
@ -565,29 +566,25 @@ async function submitNewScheduleInline(tr, submitBtn) {
|
||||||
if (interval_seconds != null) payload.interval_seconds = interval_seconds;
|
if (interval_seconds != null) payload.interval_seconds = interval_seconds;
|
||||||
if (description) payload.description = description;
|
if (description) payload.description = description;
|
||||||
|
|
||||||
const originalLabel = submitBtn.innerHTML;
|
asyncBtn(submitBtn, async () => {
|
||||||
submitBtn.disabled = true;
|
try {
|
||||||
submitBtn.innerHTML = '<span class="spinner">◐</span>';
|
const resp = await fetch('/api/schedules', {
|
||||||
try {
|
method: 'POST',
|
||||||
const resp = await fetch('/api/schedules', {
|
headers: { 'Content-Type': 'application/json' },
|
||||||
method: 'POST',
|
body: JSON.stringify(payload),
|
||||||
headers: { 'Content-Type': 'application/json' },
|
});
|
||||||
body: JSON.stringify(payload),
|
if (!resp.ok) {
|
||||||
});
|
const text = await resp.text().catch(() => '');
|
||||||
if (!resp.ok) {
|
themedToast('schedule submit failed: http ' + resp.status + (text ? '\n\n' + text : ''), { type: 'error' });
|
||||||
const text = await resp.text().catch(() => '');
|
return;
|
||||||
themedToast('schedule submit failed: http ' + resp.status + (text ? '\n\n' + text : ''), { type: 'error' });
|
}
|
||||||
return;
|
// Reset carry so the next render shows an empty row.
|
||||||
|
resetNewScheduleCarry();
|
||||||
|
await refreshSchedules();
|
||||||
|
} catch (err) {
|
||||||
|
themedToast('schedule submit failed: ' + err, { type: 'error' });
|
||||||
}
|
}
|
||||||
// Reset carry so the next render shows an empty row.
|
});
|
||||||
resetNewScheduleCarry();
|
|
||||||
await refreshSchedules();
|
|
||||||
} catch (err) {
|
|
||||||
themedToast('schedule submit failed: ' + err, { type: 'error' });
|
|
||||||
} finally {
|
|
||||||
submitBtn.disabled = false;
|
|
||||||
submitBtn.innerHTML = originalLabel;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// The set of agent columns in the schedules table: operator + root
|
// The set of agent columns in the schedules table: operator + root
|
||||||
// (manager) first, then live containers (sorted), then any extra names
|
// (manager) first, then live containers (sorted), then any extra names
|
||||||
|
|
@ -985,27 +982,27 @@ async function submitEditSchedule(originalSchedule, form_) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const submitBtn = form_.querySelector('button[type="submit"]');
|
const submitBtn = form_.querySelector('button[type="submit"]');
|
||||||
const originalLabel = submitBtn ? submitBtn.textContent : '';
|
const doEdit = async () => {
|
||||||
if (submitBtn) { submitBtn.disabled = true; submitBtn.textContent = 'saving…'; }
|
try {
|
||||||
try {
|
const resp = await fetch('/api/schedules/' + encodeURIComponent(s.id), {
|
||||||
const resp = await fetch('/api/schedules/' + encodeURIComponent(s.id), {
|
method: 'PATCH',
|
||||||
method: 'PATCH',
|
headers: { 'Content-Type': 'application/json' },
|
||||||
headers: { 'Content-Type': 'application/json' },
|
body: JSON.stringify(patch),
|
||||||
body: JSON.stringify(patch),
|
});
|
||||||
});
|
if (!resp.ok) {
|
||||||
if (!resp.ok) {
|
const text = await resp.text().catch(() => '');
|
||||||
const text = await resp.text().catch(() => '');
|
themedToast('edit failed: http ' + resp.status + (text ? '\n\n' + text : ''), { type: 'error' });
|
||||||
themedToast('edit failed: http ' + resp.status + (text ? '\n\n' + text : ''), { type: 'error' });
|
return;
|
||||||
return;
|
}
|
||||||
|
editingSchedules.delete(s.id);
|
||||||
|
scheduleEditCarry.delete(s.id);
|
||||||
|
await refreshSchedules();
|
||||||
|
} catch (err) {
|
||||||
|
themedToast('edit failed: ' + err, { type: 'error' });
|
||||||
}
|
}
|
||||||
editingSchedules.delete(s.id);
|
};
|
||||||
scheduleEditCarry.delete(s.id);
|
if (submitBtn) asyncBtn(submitBtn, doEdit);
|
||||||
await refreshSchedules();
|
else await doEdit();
|
||||||
} catch (err) {
|
|
||||||
themedToast('edit failed: ' + err, { type: 'error' });
|
|
||||||
} finally {
|
|
||||||
if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = originalLabel; }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
async function fireScheduleNow(id, isOneShot, targets, btn) {
|
async function fireScheduleNow(id, isOneShot, targets, btn) {
|
||||||
const targetList = targets.length ? targets.join(', ') : '(no active targets)';
|
const targetList = targets.length ? targets.join(', ') : '(no active targets)';
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,8 @@
|
||||||
"./theme.css": "./src/theme.css",
|
"./theme.css": "./src/theme.css",
|
||||||
"./base.css": "./src/base.css",
|
"./base.css": "./src/base.css",
|
||||||
"./terminal.css": "./src/terminal.css",
|
"./terminal.css": "./src/terminal.css",
|
||||||
"./chrome.css": "./src/chrome.css"
|
"./chrome.css": "./src/chrome.css",
|
||||||
|
"./forms.js": "./src/forms.js"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"src/"
|
"src/"
|
||||||
|
|
|
||||||
34
frontend/packages/shared/src/forms.js
Normal file
34
frontend/packages/shared/src/forms.js
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
// Shared async-button primitive. Used by both the dashboard and the
|
||||||
|
// per-agent UI for any button that triggers a network action.
|
||||||
|
//
|
||||||
|
// `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. Saves `btn.innerHTML` and replaces it with a spinner during the
|
||||||
|
// async operation.
|
||||||
|
// 3. Re-enables the button and restores the original content when `fn`
|
||||||
|
// resolves or rejects (via `finally`), so callers don't need
|
||||||
|
// save/restore boilerplate.
|
||||||
|
//
|
||||||
|
// 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.) before the re-throw, or handle it inside `fn` without
|
||||||
|
// re-throwing.
|
||||||
|
export function asyncBtn(btn, fn) {
|
||||||
|
if (btn.disabled) return; // double-click guard
|
||||||
|
const orig = btn.innerHTML;
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.innerHTML = '<span class="spinner">◐</span>';
|
||||||
|
fn().finally(() => {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.innerHTML = orig;
|
||||||
|
});
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue