Open History to see the last commit
1import type {
2 EnvironmentId,
3 PullRequestActor,
4 PullRequestDiffSide,
5 PullRequestRef,
6 PullRequestReviewPosition,
7 PullRequestReviewThread,
8 PullRequestThreadCommentsResult,
9 PullRequestThreadComment,
10} from "@t3tools/contracts";
11import {
12 HammerIcon,
13 MessageSquareIcon,
14 MessageSquarePlusIcon,
15 Trash2Icon,
16 CircleCheckIcon,
17 CircleIcon,
18} from "lucide-react";
19import { T, useGT } from "gt-react";
20import { type ReactNode, useRef, useState } from "react";
21import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
22
23import { RelativeTime } from "~/components/RelativeTime";
24import { cn } from "~/lib/utils";
25import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldSpeech";
26
27import { Button } from "../ui/button";
28import { PullRequestEditButton } from "./PullRequestEditButton";
29import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
30import {
31 editPullRequestThreadComment,
32 mergePullRequestThreadComments,
33 visibleBody,
34} from "./pullRequestDetail.logic";
35import { PullRequestActorAvatar, PullRequestActorLabel } from "./pullRequestPresentation";
36import { PullRequestMarkdown } from "./PullRequestMarkdown";
37import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
38import { PullRequestReactionBar } from "./PullRequestReactions";
39import type { PendingReviewComment } from "./pullRequestReviewStore";
40import {
41 PullRequestMarkdownTextarea,
42 type PullRequestCompletionScope,
43} from "./PullRequestMarkdownTextarea";
44import { SharedTooltipTrigger } from "../ui/shared-tooltip";
45
46const CARD_CLASS =
47 "mx-3 my-2 rounded-xl border border-border/70 bg-background p-3 text-sm shadow-sm";
48
49function submitKeys(input: {
50 readonly value: string;
51 readonly pending: boolean;
52 readonly allowEmpty?: boolean;
53 readonly onSubmit: () => void;
54 readonly onCancel?: (() => void) | undefined;
55}) {
56 return (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
57 // Unclaimed, an IME Escape would reach the pull requests page and leave it.
58 if (event.nativeEvent.isComposing || event.keyCode === 229) {
59 event.stopPropagation();
60 return;
61 }
62 if (event.key === "Escape" && input.onCancel) {
63 event.preventDefault();
64 event.stopPropagation();
65 input.onCancel();
66 }
67 if (isCommentSubmitShortcut(event, input.value, input.pending, input.allowEmpty)) {
68 event.preventDefault();
69 input.onSubmit();
70 }
71 };
72}
73
74export function toViewerSide(side: PullRequestDiffSide) {
75 return side === "left" ? ("deletions" as const) : ("additions" as const);
76}
77
78export function getReviewPositionAnchor(position: PullRequestReviewPosition): {
79 line: number;
80 side: PullRequestDiffSide;
81} {
82 switch (position.kind) {
83 case "added":
84 return { line: position.newLine, side: "right" };
85 case "deleted":
86 return { line: position.oldLine, side: "left" };
87 case "context":
88 return {
89 line: position.side === "left" ? position.oldLine : position.newLine,
90 side: position.side,
91 };
92 }
93}
94
95export function PendingReviewCommentCard({
96 comment,
97 onRemove,
98}: {
99 comment: PendingReviewComment;
100 onRemove: () => void;
101}) {
102 const gt = useGT();
103 return (
104 <div
105 className={cn(CARD_CLASS, "border-dashed")}
106 contentEditable={false}
107 onPointerDown={(event) => event.stopPropagation()}
108 >
109 <div className="flex items-center gap-2 text-xs text-muted-foreground">
110 <MessageSquareIcon className="size-3.5" />
111 <span>
112 <T>Pending. Sent when you submit the review</T>
113 </span>
114 <Button
115 size="icon-xs"
116 variant="ghost"
117 className="ml-auto"
118 aria-label={gt("Discard this comment")}
119 onClick={onRemove}
120 >
121 <Trash2Icon className="size-3.5" />
122 </Button>
123 </div>
124 <p className="mt-2 whitespace-pre-wrap leading-relaxed">{comment.body}</p>
125 </div>
126 );
127}
128
129/** The conversations on one diff line. Resolved ones hide behind their authors' avatars. */
130export function InlineReviewThreads({
131 threads,
132 renderThread,
133}: {
134 threads: ReadonlyArray<PullRequestReviewThread>;
135 renderThread: (thread: PullRequestReviewThread, hidden: boolean) => ReactNode;
136}) {
137 const gt = useGT();
138 const [shown, setShown] = useState<ReadonlySet<string>>(() => new Set());
139 // A conversation seen open stays shown once resolved, so it does not vanish under the reader.
140 const open = threads.filter((thread) => !thread.isResolved);
141 if (open.some((thread) => !shown.has(thread.id))) {
142 setShown(new Set([...shown, ...open.map((thread) => thread.id)]));
143 }
144 const resolved = threads.filter((thread) => thread.isResolved);
145 const expanded = resolved.every((thread) => shown.has(thread.id));
146 const authors = new Map<string, PullRequestActor | null>();
147 for (const comment of resolved.flatMap((thread) => thread.comments)) {
148 authors.set(comment.author?.login ?? "ghost", comment.author);
149 }
150 if (authors.size === 0) authors.set("ghost", null);
151 const label = gt(
152 "{count, plural, =1 {Resolved conversation} other {{count} resolved conversations}}",
153 { count: resolved.length },
154 );
155 return (
156 <>
157 {resolved.length > 0 ? (
158 <SharedTooltipTrigger
159 render={
160 <button
161 type="button"
162 data-resolved-threads
163 aria-label={label}
164 aria-expanded={expanded}
165 // Sits on the commented line, which is the row above this annotation.
166 className="absolute right-3 bottom-full flex h-[var(--diffs-line-height,20px)] cursor-pointer items-center -space-x-1 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
167 contentEditable={false}
168 onPointerDown={(event) => event.stopPropagation()}
169 onClick={() =>
170 setShown(new Set((expanded ? open : threads).map((thread) => thread.id)))
171 }
172 />
173 }
174 label={label}
175 side="left"
176 >
177 {[...authors].slice(0, 3).map(([login, author]) => (
178 <PullRequestActorAvatar key={login} actor={author} className="ring-1 ring-background" />
179 ))}
180 </SharedTooltipTrigger>
181 ) : null}
182 {threads.map((thread) => renderThread(thread, thread.isResolved && !shown.has(thread.id)))}
183 </>
184 );
185}
186
187export function ReviewThreadCard({
188 thread,
189 workspaceRoot,
190 canReply,
191 canResolve,
192 canReact,
193 environmentId,
194 reference,
195 completionScope,
196 pending,
197 fixPending,
198 fixLabel,
199 onFix,
200 onAddToChat,
201 onReply,
202 onLoadMore,
203 canEditComment,
204 onEditComment,
205 onToggleResolved,
206 onReacted,
207 hidden,
208}: {
209 thread: PullRequestReviewThread;
210 workspaceRoot: string;
211 canReply: boolean;
212 canResolve: boolean;
213 canReact: boolean;
214 environmentId: EnvironmentId;
215 reference: PullRequestRef;
216 completionScope: PullRequestCompletionScope | null;
217 pending: boolean;
218 fixPending?: boolean;
219 fixLabel?: string;
220 onFix?: () => void;
221 /**
222 * Absent where there is no composer beside the panel to add the conversation to. Handed the
223 * thread with every comment the reader has loaded, not only the first page.
224 */
225 onAddToChat?: (thread: PullRequestReviewThread) => void;
226 onReply: (body: string) => Promise<boolean>;
227 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
228 canEditComment: (comment: PullRequestThreadComment) => boolean;
229 onEditComment: (commentId: string, body: string) => Promise<boolean>;
230 onToggleResolved: () => void;
231 onReacted: () => void;
232 /** Set on a diff line. Hidden draws nothing but stays mounted, so an unsent reply survives. */
233 hidden?: boolean;
234}) {
235 const gt = useGT();
236 const [expanded, setExpanded] = useState(hidden !== undefined || !thread.isResolved);
237 const [replying, setReplying] = useState(false);
238 const [reply, setReply] = useState("");
239 const [editingId, setEditingId] = useState<string | null>(null);
240 const [savingEdit, setSavingEdit] = useState(false);
241 const sendingRef = useRef(false);
242 const replyRef = useRef<HTMLTextAreaElement>(null);
243 const [loadedPage, setLoadedPage] = useState<
244 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
245 >(null);
246 const [loadingMore, setLoadingMore] = useState(false);
247 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
248 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
249 const nextCommentsCursor =
250 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
251 const commentCount = thread.commentCount ?? comments.length;
252
253 const saveEdit = async (commentId: string, body: string) => {
254 if (savingEdit) return;
255 setSavingEdit(true);
256 const saved = await onEditComment(commentId, body);
257 setSavingEdit(false);
258 if (saved) {
259 setLoadedPage((previous) =>
260 previous?.threadId === thread.id
261 ? {
262 ...previous,
263 comments: editPullRequestThreadComment(previous.comments, commentId, body),
264 }
265 : previous,
266 );
267 setEditingId(null);
268 }
269 };
270
271 const send = async (text: string) => {
272 const trimmed = text.trim();
273 if (trimmed.length === 0 || pending || sendingRef.current) return;
274 sendingRef.current = true;
275 const result = await settlePromise(() => onReply(trimmed));
276 sendingRef.current = false;
277 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
278 if (!result.value) return;
279 // Replies return no comment; retain loaded data and reopen pagination for a later read.
280 setLoadedPage((previous) =>
281 previous?.threadId === thread.id
282 ? {
283 ...previous,
284 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
285 }
286 : previous,
287 );
288 setReply("");
289 setReplying(false);
290 };
291 const loadMore = async () => {
292 if (nextCommentsCursor === null || loadingMore) return;
293 setLoadingMore(true);
294 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
295 setLoadingMore(false);
296 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
297 const page = result.value;
298 if (page === null) return;
299 setLoadedPage((previous) => ({
300 threadId: thread.id,
301 comments: mergePullRequestThreadComments(
302 previous?.threadId === thread.id ? previous.comments : [],
303 page.comments,
304 ),
305 nextCursor: page.nextCursor,
306 }));
307 };
308
309 if (hidden) return null;
310
311 return (
312 <div
313 className={cn(CARD_CLASS, !expanded && "py-1")}
314 contentEditable={false}
315 onPointerDown={(event) => event.stopPropagation()}
316 >
317 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
318 {thread.isResolved ? (
319 <CircleCheckIcon className="size-3.5 text-success-foreground" />
320 ) : (
321 <CircleIcon className="size-3.5" />
322 )}
323 <button
324 type="button"
325 className="hover:text-foreground"
326 aria-expanded={expanded}
327 onClick={() => setExpanded((current) => !current)}
328 >
329 {thread.isResolved
330 ? gt("Resolved", { $context: "review thread state" })
331 : gt("Open", { $context: "review thread state" })}{" "}
332 ·{" "}
333 {gt("{count, plural, one {{count} comment} other {{count} comments}}", {
334 count: commentCount,
335 })}
336 </button>
337 {thread.isOutdated ? (
338 <span>
339 <T context="review thread state">Outdated</T>
340 </span>
341 ) : null}
342 {onFix ? (
343 <Button
344 size="compact"
345 variant="ghost"
346 className="ml-auto"
347 disabled={pending || fixPending}
348 onClick={onFix}
349 >
350 <HammerIcon className="size-3" />
351 {fixPending ? gt("Preparing...") : (fixLabel ?? gt("Fix in a thread"))}
352 </Button>
353 ) : null}
354 {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
355 <Button
356 size="compact"
357 variant="ghost"
358 className={onFix ? undefined : "ml-auto"}
359 onClick={() => onAddToChat({ ...thread, comments })}
360 >
361 <MessageSquarePlusIcon className="size-3" />
362 <T>Add to chat</T>
363 </Button>
364 ) : null}
365 {canResolve ? (
366 <Button
367 size="compact"
368 variant="ghost"
369 className={onFix || onAddToChat ? undefined : "ml-auto"}
370 disabled={pending}
371 onClick={onToggleResolved}
372 >
373 {thread.isResolved ? gt("Unresolve") : gt("Resolve")}
374 </Button>
375 ) : null}
376 </div>
377
378 {expanded ? (
379 <>
380 <div className="mt-2 space-y-3">
381 {comments.map((comment) => (
382 <article key={comment.id} className="group min-w-0">
383 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
384 <PullRequestActorLabel actor={comment.author} />
385 <span>
386 <RelativeTime timestamp={comment.createdAt} />
387 </span>
388 <PullRequestReactionBar
389 className="ml-auto justify-end"
390 reactions={comment.reactions ?? []}
391 canReact={canReact}
392 subjectId={comment.id}
393 environmentId={environmentId}
394 reference={reference}
395 onRefresh={onReacted}
396 />
397 </div>
398 {editingId === comment.id ? (
399 <PullRequestMarkdownEditor
400 className="mt-1"
401 value={comment.body}
402 cwd={workspaceRoot}
403 environmentId={environmentId}
404 completionScope={completionScope}
405 label={gt("Edit comment")}
406 saving={savingEdit}
407 onSave={(body) => void saveEdit(comment.id, body)}
408 onCancel={() => setEditingId(null)}
409 />
410 ) : (
411 <div className="mt-1 flex items-start gap-1">
412 <PullRequestMarkdown
413 className="min-w-0 flex-1 text-sm"
414 text={comment.body}
415 cwd={workspaceRoot}
416 environmentId={environmentId}
417 />
418 {canEditComment(comment) ? (
419 <PullRequestEditButton
420 aria-label={gt("Edit comment")}
421 onClick={() => setEditingId(comment.id)}
422 />
423 ) : null}
424 </div>
425 )}
426 </article>
427 ))}
428 </div>
429 {nextCommentsCursor !== null ? (
430 <div className="mt-2">
431 <Button
432 size="xs"
433 variant="ghost"
434 disabled={loadingMore}
435 onClick={() => void loadMore()}
436 >
437 {loadingMore ? gt("Loading...") : gt("Load more comments")}
438 </Button>
439 </div>
440 ) : null}
441
442 {canReply ? (
443 replying ? (
444 <SpeechTextField
445 environmentId={environmentId}
446 projectId={reference.projectId}
447 ownerKey={JSON.stringify(["pr-reply", environmentId, reference, thread.id])}
448 text={reply}
449 textareaRef={replyRef}
450 onTextChange={setReply}
451 disabled={pending}
452 >
453 {(speech) => (
454 <div className="mt-2">
455 <PullRequestMarkdownTextarea
456 ref={replyRef}
457 readOnly={speech.freezesEditor}
458 autoFocus
459 size="sm"
460 completionScope={completionScope}
461 value={reply}
462 placeholder={gt("Reply", { $context: "noun, placeholder" })}
463 aria-label={gt("Reply to this conversation")}
464 onValueChange={setReply}
465 onKeyDown={submitKeys({
466 value: reply,
467 pending,
468 allowEmpty: speech.blocksSubmission,
469 onSubmit: () => speech.submitAfterDictation((text) => void send(text)),
470 onCancel: () =>
471 speech.state.phase === "idle" ? setReplying(false) : speech.cancel(),
472 })}
473 />
474 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
475 <TextFieldSpeechControls speech={speech} disabled={pending} />
476 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
477 <T>Cancel</T>
478 </Button>
479 <Button
480 size="xs"
481 disabled={
482 speech.preparing ||
483 pending ||
484 (!speech.blocksSubmission && reply.trim().length === 0)
485 }
486 onClick={() => speech.submitAfterDictation((text) => void send(text))}
487 >
488 <T context="verb, button">Reply</T>
489 </Button>
490 </div>
491 </div>
492 )}
493 </SpeechTextField>
494 ) : (
495 <Button size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
496 <T context="verb, button">Reply</T>
497 </Button>
498 )
499 ) : null}
500 </>
501 ) : null}
502 </div>
503 );
504}