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 = patchesAtom(queries, theme);
56 const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });
57 useEffect(() => {
58 const previous = previousPreview.current;
59 previousPreview.current = { scope, revision, queries };
60 for (const { query } of queries) {
61 const changed = previous.scope === scope && previous.revision !== revision;
62 const cached =
63 !previous.queries.some((entry) => entry.query === query) &&
64 registry.get(query)._tag !== "Initial" &&
65 !registry.get(query).waiting;
66 if (changed || cached) registry.refresh(query);
67 }
68 }, [scope, revision, queries, registry]);
69 const patches = useAtomValue(queriedPatchesAtom);
70 const retry = useStableCallback((path: string) => {
71 const files = sortedReviewFiles(source);
72 const query = queries.find(({ index }) => files[index]?.path === path)?.query;
73 if (query) registry.refresh(query);
74 });
75 const files = sortedReviewFiles(source);
76 const pendingIndex = files.findIndex((_, index) => {
77 const patch = patches.get(index);
78 return !patch || patch._tag === "Initial";
79 });
80 const settledFileCount = source
81 ? pendingIndex < 0
82 ? files.length
83 : pendingIndex
84 : preview?.kind === "files"
85 ? preview.files.length
86 : 0;
87 const requestFiles = (indices: number[]) =>
88 setRequested((current) => {
89 const previous = current.scope === scope ? current.indices : [0, 1, 2, 3];
90 const added = indices.filter((index) => !previous.includes(index));
91 return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
92 });
93 const loadNextFiles = () =>
94 requestFiles(Array.from({ length: 4 }, (_, index) => settledFileCount + index));
95 const requestFile = (index: number) => requestFiles([index]);
96 const renderableFiles = source
97 ? files.map((file, index): FileDiffMetadata => {
98 const result = patches.get(index);
99 if (result?._tag === "Success" && result.value.patch?.kind === "files") {
100 const loaded = result.value.patch.files.find(
101 (candidate) => resolveFileDiffPath(candidate) === file.path,
102 );
103 if (loaded) return loaded;
104 }
105 return {
106 name: file.path,
107 ...(file.previousPath ? { prevName: file.previousPath } : {}),
108 type: file.previousPath ? "rename-changed" : "change",
109 hunks: [],
110 additionLines: [],
111 deletionLines: [],
112 splitLineCount: 0,
113 unifiedLineCount: 0,
114 isPartial: true,
115 cacheKey: `${scope}:${file.path}:pending`,
116 };
117 })
118 : (preview?.kind === "files" ? preview.files : []).toSorted((a, b) =>
119 filePathCollator.compare(resolveFileDiffPath(a), resolveFileDiffPath(b)),
120 );
121 const fileStates = new Map(
122 files.map((file, index) => {
123 const patch = patches.get(index);
124 return [
125 file.path,
126 {
127 error:
128 patch?._tag === "Failure" ||
129 (patch?._tag === "Success" &&
130 (patch.value.patch?.kind !== "files" ||
131 !patch.value.patch.files.some(
132 (candidate) => resolveFileDiffPath(candidate) === file.path,
133 ))),
134 truncated: patch?._tag === "Success" && patch.value.source.truncated,
135 },
136 ] as const;
137 }),
138 );
139 const readyFilePaths = new Set(
140 files
141 .filter((_, index) => {
142 const patch = patches.get(index);
143 return patch && patch._tag !== "Initial";
144 })
145 .map((file) => file.path),
146 );
147 return {
148 scope,
149 fileStates,
150 isPending: [...patches.values()].some((patch) => patch._tag === "Initial" || patch.waiting),
151 retry,
152 requestFile,
153 readyFilePaths,
154 renderableFiles,
155 settledFileCount,
156 loadNextFiles,
157 };
158}
159
160// The refresh effect and the patches atom key on the identity of these queries.
161function reviewFileQueries({
162 environmentId,
163 cwd,
164 source,
165 baseRef,
166 ignoreWhitespace,
167 scope,
168 requested,
169}: {
170 environmentId: EnvironmentId | undefined;
171 cwd: string | undefined;
172 source: ReviewDiffPreviewSource | null;
173 baseRef: string | null;
174 ignoreWhitespace: boolean;
175 scope: string;
176 requested: { scope: string; indices: number[] };
177}) {
178 const indices = requested.scope === scope ? requested.indices : DEFAULT_INDICES;
179 const files = sortedReviewFiles(source);
180 const queries =
181 !environmentId || !cwd || !source
182 ? []
183 : indices
184 .filter((index) => index < files.length)
185 .map((index) => {
186 const file = files[index]!;
187 return {
188 index,
189 query: reviewEnvironment.diffFilePatch({
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 };
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
214function patchesAtom(
215 queries: ReadonlyArray<{
216 index: number;
217 query: ReturnType<typeof reviewEnvironment.diffFilePatch>;
218 }>,
219 theme: "light" | "dark",
220) {
221 // Derived atoms parse each query result once, even when another file finishes loading.
222 const parsedQuery = Atom.family((query: ReturnType<typeof reviewEnvironment.diffFilePatch>) =>
223 Atom.map(query, (result) =>
224 AsyncResult.map(result, (source) => {
225 let patch = getRenderablePatch(source.diff, `diff-panel:${theme}`, {
226 compactPartialHunkOffsets: true,
227 });
228 if (patch?.kind === "files" && patch.files.length === 1 && source.files?.length === 1) {
229 const stat = source.files[0]!;
230 const file = { ...patch.files[0]!, name: stat.path };
231 if (stat.previousPath !== null) file.prevName = stat.previousPath;
232 else delete file.prevName;
233 patch = { ...patch, files: [file] };
234 }
235 return { source, patch };
236 }),
237 ),
238 );
239 return Atom.make(
240 (get) => new Map(queries.map(({ index, query }) => [index, get(parsedQuery(query))])),
241 );
242}