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

useReviewDiffData.ts

305 lines10.3 KB

1import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
2​
3import { countReviewCommentContexts, parseReviewInlineComments } from "./reviewCommentSelection";
4import { getCachedNativeReviewDiffData } from "./nativeReviewDiffAdapter";
5import { markReviewEvent, measureReviewWork } from "./reviewPerf";
6import { getCachedReviewParsedDiff } from "./reviewState";
7import {
8 applyReviewDiffMetadata,
9 buildReviewParsedDiff,
10 type ReviewParsedDiff,
11 type ReviewRenderableFile,
12 type ReviewSectionItem,
13} from "./reviewModel";
14​
15import type {
16 EnvironmentId,
17 ReviewDiffFileStat,
18 ReviewDiffPreviewSource,
19} from "@t3tools/contracts";
20import { RegistryContext, useAtomValue } from "@effect/atom-react";
21import * as AsyncResult from "effect/reactivity/AsyncResult";
22import * as Atom from "effect/reactivity/Atom";
23import { reviewEnvironment } from "../../state/review";
24​
25const EMPTY_INLINE_REVIEW_COMMENTS = Object.freeze([]);
26type ParsedFilePatch = AsyncResult.AsyncResult<
27 { source: ReviewDiffPreviewSource; parsed: ReviewParsedDiff },
28 unknown
29>;
30const normalizedFiles = new WeakMap<
31 ParsedFilePatch,
32 { stat: ReviewDiffFileStat; diffHash: string; file: ReviewRenderableFile }
33>();
34​
35function getCachedReviewFile(
36 stat: ReviewDiffFileStat,
37 diffHash: string,
38 patch: ParsedFilePatch | null | undefined,
39): ReviewRenderableFile {
40 const cached = patch && normalizedFiles.get(patch);
41 if (cached && cached.stat === stat && cached.diffHash === diffHash) return cached.file;
42 const parsed = patch?._tag === "Success" ? patch.value.parsed : null;
43 const sourceFiles = patch?._tag === "Success" ? patch.value.source.files : undefined;
44 const loaded =
45 parsed?.kind === "files"
46 ? (parsed.files.find((file) => file.path === stat.path) ??
47 (parsed.files.length === 1 &&
48 sourceFiles?.length === 1 &&
49 sourceFiles[0]?.path === stat.path
50 ? parsed.files[0]
51 : undefined))
52 : undefined;
53 const file: ReviewRenderableFile = {
54 ...(loaded ?? {
55 path: stat.path,
56 previousPath: stat.previousPath,
57 changeType: "change" as const,
58 languageHint: null,
59 additionLines: [],
60 deletionLines: [],
61 rows: [],
62 cacheKey: `${diffHash}:${stat.path}`,
63 }),
64 id: stat.path,
65 path: stat.path,
66 previousPath: stat.previousPath,
67 additions: stat.additions,
68 deletions: stat.deletions,
69 ...(patch?._tag === "Success"
70 ? patch.value.source.truncated
71 ? { notice: "File preview exceeds the size limit. Counts include all changes." }
72 : loaded
73 ? {}
74 : { notice: "Could not display file preview." }
75 : {
76 notice:
77 patch?._tag === "Failure"
78 ? "Could not load diff. Select the file to retry."
79 : "Loading diff…",
80 }),
81 };
82 if (patch) normalizedFiles.set(patch, { stat, diffHash, file });
83 return file;
85​
86function isReviewDiffDebugLoggingEnabled(): boolean {
87 return typeof __DEV__ !== "undefined" ? __DEV__ : false;
89​
90function logReviewDiffDiagnostic(message: string, details?: Record<string, unknown>): void {
91 if (!isReviewDiffDebugLoggingEnabled()) {
92 return;
93 }
94​
95 if (details) {
96 console.log(`[review-sheet] ${message}`, details);
97 return;
98 }
99​
100 console.log(`[review-sheet] ${message}`);
102​
103export function formatHeaderDiffSummary(
104 parsedDiff: ReviewParsedDiff,
105 files?: ReviewSectionItem["files"],
106): {
107 readonly additions: string | null;
108 readonly deletions: string | null;
109} {
110 if (files) {
111 return {
112 additions: `+${files.reduce((total, file) => total + file.additions, 0)}`,
113 deletions: `-${files.reduce((total, file) => total + file.deletions, 0)}`,
114 };
115 }
116 if (parsedDiff.kind !== "files") return { additions: null, deletions: null };
117 return { additions: `+${parsedDiff.additions}`, deletions: `-${parsedDiff.deletions}` };
119​
120export function useReviewDiffData(input: {
121 readonly threadKey: string | null;
122 readonly environmentId: EnvironmentId | undefined;
123 readonly cwd: string | null;
124 readonly selectedSection: ReviewSectionItem | null;
125 readonly revision: string | undefined;
126 readonly draftMessage: string;
127}) {
128 const { draftMessage, selectedSection, threadKey } = input;
129 const selectedSectionId = selectedSection?.id ?? null;
130 const source = selectedSection?.source;
131 const lazySource = source?.truncated && source.files ? source : null;
132 const previewDiff = useMemo<ReviewParsedDiff>(
133 () =>
134 lazySource
135 ? { kind: "empty" }
136 : measureReviewWork("parse-diff", () =>
137 getCachedReviewParsedDiff({
138 threadKey,
139 sectionId: selectedSection?.id ?? null,
140 diff: selectedSection?.diff,
141 }),
142 ),
143 [lazySource, selectedSection?.diff, selectedSection?.id, threadKey],
144 );
145 const registry = useContext(RegistryContext);
146 const { environmentId, cwd } = input;
147 const scope = JSON.stringify([
148 environmentId,
149 cwd,
150 source?.kind,
151 source?.baseRef,
152 source?.diffHash,
153 ]);
154 const [requested, setRequested] = useState({ scope, indices: [0, 1, 2] });
155 const indices = useMemo(
156 () => new Set(requested.scope === scope ? requested.indices : [0, 1, 2]),
157 [requested, scope],
158 );
159 const queries = useMemo(
160 () =>
161 !environmentId || !cwd || !lazySource
162 ? []
163 : (lazySource.files ?? []).map((file, index) =>
164 indices.has(index)
165 ? reviewEnvironment.diffFilePatch({
166 environmentId,
167 input: {
168 cacheKey: scope,
169 request: {
170 cwd,
171 ...(lazySource.baseRef ? { baseRef: lazySource.baseRef } : {}),
172 file: {
173 path: file.path,
174 previousPath: file.previousPath,
175 sourceKind: lazySource.kind,
176 },
177 },
178 },
179 })
180 : null,
181 ),
182 [environmentId, cwd, lazySource, indices, scope],
183 );
184 const parsedQuery = useMemo(
185 () =>
186 Atom.family((query: ReturnType<typeof reviewEnvironment.diffFilePatch>) =>
187 Atom.map(query, (result) =>
188 AsyncResult.map(result, (source) => ({
189 source,
190 parsed: buildReviewParsedDiff(source.diff, source.diffHash),
191 })),
192 ),
193 ),
194 [],
195 );
196 const patches = useAtomValue(
197 useMemo(
198 () => Atom.make((get) => queries.map((query) => (query ? get(parsedQuery(query)) : null))),
199 [queries, parsedQuery],
200 ),
201 );
202 const previousPreview = useRef({
203 scope,
204 revision: input.revision,
205 queries: [] as typeof queries,
206 });
207 useEffect(() => {
208 const previous = previousPreview.current;
209 previousPreview.current = { scope, revision: input.revision, queries };
210 for (const query of queries) {
211 if (!query) continue;
212 const changed = previous.scope === scope && previous.revision !== input.revision;
213 const cached =
214 !previous.queries.includes(query) &&
215 registry.get(query)._tag !== "Initial" &&
216 !registry.get(query).waiting;
217 if (changed || cached) registry.refresh(query);
218 }
219 }, [input.revision, queries, registry, scope]);
220 const loadVisibleFile = useCallback(
221 (fileId: string | null, retry = false) => {
222 const index =
223 fileId === null ? 0 : (lazySource?.files?.findIndex((file) => file.path === fileId) ?? -1);
224 if (index < 0) return;
225 setRequested((current) => {
226 const previous = current.scope === scope ? current.indices : [0, 1, 2];
227 const added = [index, index + 1, index + 2].filter((next) => !previous.includes(next));
228 return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
229 });
230 if (retry && patches[index]?._tag === "Failure" && queries[index])
231 registry.refresh(queries[index]);
232 },
233 [lazySource, scope, patches, queries, registry],
234 );
235 const parsedDiff = useMemo<ReviewParsedDiff>(() => {
236 if (!lazySource?.files) return applyReviewDiffMetadata(previewDiff, selectedSection);
237 const files = lazySource.files.map((stat, index) =>
238 getCachedReviewFile(stat, lazySource.diffHash, patches[index]),
239 );
240 return {
241 kind: "files",
242 files,
243 fileCount: files.length,
244 additions: files.reduce((total, file) => total + file.additions, 0),
245 deletions: files.reduce((total, file) => total + file.deletions, 0),
246 notice: null,
247 };
248 }, [lazySource, previewDiff, selectedSection, patches]);
249 const headerDiffSummary = useMemo(
250 () => formatHeaderDiffSummary(parsedDiff, selectedSection?.files),
251 [parsedDiff, selectedSection?.files],
252 );
253 const inlineReviewComments = useMemo(
254 () => parseReviewInlineComments(draftMessage),
255 [draftMessage],
256 );
257 const selectedSectionInlineComments = useMemo(() => {
258 if (!selectedSectionId || inlineReviewComments.length === 0) {
259 return EMPTY_INLINE_REVIEW_COMMENTS;
260 }
261 return inlineReviewComments.filter((comment) => comment.sectionId === selectedSectionId);
262 }, [inlineReviewComments, selectedSectionId]);
263 const nativeReviewDiffData = useMemo(
264 () =>
265 measureReviewWork("build-native-diff-data", () =>
266 getCachedNativeReviewDiffData({
267 parsedDiff,
268 comments: selectedSectionInlineComments,
269 }),
270 ),
271 [parsedDiff, selectedSectionInlineComments],
272 );
273 const pendingReviewCommentCount = useMemo(
274 () => countReviewCommentContexts(draftMessage),
275 [draftMessage],
276 );
277​
278 useEffect(() => {
279 if (parsedDiff.kind !== "files") {
280 return;
281 }
282​
283 markReviewEvent("parsed-diff-ready", {
284 sectionId: selectedSection?.id ?? null,
285 fileCount: parsedDiff.fileCount,
286 additions: parsedDiff.additions,
287 deletions: parsedDiff.deletions,
288 renderedItems: nativeReviewDiffData.rows.length,
289 });
290 logReviewDiffDiagnostic("parsed diff files", {
291 selectedSectionId: selectedSection?.id ?? null,
292 fileCount: parsedDiff.fileCount,
293 renderableFileCount: parsedDiff.files.length,
294 });
295 }, [nativeReviewDiffData.rows.length, parsedDiff, selectedSection?.id]);
296​
297 return {
298 parsedDiff,
299 loadVisibleFile,
300 isPending: patches.some((patch) => patch?._tag === "Initial" || patch?.waiting),
301 headerDiffSummary,
302 nativeReviewDiffData,
303 pendingReviewCommentCount,
304 };