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 { T, useGT, Var, plural, part } from "gt-react";
11import { useState } from "react";
12
13import { useRenderedAppearance } from "~/hooks/useTheme";
14import {
15 getRenderablePatch,
16 useDiffThemeName,
17 resolveFileDiffPreviousPath,
18} from "~/lib/diffRendering";
19import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
20import {
21 buildDiffReviewComment,
22 diffReviewSelectionId,
23 resolveDiffReviewAnchor,
24 type ReviewCommentContext,
25} from "~/reviewCommentContext";
26
27import { DiffCommentAnnotation } from "../../diffs/DiffCommentAnnotation";
28import { DIFF_VIEW_UNSAFE_CSS } from "../../diffs/StyledDiffCodeView";
29import { Button } from "../../ui/button";
30import {
31 getReviewPositionAnchor,
32 PendingReviewCommentCard,
33 toViewerSide,
34} from "../PullRequestReviewAnnotation";
35import type { PendingReviewComment } from "../pullRequestReviewStore";
36import { excerptRows, fileDiffRows, rowsToPatch } from "@t3tools/client-runtime/review-guide-tour";
37import type { PullRequestCompletionScope } from "../PullRequestMarkdownTextarea";
38import { excerptLoader } from "./GuideExcerpt.logic";
39import { GuideNoteMarker } from "./GuideNotes";
40import { GuideProse } from "./GuideProse";
41
42const EXCERPT_UNSAFE_CSS = `${DIFF_VIEW_UNSAFE_CSS}
43[data-code]::-webkit-scrollbar-thumb {
44 background-color: var(--diffs-bg-context);
45}
46`;
47
48export interface ExcerptNoteMarker {
49 readonly line: number;
50 readonly markers: ReadonlyArray<{ readonly marker: string; readonly title: string }>;
51}
52
53export interface ExcerptCommenting {
54 readonly canComment: boolean;
55 /** The host anchors a comment to a range of lines rather than to its last one. */
56 readonly rangeComments: boolean;
57 readonly completionScope: PullRequestCompletionScope | null;
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
76export interface CommentDraft {
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
102export function GuideExcerpt({
103 excerpt,
104 file,
105 loading,
106 notes,
107 commenting,
108 loadDiffFiles,
109 onOpenFile,
110}: {
111 excerpt: PullRequestReviewGuideExcerpt;
112 file: FileDiffMetadata | null;
113 loading: boolean;
114 notes: ReadonlyArray<ExcerptNoteMarker>;
115 commenting: ExcerptCommenting | null;
116 loadDiffFiles: FileDiffContentsLoader;
117 onOpenFile: (path: string) => void;
118}) {
119 // Keep selections outside ExcerptDiff to survive head reloads.
120 const [draft, setDraft] = useState<CommentDraft | null>(null);
121 const slice = excerptSlice(file, excerpt);
122
123 return (
124 <figure className="flex min-w-0 flex-col gap-1.5">
125 {excerpt.caption.trim() !== "" ? (
126 <figcaption className="text-xs text-muted-foreground">
127 <GuideProse text={excerpt.caption} plain />
128 </figcaption>
129 ) : null}
130 {slice !== null && file !== null ? (
131 <ExcerptDiff
132 excerpt={excerpt}
133 file={file}
134 slice={slice}
135 draft={draft}
136 setDraft={setDraft}
137 loadDiffFiles={loadDiffFiles}
138 notes={notes}
139 commenting={commenting}
140 onOpenFile={onOpenFile}
141 />
142 ) : loading ? (
143 <p className="rounded-lg border border-border/60 px-3 py-2 text-xs text-muted-foreground">
144 <T>
145 Loading <Var>{excerpt.path}</Var>...
146 </T>
147 </p>
148 ) : (
149 <div className="flex items-center justify-between gap-3 rounded-lg border border-border/60 px-3 py-2 text-xs text-muted-foreground">
150 <span className="min-w-0 truncate">
151 <T>
152 <span className="font-mono text-foreground">
153 <Var>{excerpt.path}</Var>
154 </span>{" "}
155 lines <Var>{excerpt.start}</Var>-<Var>{excerpt.end}</Var> are not in the loaded diff.
156 </T>
157 </span>
158 <Button size="xs" variant="outline" onClick={() => onOpenFile(excerpt.path)}>
159 <T>Open in Code</T>
160 </Button>
161 </div>
162 )}
163 </figure>
164 );
165}
166
167function ExcerptDiff({
168 excerpt,
169 file,
170 slice,
171 draft,
172 setDraft,
173 loadDiffFiles,
174 notes,
175 commenting,
176 onOpenFile,
177}: {
178 excerpt: PullRequestReviewGuideExcerpt;
179 file: FileDiffMetadata;
180 slice: ExcerptSlice;
181 draft: CommentDraft | null;
182 setDraft: (draft: CommentDraft | null) => void;
183 loadDiffFiles: FileDiffContentsLoader;
184 notes: ReadonlyArray<ExcerptNoteMarker>;
185 commenting: ExcerptCommenting | null;
186 onOpenFile: (path: string) => void;
187}) {
188 const resolvedTheme = useRenderedAppearance();
189 const diffThemeName = useDiffThemeName(resolvedTheme);
190 const loadExcerptFiles = excerptLoader(excerpt, file, slice.rows, loadDiffFiles);
191
192 const annotations = (() => {
193 const groups = new Map<string, DiffLineAnnotation<ExcerptAnnotation>>();
194 const at = (side: "additions" | "deletions", line: number) => {
195 const key = `${side}:${line}`;
196 const existing = groups.get(key);
197 if (existing !== undefined) return existing;
198 const created: DiffLineAnnotation<ExcerptAnnotation> = {
199 side,
200 lineNumber: line,
201 metadata: { markers: [], pending: [], draft: false },
202 };
203 groups.set(key, created);
204 return created;
205 };
206 const update = (
207 side: "additions" | "deletions",
208 line: number,
209 change: (metadata: ExcerptAnnotation) => ExcerptAnnotation,
210 ) => {
211 const group = at(side, line);
212 groups.set(`${side}:${line}`, { ...group, metadata: change(group.metadata) });
213 };
214 const noteSide = excerpt.side === "new" ? "additions" : "deletions";
215 for (const note of notes) {
216 update(noteSide, note.line, (metadata) => ({
217 ...metadata,
218 markers: [...metadata.markers, ...note.markers],
219 }));
220 }
221 for (const comment of commenting?.pending ?? []) {
222 if (comment.path !== excerpt.path) continue;
223 const anchor = getReviewPositionAnchor(comment.position);
224 const side = toViewerSide(anchor.side);
225 if (!slice.drawn[side].has(anchor.line)) continue;
226 update(side, anchor.line, (metadata) => ({
227 ...metadata,
228 pending: [...metadata.pending, comment],
229 }));
230 }
231 if (draft !== null) {
232 const anchor = getReviewPositionAnchor(draft.position);
233 update(toViewerSide(anchor.side), anchor.line, (metadata) => ({ ...metadata, draft: true }));
234 }
235 return [...groups.values()];
236 })();
237
238 const beginComment = (range: SelectedLineRange | null) => {
239 const next = commentDraftFor(file, range, commenting);
240 if (next !== null) setDraft(next);
241 };
242 const gt = useGT();
243 const interactive = commenting !== null && draft === null;
244
245 const options = {
246 diffStyle: "unified" as const,
247 lineDiffType: "none" as const,
248 overflow: "scroll" as const,
249 theme: diffThemeName,
250 themeType: resolvedTheme,
251 preferredHighlighter: PREFERRED_HIGHLIGHTER,
252 unsafeCSS: EXCERPT_UNSAFE_CSS,
253 enableGutterUtility: interactive,
254 enableLineSelection: interactive,
255 onGutterUtilityClick: beginComment,
256 onLineSelectionEnd: beginComment,
257 ...(loadExcerptFiles === null
258 ? { hunkSeparators: "simple" as const }
259 : { loadDiffFiles: loadExcerptFiles }),
260 };
261
262 return (
263 <div className="min-w-0 overflow-hidden rounded-lg border border-border/60">
264 <FileDiff<ExcerptAnnotation>
265 fileDiff={slice.fileDiff}
266 options={options}
267 lineAnnotations={annotations}
268 selectedLines={draft?.range ?? null}
269 renderAnnotation={(annotation) => (
270 <div className="font-sans">
271 {annotation.metadata.markers.length > 0 ? (
272 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1 text-xs">
273 {annotation.metadata.markers.map((entry) => (
274 <span key={entry.marker} className="inline-flex items-center gap-1.5">
275 <GuideNoteMarker marker={entry.marker} />
276 <span className="text-foreground">{entry.title}</span>
277 </span>
278 ))}
279 </div>
280 ) : null}
281 {annotation.metadata.pending.map((comment) => (
282 <PendingReviewCommentCard
283 key={comment.id}
284 comment={comment}
285 onRemove={() => commenting?.onRemove(comment.id)}
286 />
287 ))}
288 {annotation.metadata.draft && draft !== null && commenting !== null ? (
289 <GuideCommentDraft
290 path={excerpt.path}
291 file={file}
292 draft={draft}
293 commenting={commenting}
294 onClose={() => setDraft(null)}
295 />
296 ) : null}
297 </div>
298 )}
299 renderHeaderMetadata={() => (
300 <span className="flex items-center gap-2 text-xs text-muted-foreground">
301 <span className="tabular-nums">
302 {excerpt.side === "old"
303 ? gt`${plural(
304 { total: slice.total },
305 {
306 one: part`removed code, showing ${{ shown: slice.shown }} of ${{ total: slice.total }} diff line`,
307 other: part`removed code, showing ${{ shown: slice.shown }} of ${{ total: slice.total }} diff lines`,
308 },
309 )}`
310 : gt`${plural(
311 { total: slice.total },
312 {
313 one: part`showing ${{ shown: slice.shown }} of ${{ total: slice.total }} diff line`,
314 other: part`showing ${{ shown: slice.shown }} of ${{ total: slice.total }} diff lines`,
315 },
316 )}`}
317 </span>
318 <Button
319 size="icon-xs"
320 variant="ghost-muted"
321 aria-label={gt`Open ${{ path: excerpt.path }} in Code`}
322 onClick={() => onOpenFile(excerpt.path)}
323 >
324 <ArrowUpRightIcon aria-hidden />
325 </Button>
326 </span>
327 )}
328 />
329 </div>
330 );
331}
332
333function previousPathOf(file: FileDiffMetadata, path: string): string | null {
334 const previous = resolveFileDiffPreviousPath(file);
335 return previous === path ? null : previous;
336}
337
338export function commentDraftFor(
339 file: FileDiffMetadata,
340 range: SelectedLineRange | null,
341 commenting: ExcerptCommenting | null,
342): CommentDraft | null {
343 if (range === null || commenting === null) return null;
344 const anchor = resolveDiffReviewAnchor(file, range, commenting.rangeComments);
345 return anchor === null ? null : { range, ...anchor };
346}
347
348export function GuideCommentDraft({
349 path,
350 file,
351 draft,
352 commenting,
353 onClose,
354}: {
355 path: string;
356 file: FileDiffMetadata;
357 draft: CommentDraft;
358 commenting: ExcerptCommenting;
359 onClose: () => void;
360}) {
361 const gt = useGT();
362 const onAskAgent = commenting.onAskAgent;
363 const askAgent = (request: string) => {
364 if (onAskAgent === null) return;
365 const comment = buildDiffReviewComment({
366 id: `pull-request-guide:${diffReviewSelectionId(path, draft.range)}`,
367 sectionId: `pull-request-guide:${path}`,
368 // oxlint-disable-next-line t3code/no-untranslated-copy -- context title sent to the agent
369 sectionTitle: "Review guide",
370 filePath: path,
371 fileDiff: file,
372 range: draft.range,
373 text: request,
374 });
375 onClose();
376 if (comment !== null) onAskAgent(comment, request);
377 };
378 return (
379 <DiffCommentAnnotation
380 kind="draft"
381 rangeLabel={`${path}:${getReviewPositionAnchor(draft.position).line}`}
382 text=""
383 completionScope={commenting.canComment ? commenting.completionScope : null}
384 placeholder={
385 commenting.canComment ? gt`Add a comment…` : gt`Ask the agent about these lines…`
386 }
387 submitLabel={commenting.canComment ? gt`Add to review` : gt`Ask agent`}
388 {...(commenting.canComment && onAskAgent !== null
389 ? {
390 secondaryAction: {
391 label: gt`Ask agent`,
392 onAction: (text: string) => askAgent(text),
393 },
394 }
395 : {})}
396 onCancel={onClose}
397 onComment={(body) => {
398 if (!commenting.canComment) {
399 askAgent(body);
400 return;
401 }
402 commenting.onComment({
403 path,
404 oldPath: previousPathOf(file, path),
405 position: draft.position,
406 startPosition: draft.startPosition,
407 body,
408 });
409 onClose();
410 }}
411 />
412 );
413}