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

PullRequestReviewAnnotation.tsx

504 lines17.7 KB

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 { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
29import { PullRequestEditButton } from "./PullRequestEditButton";
30import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
31import {
32 editPullRequestThreadComment,
33 mergePullRequestThreadComments,
34 visibleBody,
35} from "./pullRequestDetail.logic";
36import { PullRequestActorAvatar, PullRequestActorLabel } from "./pullRequestPresentation";
37import { PullRequestMarkdown } from "./PullRequestMarkdown";
38import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
39import { PullRequestReactionBar } from "./PullRequestReactions";
40import type { PendingReviewComment } from "./pullRequestReviewStore";
41import {
42 PullRequestMarkdownTextarea,
43 type PullRequestCompletionScope,
44} from "./PullRequestMarkdownTextarea";
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 input.onCancel();
65 }
66 if (isCommentSubmitShortcut(event, input.value, input.pending, input.allowEmpty)) {
67 event.preventDefault();
68 input.onSubmit();
69 }
70 };
72​
73export function toViewerSide(side: PullRequestDiffSide) {
74 return side === "left" ? ("deletions" as const) : ("additions" as const);
76​
77export function getReviewPositionAnchor(position: PullRequestReviewPosition): {
78 line: number;
79 side: PullRequestDiffSide;
80} {
81 switch (position.kind) {
82 case "added":
83 return { line: position.newLine, side: "right" };
84 case "deleted":
85 return { line: position.oldLine, side: "left" };
86 case "context":
87 return {
88 line: position.side === "left" ? position.oldLine : position.newLine,
89 side: position.side,
90 };
91 }
93​
94export function PendingReviewCommentCard({
95 comment,
96 onRemove,
97}: {
98 comment: PendingReviewComment;
99 onRemove: () => void;
100}) {
101 const gt = useGT();
102 return (
103 <div
104 className={cn(CARD_CLASS, "border-dashed")}
105 contentEditable={false}
106 onPointerDown={(event) => event.stopPropagation()}
107 >
108 <div className="flex items-center gap-2 text-xs text-muted-foreground">
109 <MessageSquareIcon className="size-3.5" />
110 <span>
111 <T>Pending. Sent when you submit the review</T>
112 </span>
113 <Button
114 size="icon-xs"
115 variant="ghost"
116 className="ml-auto"
117 aria-label={gt("Discard this comment")}
118 onClick={onRemove}
119 >
120 <Trash2Icon className="size-3.5" />
121 </Button>
122 </div>
123 <p className="mt-2 whitespace-pre-wrap leading-relaxed">{comment.body}</p>
124 </div>
125 );
127​
128/** The conversations on one diff line. Resolved ones hide behind their authors' avatars. */
129export function InlineReviewThreads({
130 threads,
131 renderThread,
132}: {
133 threads: ReadonlyArray<PullRequestReviewThread>;
134 renderThread: (thread: PullRequestReviewThread, hidden: boolean) => ReactNode;
135}) {
136 const gt = useGT();
137 const [shown, setShown] = useState<ReadonlySet<string>>(() => new Set());
138 // A conversation seen open stays shown once resolved, so it does not vanish under the reader.
139 const open = threads.filter((thread) => !thread.isResolved);
140 if (open.some((thread) => !shown.has(thread.id))) {
141 setShown(new Set([...shown, ...open.map((thread) => thread.id)]));
142 }
143 const resolved = threads.filter((thread) => thread.isResolved);
144 const expanded = resolved.every((thread) => shown.has(thread.id));
145 const authors = new Map<string, PullRequestActor | null>();
146 for (const comment of resolved.flatMap((thread) => thread.comments)) {
147 authors.set(comment.author?.login ?? "ghost", comment.author);
148 }
149 if (authors.size === 0) authors.set("ghost", null);
150 const label = gt(
151 "{count, plural, =1 {Resolved conversation} other {{count} resolved conversations}}",
152 { count: resolved.length },
153 );
154 return (
155 <>
156 {resolved.length > 0 ? (
157 <Tooltip>
158 <TooltipTrigger
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 >
175 {[...authors].slice(0, 3).map(([login, author]) => (
176 <PullRequestActorAvatar
177 key={login}
178 actor={author}
179 className="ring-1 ring-background"
180 />
181 ))}
182 </TooltipTrigger>
183 <TooltipPopup side="left">{label}</TooltipPopup>
184 </Tooltip>
185 ) : null}
186 {threads.map((thread) => renderThread(thread, thread.isResolved && !shown.has(thread.id)))}
187 </>
188 );
190​
191export function ReviewThreadCard({
192 thread,
193 workspaceRoot,
194 canReply,
195 canResolve,
196 canReact,
197 environmentId,
198 reference,
199 completionScope,
200 pending,
201 fixPending,
202 fixLabel,
203 onFix,
204 onAddToChat,
205 onReply,
206 onLoadMore,
207 canEditComment,
208 onEditComment,
209 onToggleResolved,
210 onReacted,
211 hidden,
212}: {
213 thread: PullRequestReviewThread;
214 workspaceRoot: string;
215 canReply: boolean;
216 canResolve: boolean;
217 canReact: boolean;
218 environmentId: EnvironmentId;
219 reference: PullRequestRef;
220 completionScope: PullRequestCompletionScope | null;
221 pending: boolean;
222 fixPending?: boolean;
223 fixLabel?: string;
224 onFix?: () => void;
225 /**
226 * Absent where there is no composer beside the panel to add the conversation to. Handed the
227 * thread with every comment the reader has loaded, not only the first page.
228 */
229 onAddToChat?: (thread: PullRequestReviewThread) => void;
230 onReply: (body: string) => Promise<boolean>;
231 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
232 canEditComment: (comment: PullRequestThreadComment) => boolean;
233 onEditComment: (commentId: string, body: string) => Promise<boolean>;
234 onToggleResolved: () => void;
235 onReacted: () => void;
236 /** Set on a diff line. Hidden draws nothing but stays mounted, so an unsent reply survives. */
237 hidden?: boolean;
238}) {
239 const gt = useGT();
240 const [expanded, setExpanded] = useState(hidden !== undefined || !thread.isResolved);
241 const [replying, setReplying] = useState(false);
242 const [reply, setReply] = useState("");
243 const [editingId, setEditingId] = useState<string | null>(null);
244 const [savingEdit, setSavingEdit] = useState(false);
245 const sendingRef = useRef(false);
246 const replyRef = useRef<HTMLTextAreaElement>(null);
247 const [loadedPage, setLoadedPage] = useState<
248 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
249 >(null);
250 const [loadingMore, setLoadingMore] = useState(false);
251 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
252 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
253 const nextCommentsCursor =
254 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
255 const commentCount = thread.commentCount ?? comments.length;
256​
257 const saveEdit = async (commentId: string, body: string) => {
258 if (savingEdit) return;
259 setSavingEdit(true);
260 const saved = await onEditComment(commentId, body);
261 setSavingEdit(false);
262 if (saved) {
263 setLoadedPage((previous) =>
264 previous?.threadId === thread.id
265 ? {
266 ...previous,
267 comments: editPullRequestThreadComment(previous.comments, commentId, body),
268 }
269 : previous,
270 );
271 setEditingId(null);
272 }
273 };
274​
275 const send = async (text: string) => {
276 const trimmed = text.trim();
277 if (trimmed.length === 0 || pending || sendingRef.current) return;
278 sendingRef.current = true;
279 const result = await settlePromise(() => onReply(trimmed));
280 sendingRef.current = false;
281 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
282 if (!result.value) return;
283 // Replies return no comment; retain loaded data and reopen pagination for a later read.
284 setLoadedPage((previous) =>
285 previous?.threadId === thread.id
286 ? {
287 ...previous,
288 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
289 }
290 : previous,
291 );
292 setReply("");
293 setReplying(false);
294 };
295 const loadMore = async () => {
296 if (nextCommentsCursor === null || loadingMore) return;
297 setLoadingMore(true);
298 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
299 setLoadingMore(false);
300 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
301 const page = result.value;
302 if (page === null) return;
303 setLoadedPage((previous) => ({
304 threadId: thread.id,
305 comments: mergePullRequestThreadComments(
306 previous?.threadId === thread.id ? previous.comments : [],
307 page.comments,
308 ),
309 nextCursor: page.nextCursor,
310 }));
311 };
312​
313 if (hidden) return null;
314​
315 return (
316 <div
317 className={cn(CARD_CLASS, !expanded && "py-1")}
318 contentEditable={false}
319 onPointerDown={(event) => event.stopPropagation()}
320 >
321 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
322 {thread.isResolved ? (
323 <CircleCheckIcon className="size-3.5 text-success-foreground" />
324 ) : (
325 <CircleIcon className="size-3.5" />
326 )}
327 <button
328 type="button"
329 className="hover:text-foreground"
330 aria-expanded={expanded}
331 onClick={() => setExpanded((current) => !current)}
332 >
333 {thread.isResolved
334 ? gt("Resolved", { $context: "review thread state" })
335 : gt("Open", { $context: "review thread state" })}{" "}
336 ·{" "}
337 {gt("{count, plural, one {{count} comment} other {{count} comments}}", {
338 count: commentCount,
339 })}
340 </button>
341 {thread.isOutdated ? <span>outdated</span> : 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 );