38 lines · 1.4 KBRaw
| 1 | import type { CodeGraph } from "@refs/backend/contract"; |
| 2 | import { useEffect, useState } from "react"; |
| 3 | |
| 4 | const RETRY_MS = 2500; |
| 5 | |
| 6 | export type GraphLoad = { readonly kind: "loading" } | { readonly kind: "ready"; readonly graph: CodeGraph } | { readonly kind: "failed" }; |
| 7 | |
| 8 | /** |
| 9 | * Loads a commit's code map in the browser, after the page shows. The response is cached for good, so a second |
| 10 | * visit is instant. A map that is still building is asked for again until it is ready. |
| 11 | */ |
| 12 | export function useCodeGraph(repo: string, commit: string): GraphLoad { |
| 13 | const [load, setLoad] = useState<GraphLoad>({ kind: "loading" }); |
| 14 | useEffect(() => { |
| 15 | let current = true; |
| 16 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 17 | setLoad({ kind: "loading" }); |
| 18 | const ask = () => { |
| 19 | fetch(`/${repo}/code-graph/${commit}`) |
| 20 | .then(async (response) => { |
| 21 | if (!current) return; |
| 22 | if (response.status === 202) timer = setTimeout(ask, RETRY_MS); |
| 23 | else if (response.ok) setLoad({ kind: "ready", graph: (await response.json()) as CodeGraph }); |
| 24 | else setLoad({ kind: "failed" }); |
| 25 | }) |
| 26 | .catch((error: unknown) => { |
| 27 | console.error("could not load the code map", error); |
| 28 | if (current) setLoad({ kind: "failed" }); |
| 29 | }); |
| 30 | }; |
| 31 | ask(); |
| 32 | return () => { |
| 33 | current = false; |
| 34 | clearTimeout(timer); |
| 35 | }; |
| 36 | }, [repo, commit]); |
| 37 | return load; |
| 38 | } |