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

useReviewDiffData.ts

267 lines9.1 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 { 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​
103function 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: `+${formatDiffCount(files.reduce((total, file) => total + file.additions, 0))}`,
113 deletions: `-${formatDiffCount(files.reduce((total, file) => total + file.deletions, 0))}`,
114 };
115 }
116 if (parsedDiff.kind !== "files") return { additions: null, deletions: null };
117 return {
118 additions: `+${formatDiffCount(parsedDiff.additions)}`,
119 deletions: `-${formatDiffCount(parsedDiff.deletions)}`,
120 };
122​
123export function useReviewDiffData(input: {
124 readonly threadKey: string | null;
125 readonly environmentId: EnvironmentId | undefined;
126 readonly cwd: string | null;
127 readonly selectedSection: ReviewSectionItem | null;
128 readonly draftMessage: string;
129}) {
130 const { draftMessage, selectedSection, threadKey } = input;
131 const selectedSectionId = selectedSection?.id ?? null;
132 const source = selectedSection?.source;
133 const lazySource = source?.truncated && source.files ? source : null;
134 const previewDiff: ReviewParsedDiff = lazySource
135 ? { kind: "empty" }
136 : getCachedReviewParsedDiff({
137 threadKey,
138 sectionId: selectedSection?.id ?? null,
139 diff: selectedSection?.diff,
140 });
141 const registry = useContext(RegistryContext);
142 const { environmentId, cwd } = input;
143 const scope = JSON.stringify([
144 environmentId,
145 cwd,
146 source?.kind,
147 source?.baseRef,
148 source?.diffHash,
149 ]);
150 const [requested, setRequested] = useState({ scope, indices: [0, 1, 2] });
151 const indices = useMemo(
152 () => new Set(requested.scope === scope ? requested.indices : [0, 1, 2]),
153 [requested, scope],
154 );
155 const queries = useMemo(
156 () =>
157 !environmentId || !cwd || !lazySource
158 ? []
159 : (lazySource.files ?? []).map((file, index) =>
160 indices.has(index)
161 ? reviewEnvironment.diffFilePatch({
162 environmentId,
163 input: {
164 cacheKey: scope,
165 // Newer preview revisions refresh patches read under an older one.
166 preview: { cwd },
167 request: {
168 cwd,
169 ...(lazySource.baseRef ? { baseRef: lazySource.baseRef } : {}),
170 file: {
171 path: file.path,
172 previousPath: file.previousPath,
173 sourceKind: lazySource.kind,
174 },
175 },
176 },
177 })
178 : null,
179 ),
180 [environmentId, cwd, lazySource, indices, scope],
181 );
182 const parsedQuery = useMemo(
183 () =>
184 Atom.family((query: ReturnType<typeof reviewEnvironment.diffFilePatch>) =>
185 Atom.map(query, (result) =>
186 AsyncResult.map(result, (source) => ({
187 source,
188 parsed: buildReviewParsedDiff(source.diff, source.diffHash),
189 })),
190 ),
191 ),
192 [],
193 );
194 const patches = useAtomValue(
195 useMemo(
196 () => Atom.make((get) => queries.map((query) => (query ? get(parsedQuery(query)) : null))),
197 [queries, parsedQuery],
198 ),
199 );
200 const loadVisibleFile = useCallback(
201 (fileId: string | null, retry = false) => {
202 const index =
203 fileId === null ? 0 : (lazySource?.files?.findIndex((file) => file.path === fileId) ?? -1);
204 if (index < 0) return;
205 setRequested((current) => {
206 const previous = current.scope === scope ? current.indices : [0, 1, 2];
207 const added = [index, index + 1, index + 2].filter((next) => !previous.includes(next));
208 return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
209 });
210 if (retry && patches[index]?._tag === "Failure" && queries[index])
211 registry.refresh(queries[index]);
212 },
213 [lazySource, scope, patches, queries, registry],
214 );
215 const parsedDiff = useMemo<ReviewParsedDiff>(() => {
216 if (!lazySource?.files) return applyReviewDiffMetadata(previewDiff, selectedSection);
217 const files = lazySource.files.map((stat, index) =>
218 getCachedReviewFile(stat, lazySource.diffHash, patches[index]),
219 );
220 return {
221 kind: "files",
222 files,
223 fileCount: files.length,
224 additions: files.reduce((total, file) => total + file.additions, 0),
225 deletions: files.reduce((total, file) => total + file.deletions, 0),
226 notice: null,
227 };
228 }, [lazySource, previewDiff, selectedSection, patches]);
229 const headerDiffSummary = useMemo(
230 () => formatHeaderDiffSummary(parsedDiff, selectedSection?.files),
231 [parsedDiff, selectedSection?.files],
232 );
233 const inlineReviewComments = parseReviewInlineComments(draftMessage);
234 const selectedSectionInlineComments = useMemo(() => {
235 if (!selectedSectionId || inlineReviewComments.length === 0) {
236 return EMPTY_INLINE_REVIEW_COMMENTS;
237 }
238 return inlineReviewComments.filter((comment) => comment.sectionId === selectedSectionId);
239 }, [inlineReviewComments, selectedSectionId]);
240 const nativeReviewDiffData = getCachedNativeReviewDiffData({
241 parsedDiff,
242 comments: selectedSectionInlineComments,
243 });
244 const pendingReviewCommentCount = countReviewCommentContexts(draftMessage);
245​
246 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records review perf marks and diagnostic logs once a parsed diff has committed
247 useEffect(() => {
248 if (parsedDiff.kind !== "files") {
249 return;
250 }
251​
252 logReviewDiffDiagnostic("parsed diff files", {
253 selectedSectionId: selectedSection?.id ?? null,
254 fileCount: parsedDiff.fileCount,
255 renderableFileCount: parsedDiff.files.length,
256 });
257 }, [parsedDiff, selectedSection?.id]);
258​
259 return {
260 parsedDiff,
261 loadVisibleFile,
262 isPending: patches.some((patch) => patch?._tag === "Initial" || patch?.waiting),
263 headerDiffSummary,
264 nativeReviewDiffData,
265 pendingReviewCommentCount,
266 };