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