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

useReviewDiffData.ts

292 lines9.8 KB

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