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

useReviewFilePatches.ts

245 lines8.1 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 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 additionCharacterCount: 0,
115 deletionCharacterCount: 0,
116 splitLineCount: 0,
117 unifiedLineCount: 0,
118 isPartial: true,
119 cacheKey: `${scope}:${file.path}:pending`,
120 };
121 })
122 : (preview?.kind === "files" ? preview.files : []).toSorted((a, b) =>
123 filePathCollator.compare(resolveFileDiffPath(a), resolveFileDiffPath(b)),
124 );
125 const fileStates = new Map(
126 files.map((file, index) => {
127 const patch = patches.get(index);
128 return [
129 file.path,
130 {
131 error:
132 patch?._tag === "Failure" ||
133 (patch?._tag === "Success" &&
134 (patch.value.patch?.kind !== "files" ||
135 !patch.value.patch.files.some(
136 (candidate) => resolveFileDiffPath(candidate) === file.path,
137 ))),
138 truncated: patch?._tag === "Success" && patch.value.source.truncated,
139 },
140 ] as const;
141 }),
142 );
143 const readyFilePaths = new Set(
144 files
145 .filter((_, index) => {
146 const patch = patches.get(index);
147 return patch && patch._tag !== "Initial";
148 })
149 .map((file) => file.path),
150 );
151 return {
152 scope,
153 fileStates,
154 isPending: [...patches.values()].some((patch) => patch._tag === "Initial" || patch.waiting),
155 retry,
156 requestFile,
157 readyFilePaths,
158 renderableFiles,
159 settledFileCount,
160 loadNextFiles,
161 };
163​
164function reviewFileQueries({
165 environmentId,
166 cwd,
167 source,
168 baseRef,
169 ignoreWhitespace,
170 scope,
171 requested,
172}: {
173 environmentId: EnvironmentId | undefined;
174 cwd: string | undefined;
175 source: ReviewDiffPreviewSource | null;
176 baseRef: string | null;
177 ignoreWhitespace: boolean;
178 scope: string;
179 requested: { scope: string; indices: number[] };
180}) {
181 const indices = requested.scope === scope ? requested.indices : DEFAULT_INDICES;
182 const files = sortedReviewFiles(source);
183 const queries =
184 !environmentId || !cwd || !source
185 ? []
186 : indices
187 .filter((index) => index < files.length)
188 .map((index) => {
189 const file = files[index]!;
190 const target: ReviewPatchTarget = {
191 environmentId,
192 input: {
193 cacheKey: scope,
194 request: {
195 cwd,
196 ...(baseRef ? { baseRef } : {}),
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});