import { useEffect, useSyncExternalStore } from "react"; import { api, type RunbookSummary } from "../api/client"; // The list of runbook titles, by what they are about — shared by every page that shows a "runbook" button, fetched once, and fetched // again whenever one is added, changed or removed (RUNBOOKS_CHANGED). export const RUNBOOKS_CHANGED = "runbooks-changed"; let items: RunbookSummary[] | null = null; let loading = false; const listeners = new Set<() => void>(); function load(force = false): void { if (loading || (items !== null && !force)) return; loading = true; api.runbooks .summary() .then((res) => { items = res.runbooks; listeners.forEach((l) => l()); }) .catch(() => { // Only a convenience on top of the pages: without it they simply show no runbook buttons. }) .finally(() => { loading = false; }); } if (typeof window !== "undefined") window.addEventListener(RUNBOOKS_CHANGED, () => load(true)); function subscribe(listener: () => void): () => void { listeners.add(listener); return () => { listeners.delete(listener); }; } /** Every runbook's title and what it is for; null until loaded. */ export function useRunbookSummary(): RunbookSummary[] | null { useEffect(() => load(), []); return useSyncExternalStore(subscribe, () => items); }