Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useReviewFilePatches.ts

245 lines8.0 KB

1import { RegistryContext, useAtomValue } from "@effect/atom-react";
2import type { FileDiffMetadata } from "@pierre/diffs";
3import type {
4 EnvironmentId,
5 ReviewDiffPreviewInput,
6 ReviewDiffPreviewSource,
7} from "@t3tools/contracts";
8import * as AsyncResult from "effect/reactivity/AsyncResult";
9import * as Atom from "effect/reactivity/Atom";
10import { useContext, useState } from "react";
11import { useStableCallback } from "~/hooks/useStableCallback";
12import { getRenderablePatch, resolveFileDiffPath, type RenderablePatch } from "~/lib/diffRendering";
13import { reviewEnvironment } from "~/state/review";
14​
15const filePathCollator = new Intl.Collator(undefined, {
16 numeric: true,
17 sensitivity: "base",
18});
19const DEFAULT_INDICES = [0, 1, 2, 3];
20​
21export function useReviewFilePatches({
22 environmentId,
23 cwd,
24 source,
25 baseRef,
26 ignoreWhitespace,
27 theme,
28 previewInput,
29 preview,
30}: {
31 environmentId: EnvironmentId | undefined;
32 cwd: string | undefined;
33 source: ReviewDiffPreviewSource | null;
34 baseRef: string | null;
35 ignoreWhitespace: boolean;
36 theme: "light" | "dark";
37 /** The preview the file list came from; a newer revision of it refreshes loaded patches. */
38 previewInput: ReviewDiffPreviewInput | undefined;
39 preview: RenderablePatch | null;
40}) {
41 const registry = useContext(RegistryContext);
42 const scope = JSON.stringify([
43 environmentId,
44 cwd,
45 source?.kind,
46 source?.diffHash,
47 baseRef,
48 ignoreWhitespace,
49 ]);
50 const [requested, setRequested] = useState(() => ({ scope, indices: DEFAULT_INDICES }));
51 const queries = reviewFileQueries({
52 environmentId,
53 cwd,
54 source,
55 baseRef,
56 ignoreWhitespace,
57 previewInput,
58 scope,
59 requested,
60 });
61 const queriedPatchesAtom = reviewPatchesAtom(
62 JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]),
63 );
64 const patches = useAtomValue(queriedPatchesAtom);
65 const retry = useStableCallback((path: string) => {
66 const files = sortedReviewFiles(source);
67 const query = queries.find(({ index }) => files[index]?.path === path)?.query;
68 if (query) registry.refresh(query);
69 });
70 const files = sortedReviewFiles(source);
71 const pendingIndex = files.findIndex((_, index) => {
72 const patch = patches.get(index);
73 return !patch || patch._tag === "Initial";
74 });
75 const settledFileCount = source
76 ? pendingIndex < 0
77 ? files.length
78 : pendingIndex
79 : preview?.kind === "files"
80 ? preview.files.length
81 : 0;
82 const requestFiles = (indices: number[]) =>
83 setRequested((current) => {
84 const previous = current.scope === scope ? current.indices : [0, 1, 2, 3];
85 const added = indices.filter((index) => !previous.includes(index));
86 return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
87 });
88 // The first unsettled file already requested means a batch is in flight; wait for it.
89 const loadNextFiles = () => {
90 if (queries.some(({ index }) => index === settledFileCount)) return;
91 requestFiles(Array.from({ length: 4 }, (_, index) => settledFileCount + index));
92 };
93 const requestFile = (index: number) => requestFiles([index]);
94 const renderableFiles = source
95 ? files.map((file, index): FileDiffMetadata => {
96 const result = patches.get(index);
97 if (result?._tag === "Success" && result.value.patch?.kind === "files") {
98 const loaded = result.value.patch.files.find(
99 (candidate) => resolveFileDiffPath(candidate) === file.path,
100 );
101 if (loaded) return loaded;
102 }
103 return {
104 name: file.path,
105 ...(file.previousPath ? { prevName: file.previousPath } : {}),
106 type: file.previousPath ? "rename-changed" : "change",
107 hunks: [],
108 additionLines: [],
109 deletionLines: [],
110 additionCharacterCount: 0,
111 deletionCharacterCount: 0,
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 };
159​
160function reviewFileQueries({
161 environmentId,
162 cwd,
163 source,
164 baseRef,
165 ignoreWhitespace,
166 previewInput,
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 previewInput: ReviewDiffPreviewInput | undefined;
176 scope: string;
177 requested: { scope: string; indices: number[] };
178}) {
179 const indices = requested.scope === scope ? requested.indices : DEFAULT_INDICES;
180 const files = sortedReviewFiles(source);
181 const queries =
182 !environmentId || !cwd || !source
183 ? []
184 : indices
185 .filter((index) => index < files.length)
186 .map((index) => {
187 const file = files[index]!;
188 const target: ReviewPatchTarget = {
189 environmentId,
190 input: {
191 cacheKey: scope,
192 ...(previewInput ? { preview: previewInput } : {}),
193 request: {
194 cwd,
195 ...(baseRef ? { baseRef } : {}),
196 ...(source.kind === "commit" ? { commitSha: source.id } : {}),
197 ignoreWhitespace,
198 file: {
199 path: file.path,
200 previousPath: file.previousPath,
201 sourceKind: source.kind,
202 },
203 },
204 },
205 };
206 return { index, target, query: reviewEnvironment.diffFilePatch(target) };
207 });
208 return queries;
210​
211function sortedReviewFiles(source: ReviewDiffPreviewSource | null) {
212 return source?.files?.toSorted((a, b) => filePathCollator.compare(a.path, b.path)) ?? [];
214​
215type ReviewPatchTarget = Parameters<typeof reviewEnvironment.diffFilePatch>[0];
216​
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​
236const reviewPatchesAtom = Atom.family((key: string) => {
237 const [theme, entries] = JSON.parse(key) as [
238 "light" | "dark",
239 ReadonlyArray<readonly [number, ReviewPatchTarget]>,
240 ];
241 const parsed = entries.map(
242 ([index, target]) => [index, parsedPatchAtom(JSON.stringify([theme, target]))] as const,
243 );
244 return Atom.make((get) => new Map(parsed.map(([index, atom]) => [index, get(atom)])));
245});