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

PullRequestReviewAnnotation.tsx

486 lines17.0 KB

1import type {
2 EnvironmentId,
3 PullRequestActor,
4 PullRequestDiffSide,
5 PullRequestRef,
6 PullRequestReviewPosition,
7 PullRequestReviewThread,
8 PullRequestThreadCommentsResult,
9 PullRequestThreadComment,
10} from "@t3tools/contracts";
11import {
12 HammerIcon,
13 MessageSquareIcon,
14 MessageSquarePlusIcon,
15 Trash2Icon,
16 CircleCheckIcon,
17 CircleIcon,
18} from "lucide-react";
19import { type ReactNode, useRef, useState } from "react";
20import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
21​
22import { RelativeTime } from "~/components/RelativeTime";
23import { cn } from "~/lib/utils";
24import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldSpeech";
25​
26import { Button } from "../ui/button";
27import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
28import { PullRequestEditButton } from "./PullRequestEditButton";
29import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
30import {
31 editPullRequestThreadComment,
32 mergePullRequestThreadComments,
33 visibleBody,
34} from "./pullRequestDetail.logic";
35import { PullRequestActorAvatar, PullRequestActorLabel } from "./pullRequestPresentation";
36import { PullRequestMarkdown } from "./PullRequestMarkdown";
37import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
38import { PullRequestReactionBar } from "./PullRequestReactions";
39import type { PendingReviewComment } from "./pullRequestReviewStore";
40import {
41 PullRequestMarkdownTextarea,
42 type PullRequestCompletionScope,
43} from "./PullRequestMarkdownTextarea";
44​
45const CARD_CLASS =
46 "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm";
47​
48function submitKeys(input: {
49 readonly value: string;
50 readonly pending: boolean;
51 readonly allowEmpty?: boolean;
52 readonly onSubmit: () => void;
53 readonly onCancel?: (() => void) | undefined;
54}) {
55 return (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
56 if (event.key === "Escape" && input.onCancel) {
57 event.preventDefault();
58 input.onCancel();
59 }
60 if (isCommentSubmitShortcut(event, input.value, input.pending, input.allowEmpty)) {
61 event.preventDefault();
62 input.onSubmit();
63 }
64 };
66​
67export function toViewerSide(side: PullRequestDiffSide) {
68 return side === "left" ? ("deletions" as const) : ("additions" as const);
70​
71export function getReviewPositionAnchor(position: PullRequestReviewPosition): {
72 line: number;
73 side: PullRequestDiffSide;
74} {
75 switch (position.kind) {
76 case "added":
77 return { line: position.newLine, side: "right" };
78 case "deleted":
79 return { line: position.oldLine, side: "left" };
80 case "context":
81 return {
82 line: position.side === "left" ? position.oldLine : position.newLine,
83 side: position.side,
84 };
85 }
87​
88export function PendingReviewCommentCard({
89 comment,
90 onRemove,
91}: {
92 comment: PendingReviewComment;
93 onRemove: () => void;
94}) {
95 return (
96 <div
97 className={cn(CARD_CLASS, "border-dashed")}
98 contentEditable={false}
99 onPointerDown={(event) => event.stopPropagation()}
100 >
101 <div className="flex items-center gap-2 text-xs text-muted-foreground">
102 <MessageSquareIcon className="size-3.5" />
103 <span>Pending. Sent when you submit the review</span>
104 <Button
105 size="icon-xs"
106 variant="ghost"
107 className="ml-auto"
108 aria-label="Discard this comment"
109 onClick={onRemove}
110 >
111 <Trash2Icon className="size-3.5" />
112 </Button>
113 </div>
114 <p className="mt-2 whitespace-pre-wrap leading-relaxed">{comment.body}</p>
115 </div>
116 );
118​
119/** The conversations on one diff line. Resolved ones hide behind their authors' avatars. */
120export function InlineReviewThreads({
121 threads,
122 renderThread,
123}: {
124 threads: ReadonlyArray<PullRequestReviewThread>;
125 renderThread: (thread: PullRequestReviewThread, hidden: boolean) => ReactNode;
126}) {
127 const [shown, setShown] = useState<ReadonlySet<string>>(() => new Set());
128 // A conversation seen open stays shown once resolved, so it does not vanish under the reader.
129 const open = threads.filter((thread) => !thread.isResolved);
130 if (open.some((thread) => !shown.has(thread.id))) {
131 setShown(new Set([...shown, ...open.map((thread) => thread.id)]));
132 }
133 const resolved = threads.filter((thread) => thread.isResolved);
134 const expanded = resolved.every((thread) => shown.has(thread.id));
135 const authors = new Map<string, PullRequestActor | null>();
136 for (const comment of resolved.flatMap((thread) => thread.comments)) {
137 authors.set(comment.author?.login ?? "ghost", comment.author);
138 }
139 if (authors.size === 0) authors.set("ghost", null);
140 const label =
141 resolved.length === 1 ? "Resolved conversation" : `${resolved.length} resolved conversations`;
142 return (
143 <>
144 {resolved.length > 0 ? (
145 <Tooltip>
146 <TooltipTrigger
147 render={
148 <button
149 type="button"
150 data-resolved-threads
151 aria-label={label}
152 aria-expanded={expanded}
153 // Sits on the commented line, which is the row above this annotation.
154 className="absolute right-3 bottom-full flex h-[var(--diffs-line-height,20px)] cursor-pointer items-center -space-x-1 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
155 contentEditable={false}
156 onPointerDown={(event) => event.stopPropagation()}
157 onClick={() =>
158 setShown(new Set((expanded ? open : threads).map((thread) => thread.id)))
159 }
160 />
161 }
162 >
163 {[...authors].slice(0, 3).map(([login, author]) => (
164 <PullRequestActorAvatar
165 key={login}
166 actor={author}
167 className="ring-1 ring-background"
168 />
169 ))}
170 </TooltipTrigger>
171 <TooltipPopup side="left">{label}</TooltipPopup>
172 </Tooltip>
173 ) : null}
174 {threads.map((thread) => renderThread(thread, thread.isResolved && !shown.has(thread.id)))}
175 </>
176 );
178​
179export function ReviewThreadCard({
180 thread,
181 workspaceRoot,
182 canReply,
183 canResolve,
184 canReact,
185 environmentId,
186 reference,
187 completionScope,
188 pending,
189 fixPending,
190 fixLabel = "Fix in a thread",
191 onFix,
192 onAddToChat,
193 onReply,
194 onLoadMore,
195 canEditComment,
196 onEditComment,
197 onToggleResolved,
198 onReacted,
199 hidden,
200}: {
201 thread: PullRequestReviewThread;
202 workspaceRoot: string;
203 canReply: boolean;
204 canResolve: boolean;
205 canReact: boolean;
206 environmentId: EnvironmentId;
207 reference: PullRequestRef;
208 completionScope: PullRequestCompletionScope | null;
209 pending: boolean;
210 fixPending?: boolean;
211 fixLabel?: string;
212 onFix?: () => void;
213 /**
214 * Absent where there is no composer beside the panel to add the conversation to. Handed the
215 * thread with every comment the reader has loaded, not only the first page.
216 */
217 onAddToChat?: (thread: PullRequestReviewThread) => void;
218 onReply: (body: string) => Promise<boolean>;
219 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
220 canEditComment: (comment: PullRequestThreadComment) => boolean;
221 onEditComment: (commentId: string, body: string) => Promise<boolean>;
222 onToggleResolved: () => void;
223 onReacted: () => void;
224 /** Set on a diff line. Hidden draws nothing but stays mounted, so an unsent reply survives. */
225 hidden?: boolean;
226}) {
227 const [expanded, setExpanded] = useState(hidden !== undefined || !thread.isResolved);
228 const [replying, setReplying] = useState(false);
229 const [reply, setReply] = useState("");
230 const [editingId, setEditingId] = useState<string | null>(null);
231 const [savingEdit, setSavingEdit] = useState(false);
232 const sendingRef = useRef(false);
233 const replyRef = useRef<HTMLTextAreaElement>(null);
234 const [loadedPage, setLoadedPage] = useState<
235 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
236 >(null);
237 const [loadingMore, setLoadingMore] = useState(false);
238 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
239 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
240 const nextCommentsCursor =
241 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
242 const commentCount = thread.commentCount ?? comments.length;
243​
244 const saveEdit = async (commentId: string, body: string) => {
245 if (savingEdit) return;
246 setSavingEdit(true);
247 const saved = await onEditComment(commentId, body);
248 setSavingEdit(false);
249 if (saved) {
250 setLoadedPage((previous) =>
251 previous?.threadId === thread.id
252 ? {
253 ...previous,
254 comments: editPullRequestThreadComment(previous.comments, commentId, body),
255 }
256 : previous,
257 );
258 setEditingId(null);
259 }
260 };
261​
262 const send = async (text: string) => {
263 const trimmed = text.trim();
264 if (trimmed.length === 0 || pending || sendingRef.current) return;
265 sendingRef.current = true;
266 const result = await settlePromise(() => onReply(trimmed));
267 sendingRef.current = false;
268 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
269 if (!result.value) return;
270 // Replies return no comment; retain loaded data and reopen pagination for a later read.
271 setLoadedPage((previous) =>
272 previous?.threadId === thread.id
273 ? {
274 ...previous,
275 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
276 }
277 : previous,
278 );
279 setReply("");
280 setReplying(false);
281 };
282 const loadMore = async () => {
283 if (nextCommentsCursor === null || loadingMore) return;
284 setLoadingMore(true);
285 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
286 setLoadingMore(false);
287 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
288 const page = result.value;
289 if (page === null) return;
290 setLoadedPage((previous) => ({
291 threadId: thread.id,
292 comments: mergePullRequestThreadComments(
293 previous?.threadId === thread.id ? previous.comments : [],
294 page.comments,
295 ),
296 nextCursor: page.nextCursor,
297 }));
298 };
299​
300 if (hidden) return null;
301​
302 return (
303 <div
304 className={cn(CARD_CLASS, !expanded && "py-1")}
305 contentEditable={false}
306 onPointerDown={(event) => event.stopPropagation()}
307 >
308 <div className="flex items-center gap-2 text-xs text-muted-foreground">
309 {thread.isResolved ? (
310 <CircleCheckIcon className="size-3.5 text-success-foreground" />
311 ) : (
312 <CircleIcon className="size-3.5" />
313 )}
314 <button
315 type="button"
316 className="hover:text-foreground"
317 aria-expanded={expanded}
318 onClick={() => setExpanded((current) => !current)}
319 >
320 {thread.isResolved ? "Resolved" : "Open"} · {commentCount}{" "}
321 {commentCount === 1 ? "comment" : "comments"}
322 </button>
323 {thread.isOutdated ? <span>outdated</span> : null}
324 {onFix ? (
325 <Button
326 size="compact"
327 variant="ghost"
328 className="ml-auto"
329 disabled={pending || fixPending}
330 onClick={onFix}
331 >
332 <HammerIcon className="size-3" />
333 {fixPending ? "Preparing..." : fixLabel}
334 </Button>
335 ) : null}
336 {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
337 <Button
338 size="compact"
339 variant="ghost"
340 className={onFix ? undefined : "ml-auto"}
341 onClick={() => onAddToChat({ ...thread, comments })}
342 >
343 <MessageSquarePlusIcon className="size-3" />
344 Add to chat
345 </Button>
346 ) : null}
347 {canResolve ? (
348 <Button
349 size="compact"
350 variant="ghost"
351 className={onFix || onAddToChat ? undefined : "ml-auto"}
352 disabled={pending}
353 onClick={onToggleResolved}
354 >
355 {thread.isResolved ? "Unresolve" : "Resolve"}
356 </Button>
357 ) : null}
358 </div>
359​
360 {expanded ? (
361 <>
362 <div className="mt-2 space-y-3">
363 {comments.map((comment) => (
364 <article key={comment.id} className="group min-w-0">
365 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
366 <PullRequestActorLabel actor={comment.author} />
367 <span>
368 <RelativeTime timestamp={comment.createdAt} />
369 </span>
370 <PullRequestReactionBar
371 className="ml-auto justify-end"
372 reactions={comment.reactions ?? []}
373 canReact={canReact}
374 subjectId={comment.id}
375 environmentId={environmentId}
376 reference={reference}
377 onRefresh={onReacted}
378 />
379 </div>
380 {editingId === comment.id ? (
381 <PullRequestMarkdownEditor
382 className="mt-1"
383 value={comment.body}
384 cwd={workspaceRoot}
385 environmentId={environmentId}
386 completionScope={completionScope}
387 label="Edit comment"
388 saving={savingEdit}
389 onSave={(body) => void saveEdit(comment.id, body)}
390 onCancel={() => setEditingId(null)}
391 />
392 ) : (
393 <div className="mt-1 flex items-start gap-1">
394 <PullRequestMarkdown
395 className="min-w-0 flex-1 text-sm"
396 text={comment.body}
397 cwd={workspaceRoot}
398 environmentId={environmentId}
399 />
400 {canEditComment(comment) ? (
401 <PullRequestEditButton
402 aria-label="Edit comment"
403 onClick={() => setEditingId(comment.id)}
404 />
405 ) : null}
406 </div>
407 )}
408 </article>
409 ))}
410 </div>
411 {nextCommentsCursor !== null ? (
412 <div className="mt-2">
413 <Button
414 size="xs"
415 variant="ghost"
416 disabled={loadingMore}
417 onClick={() => void loadMore()}
418 >
419 {loadingMore ? "Loading..." : "Load more comments"}
420 </Button>
421 </div>
422 ) : null}
423​
424 {canReply ? (
425 replying ? (
426 <SpeechTextField
427 environmentId={environmentId}
428 projectId={reference.projectId}
429 ownerKey={JSON.stringify(["pr-reply", environmentId, reference, thread.id])}
430 text={reply}
431 textareaRef={replyRef}
432 onTextChange={setReply}
433 disabled={pending}
434 >
435 {(speech) => (
436 <div className="mt-2">
437 <PullRequestMarkdownTextarea
438 ref={replyRef}
439 readOnly={speech.freezesEditor}
440 autoFocus
441 size="sm"
442 completionScope={completionScope}
443 value={reply}
444 placeholder="Reply"
445 aria-label="Reply to this conversation"
446 onValueChange={setReply}
447 onKeyDown={submitKeys({
448 value: reply,
449 pending,
450 allowEmpty: speech.blocksSubmission,
451 onSubmit: () => speech.submitAfterDictation((text) => void send(text)),
452 onCancel: () =>
453 speech.state.phase === "idle" ? setReplying(false) : speech.cancel(),
454 })}
455 />
456 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
457 <TextFieldSpeechControls speech={speech} disabled={pending} />
458 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
459 Cancel
460 </Button>
461 <Button
462 size="xs"
463 disabled={
464 speech.preparing ||
465 pending ||
466 (!speech.blocksSubmission && reply.trim().length === 0)
467 }
468 onClick={() => speech.submitAfterDictation((text) => void send(text))}
469 >
470 Reply
471 </Button>
472 </div>
473 </div>
474 )}
475 </SpeechTextField>
476 ) : (
477 <Button size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
478 Reply
479 </Button>
480 )
481 ) : null}
482 </>
483 ) : null}
484 </div>
485 );