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

useReviewFilePatches.ts

238 lines7.8 KB

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 { files, queries } = useReviewFileQueries({
47 environmentId,
48 cwd,
49 source,
50 baseRef,
51 ignoreWhitespace,
52 scope,
53 requested,
54 });
55 const previousPreview = useRef({ scope, revision, queries: [] as typeof queries });
56 useEffect(() => {
57 const previous = previousPreview.current;
58 previousPreview.current = { scope, revision, queries };
59 for (const { query } of queries) {
60 const changed = previous.scope === scope && previous.revision !== revision;
61 const cached =
62 !previous.queries.some((entry) => entry.query === query) &&
63 registry.get(query)._tag !== "Initial" &&
64 !registry.get(query).waiting;
65 if (changed || cached) registry.refresh(query);
66 }
67 }, [scope, revision, queries, registry]);
68 const patches = useAtomValue(usePatchesAtom(queries, theme));
69 const pendingIndex = files.findIndex((_, index) => {
70 const patch = patches.get(index);
71 return !patch || patch._tag === "Initial";
72 });
73 const settledFileCount = source
74 ? pendingIndex < 0
75 ? files.length
76 : pendingIndex
77 : preview?.kind === "files"
78 ? preview.files.length
79 : 0;
80 const requestFiles = (indices: number[]) =>
81 setRequested((current) => {
82 const previous = current.scope === scope ? current.indices : [0, 1, 2, 3];
83 const added = indices.filter((index) => !previous.includes(index));
84 return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
85 });
86 const loadNextFiles = () =>
87 requestFiles(Array.from({ length: 4 }, (_, index) => settledFileCount + index));
88 const requestFile = (index: number) => requestFiles([index]);
89 const retry = useStableCallback((path: string) => {
90 const query = queries.find(({ index }) => files[index]?.path === path)?.query;
91 if (query) registry.refresh(query);
92 });
93 const renderableFiles = source
94 ? files.map((file, index): FileDiffMetadata => {
95 const result = patches.get(index);
96 if (result?._tag === "Success" && result.value.patch?.kind === "files") {
97 const loaded = result.value.patch.files.find(
98 (candidate) => resolveFileDiffPath(candidate) === file.path,
99 );
100 if (loaded) return loaded;
101 }
102 return {
103 name: file.path,
104 ...(file.previousPath ? { prevName: file.previousPath } : {}),
105 type: file.previousPath ? "rename-changed" : "change",
106 hunks: [],
107 additionLines: [],
108 deletionLines: [],
109 splitLineCount: 0,
110 unifiedLineCount: 0,
111 isPartial: true,
112 cacheKey: `${scope}:${file.path}:pending`,
113 };
114 })
115 : (preview?.kind === "files" ? preview.files : []).toSorted((a, b) =>
116 filePathCollator.compare(resolveFileDiffPath(a), resolveFileDiffPath(b)),
117 );
118 const fileStates = new Map(
119 files.map((file, index) => {
120 const patch = patches.get(index);
121 return [
122 file.path,
123 {
124 error:
125 patch?._tag === "Failure" ||
126 (patch?._tag === "Success" &&
127 (patch.value.patch?.kind !== "files" ||
128 !patch.value.patch.files.some(
129 (candidate) => resolveFileDiffPath(candidate) === file.path,
130 ))),
131 truncated: patch?._tag === "Success" && patch.value.source.truncated,
132 },
133 ] as const;
134 }),
135 );
136 const readyFilePaths = new Set(
137 files
138 .filter((_, index) => {
139 const patch = patches.get(index);
140 return patch && patch._tag !== "Initial";
141 })
142 .map((file) => file.path),
143 );
144 return {
145 scope,
146 fileStates,
147 isPending: [...patches.values()].some((patch) => patch._tag === "Initial" || patch.waiting),
148 retry,
149 requestFile,
150 readyFilePaths,
151 renderableFiles,
152 settledFileCount,
153 loadNextFiles,
154 };
156​
157// The caller runs more hooks after these values, so the compiler would rebuild them
158// every render there; the refresh effect and the patches atom key on their identity.
159function useReviewFileQueries({
160 environmentId,
161 cwd,
162 source,
163 baseRef,
164 ignoreWhitespace,
165 scope,
166 requested,
167}: {
168 environmentId: EnvironmentId | undefined;
169 cwd: string | undefined;
170 source: ReviewDiffPreviewSource | null;
171 baseRef: string | null;
172 ignoreWhitespace: boolean;
173 scope: string;
174 requested: { scope: string; indices: number[] };
175}) {
176 "use memo";
177 const indices = requested.scope === scope ? requested.indices : DEFAULT_INDICES;
178 const files = source?.files?.toSorted((a, b) => filePathCollator.compare(a.path, b.path)) ?? [];
179 const queries =
180 !environmentId || !cwd || !source
181 ? []
182 : indices
183 .filter((index) => index < files.length)
184 .map((index) => {
185 const file = files[index]!;
186 return {
187 index,
188 query: reviewEnvironment.diffFilePatch({
189 environmentId,
190 input: {
191 cacheKey: scope,
192 request: {
193 cwd,
194 ...(baseRef ? { baseRef } : {}),
195 ignoreWhitespace,
196 file: {
197 path: file.path,
198 previousPath: file.previousPath,
199 sourceKind: source.kind,
200 },
201 },
202 },
203 }),
204 };
205 });
206 return { files, queries };
208​
209function usePatchesAtom(
210 queries: ReadonlyArray<{
211 index: number;
212 query: ReturnType<typeof reviewEnvironment.diffFilePatch>;
213 }>,
214 theme: "light" | "dark",
215) {
216 "use memo";
217 // Derived atoms parse each query result once, even when another file finishes loading.
218 const parsedQuery = Atom.family((query: ReturnType<typeof reviewEnvironment.diffFilePatch>) =>
219 Atom.map(query, (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 return Atom.make(
236 (get) => new Map(queries.map(({ index, query }) => [index, get(parsedQuery(query))])),
237 );