Skip to content
refs
84 lines · 3.6 KBRaw
1import { encodePath } from "@refs/backend/contract";
2import { useCallback, useEffect, useRef, useState } from "react";
3import type { CodeToken } from "../highlight";
4
5type Entry = { readonly state: "loading" } | { readonly state: "ready"; readonly lines: readonly string[] } | { readonly state: "failed" };
6
7export interface FileSources {
8 /** A file's lines, or null while they load or when they could not be read. */
9 lines(path: string): readonly string[] | null;
10 failed(path: string): boolean;
11 /** Starts loading the files that are not loaded yet. */
12 request(paths: readonly string[]): void;
13}
14
15const splitLines = (text: string) => text.replace(/\r\n?/g, "\n").replace(/\n$/, "").split("\n");
16
17/** 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. */
18export function useFileSources(repo: string, commit: string, known: ReadonlyMap<string, string>): FileSources {
19 const entries = useRef(new Map<string, Entry>());
20 const [, setVersion] = useState(0);
21 const commitRef = useRef(commit);
22 if (commitRef.current !== commit) {
23 commitRef.current = commit;
24 entries.current = new Map();
25 }
26 for (const [path, text] of known) if (!entries.current.has(path)) entries.current.set(path, { state: "ready", lines: splitLines(text) });
27
28 const request = useCallback(
29 (paths: readonly string[]) => {
30 for (const path of paths) {
31 if (entries.current.has(path)) continue;
32 entries.current.set(path, { state: "loading" });
33 const forCommit = commit;
34 fetch(`/${repo}/code-graph/${commit}/file/${encodePath(path.split("/"))}`)
35 .then((response) => (response.ok ? response.text() : Promise.reject(new Error(`${response.status} for ${path}`))))
36 .then((text) => ({ state: "ready" as const, lines: splitLines(text) }))
37 .catch((error: unknown) => {
38 console.error("could not read file for the code map", error);
39 return { state: "failed" as const };
40 })
41 .then((entry) => {
42 if (commitRef.current !== forCommit) return;
43 entries.current.set(path, entry);
44 setVersion((version) => version + 1);
45 });
46 }
47 },
48 [repo, commit],
49 );
50
51 return {
52 lines: (path) => {
53 const entry = entries.current.get(path);
54 return entry?.state === "ready" ? entry.lines : null;
55 },
56 failed: (path) => entries.current.get(path)?.state === "failed",
57 request,
58 };
59}
60
61/** The highlighter is large and works in the browser only, so the server build leaves it out. */
62const loadHighlighter = import.meta.env.SSR ? null : () => import("../highlight");
63const highlighted = new Map<string, Promise<CodeToken[][] | null>>();
64
65/** 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. */
66export function useFileHighlight(key: string, path: string, lines: readonly string[] | null): CodeToken[][] | null {
67 const [tokens, setTokens] = useState<CodeToken[][] | null>(null);
68 useEffect(() => {
69 setTokens(null);
70 if (!lines || !loadHighlighter) return;
71 let current = true;
72 const cacheKey = `${key}:${path}`;
73 let pending = highlighted.get(cacheKey);
74 if (!pending) {
75 pending = loadHighlighter().then((module) => module.highlightLines(path.split("/").pop() ?? path, lines));
76 highlighted.set(cacheKey, pending);
77 }
78 pending.then((result) => current && setTokens(result)).catch((error: unknown) => console.error("highlighting failed", error));
79 return () => {
80 current = false;
81 };
82 }, [key, path, lines]);
83 return tokens;
84}