@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 412 lines 13.8 KB
Raw
1 import type {
2 DiffLineAnnotation,
3 FileDiffContentsLoader,
4 FileDiffMetadata,
5 SelectedLineRange,
6 } from "@pierre/diffs";
7 import { FileDiff } from "@pierre/diffs/react";
8 import type { PullRequestReviewGuideExcerpt, PullRequestReviewPosition } from "@t3tools/contracts";
9 import { ArrowUpRightIcon } from "lucide-react";
10 import { T, useGT, Var } from "gt-react";
11 import { useState } from "react";
12
13 import { useRenderedAppearance } from "~/hooks/useTheme";
14 import {
15 getRenderablePatch,
16 resolveDiffThemeName,
17 resolveFileDiffPreviousPath,
18 } from "~/lib/diffRendering";
19 import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
20 import {
21 buildDiffReviewComment,
22 diffReviewSelectionId,
23 resolveDiffReviewAnchor,
24 type ReviewCommentContext,
25 } from "~/reviewCommentContext";
26
27 import { DiffCommentAnnotation } from "../../diffs/DiffCommentAnnotation";
28 import { DIFF_VIEW_UNSAFE_CSS } from "../../diffs/StyledDiffCodeView";
29 import { Button } from "../../ui/button";
30 import {
31 getReviewPositionAnchor,
32 PendingReviewCommentCard,
33 toViewerSide,
34 } from "../PullRequestReviewAnnotation";
35 import type { PendingReviewComment } from "../pullRequestReviewStore";
36 import { excerptRows, fileDiffRows, rowsToPatch } from "@t3tools/client-runtime/review-guide-tour";
37 import type { PullRequestCompletionScope } from "../PullRequestMarkdownTextarea";
38 import { excerptLoader } from "./GuideExcerpt.logic";
39 import { GuideNoteMarker } from "./GuideNotes";
40 import { GuideProse } from "./GuideProse";
41
42 const EXCERPT_UNSAFE_CSS = `${DIFF_VIEW_UNSAFE_CSS}
43 [data-code]::-webkit-scrollbar-thumb {
44 background-color: var(--diffs-bg-context);
45 }
46 `;
47
48 export interface ExcerptNoteMarker {
49 readonly line: number;
50 readonly markers: ReadonlyArray<{ readonly marker: string; readonly title: string }>;
51 }
52
53 export 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
70 interface ExcerptAnnotation {
71 readonly markers: ExcerptNoteMarker["markers"];
72 readonly pending: ReadonlyArray<PendingReviewComment>;
73 readonly draft: boolean;
74 }
75
76 export interface CommentDraft {
77 readonly range: SelectedLineRange;
78 readonly position: PullRequestReviewPosition;
79 readonly startPosition?: PullRequestReviewPosition;
80 }
81
82 type ExcerptSlice = NonNullable<ReturnType<typeof excerptSlice>>;
83
84 function 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 export 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
167 function 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 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 const next = commentDraftFor(file, range, commenting);
239 if (next !== null) setDraft(next);
240 };
241 const gt = useGT();
242 const interactive = commenting !== null && draft === null;
243
244 const options = {
245 diffStyle: "unified" as const,
246 lineDiffType: "none" as const,
247 overflow: "scroll" as const,
248 theme: resolveDiffThemeName(resolvedTheme),
249 themeType: resolvedTheme,
250 preferredHighlighter: PREFERRED_HIGHLIGHTER,
251 unsafeCSS: EXCERPT_UNSAFE_CSS,
252 enableGutterUtility: interactive,
253 enableLineSelection: interactive,
254 onGutterUtilityClick: beginComment,
255 onLineSelectionEnd: beginComment,
256 ...(loadExcerptFiles === null
257 ? { hunkSeparators: "simple" as const }
258 : { loadDiffFiles: loadExcerptFiles }),
259 };
260
261 return (
262 <div className="min-w-0 overflow-hidden rounded-lg border border-border/60">
263 <FileDiff<ExcerptAnnotation>
264 fileDiff={slice.fileDiff}
265 options={options}
266 lineAnnotations={annotations}
267 selectedLines={draft?.range ?? null}
268 renderAnnotation={(annotation) => (
269 <div className="font-sans">
270 {annotation.metadata.markers.length > 0 ? (
271 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1 text-xs">
272 {annotation.metadata.markers.map((entry) => (
273 <span key={entry.marker} className="inline-flex items-center gap-1.5">
274 <GuideNoteMarker marker={entry.marker} />
275 <span className="text-foreground">{entry.title}</span>
276 </span>
277 ))}
278 </div>
279 ) : null}
280 {annotation.metadata.pending.map((comment) => (
281 <PendingReviewCommentCard
282 key={comment.id}
283 comment={comment}
284 onRemove={() => commenting?.onRemove(comment.id)}
285 />
286 ))}
287 {annotation.metadata.draft && draft !== null && commenting !== null ? (
288 <GuideCommentDraft
289 path={excerpt.path}
290 file={file}
291 draft={draft}
292 commenting={commenting}
293 onClose={() => setDraft(null)}
294 />
295 ) : null}
296 </div>
297 )}
298 renderHeaderMetadata={() => (
299 <span className="flex items-center gap-2 text-xs text-muted-foreground">
300 <span className="tabular-nums">
301 {excerpt.side === "old"
302 ? gt(
303 "{total, plural, one {removed code, showing {shown} of {total} diff lines} other {removed code, showing {shown} of {total} diff lines}}",
304 {
305 shown: slice.shown,
306 total: slice.total,
307 },
308 )
309 : gt(
310 "{total, plural, one {showing {shown} of {total} diff lines} other {showing {shown} of {total} diff lines}}",
311 {
312 shown: slice.shown,
313 total: slice.total,
314 },
315 )}
316 </span>
317 <Button
318 size="icon-xs"
319 variant="ghost-muted"
320 aria-label={gt("Open {path} in Code", { path: excerpt.path })}
321 onClick={() => onOpenFile(excerpt.path)}
322 >
323 <ArrowUpRightIcon aria-hidden />
324 </Button>
325 </span>
326 )}
327 />
328 </div>
329 );
330 }
331
332 function previousPathOf(file: FileDiffMetadata, path: string): string | null {
333 const previous = resolveFileDiffPreviousPath(file);
334 return previous === path ? null : previous;
335 }
336
337 export function commentDraftFor(
338 file: FileDiffMetadata,
339 range: SelectedLineRange | null,
340 commenting: ExcerptCommenting | null,
341 ): CommentDraft | null {
342 if (range === null || commenting === null) return null;
343 const anchor = resolveDiffReviewAnchor(file, range, commenting.rangeComments);
344 return anchor === null ? null : { range, ...anchor };
345 }
346
347 export function GuideCommentDraft({
348 path,
349 file,
350 draft,
351 commenting,
352 onClose,
353 }: {
354 path: string;
355 file: FileDiffMetadata;
356 draft: CommentDraft;
357 commenting: ExcerptCommenting;
358 onClose: () => void;
359 }) {
360 const gt = useGT();
361 const onAskAgent = commenting.onAskAgent;
362 const askAgent = (request: string) => {
363 if (onAskAgent === null) return;
364 const comment = buildDiffReviewComment({
365 id: `pull-request-guide:${diffReviewSelectionId(path, draft.range)}`,
366 sectionId: `pull-request-guide:${path}`,
367 // oxlint-disable-next-line t3code/no-untranslated-copy -- context title sent to the agent
368 sectionTitle: "Review guide",
369 filePath: path,
370 fileDiff: file,
371 range: draft.range,
372 text: request,
373 });
374 onClose();
375 if (comment !== null) onAskAgent(comment, request);
376 };
377 return (
378 <DiffCommentAnnotation
379 kind="draft"
380 rangeLabel={`${path}:${getReviewPositionAnchor(draft.position).line}`}
381 text=""
382 completionScope={commenting.canComment ? commenting.completionScope : null}
383 placeholder={
384 commenting.canComment ? gt("Add a comment…") : gt("Ask the agent about these lines…")
385 }
386 submitLabel={commenting.canComment ? gt("Add to review") : gt("Ask agent")}
387 {...(commenting.canComment && onAskAgent !== null
388 ? {
389 secondaryAction: {
390 label: gt("Ask agent"),
391 onAction: (text: string) => askAgent(text),
392 },
393 }
394 : {})}
395 onCancel={onClose}
396 onComment={(body) => {
397 if (!commenting.canComment) {
398 askAgent(body);
399 return;
400 }
401 commenting.onComment({
402 path,
403 oldPath: previousPathOf(file, path),
404 position: draft.position,
405 startPosition: draft.startPosition,
406 body,
407 });
408 onClose();
409 }}
410 />
411 );
412 }