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