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

PullRequestReviewAnnotation.tsx

365 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 { formatRelativeTimeLabel } from "~/timestampFormat";
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>{formatRelativeTimeLabel(comment.createdAt)}</span>
270 <PullRequestReactionBar
271 className="ml-auto justify-end"
272 reactions={comment.reactions ?? []}
273 canReact={canReact}
274 subjectId={comment.id}
275 environmentId={environmentId}
276 reference={reference}
277 onRefresh={onReacted}
278 />
279 </div>
280 {editingId === comment.id ? (
281 <PullRequestMarkdownEditor
282 className="mt-1"
283 value={comment.body}
284 cwd={workspaceRoot}
285 environmentId={environmentId}
286 label="Edit comment"
287 saving={savingEdit}
288 onSave={(body) => void saveEdit(comment.id, body)}
289 onCancel={() => setEditingId(null)}
290 />
291 ) : (
292 <div className="mt-1 flex items-start gap-1">
293 <PullRequestMarkdown
294 className="min-w-0 flex-1 text-sm"
295 text={comment.body}
296 cwd={workspaceRoot}
297 environmentId={environmentId}
298 />
299 {canEditComment(comment) ? (
300 <PullRequestEditButton
301 aria-label="Edit comment"
302 onClick={() => setEditingId(comment.id)}
303 />
304 ) : null}
305 </div>
306 )}
307 </article>
308 ))}
309 </div>
310 {nextCommentsCursor !== null ? (
311 <div className="mt-2">
312 <Button
313 size="xs"
314 variant="ghost"
315 disabled={loadingMore}
316 onClick={() => void loadMore()}
317 >
318 {loadingMore ? "Loading..." : "Load more comments"}
319 </Button>
320 </div>
321 ) : null}
322​
323 {canReply ? (
324 replying ? (
325 <div className="mt-2">
326 <Textarea
327 autoFocus
328 size="sm"
329 value={reply}
330 placeholder="Reply"
331 aria-label="Reply to this conversation"
332 onChange={(event) => setReply(event.target.value)}
333 onKeyDown={(event) =>
334 submitKeys({
335 value: reply,
336 pending,
337 onSubmit: () => void send(),
338 onCancel: () => setReplying(false),
339 })(event)
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 );