Watch
0
0
Fork
You've already forked hyperhive
0

swarm ui: ask before actions that cannot be undone, with a danger button and a useConfirm hook

Button gains a danger variant and an autofocus prop; ConfirmDialog gains danger (red confirm, focus on cancel). Destroy, delete linked account, delete claude login, remove schedule and delete flow use it. New useConfirm hook asks from inside a handler (await confirm({...})) without a dialog's state at the call site. It now guards: removing a swarm-wide egress domain, removing a domain for every agent from an agent's popover, removing a stored API-key environment, firing a schedule now, moving an agent's internet to a looser mode, the /clear message, and reload over unsaved instructions (replacing window.confirm). The review try-out's button is now called push a branch for a PR, since it pushes a branch and does not open one, and asks first. loosensInternet is a tested helper.
This commit is contained in:
iris 2026-11-19 18:42:34 +01:00 • committed by mara
commit c3e24fe2c6
19 changed files with 353 additions and 60 deletions

View file

@ -125,6 +125,7 @@ export function AgentClaudeLogin({ agent }: { agent: string }) {
open={confirming}
label={`delete the stored claude login for ${agent}`}
confirmLabel={deleting ? "deleting…" : "delete login"}
danger
confirmDisabled={deleting}
onCancel={() => setConfirming(false)}
onConfirm={() => void confirmDelete()}

View file

@ -18,6 +18,7 @@ import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { Badge } from "@hive/shared/badge.js";
import { ActionRow } from "../../ui/action-row/ActionRow.js";
import { Button } from "../../ui/button/Button.js";
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
import { Preformatted } from "../../ui/preformatted/Preformatted.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { Panel } from "../../ui/panel/Panel.js";
@ -113,6 +114,22 @@ function InstructionsForm({
const [busy, setBusy] = useState(false);
const [problem, setProblem] = useState<ProblemDetails | null>(null);
const [saved, setSaved] = useState(false);
const [confirm, confirmDialog] = useConfirm();
// Loading the agent's file drops what is typed, so unsaved edits ask first.
async function askReload() {
if (
!dirty ||
(await confirm({
label: "drop unsaved changes",
confirmLabel: "drop and reload",
danger: true,
body: <p>Drop your unsaved changes and load {agent}'s file?</p>,
}))
) {
reload();
}
}
useEffect(() => {
let cancelled = false;
@ -294,24 +311,14 @@ function InstructionsForm({
>
undo my changes
</Button>
<Button
disabled={busy}
onClick={() => {
if (
!dirty ||
window.confirm(
"Drop your unsaved changes and load the agent's file?",
)
)
reload();
}}
>
<Button disabled={busy} onClick={() => void askReload()}>
reload from {agent}
</Button>
</ActionRow>
</form>
) : null}
</div>
{confirmDialog}
</Panel>
);
}

View file

@ -22,6 +22,7 @@ import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { Badge } from "@hive/shared/badge.js";
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
import { Button } from "../../ui/button/Button.js";
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
import { BadgeSkeleton } from "../../ui/skeleton/BadgeSkeleton.js";
import { Hint } from "../../ui/hint/Hint.js";
import { TextField } from "../../ui/text-field/TextField.js";
@ -40,6 +41,7 @@ import {
maxReposBody,
parseMaxRepos,
reposSummary,
loosensInternet,
type InternetMode,
} from "./permissions.js";
import "./AgentLimits.css";
@ -257,9 +259,37 @@ export function AgentPermissions({
export function AgentInternet({ agent, g }: { agent: string; g: GrantState }) {
const { grant, busy, saveError, loading, send } = g;
const [confirm, confirmDialog] = useConfirm();
if (grant === null) return loading;
const mode = internetMode(grant.unrestricted_internet, grant.internet_log);
// Letting more traffic out is asked first, and says what it lets out; going
// back to a tighter mode is not.
async function choose(next: InternetMode) {
if (grant === null) return;
if (loosensInternet(mode, next)) {
const meaning = INTERNET_MODES.find(([m]) => m === next)?.[2] ?? "";
const yes = await confirm({
label: `set ${agent} internet to ${next}`,
confirmLabel: `set ${next}`,
danger: next === "unrestricted",
body: (
<p>
Set <strong>{agent}</strong>'s internet to <strong>{next}</strong>?
This will {meaning}.
</p>
),
});
if (!yes) return;
}
void send({
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(internetBody(grant.permissions, next)),
});
}
return (
<div class="ui-agent-limits">
<BadgePopover
@ -284,18 +314,7 @@ export function AgentInternet({ agent, g }: { agent: string; g: GrantState }) {
value={label}
title={`${meaning} for ${agent}`}
disabled={busy}
onClick={
m === mode
? undefined
: () =>
void send({
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(
internetBody(grant.permissions, m),
),
})
}
onClick={m === mode ? undefined : () => void choose(m)}
/>{" "}
<Hint as="span">{meaning}</Hint>
</li>
@ -308,6 +327,7 @@ export function AgentInternet({ agent, g }: { agent: string; g: GrantState }) {
/>
) : null}
</BadgePopover>
{confirmDialog}
</div>
);
}

View file

@ -27,6 +27,7 @@ import { Badge } from "@hive/shared/badge.js";
import { ActionRow } from "../../ui/action-row/ActionRow.js";
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
import { Button } from "../../ui/button/Button.js";
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
import { FormStack } from "../../ui/form-stack/FormStack.js";
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
@ -66,6 +67,30 @@ function groupHelp(source: EntryGroup["source"], agent: string): string {
export function AllowedDomains({ agent }: { agent: string }) {
const { entries, error, busy, remove, refetch } = useAllowedDomains();
const [adding, setAdding] = useState(false);
const [confirm, confirmDialog] = useConfirm();
// A removal that applies to every agent asks first; one for this agent only
// is easy to add back.
async function removeEntry(e: Parameters<typeof remove>[0]) {
if (
e.agent === undefined &&
!(await confirm({
label: `stop allowing ${e.domain} for every agent`,
confirmLabel: "stop allowing",
danger: true,
body: (
<p>
Stop allowing <code>{e.domain}</code> for{" "}
<strong>every agent</strong>? Agents lose access to it through the
proxy, not just {agent}.
</p>
),
}))
) {
return;
}
void remove(e);
}
// A list already loaded stays under a failed refetch, so a change that
// worked is not hidden by a read that did not.
@ -114,7 +139,7 @@ export function AllowedDomains({ agent }: { agent: string }) {
e.agent === undefined ? "every agent" : agent
}`}
disabled={busy}
onClick={() => void remove(e)}
onClick={() => void removeEntry(e)}
/>
)}
</li>
@ -147,6 +172,7 @@ export function AllowedDomains({ agent }: { agent: string }) {
/>
) : null}
</Dialog>
{confirmDialog}
</div>
);
}

View file

@ -107,6 +107,7 @@ export function LinkedAccounts({
onCancel={() => setDeleteTarget(null)}
onConfirm={() => void confirmDelete()}
confirmLabel="delete"
danger
confirmDisabled={deleting}
>
{deleteTarget ? (

View file

@ -25,6 +25,17 @@ export function grantSummary(stored: string[] | undefined): string {
/** The three modes of an agent's internet access. */
export type InternetMode = "unrestricted" | "log" | "restricted";
const INTERNET_OPENNESS: Record<InternetMode, number> = {
restricted: 0,
log: 1,
unrestricted: 2,
};
/** Whether a change of mode lets more traffic through: the one that is asked first. */
export function loosensInternet(from: InternetMode, to: InternetMode): boolean {
return INTERNET_OPENNESS[to] > INTERNET_OPENNESS[from];
}
/**
* How the panel reads the stored `unrestricted_internet` and `internet_log`.
* An absent flag counts as on, and says "legacy" because the swarm never set

View file

@ -325,6 +325,7 @@ export function useAgentActions(
onCancel={() => setDestroyTarget(null)}
onConfirm={() => destroyTarget && void destroyAgent(destroyTarget)}
confirmLabel="destroy"
danger
>
{destroyTarget ? (
<p>

View file

@ -34,6 +34,7 @@ import {
moveSelection,
type AgentCommand,
} from "./command-menu.js";
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
import { useAgentCommands } from "./useAgentCommands.js";
import "./AgentInputForm.css";
@ -42,6 +43,7 @@ export function AgentInputForm({ agentName }: { agentName: string }) {
const [selected, setSelected] = useState(0);
const [closed, setClosed] = useState(false);
const { state, submitting, run } = useSubmit();
const [confirm, confirmDialog] = useConfirm();
const commands = useAgentCommands(agentName);
const query = menuQuery(body);
@ -57,10 +59,27 @@ export function AgentInputForm({ agentName }: { agentName: string }) {
setClosed(false);
}, [body]);
function submit(e: Event) {
async function submit(e: Event) {
e.preventDefault();
const base = `/api/agents/${encodeURIComponent(agentName)}`;
const route = controlRoute(body, commands);
// /clear drops the agent's conversation, so it is asked first.
if (
route === "new-session" &&
!(await confirm({
label: "start a new session",
confirmLabel: "start a new session",
danger: true,
body: (
<p>
Start a new session for <strong>{agentName}</strong>? Its current
conversation is dropped on its next turn.
</p>
),
}))
) {
return;
}
void run(
() =>
route
@ -142,6 +161,7 @@ export function AgentInputForm({ agentName }: { agentName: string }) {
{submitting ? <Spinner /> : <SendIcon />}
</button>
</form>
{confirmDialog}
</div>
);
}

View file

@ -50,6 +50,7 @@ import { Preformatted } from "../ui/preformatted/Preformatted.js";
import { SectionHeading } from "../ui/section-heading/SectionHeading.js";
import { Toolbar } from "../ui/toolbar/Toolbar.js";
import { ConfirmDialog } from "../ui/confirm-dialog/ConfirmDialog.js";
import { useConfirm } from "../ui/confirm-dialog/useConfirm.js";
import { Popover } from "../ui/popover/Popover.js";
import { Badge, type BadgeTone } from "@hive/shared/badge.js";
import { GearIcon } from "@hive/shared/icons.js";
@ -131,7 +132,7 @@ const SELECT_OPTIONS: SelectOption[] = [
{ value: "beta", label: "beta" },
];
const BUTTON_VARIANTS: ButtonVariant[] = ["primary", "default"];
const BUTTON_VARIANTS: ButtonVariant[] = ["primary", "default", "danger"];
const BADGE_TONES: BadgeTone[] = [
"neutral",
"positive",
@ -396,10 +397,46 @@ function FilterableViewSample() {
);
}
function ConfirmDialogSample() {
const [open, setOpen] = useState(false);
// `useConfirm`: ask in the middle of a handler, without a dialog's state.
function UseConfirmSample() {
const [confirm, dialog] = useConfirm();
const [answer, setAnswer] = useState("not asked yet");
async function ask() {
const yes = await confirm({
label: "sample question",
confirmLabel: "go ahead",
body: <p>Awaited in the click handler: it resolves true or false.</p>,
});
setAnswer(yes ? "confirmed" : "cancelled");
}
return (
<>
<Button onClick={() => void ask()}>ask with useConfirm</Button>
<span role="status"> answer: {answer}</span>
{dialog}
</>
);
}
function ConfirmDialogSample() {
const [open, setOpen] = useState(false);
const [dangerOpen, setDangerOpen] = useState(false);
return (
<>
<Button onClick={() => setDangerOpen(true)}>open danger confirm</Button>
<ConfirmDialog
open={dangerOpen}
label="sample danger confirm dialog"
onCancel={() => setDangerOpen(false)}
onConfirm={() => setDangerOpen(false)}
confirmLabel="delete"
danger
>
<p>
<code>danger</code> makes the confirm button red and starts the focus
on cancel, for an action that cannot be taken back.
</p>
</ConfirmDialog>
<Button onClick={() => setOpen(true)}>open confirm dialog</Button>
<ConfirmDialog
open={open}
@ -771,6 +808,9 @@ export function ComponentsPage() {
<Sample label="modal, cancel/confirm button row">
<ConfirmDialogSample />
</Sample>
<Sample label="useConfirm, awaited in a handler">
<UseConfirmSample />
</Sample>
</Section>
<Section title="Badge (@hive/shared — used by swarm-ui and the per-agent page)">

View file

@ -13,6 +13,7 @@ import { TextAreaField } from "../ui/text-area-field/TextAreaField.js";
import { Button } from "../ui/button/Button.js";
import { FormStack } from "../ui/form-stack/FormStack.js";
import { FormResult } from "../ui/submit/FormResult.js";
import { useConfirm } from "../ui/confirm-dialog/useConfirm.js";
import { useSubmit } from "../ui/submit/useSubmit.js";
// A swarm-controller without the route answers 404 with no problem body.
@ -31,6 +32,23 @@ export function LinkBackendEnvForm({
const [env, setEnv] = useState("");
// The success line is what the request did, so it is the done value.
const { state, submitting: busy, run } = useSubmit<string>();
const [confirm, confirmDialog] = useConfirm();
async function removeEnv() {
const yes = await confirm({
label: "remove the API-key environment",
confirmLabel: "remove",
danger: true,
body: (
<p>
Remove the stored API-key environment for <strong>{agent}</strong>?
The stored text cannot be read back, so it cannot be restored; paste
it again to set it.
</p>
),
});
if (yes) send("DELETE", "removed the API-key environment for");
}
function send(method: "PUT" | "DELETE", done: string) {
void run(
@ -89,11 +107,7 @@ export function LinkBackendEnvForm({
<Button variant="primary" type="submit" disabled={busy}>
{busy ? "saving…" : "save"}
</Button>
<Button
type="button"
disabled={busy}
onClick={() => send("DELETE", "removed the API-key environment for")}
>
<Button type="button" disabled={busy} onClick={() => void removeEnv()}>
remove
</Button>
</FormStack>
@ -106,6 +120,7 @@ export function LinkBackendEnvForm({
)}
failed="failed to update the API-key environment"
/>
{confirmDialog}
</Panel>
);
}

View file

@ -416,6 +416,7 @@ export function FlowEditorPage({
open={confirmDelete}
label="delete this flow"
confirmLabel="delete"
danger
onCancel={() => setConfirmDelete(false)}
onConfirm={() => void onDelete()}
>

View file

@ -13,10 +13,10 @@
// **load the repo's rules** fills the rows from the rules on the repo's default
// branch (`GET /api/review-classifier/rules`), to run as they are or to edit.
//
// **open a PR** posts the rows to `POST /api/review-classifier/open-pr`, which
// has the classifier's forge account push a branch adding them to the repo's
// rules file, with the operator as commit author, and links to the forge's page
// for opening the PR from that branch.
// **push a branch for a PR** (asked first) posts the rows to
// `POST /api/review-classifier/open-pr`, which has the classifier's forge account
// push a branch adding them to the repo's rules file, with the operator as commit
// author, and links to the forge's page for opening the PR from that branch.
//
// The inputs stay as typed after a run, so the operator can edit and run
// again. The section keeps nothing you typed and no
@ -29,6 +29,7 @@ import { ActionRow } from "../../ui/action-row/ActionRow.js";
import { Button } from "../../ui/button/Button.js";
import { FieldGrid } from "../../ui/field-grid/FieldGrid.js";
import { ConfirmDialog } from "../../ui/confirm-dialog/ConfirmDialog.js";
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
import { Disclosure } from "../../ui/disclosure/Disclosure.js";
import { ExternalLink } from "../../ui/external-link/ExternalLink.js";
import { Panel } from "../../ui/panel/Panel.js";
@ -79,6 +80,7 @@ function blankDraft(): ClassificationDraft {
export function ReviewTryOut() {
const [repo, setRepo] = useState("");
const [ask, askDialog] = useConfirm();
const [pr, setPr] = useState("");
const [drafts, setDrafts] = useState<ClassificationDraft[]>(() => [
blankDraft(),
@ -303,6 +305,23 @@ export function ReviewTryOut() {
}
}
// Pushing a branch to a forge repo is not undone from here, so it is asked.
async function askPushBranch() {
const rows = drafts.length;
const yes = await ask({
label: "push a branch for a PR",
confirmLabel: "push the branch",
body: (
<p>
Push a new branch to <strong>{repo.trim()}</strong> with{" "}
{rows === 1 ? "this classification" : `these ${rows} classifications`}
, as you? It does not open the PR; the link to open it follows.
</p>
),
});
if (yes) void openPr();
}
// Pushes the rows on a new branch of the repo and keeps the link to open
// the PR from it.
async function openPr() {
@ -354,8 +373,8 @@ export function ReviewTryOut() {
Run a review classification against a real PR and see how the model
answers it. A run posts nothing to the forge and changes no rules, but
it does appear under recent runs: change the classification and run it
again until it answers the way you want. Then open a PR to add it to
the repo's rules.
again until it answers the way you want. Then push a branch for a PR
to add it to the repo's rules.
</p>
<form class="ui-tryout-form" onSubmit={(e) => void run(e)}>
<FieldGrid class="ui-tryout-target">
@ -441,11 +460,11 @@ export function ReviewTryOut() {
{running ? "running…" : "run"}
</Button>
<Button
onClick={() => void openPr()}
onClick={() => void askPushBranch()}
disabled={opening || openPrProblem !== null}
describedBy={openPrProblem !== null ? HINT_ID : undefined}
>
{opening ? "pushing…" : "open a PR"}
{opening ? "pushing…" : "push a branch for a PR"}
</Button>
</ActionRow>
{capProblem !== null ? (
@ -476,6 +495,7 @@ export function ReviewTryOut() {
) : null}
</form>
</Disclosure>
{askDialog}
<ConfirmDialog
open={confirmLoad}
label="replace the classifications"

View file

@ -14,6 +14,7 @@ import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { Button } from "../../ui/button/Button.js";
import { ConfirmDialog } from "../../ui/confirm-dialog/ConfirmDialog.js";
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
import { FilterableView } from "../../ui/filterable-view/FilterableView.js";
import { Toolbar } from "../../ui/toolbar/Toolbar.js";
import { LazyDisclosure } from "../../ui/disclosure/LazyDisclosure.js";
@ -89,6 +90,7 @@ function SchedulesBody() {
const [creating, setCreating] = useState(false);
const [pendingIds, setPendingIds] = useState<Set<string>>(new Set());
const [removeTarget, setRemoveTarget] = useState<Schedule | null>(null);
const [confirm, fireDialog] = useConfirm();
const [actionError, setActionError] = useState<ProblemDetails | null>(null);
function markPending(id: string, on: boolean) {
@ -120,7 +122,20 @@ function SchedulesBody() {
}
}
function fireNow(s: Schedule) {
async function fireNow(s: Schedule) {
const repeats = s.interval_seconds !== null;
const yes = await confirm({
label: "fire schedule now",
confirmLabel: "fire now",
body: (
<p>
Fire <strong>{s.name}</strong> now? It sends its message to{" "}
{s.agents.join(", ")} at once, and its start moves to this moment
{repeats ? ", so it repeats from now on" : ""}. That cannot be undone.
</p>
),
});
if (!yes) return;
return act(s.id, () =>
fetch(`/api/schedules/${encodeURIComponent(s.id)}`, {
method: "PATCH",
@ -232,10 +247,12 @@ function SchedulesBody() {
}
/>
) : null}
{fireDialog}
<ConfirmDialog
open={removeTarget !== null}
label="remove schedule"
confirmLabel="remove"
danger
onCancel={() => setRemoveTarget(null)}
onConfirm={confirmRemove}
>

View file

@ -22,6 +22,7 @@ import {
useDeniedDomains,
} from "../../agent/detail/useAllowedDomains.js";
import { Button } from "../../ui/button/Button.js";
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
import { LazyDisclosure } from "../../ui/disclosure/LazyDisclosure.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { Hint } from "../../ui/hint/Hint.js";
@ -46,6 +47,27 @@ function DomainSection({
}) {
const { entries, behind, error, busy, remove, refetch } = list;
const [adding, setAdding] = useState(false);
const [confirm, confirmDialog] = useConfirm();
async function removeEntry(e: Parameters<typeof remove>[0]) {
const verb = kind === "deny" ? "Stop denying" : "Stop allowing";
if (
!(await confirm({
label: `${verb.toLowerCase()} ${e.domain} swarm-wide`,
confirmLabel: "remove",
danger: true,
body: (
<p>
{verb} <code>{e.domain}</code> for <strong>every agent</strong> on
the swarm?
</p>
),
}))
) {
return;
}
void remove(e);
}
// A list already loaded stays under a failed refetch, so a change that
// worked is not hidden by a read that did not.
@ -94,7 +116,7 @@ function DomainSection({
<Button
disabled={busy}
ariaLabel={`remove ${e.domain}`}
onClick={() => void remove(e)}
onClick={() => void removeEntry(e)}
>
remove
</Button>
@ -121,6 +143,7 @@ function DomainSection({
/>
) : null}
</Dialog>
{confirmDialog}
</>
)}
</section>

View file

@ -15,6 +15,11 @@
color: var(--fg);
border: none;
}
.ui-button-danger {
background: color-mix(in srgb, var(--red) 14%, var(--bg-elev));
color: var(--red);
border: 1px solid var(--red);
}
.ui-button-default {
background: var(--bg-elev);
color: var(--fg);

View file

@ -1,14 +1,13 @@
// <Button> — the shared clickable-action control (form submit today,
// any future toolbar/dialog action later). `variant` is `'primary'`
// (the one emphasised action on a page, e.g. a form's submit) or
// `'default'` (everything else) — two is enough for every real caller
// so far; a third reading gets added the day something needs it, not
// speculatively.
// `'default'` (everything else), or `'danger'` (the action that cannot be
// taken back: destroy, delete, a removal that cuts access).
import type { ComponentChildren } from "preact";
import { Spinner } from "../spinner/Spinner.js";
import "./Button.css";
export type ButtonVariant = "primary" | "default";
export type ButtonVariant = "primary" | "default" | "danger";
export function Button({
variant = "default",
@ -18,6 +17,7 @@ export function Button({
onClick,
describedBy,
ariaLabel,
autofocus = false,
children,
}: {
variant?: ButtonVariant;
@ -33,6 +33,9 @@ export function Button({
/** A name that says what the button acts on, where its visible text repeats
* across a list ("remove", "edit"). It should start with the visible text. */
ariaLabel?: string;
/** Takes the focus when the dialog around it opens, in place of its first
* control. A destructive confirm puts it on the safe button. */
autofocus?: boolean;
children: ComponentChildren;
}) {
return (
@ -44,6 +47,7 @@ export function Button({
onClick={onClick}
aria-describedby={describedBy}
aria-label={ariaLabel}
autofocus={autofocus || undefined}
>
<span class="ui-button-label">{children}</span>
{busy ? (

View file

@ -24,6 +24,7 @@ export function ConfirmDialog({
confirmLabel = "confirm",
cancelLabel = "cancel",
confirmDisabled = false,
danger = false,
children,
}: {
open: boolean;
@ -33,6 +34,9 @@ export function ConfirmDialog({
confirmLabel?: string;
cancelLabel?: string;
confirmDisabled?: boolean;
/** The action cannot be taken back: the confirm button is red and the focus
* starts on cancel. */
danger?: boolean;
children: ComponentChildren;
}) {
return (
@ -40,9 +44,11 @@ export function ConfirmDialog({
<div class="confirm-dialog">
<div class="confirm-dialog-body">{children}</div>
<div class="confirm-dialog-actions">
<Button onClick={onCancel}>{cancelLabel}</Button>
<Button onClick={onCancel} autofocus={danger}>
{cancelLabel}
</Button>
<Button
variant="primary"
variant={danger ? "danger" : "primary"}
onClick={onConfirm}
disabled={confirmDisabled}
>

View file

@ -0,0 +1,54 @@
// useConfirm — ask before an action, in place, without a dialog's state at every
// call site: `const [confirm, dialog] = useConfirm()`, render `{dialog}` once,
// and `if (!(await confirm({ ... }))) return;` before the action. Resolves
// true on the confirm button and false on cancel, Escape or a click outside.
import type { ComponentChildren } from "preact";
import { useRef, useState } from "preact/hooks";
import { ConfirmDialog } from "./ConfirmDialog.js";
export interface ConfirmRequest {
/** The dialog's accessible name. */
label: string;
confirmLabel: string;
/** The action cannot be taken back: a red confirm button, focus on cancel. */
danger?: boolean;
/** What will happen, in a sentence or two. */
body: ComponentChildren;
}
export function useConfirm(): [
(request: ConfirmRequest) => Promise<boolean>,
ComponentChildren,
] {
const [request, setRequest] = useState<ConfirmRequest | null>(null);
const resolveRef = useRef<((answer: boolean) => void) | null>(null);
function confirm(next: ConfirmRequest): Promise<boolean> {
// A second request while one is open cancels the first.
resolveRef.current?.(false);
setRequest(next);
return new Promise<boolean>((resolve) => {
resolveRef.current = resolve;
});
}
function answer(yes: boolean) {
resolveRef.current?.(yes);
resolveRef.current = null;
setRequest(null);
}
const dialog = (
<ConfirmDialog
open={request !== null}
label={request?.label ?? ""}
confirmLabel={request?.confirmLabel}
danger={request?.danger}
onCancel={() => answer(false)}
onConfirm={() => answer(true)}
>
{request?.body}
</ConfirmDialog>
);
return [confirm, dialog];
}

View file

@ -8,6 +8,7 @@ import {
internetBody,
internetMode,
internetSummary,
loosensInternet,
MAX_REPOS,
maxReposBody,
parseMaxRepos,
@ -109,3 +110,13 @@ test("the limit's body carries the stored list, so the PUT does not reset it", (
});
assert.deepEqual(maxReposBody(undefined, 0), { max_repos: 0 });
});
test("only a change that lets more traffic through is asked first", () => {
assert.equal(loosensInternet("restricted", "log"), true);
assert.equal(loosensInternet("restricted", "unrestricted"), true);
assert.equal(loosensInternet("log", "unrestricted"), true);
assert.equal(loosensInternet("unrestricted", "restricted"), false);
assert.equal(loosensInternet("unrestricted", "log"), false);
assert.equal(loosensInternet("log", "restricted"), false);
assert.equal(loosensInternet("log", "log"), false);
});