Open History to see the last commit
1import { useCallback, useContext, useEffect, useMemo, useState } from "react";
2import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
3
4import { 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 OrchestrationMessageContext,
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;
85}
86
87function isReviewDiffDebugLoggingEnabled(): boolean {
88 return typeof __DEV__ !== "undefined" ? __DEV__ : false;
89}
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}`);
102}
103
104function 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 };
122}
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 readonly draftContext: OrchestrationMessageContext | undefined;
131}) {
132 const { draftMessage, draftContext, selectedSection, threadKey } = input;
133 const selectedSectionId = selectedSection?.id ?? null;
134 const source = selectedSection?.source;
135 const lazySource = source?.truncated && source.files ? source : null;
136 const previewDiff: ReviewParsedDiff = lazySource
137 ? { kind: "empty" }
138 : getCachedReviewParsedDiff({
139 threadKey,
140 sectionId: selectedSection?.id ?? null,
141 diff: selectedSection?.diff,
142 });
143 const registry = useContext(RegistryContext);
144 const { environmentId, cwd } = input;
145 const scope = JSON.stringify([
146 environmentId,
147 cwd,
148 source?.kind,
149 source?.baseRef,
150 source?.diffHash,
151 ]);
152 const [requested, setRequested] = useState({ scope, indices: [0, 1, 2] });
153 const indices = useMemo(
154 () => new Set(requested.scope === scope ? requested.indices : [0, 1, 2]),
155 [requested, scope],
156 );
157 const queries = useMemo(
158 () =>
159 !environmentId || !cwd || !lazySource
160 ? []
161 : (lazySource.files ?? []).map((file, index) =>
162 indices.has(index)
163 ? reviewEnvironment.diffFilePatch({
164 environmentId,
165 input: {
166 cacheKey: scope,
167 // Newer preview revisions refresh patches read under an older one.
168 preview: { cwd },
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 loadVisibleFile = useCallback(
203 (fileId: string | null, retry = false) => {
204 const index =
205 fileId === null ? 0 : (lazySource?.files?.findIndex((file) => file.path === fileId) ?? -1);
206 if (index < 0) return;
207 setRequested((current) => {
208 const previous = current.scope === scope ? current.indices : [0, 1, 2];
209 const added = [index, index + 1, index + 2].filter((next) => !previous.includes(next));
210 return added.length === 0 ? current : { scope, indices: [...previous, ...added] };
211 });
212 if (retry && patches[index]?._tag === "Failure" && queries[index])
213 registry.refresh(queries[index]);
214 },
215 [lazySource, scope, patches, queries, registry],
216 );
217 const parsedDiff = useMemo<ReviewParsedDiff>(() => {
218 if (!lazySource?.files) return applyReviewDiffMetadata(previewDiff, selectedSection);
219 const files = lazySource.files.map((stat, index) =>
220 getCachedReviewFile(stat, lazySource.diffHash, patches[index]),
221 );
222 return {
223 kind: "files",
224 files,
225 fileCount: files.length,
226 additions: files.reduce((total, file) => total + file.additions, 0),
227 deletions: files.reduce((total, file) => total + file.deletions, 0),
228 notice: null,
229 };
230 }, [lazySource, previewDiff, selectedSection, patches]);
231 const headerDiffSummary = useMemo(
232 () => formatHeaderDiffSummary(parsedDiff, selectedSection?.files),
233 [parsedDiff, selectedSection?.files],
234 );
235 const inlineReviewComments = parseReviewInlineComments(draftMessage, draftContext);
236 const selectedSectionInlineComments = useMemo(() => {
237 if (!selectedSectionId || inlineReviewComments.length === 0) {
238 return EMPTY_INLINE_REVIEW_COMMENTS;
239 }
240 return inlineReviewComments.filter((comment) => comment.sectionId === selectedSectionId);
241 }, [inlineReviewComments, selectedSectionId]);
242 const nativeReviewDiffData = getCachedNativeReviewDiffData({
243 parsedDiff,
244 comments: selectedSectionInlineComments,
245 });
246 const pendingReviewCommentCount = inlineReviewComments.length;
247
248 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records review perf marks and diagnostic logs once a parsed diff has committed
249 useEffect(() => {
250 if (parsedDiff.kind !== "files") {
251 return;
252 }
253
254 logReviewDiffDiagnostic("parsed diff files", {
255 selectedSectionId: selectedSection?.id ?? null,
256 fileCount: parsedDiff.fileCount,
257 renderableFileCount: parsedDiff.files.length,
258 });
259 }, [parsedDiff, selectedSection?.id]);
260
261 return {
262 parsedDiff,
263 loadVisibleFile,
264 isPending: patches.some((patch) => patch?._tag === "Initial" || patch?.waiting),
265 headerDiffSummary,
266 nativeReviewDiffData,
267 pendingReviewCommentCount,
268 };
269}