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

PullRequestReviewAnnotation.tsx

366 lines12.0 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 // Replies return no comment; retain loaded data and reopen pagination for a later read.
186 setLoadedPage((previous) =>
187 previous?.threadId === thread.id
188 ? {
189 ...previous,
190 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
191 }
192 : previous,
193 );
194 setReply("");
195 setReplying(false);
196 };
197 const loadMore = async () => {
198 if (nextCommentsCursor === null || loadingMore) return;
199 setLoadingMore(true);
200 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
201 setLoadingMore(false);
202 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
203 const page = result.value;
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 };
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 <MorphIcon
223 className={cn("size-3.5", thread.isResolved && "text-success-foreground")}
224 icon={thread.isResolved ? CircleCheck : Circle}
225 />
226 <button
227 type="button"
228 className="hover:text-foreground"
229 aria-expanded={expanded}
230 onClick={() => setExpanded((current) => !current)}
231 >
232 {thread.isResolved ? "Resolved" : "Open"} · {commentCount}{" "}
233 {commentCount === 1 ? "comment" : "comments"}
234 </button>
235 {thread.isOutdated ? <span>outdated</span> : null}
236 {onFix ? (
237 <Button
238 size="xs"
239 variant="ghost"
240 className="ml-auto"
241 disabled={pending || fixPending}
242 onClick={onFix}
243 >
244 <HammerIcon className="size-3" />
245 {fixPending ? "Preparing..." : fixLabel}
246 </Button>
247 ) : null}
248 {canResolve ? (
249 <Button
250 size="xs"
251 variant="ghost"
252 className={onFix ? undefined : "ml-auto"}
253 disabled={pending}
254 onClick={onToggleResolved}
255 >
256 {thread.isResolved ? "Unresolve" : "Resolve"}
257 </Button>
258 ) : null}
259 </div>
260​
261 {expanded ? (
262 <>
263 <div className="mt-2 space-y-3">
264 {comments.map((comment) => (
265 <article key={comment.id} className="group min-w-0">
266 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
267 <PullRequestActorLabel actor={comment.author} />
268 <span>
269 <RelativeTime timestamp={comment.createdAt} />
270 </span>
271 <PullRequestReactionBar
272 className="ml-auto justify-end"
273 reactions={comment.reactions ?? []}
274 canReact={canReact}
275 subjectId={comment.id}
276 environmentId={environmentId}
277 reference={reference}
278 onRefresh={onReacted}
279 />
280 </div>
281 {editingId === comment.id ? (
282 <PullRequestMarkdownEditor
283 className="mt-1"
284 value={comment.body}
285 cwd={workspaceRoot}
286 environmentId={environmentId}
287 label="Edit comment"
288 saving={savingEdit}
289 onSave={(body) => void saveEdit(comment.id, body)}
290 onCancel={() => setEditingId(null)}
291 />
292 ) : (
293 <div className="mt-1 flex items-start gap-1">
294 <PullRequestMarkdown
295 className="min-w-0 flex-1 text-sm"
296 text={comment.body}
297 cwd={workspaceRoot}
298 environmentId={environmentId}
299 />
300 {canEditComment(comment) ? (
301 <PullRequestEditButton
302 aria-label="Edit comment"
303 onClick={() => setEditingId(comment.id)}
304 />
305 ) : null}
306 </div>
307 )}
308 </article>
309 ))}
310 </div>
311 {nextCommentsCursor !== null ? (
312 <div className="mt-2">
313 <Button
314 size="xs"
315 variant="ghost"
316 disabled={loadingMore}
317 onClick={() => void loadMore()}
318 >
319 {loadingMore ? "Loading..." : "Load more comments"}
320 </Button>
321 </div>
322 ) : null}
323​
324 {canReply ? (
325 replying ? (
326 <div className="mt-2">
327 <Textarea
328 autoFocus
329 size="sm"
330 value={reply}
331 placeholder="Reply"
332 aria-label="Reply to this conversation"
333 onChange={(event) => setReply(event.target.value)}
334 onKeyDown={(event) =>
335 submitKeys({
336 value: reply,
337 pending,
338 onSubmit: () => void send(),
339 onCancel: () => setReplying(false),
340 })(event)
341 }
342 />
343 <div className="mt-2 flex justify-end gap-2">
344 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
345 Cancel
346 </Button>
347 <Button
348 size="xs"
349 disabled={pending || reply.trim().length === 0}
350 onClick={() => void send()}
351 >
352 Reply
353 </Button>
354 </div>
355 </div>
356 ) : (
357 <Button size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
358 Reply
359 </Button>
360 )
361 ) : null}
362 </>
363 ) : null}
364 </div>
365 );