import type { CodeGraph } from "@refs/backend/contract"; import { useEffect, useState } from "react"; const RETRY_MS = 2500; export type GraphLoad = { readonly kind: "loading" } | { readonly kind: "ready"; readonly graph: CodeGraph } | { readonly kind: "failed" }; /** * Loads a commit's code map in the browser, after the page shows. The response is cached for good, so a second * visit is instant. A map that is still building is asked for again until it is ready. */ export function useCodeGraph(repo: string, commit: string): GraphLoad { const [load, setLoad] = useState({ kind: "loading" }); useEffect(() => { let current = true; let timer: ReturnType | undefined; setLoad({ kind: "loading" }); const ask = () => { fetch(`/${repo}/code-graph/${commit}`) .then(async (response) => { if (!current) return; if (response.status === 202) timer = setTimeout(ask, RETRY_MS); else if (response.ok) setLoad({ kind: "ready", graph: (await response.json()) as CodeGraph }); else setLoad({ kind: "failed" }); }) .catch((error: unknown) => { console.error("could not load the code map", error); if (current) setLoad({ kind: "failed" }); }); }; ask(); return () => { current = false; clearTimeout(timer); }; }, [repo, commit]); return load; }