Open History to see the last commit
1import { RegistryContext, useAtomValue } from "@effect/atom-react";
2import type { FileDiffMetadata } from "@pierre/diffs";
3import type { EnvironmentId, ReviewDiffPreviewSource } from "@t3tools/contracts";
4import * as AsyncResult from "effect/reactivity/AsyncResult";
5import * as Atom from "effect/reactivity/Atom";
6import { useContext, useEffect, useRef, useState } from "react";
7import { useStableCallback } from "~/hooks/useStableCallback";
8import { getRenderablePatch, resolveFileDiffPath, type RenderablePatch } from "~/lib/diffRendering";
9import { reviewEnvironment } from "~/state/review";
10
11const filePathCollator = new Intl.Collator(undefined, {
12 numeric: true,
13 sensitivity: "base",
14});
15const DEFAULT_INDICES = [0, 1, 2, 3];
16
17export function useReviewFilePatches({
18 environmentId,
19 cwd,
20 source,
21 baseRef,
22 ignoreWhitespace,
23 theme,
24 revision,
25 preview,
26}: {
27 environmentId: EnvironmentId | undefined;
28 cwd: string | undefined;
29 source: ReviewDiffPreviewSource | null;
30 baseRef: string | null;
31 ignoreWhitespace: boolean;
32 theme: "light" | "dark";
33 revision: string | undefined;
34 preview: RenderablePatch | null;
35}) {
36 const registry = useContext(RegistryContext);
37 const scope = JSON.stringify([
38 environmentId,
39 cwd,
40 source?.kind,
41 source?.diffHash,
42 baseRef,
43 ignoreWhitespace,
44 ]);
45 const [requested, setRequested] = useState(() => ({ scope, indices: DEFAULT_INDICES }));
46 const queries = reviewFileQueries({
47 environmentId,
48 cwd,
49 source,
50 baseRef,
51 ignoreWhitespace,
52 scope,
53 requested,
54 });
55 const queriedPatchesAtom = reviewPatchesAtom(
56 JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),
57 );
58 const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });
59 useEffect(() => {
60 const previous = previousPreview.current;
61 previousPreview.current = { scope, revision, queries };
62 for (const { query } of queries) {
63 const changed = previous.scope === scope && previous.revision !== revision;
64 const cached =
65 !previous.queries.some((entry) => entry.query === query) &&
66 registry.get(query)._tag !== "Initial" &&
67 !registry.get(query).waiting;
68 if (changed || cached) registry.refresh(query);
69 }
70 }, [scope, revision, queries, registry]);
71 const patches = useAtomValue(queriedPatchesAtom);
72 const retry = useStableCallback((path: string) => {
73 const files = sortedReviewFiles(source);
74 const query = queries.find(({ index }) => files[index]?.path === path)?.query;
75 if (query) registry.refresh(query);
76 });
77 const files = sortedReviewFiles(source);
78 const pendingIndex = files.findIndex((_, index) => {
79 const patch = patches.get(index);
80 return !patch || patch._tag === "Initial";
81 });
82 const settledFileCount = source
83 ? pendingIndex < 0
84 ? files.length
85 : pendingIndex
86 : preview?.kind === "files"
87 ? preview.files.length
88 : 0;
89 const requestFiles = (indices: number[]) =>
90 setRequested((current) => {
91 const previous = current.scope === scope ? current.indices : [0, 1, 2, 3];
92 const added = indices.filter((index) => !previous.includes(index));
93 return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
94 });
95 const loadNextFiles = () =>
96 requestFiles(Array.from({ length: 4 }, (_, index) => settledFileCount + index));
97 const requestFile = (index: number) => requestFiles([index]);
98 const renderableFiles = source
99 ? files.map((file, index): FileDiffMetadata => {
100 const result = patches.get(index);
101 if (result?._tag === "Success" && result.value.patch?.kind === "files") {
102 const loaded = result.value.patch.files.find(
103 (candidate) => resolveFileDiffPath(candidate) === file.path,
104 );
105 if (loaded) return loaded;
106 }
107 return {
108 name: file.path,
109 ...(file.previousPath ? { prevName: file.previousPath } : {}),
110 type: file.previousPath ? "rename-changed" : "change",
111 hunks: [],
112 additionLines: [],
113 deletionLines: [],
114 splitLineCount: 0,
115 unifiedLineCount: 0,
116 isPartial: true,
117 cacheKey: `${scope}:${file.path}:pending`,
118 };
119 })
120 : (preview?.kind === "files" ? preview.files : []).toSorted((a, b) =>
121 filePathCollator.compare(resolveFileDiffPath(a), resolveFileDiffPath(b)),
122 );
123 const fileStates = new Map(
124 files.map((file, index) => {
125 const patch = patches.get(index);
126 return [
127 file.path,
128 {
129 error:
130 patch?._tag === "Failure" ||
131 (patch?._tag === "Success" &&
132 (patch.value.patch?.kind !== "files" ||
133 !patch.value.patch.files.some(
134 (candidate) => resolveFileDiffPath(candidate) === file.path,
135 ))),
136 truncated: patch?._tag === "Success" && patch.value.source.truncated,
137 },
138 ] as const;
139 }),
140 );
141 const readyFilePaths = new Set(
142 files
143 .filter((_, index) => {
144 const patch = patches.get(index);
145 return patch && patch._tag !== "Initial";
146 })
147 .map((file) => file.path),
148 );
149 return {
150 scope,
151 fileStates,
152 isPending: [...patches.values()].some((patch) => patch._tag === "Initial" || patch.waiting),
153 retry,
154 requestFile,
155 readyFilePaths,
156 renderableFiles,
157 settledFileCount,
158 loadNextFiles,
159 };
160}
161
162// The refresh effect keys on the identity of these queries.
163function reviewFileQueries({
164 environmentId,
165 cwd,
166 source,
167 baseRef,
168 ignoreWhitespace,
169 scope,
170 requested,
171}: {
172 environmentId: EnvironmentId | undefined;
173 cwd: string | undefined;
174 source: ReviewDiffPreviewSource | null;
175 baseRef: string | null;
176 ignoreWhitespace: boolean;
177 scope: string;
178 requested: { scope: string; indices: number[] };
179}) {
180 const indices = requested.scope === scope ? requested.indices : DEFAULT_INDICES;
181 const files = sortedReviewFiles(source);
182 const queries =
183 !environmentId || !cwd || !source
184 ? []
185 : indices
186 .filter((index) => index < files.length)
187 .map((index) => {
188 const file = files[index]!;
189 const target: ReviewPatchTarget = {
190 environmentId,
191 input: {
192 cacheKey: scope,
193 request: {
194 cwd,
195 ...(baseRef ? { baseRef } : {}),
196 ignoreWhitespace,
197 file: {
198 path: file.path,
199 previousPath: file.previousPath,
200 sourceKind: source.kind,
201 },
202 },
203 },
204 };
205 return { index, target, query: reviewEnvironment.diffFilePatch(target) };
206 });
207 return queries;
208}
209
210function sortedReviewFiles(source: ReviewDiffPreviewSource | null) {
211 return source?.files?.toSorted((a, b) => filePathCollator.compare(a.path, b.path)) ?? [];
212}
213
214type ReviewPatchTarget = Parameters<typeof reviewEnvironment.diffFilePatch>[0];
215
216// Derived atoms parse each query result once, even when another file finishes loading.
217const parsedPatchAtom = Atom.family((key: string) => {
218 const [theme, target] = JSON.parse(key) as ["light" | "dark", ReviewPatchTarget];
219 return Atom.map(reviewEnvironment.diffFilePatch(target), (result) =>
220 AsyncResult.map(result, (source) => {
221 let patch = getRenderablePatch(source.diff, `diff-panel:${theme}`, {
222 compactPartialHunkOffsets: true,
223 });
224 if (patch?.kind === "files" && patch.files.length === 1 && source.files?.length === 1) {
225 const stat = source.files[0]!;
226 const file = { ...patch.files[0]!, name: stat.path };
227 if (stat.previousPath !== null) file.prevName = stat.previousPath;
228 else delete file.prevName;
229 patch = { ...patch, files: [file] };
230 }
231 return { source, patch };
232 }),
233 );
234});
235
236// Keyed by theme and query targets so every render with the same files reads the same atom.
237const reviewPatchesAtom = Atom.family((key: string) => {
238 const [theme, entries] = JSON.parse(key) as [
239 "light" | "dark",
240 ReadonlyArray<readonly [number, ReviewPatchTarget]>,
241 ];
242 const parsed = entries.map(
243 ([index, target]) => [index, parsedPatchAtom(JSON.stringify([theme, target]))] as const,
244 );
245 return Atom.make((get) => new Map(parsed.map(([index, atom]) => [index, get(atom)])));
246});