Open History to see the last commit
1import type { FileDiffMetadata } from "@pierre/diffs";
2import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
3import { useState } from "react";
4
5import { getRenderablePatch, resolveFileDiffPath } from "~/lib/diffRendering";
6import { pullRequestEnvironment } from "~/state/pullRequests";
7import { useEnvironmentQuery } from "~/state/query";
8
9import { pullRequestReviewKey } from "../pullRequestReviewStore";
10
11interface LoadedDiff {
12 readonly key: string;
13 readonly cursor: string | null;
14 readonly done: boolean;
15 readonly files: ReadonlyMap<string, FileDiffMetadata>;
16 readonly folded: unknown;
17}
18
19const NO_FILES: ReadonlyMap<string, FileDiffMetadata> = new Map();
20
21export function useGuideDiffFiles({
22 environmentId,
23 reference,
24 headSha,
25 wantedPaths,
26}: {
27 environmentId: EnvironmentId;
28 reference: PullRequestRef;
29 headSha: string;
30 wantedPaths: ReadonlyArray<string>;
31}) {
32 const key = `${environmentId}:${pullRequestReviewKey(reference)}:${headSha}`;
33 const [loaded, setLoaded] = useState<LoadedDiff>({
34 key,
35 cursor: null,
36 done: false,
37 files: NO_FILES,
38 folded: null,
39 });
40 const current: LoadedDiff =
41 loaded.key === key ? loaded : { key, cursor: null, done: false, files: NO_FILES, folded: null };
42 const missing = wantedPaths.some((path) => !current.files.has(path));
43 const loading = missing && !current.done;
44 const query = useEnvironmentQuery(
45 loading
46 ? pullRequestEnvironment.diff({
47 environmentId,
48 input: { ...reference, ...(current.cursor === null ? {} : { cursor: current.cursor }) },
49 })
50 : null,
51 );
52
53 // Each page is folded in once, during the render that first sees it.
54 const data = query.data;
55 if (data !== null && !current.done && current.folded !== data) {
56 const parsed = getRenderablePatch(
57 data.patch,
58 `pull-request-guide:${key}:${current.cursor ?? "first"}`,
59 );
60 const files = new Map(current.files);
61 if (parsed?.kind === "files") {
62 for (const file of parsed.files) files.set(resolveFileDiffPath(file), file);
63 }
64 setLoaded({
65 key,
66 cursor: data.nextCursor,
67 done: data.nextCursor === null,
68 files,
69 folded: data,
70 });
71 }
72
73 return {
74 files: current.files,
75 loading: loading && query.error === null,
76 error: loading ? query.error : null,
77 retry: query.refresh,
78 };
79}