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