import { encodePath } from "@refs/backend/contract"; import { useCallback, useEffect, useRef, useState } from "react"; import type { CodeToken } from "../highlight"; type Entry = { readonly state: "loading" } | { readonly state: "ready"; readonly lines: readonly string[] } | { readonly state: "failed" }; export interface FileSources { /** A file's lines, or null while they load or when they could not be read. */ lines(path: string): readonly string[] | null; failed(path: string): boolean; /** Starts loading the files that are not loaded yet. */ request(paths: readonly string[]): void; } const splitLines = (text: string) => text.replace(/\r\n?/g, "\n").replace(/\n$/, "").split("\n"); /** The text of a commit's files, read on first use and kept for the page's life. The browser caches each file for good, since the commit pins it. */ export function useFileSources(repo: string, commit: string, known: ReadonlyMap): FileSources { const entries = useRef(new Map()); const [, setVersion] = useState(0); const commitRef = useRef(commit); if (commitRef.current !== commit) { commitRef.current = commit; entries.current = new Map(); } for (const [path, text] of known) if (!entries.current.has(path)) entries.current.set(path, { state: "ready", lines: splitLines(text) }); const request = useCallback( (paths: readonly string[]) => { for (const path of paths) { if (entries.current.has(path)) continue; entries.current.set(path, { state: "loading" }); const forCommit = commit; fetch(`/${repo}/code-graph/${commit}/file/${encodePath(path.split("/"))}`) .then((response) => (response.ok ? response.text() : Promise.reject(new Error(`${response.status} for ${path}`)))) .then((text) => ({ state: "ready" as const, lines: splitLines(text) })) .catch((error: unknown) => { console.error("could not read file for the code map", error); return { state: "failed" as const }; }) .then((entry) => { if (commitRef.current !== forCommit) return; entries.current.set(path, entry); setVersion((version) => version + 1); }); } }, [repo, commit], ); return { lines: (path) => { const entry = entries.current.get(path); return entry?.state === "ready" ? entry.lines : null; }, failed: (path) => entries.current.get(path)?.state === "failed", request, }; } /** The highlighter is large and works in the browser only, so the server build leaves it out. */ const loadHighlighter = import.meta.env.SSR ? null : () => import("../highlight"); const highlighted = new Map>(); /** The colours of a whole file's lines, so a slice of it colours as it does in the file view. Null while loading and for plain files. */ export function useFileHighlight(key: string, path: string, lines: readonly string[] | null): CodeToken[][] | null { const [tokens, setTokens] = useState(null); useEffect(() => { setTokens(null); if (!lines || !loadHighlighter) return; let current = true; const cacheKey = `${key}:${path}`; let pending = highlighted.get(cacheKey); if (!pending) { pending = loadHighlighter().then((module) => module.highlightLines(path.split("/").pop() ?? path, lines)); highlighted.set(cacheKey, pending); } pending.then((result) => current && setTokens(result)).catch((error: unknown) => console.error("highlighting failed", error)); return () => { current = false; }; }, [key, path, lines]); return tokens; }