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

PullRequestReviewAnnotation.tsx

500 lines17.6 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 { 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 };
73​
74export function toViewerSide(side: PullRequestDiffSide) {
75 return side === "left" ? ("deletions" as const) : ("additions" as const);
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 }
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 );
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 );
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 ? <span>outdated</span> : null}
338 {onFix ? (
339 <Button
340 size="compact"
341 variant="ghost"
342 className="ml-auto"
343 disabled={pending || fixPending}
344 onClick={onFix}
345 >
346 <HammerIcon className="size-3" />
347 {fixPending ? gt("Preparing...") : (fixLabel ?? gt("Fix in a thread"))}
348 </Button>
349 ) : null}
350 {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
351 <Button
352 size="compact"
353 variant="ghost"
354 className={onFix ? undefined : "ml-auto"}
355 onClick={() => onAddToChat({ ...thread, comments })}
356 >
357 <MessageSquarePlusIcon className="size-3" />
358 <T>Add to chat</T>
359 </Button>
360 ) : null}
361 {canResolve ? (
362 <Button
363 size="compact"
364 variant="ghost"
365 className={onFix || onAddToChat ? undefined : "ml-auto"}
366 disabled={pending}
367 onClick={onToggleResolved}
368 >
369 {thread.isResolved ? gt("Unresolve") : gt("Resolve")}
370 </Button>
371 ) : null}
372 </div>
373​
374 {expanded ? (
375 <>
376 <div className="mt-2 space-y-3">
377 {comments.map((comment) => (
378 <article key={comment.id} className="group min-w-0">
379 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
380 <PullRequestActorLabel actor={comment.author} />
381 <span>
382 <RelativeTime timestamp={comment.createdAt} />
383 </span>
384 <PullRequestReactionBar
385 className="ml-auto justify-end"
386 reactions={comment.reactions ?? []}
387 canReact={canReact}
388 subjectId={comment.id}
389 environmentId={environmentId}
390 reference={reference}
391 onRefresh={onReacted}
392 />
393 </div>
394 {editingId === comment.id ? (
395 <PullRequestMarkdownEditor
396 className="mt-1"
397 value={comment.body}
398 cwd={workspaceRoot}
399 environmentId={environmentId}
400 completionScope={completionScope}
401 label={gt("Edit comment")}
402 saving={savingEdit}
403 onSave={(body) => void saveEdit(comment.id, body)}
404 onCancel={() => setEditingId(null)}
405 />
406 ) : (
407 <div className="mt-1 flex items-start gap-1">
408 <PullRequestMarkdown
409 className="min-w-0 flex-1 text-sm"
410 text={comment.body}
411 cwd={workspaceRoot}
412 environmentId={environmentId}
413 />
414 {canEditComment(comment) ? (
415 <PullRequestEditButton
416 aria-label={gt("Edit comment")}
417 onClick={() => setEditingId(comment.id)}
418 />
419 ) : null}
420 </div>
421 )}
422 </article>
423 ))}
424 </div>
425 {nextCommentsCursor !== null ? (
426 <div className="mt-2">
427 <Button
428 size="xs"
429 variant="ghost"
430 disabled={loadingMore}
431 onClick={() => void loadMore()}
432 >
433 {loadingMore ? gt("Loading...") : gt("Load more comments")}
434 </Button>
435 </div>
436 ) : null}
437​
438 {canReply ? (
439 replying ? (
440 <SpeechTextField
441 environmentId={environmentId}
442 projectId={reference.projectId}
443 ownerKey={JSON.stringify(["pr-reply", environmentId, reference, thread.id])}
444 text={reply}
445 textareaRef={replyRef}
446 onTextChange={setReply}
447 disabled={pending}
448 >
449 {(speech) => (
450 <div className="mt-2">
451 <PullRequestMarkdownTextarea
452 ref={replyRef}
453 readOnly={speech.freezesEditor}
454 autoFocus
455 size="sm"
456 completionScope={completionScope}
457 value={reply}
458 placeholder={gt("Reply", { $context: "noun, placeholder" })}
459 aria-label={gt("Reply to this conversation")}
460 onValueChange={setReply}
461 onKeyDown={submitKeys({
462 value: reply,
463 pending,
464 allowEmpty: speech.blocksSubmission,
465 onSubmit: () => speech.submitAfterDictation((text) => void send(text)),
466 onCancel: () =>
467 speech.state.phase === "idle" ? setReplying(false) : speech.cancel(),
468 })}
469 />
470 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
471 <TextFieldSpeechControls speech={speech} disabled={pending} />
472 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
473 <T>Cancel</T>
474 </Button>
475 <Button
476 size="xs"
477 disabled={
478 speech.preparing ||
479 pending ||
480 (!speech.blocksSubmission && reply.trim().length === 0)
481 }
482 onClick={() => speech.submitAfterDictation((text) => void send(text))}
483 >
484 <T context="verb, button">Reply</T>
485 </Button>
486 </div>
487 </div>
488 )}
489 </SpeechTextField>
490 ) : (
491 <Button size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
492 <T context="verb, button">Reply</T>
493 </Button>
494 )
495 ) : null}
496 </>
497 ) : null}
498 </div>
499 );