Watch
0
0
Fork
You've already forked hyperhive
0

swarm-ui: a header bell with the count of firing alerts opens a list of them and a link to Grafana

This commit is contained in:
iris 2026-11-21 15:01:16 +01:00
commit 70e5de5571

View file

@ -0,0 +1,91 @@
// <AlertsMenu> — a header bell with the count of firing alerts, opening a
// popover that lists them and links to Grafana. It draws nothing while no
// alert fires, and while the alerts can't be read (the swarm may have no
// Grafana): no button beats a dead one. It polls `GET /api/alerts`, the same
// list the reports tab shows.
import { useRef, useState } from "preact/hooks";
import { BellIcon } from "@hive/shared/icons.js";
import { IconButton } from "@hive/shared/icon-button.js";
import { useDismiss } from "@hive/shared/use-dismiss.js";
import "@hive/shared/icon-button.css";
import { ExternalLink } from "../ui/external-link/ExternalLink.js";
import { fetchJson, usePolled } from "../ui/polled/usePolled.js";
import { RelativeTime } from "../ui/relative-time/RelativeTime.js";
import {
GRAFANA_ALERTS_URL,
activeSinceMs,
alertKey,
alertsLabel,
firingAlerts,
type Alert,
} from "../pages/alerts.js";
import "./AlertsMenu.css";
const POLL_MS = 30_000;
export function AlertsMenu() {
const { data, error } = usePolled(
POLL_MS,
(signal) => fetchJson<Alert[]>("/api/alerts", signal),
{ cacheKey: "alerts" },
);
// A failed poll keeps the last answer in `data`, so the bell checks `error`
// too rather than show a list that may have gone stale. The controller
// answers 503 both for a swarm with no Grafana and for a Grafana that
// didn't answer, so a swarm without one costs an error response per poll.
const firing = data && !error ? firingAlerts(data) : [];
return firing.length === 0 ? null : <AlertsButton firing={firing} />;
}
function AlertsButton({ firing }: { firing: Alert[] }) {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
useDismiss({
open,
onDismiss: () => setOpen(false),
inside: [rootRef],
focusOnEscape: () => rootRef.current?.querySelector("button") ?? null,
});
const label = alertsLabel(firing.length);
return (
<div class="alerts-menu" ref={rootRef}>
<IconButton
label={label}
onClick={() => setOpen((v) => !v)}
expanded={open}
>
<BellIcon />
<span class="alerts-menu-count" aria-hidden="true">
{firing.length}
</span>
</IconButton>
{open ? (
<div class="alerts-menu-popover" role="group" aria-label={label}>
<ul class="alerts-menu-list">
{firing.map((a) => {
const since = activeSinceMs(a);
return (
<li key={alertKey(a)} class="alerts-menu-item">
<span class="alerts-menu-name">{a.name}</span>
{since !== null ? (
<span class="alerts-menu-since">
<RelativeTime epochMs={since} />
</span>
) : null}
{a.summary ? (
<span class="alerts-menu-summary">{a.summary}</span>
) : null}
</li>
);
})}
</ul>
<ExternalLink href={GRAFANA_ALERTS_URL} class="alerts-menu-link">
open Grafana's alert list
</ExternalLink>
</div>
) : null}
</div>
);
}