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

PullRequestReviewAnnotation.tsx

372 lines12.5 KB

1/**
2 * Pull-request-specific annotations: conversations already on the host and comments queued for
3 * the review being written. New comment composition uses the shared diff annotation.
4 */
5import type {
6 EnvironmentId,
7 PullRequestRef,
8 PullRequestReviewThread,
9 PullRequestThreadCommentsResult,
10 PullRequestThreadComment,
11} from "@t3tools/contracts";
12import {
13 CheckCircle2Icon,
14 CircleIcon,
15 HammerIcon,
16 MessageSquareIcon,
17 PencilIcon,
18 Trash2Icon,
19} from "lucide-react";
20import { useRef, useState } from "react";
21​
22import { formatRelativeTimeLabel } from "~/timestampFormat";
23import { cn } from "~/lib/utils";
24​
25import { Button } from "../ui/button";
26import { Textarea } from "../ui/textarea";
27import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
28import {
29 editPullRequestThreadComment,
30 mergePullRequestThreadComments,
31} from "./pullRequestDetail.logic";
32import { PullRequestActorLabel } from "./pullRequestPresentation";
33import { PullRequestMarkdown } from "./PullRequestMarkdown";
34import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
35import { PullRequestReactionBar } from "./PullRequestReactions";
36import type { PendingReviewComment } from "./pullRequestReviewStore";
37​
38const CARD_CLASS =
39 "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm";
40​
41/** Sends a reply on ⌘/Ctrl+Enter and abandons it on Escape. */
42function submitKeys(input: {
43 readonly value: string;
44 readonly pending: boolean;
45 readonly onSubmit: () => void;
46 readonly onCancel?: (() => void) | undefined;
47}) {
48 return (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
49 if (event.key === "Escape" && input.onCancel) {
50 event.preventDefault();
51 input.onCancel();
52 }
53 if (isCommentSubmitShortcut(event, input.value, input.pending)) {
54 event.preventDefault();
55 input.onSubmit();
56 }
57 };
59​
60/** A comment waiting to be sent with the rest of the review. */
61export function PendingReviewCommentCard({
62 comment,
63 onRemove,
64}: {
65 comment: PendingReviewComment;
66 onRemove: () => void;
67}) {
68 return (
69 <div
70 className={cn(CARD_CLASS, "border-dashed")}
71 contentEditable={false}
72 onPointerDown={(event) => event.stopPropagation()}
73 >
74 <div className="flex items-center gap-2 text-xs text-muted-foreground">
75 <MessageSquareIcon className="size-3.5" />
76 <span>Pending — sent when you submit the review</span>
77 <Button
78 size="icon-xs"
79 variant="ghost"
80 className="ml-auto"
81 aria-label="Discard this comment"
82 onClick={onRemove}
83 >
84 <Trash2Icon className="size-3.5" />
85 </Button>
86 </div>
87 <p className="mt-2 whitespace-pre-wrap leading-relaxed">{comment.body}</p>
88 </div>
89 );
91​
92/** A conversation already on the host, with whatever this host lets the reader do to it. */
93export function ReviewThreadCard({
94 thread,
95 workspaceRoot,
96 canReply,
97 canResolve,
98 canReact,
99 environmentId,
100 reference,
101 pending,
102 fixPending,
103 fixLabel = "Fix in a thread",
104 onFix,
105 onReply,
106 onLoadMore,
107 canEditComment,
108 onEditComment,
109 onToggleResolved,
110 onReacted,
111}: {
112 thread: PullRequestReviewThread;
113 workspaceRoot: string;
114 canReply: boolean;
115 canResolve: boolean;
116 canReact: boolean;
117 environmentId: EnvironmentId;
118 reference: PullRequestRef;
119 pending: boolean;
120 /** True while this thread's own hand-off is preparing, so only its button says so. */
121 fixPending?: boolean;
122 fixLabel?: string;
123 /** Absent where a thread is shown outside the pull request page's reach. */
124 onFix?: () => void;
125 /** Resolves to whether the host took it, so a reply that failed keeps the words it was given. */
126 onReply: (body: string) => Promise<boolean>;
127 /** Reads one more page only after the reader asks for it. */
128 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
129 /** Whether this reader wrote this remark, which is what rewriting one takes. */
130 canEditComment: (comment: PullRequestThreadComment) => boolean;
131 /** Resolves to whether the host took it, like `onReply`. */
132 onEditComment: (commentId: string, body: string) => Promise<boolean>;
133 onToggleResolved: () => void;
134 onReacted: () => void;
135}) {
136 // A resolved thread is finished work, so it opens collapsed and stays one line until asked for.
137 const [expanded, setExpanded] = useState(!thread.isResolved);
138 const [replying, setReplying] = useState(false);
139 const [reply, setReply] = useState("");
140 const [editingId, setEditingId] = useState<string | null>(null);
141 const [savingEdit, setSavingEdit] = useState(false);
142 const sendingRef = useRef(false);
143 const [loadedPage, setLoadedPage] = useState<
144 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
145 >(null);
146 const [loadingMore, setLoadingMore] = useState(false);
147 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
148 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
149 const nextCommentsCursor =
150 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
151 const commentCount = thread.commentCount ?? comments.length;
152​
153 const saveEdit = async (commentId: string, body: string) => {
154 if (savingEdit) return;
155 setSavingEdit(true);
156 const saved = await onEditComment(commentId, body);
157 setSavingEdit(false);
158 if (saved) {
159 setLoadedPage((previous) =>
160 previous?.threadId === thread.id
161 ? {
162 ...previous,
163 comments: editPullRequestThreadComment(previous.comments, commentId, body),
164 }
165 : previous,
166 );
167 setEditingId(null);
168 }
169 };
170​
171 const send = async () => {
172 const trimmed = reply.trim();
173 if (trimmed.length === 0 || pending || sendingRef.current) return;
174 sendingRef.current = true;
175 // Cleared only once the host has it. Otherwise a failed reply leaves an error toast and an
176 // empty box, and the words have to be written again.
177 try {
178 if (await onReply(trimmed)) {
179 // The mutation returns no comment. Keep what the reader loaded and reopen its cursor so
180 // the new reply remains reachable without spending requests until they ask to load it.
181 setLoadedPage((previous) =>
182 previous?.threadId === thread.id
183 ? {
184 ...previous,
185 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
186 }
187 : previous,
188 );
189 setReply("");
190 setReplying(false);
191 }
192 } finally {
193 sendingRef.current = false;
194 }
195 };
196 const loadMore = async () => {
197 if (nextCommentsCursor === null || loadingMore) return;
198 setLoadingMore(true);
199 try {
200 const page = await onLoadMore(nextCommentsCursor);
201 if (page === null) return;
202 setLoadedPage((previous) => ({
203 threadId: thread.id,
204 comments: mergePullRequestThreadComments(
205 previous?.threadId === thread.id ? previous.comments : [],
206 page.comments,
207 ),
208 nextCursor: page.nextCursor,
209 }));
210 } finally {
211 setLoadingMore(false);
212 }
213 };
214​
215 return (
216 <div
217 className={CARD_CLASS}
218 contentEditable={false}
219 onPointerDown={(event) => event.stopPropagation()}
220 >
221 <div className="flex items-center gap-2 text-xs text-muted-foreground">
222 {thread.isResolved ? (
223 <CheckCircle2Icon className="size-3.5 text-emerald-600 dark:text-emerald-500" />
224 ) : (
225 <CircleIcon className="size-3.5" />
226 )}
227 <button
228 type="button"
229 className="hover:text-foreground"
230 aria-expanded={expanded}
231 onClick={() => setExpanded((current) => !current)}
232 >
233 {thread.isResolved ? "Resolved" : "Open"} · {commentCount}{" "}
234 {commentCount === 1 ? "comment" : "comments"}
235 </button>
236 {thread.isOutdated ? <span>outdated</span> : null}
237 {onFix ? (
238 <Button
239 size="xs"
240 variant="ghost"
241 className="ml-auto"
242 disabled={pending || fixPending}
243 onClick={onFix}
244 >
245 <HammerIcon className="size-3" />
246 {fixPending ? "Preparing..." : fixLabel}
247 </Button>
248 ) : null}
249 {canResolve ? (
250 <Button
251 size="xs"
252 variant="ghost"
253 className={onFix ? undefined : "ml-auto"}
254 disabled={pending}
255 onClick={onToggleResolved}
256 >
257 {thread.isResolved ? "Unresolve" : "Resolve"}
258 </Button>
259 ) : null}
260 </div>
261​
262 {expanded ? (
263 <>
264 <div className="mt-2 space-y-3">
265 {comments.map((comment) => (
266 <article key={comment.id} className="group min-w-0">
267 <div className="flex items-center gap-2 text-xs text-muted-foreground">
268 <PullRequestActorLabel actor={comment.author} className="text-foreground" />
269 <span>{formatRelativeTimeLabel(comment.createdAt)}</span>
270 </div>
271 {editingId === comment.id ? (
272 <PullRequestMarkdownEditor
273 className="mt-1"
274 value={comment.body}
275 cwd={workspaceRoot}
276 label="Edit comment"
277 saving={savingEdit}
278 onSave={(body) => void saveEdit(comment.id, body)}
279 onCancel={() => setEditingId(null)}
280 />
281 ) : (
282 <div className="mt-1 flex items-start gap-1">
283 <PullRequestMarkdown
284 className="min-w-0 flex-1 text-sm"
285 text={comment.body}
286 cwd={workspaceRoot}
287 />
288 {canEditComment(comment) ? (
289 <Button
290 size="icon-xs"
291 variant="ghost"
292 className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
293 aria-label="Edit comment"
294 onClick={() => setEditingId(comment.id)}
295 >
296 <PencilIcon className="size-3" />
297 </Button>
298 ) : null}
299 </div>
300 )}
301 <PullRequestReactionBar
302 className="mt-1.5"
303 reactions={comment.reactions ?? []}
304 canReact={canReact}
305 subjectId={comment.id}
306 environmentId={environmentId}
307 reference={reference}
308 onRefresh={onReacted}
309 />
310 </article>
311 ))}
312 </div>
313 {nextCommentsCursor !== null ? (
314 <div className="mt-2">
315 <Button
316 size="xs"
317 variant="ghost"
318 className="px-1"
319 disabled={loadingMore}
320 onClick={() => void loadMore()}
321 >
322 {loadingMore ? "Loading..." : "Load more comments"}
323 </Button>
324 </div>
325 ) : null}
326​
327 {canReply ? (
328 replying ? (
329 <div className="mt-2">
330 <Textarea
331 autoFocus
332 size="sm"
333 value={reply}
334 placeholder="Reply"
335 aria-label="Reply to this conversation"
336 onChange={(event) => setReply(event.target.value)}
337 onKeyDown={submitKeys({
338 value: reply,
339 pending,
340 onSubmit: () => void send(),
341 onCancel: () => setReplying(false),
342 })}
343 />
344 <div className="mt-2 flex justify-end gap-2">
345 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
346 Cancel
347 </Button>
348 <Button
349 size="xs"
350 disabled={pending || reply.trim().length === 0}
351 onClick={() => void send()}
352 >
353 Reply
354 </Button>
355 </div>
356 </div>
357 ) : (
358 <Button
359 size="xs"
360 variant="ghost"
361 className="mt-2 px-1"
362 onClick={() => setReplying(true)}
363 >
364 Reply
365 </Button>
366 )
367 ) : null}
368 </>
369 ) : null}
370 </div>
371 );