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 { useCallback, useMemo, 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
78export function GuideExcerpt({
79 excerpt,
80 file,
81 loading,
82 notes,
83 commenting,
84 loadDiffFiles,
85 onOpenFile,
86}: {
87 excerpt: PullRequestReviewGuideExcerpt;
88 file: FileDiffMetadata | null;
89 loading: boolean;
90 notes: ReadonlyArray<ExcerptNoteMarker>;
91 commenting: ExcerptCommenting | null;
92 loadDiffFiles: FileDiffContentsLoader;
93 onOpenFile: (path: string) => void;
94}) {
95 const [draft, setDraft] = useState<ExcerptDraft | null>(null);
96 const { resolvedTheme } = useTheme();
97 const slice = useMemo(() => {
98 if (file === null) return null;
99 const rows = fileDiffRows(file);
100 const shown = excerptRows(rows, excerpt);
101 if (shown.length === 0) return null;
102 const parsed = getRenderablePatch(
103 rowsToPatch(excerpt.path, resolveFileDiffPreviousPath(file), shown),
104 `pull-request-guide-excerpt:${excerpt.path}:${excerpt.side}:${excerpt.start}-${excerpt.end}`,
105 );
106 const fileDiff = parsed?.kind === "files" ? parsed.files[0] : undefined;
107 if (fileDiff === undefined) return null;
108 const drawn = {
109 additions: new Set(shown.flatMap((row) => (row.newLine === null ? [] : [row.newLine]))),
110 deletions: new Set(shown.flatMap((row) => (row.oldLine === null ? [] : [row.oldLine]))),
111 };
112 return { fileDiff, rows: shown, shown: shown.length, total: rows.length, drawn };
113 }, [excerpt, file]);
114
115 // The excerpt expands against an old side of its own: the file's real old side differs from
116 // the new one wherever another hunk changed it, and the renderer needs the two to agree around
117 // the lines it shows. A slice across hunks has nothing consistent to expand into.
118 const sliceRows = slice?.rows ?? null;
119 const loadExcerptFiles = useMemo<FileDiffContentsLoader | null>(() => {
120 if (sliceRows === null || sliceRows.some((row) => row.hunk !== sliceRows[0]?.hunk)) {
121 return null;
122 }
123 return async (fileDiff) => {
124 const loaded = await loadDiffFiles(fileDiff);
125 const oldContents = excerptExpansionOldContents(loaded.newFile.contents, sliceRows);
126 if (oldContents === null) return loaded;
127 return {
128 newFile: loaded.newFile,
129 oldFile: {
130 name: loaded.oldFile?.name ?? loaded.newFile.name,
131 contents: oldContents,
132 cacheKey: `${loaded.newFile.cacheKey ?? loaded.newFile.name}:excerpt:${excerpt.side}:${excerpt.start}-${excerpt.end}`,
133 },
134 };
135 };
136 }, [excerpt.end, excerpt.side, excerpt.start, loadDiffFiles, sliceRows]);
137
138 const annotations = useMemo(() => {
139 const groups = new Map<string, DiffLineAnnotation<ExcerptAnnotation>>();
140 const at = (side: "additions" | "deletions", line: number) => {
141 const key = `${side}:${line}`;
142 const existing = groups.get(key);
143 if (existing !== undefined) return existing;
144 const created: DiffLineAnnotation<ExcerptAnnotation> = {
145 side,
146 lineNumber: line,
147 metadata: { markers: [], pending: [], draft: false },
148 };
149 groups.set(key, created);
150 return created;
151 };
152 const update = (
153 side: "additions" | "deletions",
154 line: number,
155 change: (metadata: ExcerptAnnotation) => ExcerptAnnotation,
156 ) => {
157 const group = at(side, line);
158 groups.set(`${side}:${line}`, { ...group, metadata: change(group.metadata) });
159 };
160 const noteSide = excerpt.side === "new" ? "additions" : "deletions";
161 for (const note of notes) {
162 update(noteSide, note.line, (metadata) => ({
163 ...metadata,
164 markers: [...metadata.markers, ...note.markers],
165 }));
166 }
167 for (const comment of commenting?.pending ?? []) {
168 if (comment.path !== excerpt.path) continue;
169 const anchor = getReviewPositionAnchor(comment.position);
170 const side = toViewerSide(anchor.side);
171 if (!slice?.drawn[side].has(anchor.line)) continue;
172 update(side, anchor.line, (metadata) => ({
173 ...metadata,
174 pending: [...metadata.pending, comment],
175 }));
176 }
177 if (draft !== null) {
178 const anchor = getReviewPositionAnchor(draft.position);
179 update(toViewerSide(anchor.side), anchor.line, (metadata) => ({ ...metadata, draft: true }));
180 }
181 return [...groups.values()];
182 }, [commenting?.pending, draft, excerpt.path, excerpt.side, notes, slice]);
183
184 const beginComment = useCallback(
185 (range: SelectedLineRange | null) => {
186 if (range === null || file === null) return;
187 const position = resolveDiffReviewPosition(file, range.end, range.endSide ?? range.side);
188 if (position === null) return;
189 setDraft({ range, position });
190 },
191 [file],
192 );
193 const interactive = commenting !== null && draft === null;
194 const onAskAgent = commenting?.onAskAgent ?? null;
195 const askAgent = (request: string) => {
196 if (draft === null || file === null || onAskAgent === null) return;
197 const comment = buildDiffReviewComment({
198 id: `pull-request-guide:${excerpt.path}:${draft.range.start}:${draft.range.end}`,
199 sectionId: `pull-request-guide:${excerpt.path}`,
200 sectionTitle: "Review guide",
201 filePath: excerpt.path,
202 fileDiff: file,
203 range: draft.range,
204 text: request,
205 });
206 setDraft(null);
207 if (comment !== null) onAskAgent(comment, request);
208 };
209
210 const options = useMemo(
211 () => ({
212 diffStyle: "unified" as const,
213 lineDiffType: "none" as const,
214 overflow: "scroll" as const,
215 theme: resolveDiffThemeName(resolvedTheme),
216 themeType: resolvedTheme,
217 preferredHighlighter: PREFERRED_HIGHLIGHTER,
218 unsafeCSS: EXCERPT_UNSAFE_CSS,
219 enableGutterUtility: interactive,
220 enableLineSelection: interactive,
221 onGutterUtilityClick: beginComment,
222 onLineSelectionEnd: beginComment,
223 ...(loadExcerptFiles === null
224 ? { hunkSeparators: "simple" as const }
225 : { loadDiffFiles: loadExcerptFiles }),
226 }),
227 [resolvedTheme, interactive, beginComment, loadExcerptFiles],
228 );
229
230 return (
231 <figure className="flex min-w-0 flex-col gap-1.5">
232 {excerpt.caption.trim() !== "" ? (
233 <figcaption className="text-xs text-muted-foreground">
234 <GuideProse text={excerpt.caption} plain />
235 </figcaption>
236 ) : null}
237 {slice !== null ? (
238 <div className="min-w-0 overflow-hidden rounded-lg border border-border/60">
239 <FileDiff<ExcerptAnnotation>
240 fileDiff={slice.fileDiff}
241 options={options}
242 lineAnnotations={annotations}
243 selectedLines={draft?.range ?? null}
244 renderAnnotation={(annotation) => (
245 <div className="font-sans">
246 {annotation.metadata.markers.length > 0 ? (
247 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1 text-xs">
248 {annotation.metadata.markers.map((entry) => (
249 <span key={entry.marker} className="inline-flex items-center gap-1.5">
250 <GuideNoteMarker marker={entry.marker} />
251 <span className="text-foreground">{entry.title}</span>
252 </span>
253 ))}
254 </div>
255 ) : null}
256 {annotation.metadata.pending.map((comment) => (
257 <PendingReviewCommentCard
258 key={comment.id}
259 comment={comment}
260 onRemove={() => commenting?.onRemove(comment.id)}
261 />
262 ))}
263 {annotation.metadata.draft && draft !== null && commenting !== null ? (
264 <DiffCommentAnnotation
265 kind="draft"
266 rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`}
267 text=""
268 placeholder={
269 commenting.canComment ? "Add a comment…" : "Ask the agent about these lines…"
270 }
271 submitLabel={commenting.canComment ? "Add to review" : "Ask agent"}
272 {...(commenting.canComment && onAskAgent !== null
273 ? {
274 secondaryAction: {
275 label: "Ask agent",
276 onAction: (text: string) => askAgent(text),
277 },
278 }
279 : {})}
280 onCancel={() => setDraft(null)}
281 onComment={(body) => {
282 if (!commenting.canComment) {
283 askAgent(body);
284 return;
285 }
286 commenting.onComment({
287 path: excerpt.path,
288 oldPath: file === null ? null : previousPathOf(file, excerpt.path),
289 position: draft.position,
290 body,
291 });
292 setDraft(null);
293 }}
294 />
295 ) : null}
296 </div>
297 )}
298 renderHeaderMetadata={() => (
299 <span className="flex items-center gap-2 text-xs text-muted-foreground">
300 <span className="tabular-nums">
301 {excerpt.side === "old" ? "removed code, " : ""}showing {slice.shown} of{" "}
302 {slice.total} diff lines
303 </span>
304 <Button
305 size="icon-xs"
306 variant="ghost-muted"
307 aria-label={`Open ${excerpt.path} in Code`}
308 onClick={() => onOpenFile(excerpt.path)}
309 >
310 <ArrowUpRightIcon aria-hidden />
311 </Button>
312 </span>
313 )}
314 />
315 </div>
316 ) : loading ? (
317 <p className="rounded-lg border border-border/60 px-3 py-2 text-xs text-muted-foreground">
318 Loading {excerpt.path}...
319 </p>
320 ) : (
321 <div className="flex items-center justify-between gap-3 rounded-lg border border-border/60 px-3 py-2 text-xs text-muted-foreground">
322 <span className="min-w-0 truncate">
323 <span className="font-mono text-foreground">{excerpt.path}</span> lines {excerpt.start}-
324 {excerpt.end} are not in the loaded diff.
325 </span>
326 <Button size="xs" variant="outline" onClick={() => onOpenFile(excerpt.path)}>
327 Open in Code
328 </Button>
329 </div>
330 )}
331 </figure>
332 );
333}
334
335function previousPathOf(file: FileDiffMetadata, path: string): string | null {
336 const previous = resolveFileDiffPreviousPath(file);
337 return previous === path ? null : previous;
338}