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

GuideExcerpt.tsx

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