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

PullRequestReviewAnnotation.tsx

419 lines14.2 KB

1import type {
2 EnvironmentId,
3 PullRequestDiffSide,
4 PullRequestRef,
5 PullRequestReviewPosition,
6 PullRequestReviewThread,
7 PullRequestThreadCommentsResult,
8 PullRequestThreadComment,
9} from "@t3tools/contracts";
10import {
11 HammerIcon,
12 MessageSquareIcon,
13 MessageSquarePlusIcon,
14 Trash2Icon,
15 CircleCheckIcon,
16 CircleIcon,
17} from "lucide-react";
18import { useRef, useState } from "react";
19import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
20​
21import { RelativeTime } from "~/components/RelativeTime";
22import { cn } from "~/lib/utils";
23import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldSpeech";
24​
25import { Button } from "../ui/button";
26import { PullRequestEditButton } from "./PullRequestEditButton";
27import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
28import {
29 editPullRequestThreadComment,
30 mergePullRequestThreadComments,
31 visibleBody,
32} from "./pullRequestDetail.logic";
33import { PullRequestActorLabel } from "./pullRequestPresentation";
34import { PullRequestMarkdown } from "./PullRequestMarkdown";
35import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
36import { PullRequestReactionBar } from "./PullRequestReactions";
37import type { PendingReviewComment } from "./pullRequestReviewStore";
38import {
39 PullRequestMarkdownTextarea,
40 type PullRequestCompletionScope,
41} from "./PullRequestMarkdownTextarea";
42​
43const CARD_CLASS =
44 "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm";
45​
46function submitKeys(input: {
47 readonly value: string;
48 readonly pending: boolean;
49 readonly allowEmpty?: boolean;
50 readonly onSubmit: () => void;
51 readonly onCancel?: (() => void) | undefined;
52}) {
53 return (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
54 if (event.key === "Escape" && input.onCancel) {
55 event.preventDefault();
56 input.onCancel();
57 }
58 if (isCommentSubmitShortcut(event, input.value, input.pending, input.allowEmpty)) {
59 event.preventDefault();
60 input.onSubmit();
61 }
62 };
64​
65export function toViewerSide(side: PullRequestDiffSide) {
66 return side === "left" ? ("deletions" as const) : ("additions" as const);
68​
69export function getReviewPositionAnchor(position: PullRequestReviewPosition): {
70 line: number;
71 side: PullRequestDiffSide;
72} {
73 switch (position.kind) {
74 case "added":
75 return { line: position.newLine, side: "right" };
76 case "deleted":
77 return { line: position.oldLine, side: "left" };
78 case "context":
79 return {
80 line: position.side === "left" ? position.oldLine : position.newLine,
81 side: position.side,
82 };
83 }
85​
86export function PendingReviewCommentCard({
87 comment,
88 onRemove,
89}: {
90 comment: PendingReviewComment;
91 onRemove: () => void;
92}) {
93 return (
94 <div
95 className={cn(CARD_CLASS, "border-dashed")}
96 contentEditable={false}
97 onPointerDown={(event) => event.stopPropagation()}
98 >
99 <div className="flex items-center gap-2 text-xs text-muted-foreground">
100 <MessageSquareIcon className="size-3.5" />
101 <span>Pending. Sent when you submit the review</span>
102 <Button
103 size="icon-xs"
104 variant="ghost"
105 className="ml-auto"
106 aria-label="Discard this comment"
107 onClick={onRemove}
108 >
109 <Trash2Icon className="size-3.5" />
110 </Button>
111 </div>
112 <p className="mt-2 whitespace-pre-wrap leading-relaxed">{comment.body}</p>
113 </div>
114 );
116​
117export function ReviewThreadCard({
118 thread,
119 workspaceRoot,
120 canReply,
121 canResolve,
122 canReact,
123 environmentId,
124 reference,
125 completionScope,
126 pending,
127 fixPending,
128 fixLabel = "Fix in a thread",
129 onFix,
130 onAddToChat,
131 onReply,
132 onLoadMore,
133 canEditComment,
134 onEditComment,
135 onToggleResolved,
136 onReacted,
137}: {
138 thread: PullRequestReviewThread;
139 workspaceRoot: string;
140 canReply: boolean;
141 canResolve: boolean;
142 canReact: boolean;
143 environmentId: EnvironmentId;
144 reference: PullRequestRef;
145 completionScope: PullRequestCompletionScope | null;
146 pending: boolean;
147 fixPending?: boolean;
148 fixLabel?: string;
149 onFix?: () => void;
150 /**
151 * Absent where there is no composer beside the panel to add the conversation to. Handed the
152 * thread with every comment the reader has loaded, not only the first page.
153 */
154 onAddToChat?: (thread: PullRequestReviewThread) => void;
155 onReply: (body: string) => Promise<boolean>;
156 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
157 canEditComment: (comment: PullRequestThreadComment) => boolean;
158 onEditComment: (commentId: string, body: string) => Promise<boolean>;
159 onToggleResolved: () => void;
160 onReacted: () => void;
161}) {
162 const [expanded, setExpanded] = useState(!thread.isResolved);
163 const [replying, setReplying] = useState(false);
164 const [reply, setReply] = useState("");
165 const [editingId, setEditingId] = useState<string | null>(null);
166 const [savingEdit, setSavingEdit] = useState(false);
167 const sendingRef = useRef(false);
168 const replyRef = useRef<HTMLTextAreaElement>(null);
169 const [loadedPage, setLoadedPage] = useState<
170 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
171 >(null);
172 const [loadingMore, setLoadingMore] = useState(false);
173 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
174 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
175 const nextCommentsCursor =
176 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
177 const commentCount = thread.commentCount ?? comments.length;
178​
179 const saveEdit = async (commentId: string, body: string) => {
180 if (savingEdit) return;
181 setSavingEdit(true);
182 const saved = await onEditComment(commentId, body);
183 setSavingEdit(false);
184 if (saved) {
185 setLoadedPage((previous) =>
186 previous?.threadId === thread.id
187 ? {
188 ...previous,
189 comments: editPullRequestThreadComment(previous.comments, commentId, body),
190 }
191 : previous,
192 );
193 setEditingId(null);
194 }
195 };
196​
197 const send = async (text: string) => {
198 const trimmed = text.trim();
199 if (trimmed.length === 0 || pending || sendingRef.current) return;
200 sendingRef.current = true;
201 const result = await settlePromise(() => onReply(trimmed));
202 sendingRef.current = false;
203 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
204 if (!result.value) return;
205 // Replies return no comment; retain loaded data and reopen pagination for a later read.
206 setLoadedPage((previous) =>
207 previous?.threadId === thread.id
208 ? {
209 ...previous,
210 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
211 }
212 : previous,
213 );
214 setReply("");
215 setReplying(false);
216 };
217 const loadMore = async () => {
218 if (nextCommentsCursor === null || loadingMore) return;
219 setLoadingMore(true);
220 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
221 setLoadingMore(false);
222 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
223 const page = result.value;
224 if (page === null) return;
225 setLoadedPage((previous) => ({
226 threadId: thread.id,
227 comments: mergePullRequestThreadComments(
228 previous?.threadId === thread.id ? previous.comments : [],
229 page.comments,
230 ),
231 nextCursor: page.nextCursor,
232 }));
233 };
234​
235 return (
236 <div
237 className={cn(CARD_CLASS, !expanded && "py-1")}
238 contentEditable={false}
239 onPointerDown={(event) => event.stopPropagation()}
240 >
241 <div className="flex items-center gap-2 text-xs text-muted-foreground">
242 {thread.isResolved ? (
243 <CircleCheckIcon className="size-3.5 text-success-foreground" />
244 ) : (
245 <CircleIcon className="size-3.5" />
246 )}
247 <button
248 type="button"
249 className="hover:text-foreground"
250 aria-expanded={expanded}
251 onClick={() => setExpanded((current) => !current)}
252 >
253 {thread.isResolved ? "Resolved" : "Open"} · {commentCount}{" "}
254 {commentCount === 1 ? "comment" : "comments"}
255 </button>
256 {thread.isOutdated ? <span>outdated</span> : null}
257 {onFix ? (
258 <Button
259 size="compact"
260 variant="ghost"
261 className="ml-auto"
262 disabled={pending || fixPending}
263 onClick={onFix}
264 >
265 <HammerIcon className="size-3" />
266 {fixPending ? "Preparing..." : fixLabel}
267 </Button>
268 ) : null}
269 {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
270 <Button
271 size="compact"
272 variant="ghost"
273 className={onFix ? undefined : "ml-auto"}
274 onClick={() => onAddToChat({ ...thread, comments })}
275 >
276 <MessageSquarePlusIcon className="size-3" />
277 Add to chat
278 </Button>
279 ) : null}
280 {canResolve ? (
281 <Button
282 size="compact"
283 variant="ghost"
284 className={onFix || onAddToChat ? undefined : "ml-auto"}
285 disabled={pending}
286 onClick={onToggleResolved}
287 >
288 {thread.isResolved ? "Unresolve" : "Resolve"}
289 </Button>
290 ) : null}
291 </div>
292​
293 {expanded ? (
294 <>
295 <div className="mt-2 space-y-3">
296 {comments.map((comment) => (
297 <article key={comment.id} className="group min-w-0">
298 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
299 <PullRequestActorLabel actor={comment.author} />
300 <span>
301 <RelativeTime timestamp={comment.createdAt} />
302 </span>
303 <PullRequestReactionBar
304 className="ml-auto justify-end"
305 reactions={comment.reactions ?? []}
306 canReact={canReact}
307 subjectId={comment.id}
308 environmentId={environmentId}
309 reference={reference}
310 onRefresh={onReacted}
311 />
312 </div>
313 {editingId === comment.id ? (
314 <PullRequestMarkdownEditor
315 className="mt-1"
316 value={comment.body}
317 cwd={workspaceRoot}
318 environmentId={environmentId}
319 completionScope={completionScope}
320 label="Edit comment"
321 saving={savingEdit}
322 onSave={(body) => void saveEdit(comment.id, body)}
323 onCancel={() => setEditingId(null)}
324 />
325 ) : (
326 <div className="mt-1 flex items-start gap-1">
327 <PullRequestMarkdown
328 className="min-w-0 flex-1 text-sm"
329 text={comment.body}
330 cwd={workspaceRoot}
331 environmentId={environmentId}
332 />
333 {canEditComment(comment) ? (
334 <PullRequestEditButton
335 aria-label="Edit comment"
336 onClick={() => setEditingId(comment.id)}
337 />
338 ) : null}
339 </div>
340 )}
341 </article>
342 ))}
343 </div>
344 {nextCommentsCursor !== null ? (
345 <div className="mt-2">
346 <Button
347 size="xs"
348 variant="ghost"
349 disabled={loadingMore}
350 onClick={() => void loadMore()}
351 >
352 {loadingMore ? "Loading..." : "Load more comments"}
353 </Button>
354 </div>
355 ) : null}
356​
357 {canReply ? (
358 replying ? (
359 <SpeechTextField
360 environmentId={environmentId}
361 projectId={reference.projectId}
362 ownerKey={JSON.stringify(["pr-reply", environmentId, reference, thread.id])}
363 text={reply}
364 textareaRef={replyRef}
365 onTextChange={setReply}
366 disabled={pending}
367 >
368 {(speech) => (
369 <div className="mt-2">
370 <PullRequestMarkdownTextarea
371 ref={replyRef}
372 readOnly={speech.freezesEditor}
373 autoFocus
374 size="sm"
375 completionScope={completionScope}
376 value={reply}
377 placeholder="Reply"
378 aria-label="Reply to this conversation"
379 onValueChange={setReply}
380 onKeyDown={submitKeys({
381 value: reply,
382 pending,
383 allowEmpty: speech.blocksSubmission,
384 onSubmit: () => speech.submitAfterDictation((text) => void send(text)),
385 onCancel: () =>
386 speech.state.phase === "idle" ? setReplying(false) : speech.cancel(),
387 })}
388 />
389 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
390 <TextFieldSpeechControls speech={speech} disabled={pending} />
391 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
392 Cancel
393 </Button>
394 <Button
395 size="xs"
396 disabled={
397 speech.preparing ||
398 pending ||
399 (!speech.blocksSubmission && reply.trim().length === 0)
400 }
401 onClick={() => speech.submitAfterDictation((text) => void send(text))}
402 >
403 Reply
404 </Button>
405 </div>
406 </div>
407 )}
408 </SpeechTextField>
409 ) : (
410 <Button size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
411 Reply
412 </Button>
413 )
414 ) : null}
415 </>
416 ) : null}
417 </div>
418 );