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

PullRequestReviewAnnotation.tsx

367 lines12.1 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";
13import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
14​
15import { RelativeTime } from "~/components/RelativeTime";
16import { cn } from "~/lib/utils";
17​
18import { Button } from "../ui/button";
19import { MorphIcon } from "~/components/MorphIcon";
20import { PullRequestEditButton } from "./PullRequestEditButton";
21import { Textarea } from "../ui/textarea";
22import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
23import {
24 editPullRequestThreadComment,
25 mergePullRequestThreadComments,
26} from "./pullRequestDetail.logic";
27import { PullRequestActorLabel } from "./pullRequestPresentation";
28import { PullRequestMarkdown } from "./PullRequestMarkdown";
29import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
30import { PullRequestReactionBar } from "./PullRequestReactions";
31import type { PendingReviewComment } from "./pullRequestReviewStore";
32​
33const CARD_CLASS =
34 "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm";
35​
36function submitKeys(input: {
37 readonly value: string;
38 readonly pending: boolean;
39 readonly onSubmit: () => void;
40 readonly onCancel?: (() => void) | undefined;
41}) {
42 return (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
43 if (event.key === "Escape" && input.onCancel) {
44 event.preventDefault();
45 input.onCancel();
46 }
47 if (isCommentSubmitShortcut(event, input.value, input.pending)) {
48 event.preventDefault();
49 input.onSubmit();
50 }
51 };
53​
54export function toViewerSide(side: PullRequestDiffSide) {
55 return side === "left" ? ("deletions" as const) : ("additions" as const);
57​
58export function getReviewPositionAnchor(position: PullRequestReviewPosition): {
59 line: number;
60 side: PullRequestDiffSide;
61} {
62 switch (position.kind) {
63 case "added":
64 return { line: position.newLine, side: "right" };
65 case "deleted":
66 return { line: position.oldLine, side: "left" };
67 case "context":
68 return {
69 line: position.side === "left" ? position.oldLine : position.newLine,
70 side: position.side,
71 };
72 }
74​
75export function PendingReviewCommentCard({
76 comment,
77 onRemove,
78}: {
79 comment: PendingReviewComment;
80 onRemove: () => void;
81}) {
82 return (
83 <div
84 className={cn(CARD_CLASS, "border-dashed")}
85 contentEditable={false}
86 onPointerDown={(event) => event.stopPropagation()}
87 >
88 <div className="flex items-center gap-2 text-xs text-muted-foreground">
89 <MessageSquareIcon className="size-3.5" />
90 <span>Pending — sent when you submit the review</span>
91 <Button
92 size="icon-xs"
93 variant="ghost"
94 className="ml-auto"
95 aria-label="Discard this comment"
96 onClick={onRemove}
97 >
98 <Trash2Icon className="size-3.5" />
99 </Button>
100 </div>
101 <p className="mt-2 whitespace-pre-wrap leading-relaxed">{comment.body}</p>
102 </div>
103 );
105​
106export function ReviewThreadCard({
107 thread,
108 workspaceRoot,
109 canReply,
110 canResolve,
111 canReact,
112 environmentId,
113 reference,
114 pending,
115 fixPending,
116 fixLabel = "Fix in a thread",
117 onFix,
118 onReply,
119 onLoadMore,
120 canEditComment,
121 onEditComment,
122 onToggleResolved,
123 onReacted,
124}: {
125 thread: PullRequestReviewThread;
126 workspaceRoot: string;
127 canReply: boolean;
128 canResolve: boolean;
129 canReact: boolean;
130 environmentId: EnvironmentId;
131 reference: PullRequestRef;
132 pending: boolean;
133 fixPending?: boolean;
134 fixLabel?: string;
135 onFix?: () => void;
136 onReply: (body: string) => Promise<boolean>;
137 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
138 canEditComment: (comment: PullRequestThreadComment) => boolean;
139 onEditComment: (commentId: string, body: string) => Promise<boolean>;
140 onToggleResolved: () => void;
141 onReacted: () => void;
142}) {
143 const [expanded, setExpanded] = useState(!thread.isResolved);
144 const [replying, setReplying] = useState(false);
145 const [reply, setReply] = useState("");
146 const [editingId, setEditingId] = useState<string | null>(null);
147 const [savingEdit, setSavingEdit] = useState(false);
148 const sendingRef = useRef(false);
149 const [loadedPage, setLoadedPage] = useState<
150 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
151 >(null);
152 const [loadingMore, setLoadingMore] = useState(false);
153 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
154 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
155 const nextCommentsCursor =
156 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
157 const commentCount = thread.commentCount ?? comments.length;
158​
159 const saveEdit = async (commentId: string, body: string) => {
160 if (savingEdit) return;
161 setSavingEdit(true);
162 const saved = await onEditComment(commentId, body);
163 setSavingEdit(false);
164 if (saved) {
165 setLoadedPage((previous) =>
166 previous?.threadId === thread.id
167 ? {
168 ...previous,
169 comments: editPullRequestThreadComment(previous.comments, commentId, body),
170 }
171 : previous,
172 );
173 setEditingId(null);
174 }
175 };
176​
177 const send = async () => {
178 const trimmed = reply.trim();
179 if (trimmed.length === 0 || pending || sendingRef.current) return;
180 sendingRef.current = true;
181 const result = await settlePromise(() => onReply(trimmed));
182 sendingRef.current = false;
183 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
184 if (!result.value) return;
185 // The mutation returns no comment. Keep what the reader loaded and reopen its cursor so
186 // the new reply remains reachable without spending requests until they ask to load it.
187 setLoadedPage((previous) =>
188 previous?.threadId === thread.id
189 ? {
190 ...previous,
191 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
192 }
193 : previous,
194 );
195 setReply("");
196 setReplying(false);
197 };
198 const loadMore = async () => {
199 if (nextCommentsCursor === null || loadingMore) return;
200 setLoadingMore(true);
201 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
202 setLoadingMore(false);
203 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
204 const page = result.value;
205 if (page === null) return;
206 setLoadedPage((previous) => ({
207 threadId: thread.id,
208 comments: mergePullRequestThreadComments(
209 previous?.threadId === thread.id ? previous.comments : [],
210 page.comments,
211 ),
212 nextCursor: page.nextCursor,
213 }));
214 };
215​
216 return (
217 <div
218 className={CARD_CLASS}
219 contentEditable={false}
220 onPointerDown={(event) => event.stopPropagation()}
221 >
222 <div className="flex items-center gap-2 text-xs text-muted-foreground">
223 <MorphIcon
224 className={cn("size-3.5", thread.isResolved && "text-success-foreground")}
225 icon={thread.isResolved ? CircleCheck : Circle}
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 flex-wrap items-center gap-2 text-xs text-muted-foreground">
268 <PullRequestActorLabel actor={comment.author} />
269 <span>
270 <RelativeTime timestamp={comment.createdAt} />
271 </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={(event) =>
336 submitKeys({
337 value: reply,
338 pending,
339 onSubmit: () => void send(),
340 onCancel: () => setReplying(false),
341 })(event)
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 size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
359 Reply
360 </Button>
361 )
362 ) : null}
363 </>
364 ) : null}
365 </div>
366 );