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

PullRequestReviewAnnotation.tsx

365 lines11.8 KB

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