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