Open History to see the last commit
1import type {
2 DiffLineAnnotation,
3 FileDiffContentsLoader,
4 FileDiffMetadata,
5 SelectedLineRange,
6} from "@pierre/diffs";
7import { FileDiff } from "@pierre/diffs/react";
8import type { PullRequestReviewGuideExcerpt, PullRequestReviewPosition } from "@t3tools/contracts";
9import { ArrowUpRightIcon } from "lucide-react";
10import { useState } from "react";
11
12import { useTheme } from "~/hooks/useTheme";
13import {
14 getRenderablePatch,
15 resolveDiffThemeName,
16 resolveFileDiffPreviousPath,
17} from "~/lib/diffRendering";
18import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
19import {
20 buildDiffReviewComment,
21 resolveDiffReviewPosition,
22 type ReviewCommentContext,
23} from "~/reviewCommentContext";
24
25import { DiffCommentAnnotation } from "../../diffs/DiffCommentAnnotation";
26import { DIFF_VIEW_UNSAFE_CSS } from "../../diffs/StyledDiffCodeView";
27import { Button } from "../../ui/button";
28import {
29 getReviewPositionAnchor,
30 PendingReviewCommentCard,
31 toViewerSide,
32} from "../PullRequestReviewAnnotation";
33import type { PendingReviewComment } from "../pullRequestReviewStore";
34import {
35 excerptExpansionOldContents,
36 excerptRows,
37 fileDiffRows,
38 rowsToPatch,
39} from "@t3tools/client-runtime/review-guide-tour";
40import { GuideNoteMarker } from "./GuideNotes";
41import { GuideProse } from "./GuideProse";
42
43const EXCERPT_UNSAFE_CSS = `${DIFF_VIEW_UNSAFE_CSS}
44[data-code]::-webkit-scrollbar-thumb {
45 background-color: var(--diffs-bg-context);
46}
47`;
48
49export interface ExcerptNoteMarker {
50 readonly line: number;
51 readonly markers: ReadonlyArray<{ readonly marker: string; readonly title: string }>;
52}
53
54export interface ExcerptCommenting {
55 readonly canComment: boolean;
56 readonly pending: ReadonlyArray<PendingReviewComment>;
57 readonly onComment: (comment: {
58 readonly path: string;
59 readonly oldPath: string | null;
60 readonly position: PullRequestReviewPosition;
61 readonly body: string;
62 }) => void;
63 readonly onRemove: (commentId: string) => void;
64 readonly onAskAgent: ((comment: ReviewCommentContext, request: string) => void) | null;
65}
66
67interface ExcerptAnnotation {
68 readonly markers: ExcerptNoteMarker["markers"];
69 readonly pending: ReadonlyArray<PendingReviewComment>;
70 readonly draft: boolean;
71}
72
73interface ExcerptDraft {
74 readonly range: SelectedLineRange;
75 readonly position: PullRequestReviewPosition;
76}
77
78type ExcerptSlice = NonNullable<ReturnType<typeof excerptSlice>>;
79
80function excerptSlice(file: FileDiffMetadata | null, excerpt: PullRequestReviewGuideExcerpt) {
81 if (file === null) return null;
82 const rows = fileDiffRows(file);
83 const shown = excerptRows(rows, excerpt);
84 if (shown.length === 0) return null;
85 const parsed = getRenderablePatch(
86 rowsToPatch(excerpt.path, resolveFileDiffPreviousPath(file), shown),
87 `pull-request-guide-excerpt:${excerpt.path}:${excerpt.side}:${excerpt.start}-${excerpt.end}`,
88 );
89 const fileDiff = parsed?.kind === "files" ? parsed.files[0] : undefined;
90 if (fileDiff === undefined) return null;
91 const drawn = {
92 additions: new Set(shown.flatMap((row) => (row.newLine === null ? [] : [row.newLine]))),
93 deletions: new Set(shown.flatMap((row) => (row.oldLine === null ? [] : [row.oldLine]))),
94 };
95 return { fileDiff, rows: shown, shown: shown.length, total: rows.length, drawn };
96}
97
98// The excerpt expands against an old side of its own: the file's real old side differs from
99// the new one wherever another hunk changed it, and the renderer needs the two to agree around
100// the lines it shows. A slice across hunks has nothing consistent to expand into.
101function excerptLoader(
102 excerpt: PullRequestReviewGuideExcerpt,
103 sliceRows: ExcerptSlice["rows"],
104 loadDiffFiles: FileDiffContentsLoader,
105): FileDiffContentsLoader | null {
106 if (sliceRows.some((row) => row.hunk !== sliceRows[0]?.hunk)) {
107 return null;
108 }
109 return async (fileDiff) => {
110 const loaded = await loadDiffFiles(fileDiff);
111 const oldContents = excerptExpansionOldContents(loaded.newFile.contents, sliceRows);
112 if (oldContents === null) return loaded;
113 return {
114 newFile: loaded.newFile,
115 oldFile: {
116 name: loaded.oldFile?.name ?? loaded.newFile.name,
117 contents: oldContents,
118 cacheKey: `${loaded.newFile.cacheKey ?? loaded.newFile.name}:excerpt:${excerpt.side}:${excerpt.start}-${excerpt.end}`,
119 },
120 };
121 };
122}
123
124export function GuideExcerpt({
125 excerpt,
126 file,
127 loading,
128 notes,
129 commenting,
130 loadDiffFiles,
131 onOpenFile,
132}: {
133 excerpt: PullRequestReviewGuideExcerpt;
134 file: FileDiffMetadata | null;
135 loading: boolean;
136 notes: ReadonlyArray<ExcerptNoteMarker>;
137 commenting: ExcerptCommenting | null;
138 loadDiffFiles: FileDiffContentsLoader;
139 onOpenFile: (path: string) => void;
140}) {
141 // Kept here, not in ExcerptDiff, so a selection survives the diff reloading for a new head.
142 const [draft, setDraft] = useState<ExcerptDraft | null>(null);
143 const slice = excerptSlice(file, excerpt);
144
145 return (
146 <figure className="flex min-w-0 flex-col gap-1.5">
147 {excerpt.caption.trim() !== "" ? (
148 <figcaption className="text-xs text-muted-foreground">
149 <GuideProse text={excerpt.caption} plain />
150 </figcaption>
151 ) : null}
152 {slice !== null && file !== null ? (
153 <ExcerptDiff
154 excerpt={excerpt}
155 file={file}
156 slice={slice}
157 draft={draft}
158 setDraft={setDraft}
159 loadDiffFiles={loadDiffFiles}
160 notes={notes}
161 commenting={commenting}
162 onOpenFile={onOpenFile}
163 />
164 ) : loading ? (
165 <p className="rounded-lg border border-border/60 px-3 py-2 text-xs text-muted-foreground">
166 Loading {excerpt.path}...
167 </p>
168 ) : (
169 <div className="flex items-center justify-between gap-3 rounded-lg border border-border/60 px-3 py-2 text-xs text-muted-foreground">
170 <span className="min-w-0 truncate">
171 <span className="font-mono text-foreground">{excerpt.path}</span> lines {excerpt.start}-
172 {excerpt.end} are not in the loaded diff.
173 </span>
174 <Button size="xs" variant="outline" onClick={() => onOpenFile(excerpt.path)}>
175 Open in Code
176 </Button>
177 </div>
178 )}
179 </figure>
180 );
181}
182
183// Split out so draft changes re-render the diff without re-slicing the patch.
184function ExcerptDiff({
185 excerpt,
186 file,
187 slice,
188 draft,
189 setDraft,
190 loadDiffFiles,
191 notes,
192 commenting,
193 onOpenFile,
194}: {
195 excerpt: PullRequestReviewGuideExcerpt;
196 file: FileDiffMetadata;
197 slice: ExcerptSlice;
198 draft: ExcerptDraft | null;
199 setDraft: (draft: ExcerptDraft | null) => void;
200 loadDiffFiles: FileDiffContentsLoader;
201 notes: ReadonlyArray<ExcerptNoteMarker>;
202 commenting: ExcerptCommenting | null;
203 onOpenFile: (path: string) => void;
204}) {
205 const { resolvedTheme } = useTheme();
206 const loadExcerptFiles = excerptLoader(excerpt, slice.rows, loadDiffFiles);
207
208 const annotations = (() => {
209 const groups = new Map<string, DiffLineAnnotation<ExcerptAnnotation>>();
210 const at = (side: "additions" | "deletions", line: number) => {
211 const key = `${side}:${line}`;
212 const existing = groups.get(key);
213 if (existing !== undefined) return existing;
214 const created: DiffLineAnnotation<ExcerptAnnotation> = {
215 side,
216 lineNumber: line,
217 metadata: { markers: [], pending: [], draft: false },
218 };
219 groups.set(key, created);
220 return created;
221 };
222 const update = (
223 side: "additions" | "deletions",
224 line: number,
225 change: (metadata: ExcerptAnnotation) => ExcerptAnnotation,
226 ) => {
227 const group = at(side, line);
228 groups.set(`${side}:${line}`, { ...group, metadata: change(group.metadata) });
229 };
230 const noteSide = excerpt.side === "new" ? "additions" : "deletions";
231 for (const note of notes) {
232 update(noteSide, note.line, (metadata) => ({
233 ...metadata,
234 markers: [...metadata.markers, ...note.markers],
235 }));
236 }
237 for (const comment of commenting?.pending ?? []) {
238 if (comment.path !== excerpt.path) continue;
239 const anchor = getReviewPositionAnchor(comment.position);
240 const side = toViewerSide(anchor.side);
241 if (!slice.drawn[side].has(anchor.line)) continue;
242 update(side, anchor.line, (metadata) => ({
243 ...metadata,
244 pending: [...metadata.pending, comment],
245 }));
246 }
247 if (draft !== null) {
248 const anchor = getReviewPositionAnchor(draft.position);
249 update(toViewerSide(anchor.side), anchor.line, (metadata) => ({ ...metadata, draft: true }));
250 }
251 return [...groups.values()];
252 })();
253
254 const beginComment = (range: SelectedLineRange | null) => {
255 if (range === null) return;
256 const position = resolveDiffReviewPosition(file, range.end, range.endSide ?? range.side);
257 if (position === null) return;
258 setDraft({ range, position });
259 };
260 const interactive = commenting !== null && draft === null;
261 const onAskAgent = commenting?.onAskAgent ?? null;
262 const askAgent = (request: string) => {
263 if (draft === null || onAskAgent === null) return;
264 const comment = buildDiffReviewComment({
265 id: `pull-request-guide:${excerpt.path}:${draft.range.start}:${draft.range.end}`,
266 sectionId: `pull-request-guide:${excerpt.path}`,
267 sectionTitle: "Review guide",
268 filePath: excerpt.path,
269 fileDiff: file,
270 range: draft.range,
271 text: request,
272 });
273 setDraft(null);
274 if (comment !== null) onAskAgent(comment, request);
275 };
276
277 const options = {
278 diffStyle: "unified" as const,
279 lineDiffType: "none" as const,
280 overflow: "scroll" as const,
281 theme: resolveDiffThemeName(resolvedTheme),
282 themeType: resolvedTheme,
283 preferredHighlighter: PREFERRED_HIGHLIGHTER,
284 unsafeCSS: EXCERPT_UNSAFE_CSS,
285 enableGutterUtility: interactive,
286 enableLineSelection: interactive,
287 onGutterUtilityClick: beginComment,
288 onLineSelectionEnd: beginComment,
289 ...(loadExcerptFiles === null
290 ? { hunkSeparators: "simple" as const }
291 : { loadDiffFiles: loadExcerptFiles }),
292 };
293
294 return (
295 <div className="min-w-0 overflow-hidden rounded-lg border border-border/60">
296 <FileDiff<ExcerptAnnotation>
297 fileDiff={slice.fileDiff}
298 options={options}
299 lineAnnotations={annotations}
300 selectedLines={draft?.range ?? null}
301 renderAnnotation={(annotation) => (
302 <div className="font-sans">
303 {annotation.metadata.markers.length > 0 ? (
304 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1 text-xs">
305 {annotation.metadata.markers.map((entry) => (
306 <span key={entry.marker} className="inline-flex items-center gap-1.5">
307 <GuideNoteMarker marker={entry.marker} />
308 <span className="text-foreground">{entry.title}</span>
309 </span>
310 ))}
311 </div>
312 ) : null}
313 {annotation.metadata.pending.map((comment) => (
314 <PendingReviewCommentCard
315 key={comment.id}
316 comment={comment}
317 onRemove={() => commenting?.onRemove(comment.id)}
318 />
319 ))}
320 {annotation.metadata.draft && draft !== null && commenting !== null ? (
321 <DiffCommentAnnotation
322 kind="draft"
323 rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`}
324 text=""
325 placeholder={
326 commenting.canComment ? "Add a comment…" : "Ask the agent about these lines…"
327 }
328 submitLabel={commenting.canComment ? "Add to review" : "Ask agent"}
329 {...(commenting.canComment && onAskAgent !== null
330 ? {
331 secondaryAction: {
332 label: "Ask agent",
333 onAction: (text: string) => askAgent(text),
334 },
335 }
336 : {})}
337 onCancel={() => setDraft(null)}
338 onComment={(body) => {
339 if (!commenting.canComment) {
340 askAgent(body);
341 return;
342 }
343 commenting.onComment({
344 path: excerpt.path,
345 oldPath: previousPathOf(file, excerpt.path),
346 position: draft.position,
347 body,
348 });
349 setDraft(null);
350 }}
351 />
352 ) : null}
353 </div>
354 )}
355 renderHeaderMetadata={() => (
356 <span className="flex items-center gap-2 text-xs text-muted-foreground">
357 <span className="tabular-nums">
358 {excerpt.side === "old" ? "removed code, " : ""}showing {slice.shown} of {slice.total}{" "}
359 diff lines
360 </span>
361 <Button
362 size="icon-xs"
363 variant="ghost-muted"
364 aria-label={`Open ${excerpt.path} in Code`}
365 onClick={() => onOpenFile(excerpt.path)}
366 >
367 <ArrowUpRightIcon aria-hidden />
368 </Button>
369 </span>
370 )}
371 />
372 </div>
373 );
374}
375
376function previousPathOf(file: FileDiffMetadata, path: string): string | null {
377 const previous = resolveFileDiffPreviousPath(file);
378 return previous === path ? null : previous;
379}