Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GuideExcerpt.tsx

381 lines13.5 KB

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 } from "gt-react";
11import { useState } from "react";
12​
13import { useRenderedAppearance } from "~/hooks/useTheme";
14import {
15 getRenderablePatch,
16 resolveDiffThemeName,
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);
46`;
47​
48export interface ExcerptNoteMarker {
49 readonly line: number;
50 readonly markers: ReadonlyArray<{ readonly marker: string; readonly title: string }>;
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;
69​
70interface ExcerptAnnotation {
71 readonly markers: ExcerptNoteMarker["markers"];
72 readonly pending: ReadonlyArray<PendingReviewComment>;
73 readonly draft: boolean;
75​
76interface ExcerptDraft {
77 readonly range: SelectedLineRange;
78 readonly position: PullRequestReviewPosition;
79 readonly startPosition?: PullRequestReviewPosition;
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 };
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<ExcerptDraft | 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 );
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: ExcerptDraft | null;
182 setDraft: (draft: ExcerptDraft | 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 loadExcerptFiles = excerptLoader(excerpt, file, slice.rows, loadDiffFiles);
190​
191 const annotations = (() => {
192 const groups = new Map<string, DiffLineAnnotation<ExcerptAnnotation>>();
193 const at = (side: "additions" | "deletions", line: number) => {
194 const key = `${side}:${line}`;
195 const existing = groups.get(key);
196 if (existing !== undefined) return existing;
197 const created: DiffLineAnnotation<ExcerptAnnotation> = {
198 side,
199 lineNumber: line,
200 metadata: { markers: [], pending: [], draft: false },
201 };
202 groups.set(key, created);
203 return created;
204 };
205 const update = (
206 side: "additions" | "deletions",
207 line: number,
208 change: (metadata: ExcerptAnnotation) => ExcerptAnnotation,
209 ) => {
210 const group = at(side, line);
211 groups.set(`${side}:${line}`, { ...group, metadata: change(group.metadata) });
212 };
213 const noteSide = excerpt.side === "new" ? "additions" : "deletions";
214 for (const note of notes) {
215 update(noteSide, note.line, (metadata) => ({
216 ...metadata,
217 markers: [...metadata.markers, ...note.markers],
218 }));
219 }
220 for (const comment of commenting?.pending ?? []) {
221 if (comment.path !== excerpt.path) continue;
222 const anchor = getReviewPositionAnchor(comment.position);
223 const side = toViewerSide(anchor.side);
224 if (!slice.drawn[side].has(anchor.line)) continue;
225 update(side, anchor.line, (metadata) => ({
226 ...metadata,
227 pending: [...metadata.pending, comment],
228 }));
229 }
230 if (draft !== null) {
231 const anchor = getReviewPositionAnchor(draft.position);
232 update(toViewerSide(anchor.side), anchor.line, (metadata) => ({ ...metadata, draft: true }));
233 }
234 return [...groups.values()];
235 })();
236​
237 const beginComment = (range: SelectedLineRange | null) => {
238 if (range === null) return;
239 const anchor = resolveDiffReviewAnchor(file, range, commenting?.rangeComments === true);
240 if (anchor === null) return;
241 setDraft({ range, ...anchor });
242 };
243 const gt = useGT();
244 const interactive = commenting !== null && draft === null;
245 const onAskAgent = commenting?.onAskAgent ?? null;
246 const askAgent = (request: string) => {
247 if (draft === null || onAskAgent === null) return;
248 const comment = buildDiffReviewComment({
249 id: `pull-request-guide:${diffReviewSelectionId(excerpt.path, draft.range)}`,
250 sectionId: `pull-request-guide:${excerpt.path}`,
251 // oxlint-disable-next-line t3code/no-untranslated-copy -- context title sent to the agent
252 sectionTitle: "Review guide",
253 filePath: excerpt.path,
254 fileDiff: file,
255 range: draft.range,
256 text: request,
257 });
258 setDraft(null);
259 if (comment !== null) onAskAgent(comment, request);
260 };
261​
262 const options = {
263 diffStyle: "unified" as const,
264 lineDiffType: "none" as const,
265 overflow: "scroll" as const,
266 theme: resolveDiffThemeName(resolvedTheme),
267 themeType: resolvedTheme,
268 preferredHighlighter: PREFERRED_HIGHLIGHTER,
269 unsafeCSS: EXCERPT_UNSAFE_CSS,
270 enableGutterUtility: interactive,
271 enableLineSelection: interactive,
272 onGutterUtilityClick: beginComment,
273 onLineSelectionEnd: beginComment,
274 ...(loadExcerptFiles === null
275 ? { hunkSeparators: "simple" as const }
276 : { loadDiffFiles: loadExcerptFiles }),
277 };
278​
279 return (
280 <div className="min-w-0 overflow-hidden rounded-lg border border-border/60">
281 <FileDiff<ExcerptAnnotation>
282 fileDiff={slice.fileDiff}
283 options={options}
284 lineAnnotations={annotations}
285 selectedLines={draft?.range ?? null}
286 renderAnnotation={(annotation) => (
287 <div className="font-sans">
288 {annotation.metadata.markers.length > 0 ? (
289 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1 text-xs">
290 {annotation.metadata.markers.map((entry) => (
291 <span key={entry.marker} className="inline-flex items-center gap-1.5">
292 <GuideNoteMarker marker={entry.marker} />
293 <span className="text-foreground">{entry.title}</span>
294 </span>
295 ))}
296 </div>
297 ) : null}
298 {annotation.metadata.pending.map((comment) => (
299 <PendingReviewCommentCard
300 key={comment.id}
301 comment={comment}
302 onRemove={() => commenting?.onRemove(comment.id)}
303 />
304 ))}
305 {annotation.metadata.draft && draft !== null && commenting !== null ? (
306 <DiffCommentAnnotation
307 kind="draft"
308 rangeLabel={`${excerpt.path}:${getReviewPositionAnchor(draft.position).line}`}
309 text=""
310 completionScope={commenting.canComment ? commenting.completionScope : null}
311 placeholder={
312 commenting.canComment
313 ? gt("Add a comment…")
314 : gt("Ask the agent about these lines…")
315 }
316 submitLabel={commenting.canComment ? gt("Add to review") : gt("Ask agent")}
317 {...(commenting.canComment && onAskAgent !== null
318 ? {
319 secondaryAction: {
320 label: gt("Ask agent"),
321 onAction: (text: string) => askAgent(text),
322 },
323 }
324 : {})}
325 onCancel={() => setDraft(null)}
326 onComment={(body) => {
327 if (!commenting.canComment) {
328 askAgent(body);
329 return;
330 }
331 commenting.onComment({
332 path: excerpt.path,
333 oldPath: previousPathOf(file, excerpt.path),
334 position: draft.position,
335 startPosition: draft.startPosition,
336 body,
337 });
338 setDraft(null);
339 }}
340 />
341 ) : null}
342 </div>
343 )}
344 renderHeaderMetadata={() => (
345 <span className="flex items-center gap-2 text-xs text-muted-foreground">
346 <span className="tabular-nums">
347 {excerpt.side === "old"
348 ? gt(
349 "{total, plural, one {removed code, showing {shown} of {total} diff lines} other {removed code, showing {shown} of {total} diff lines}}",
350 {
351 shown: slice.shown,
352 total: slice.total,
353 },
354 )
355 : gt(
356 "{total, plural, one {showing {shown} of {total} diff lines} other {showing {shown} of {total} diff lines}}",
357 {
358 shown: slice.shown,
359 total: slice.total,
360 },
361 )}
362 </span>
363 <Button
364 size="icon-xs"
365 variant="ghost-muted"
366 aria-label={gt("Open {path} in Code", { path: excerpt.path })}
367 onClick={() => onOpenFile(excerpt.path)}
368 >
369 <ArrowUpRightIcon aria-hidden />
370 </Button>
371 </span>
372 )}
373 />
374 </div>
375 );
377​
378function previousPathOf(file: FileDiffMetadata, path: string): string | null {
379 const previous = resolveFileDiffPreviousPath(file);
380 return previous === path ? null : previous;