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

PullRequestReviewAnnotation.tsx

511 lines17.8 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, plural, part } 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`${plural(
152 { count: resolved.length },
153 {
154 "=1": "Resolved conversation",
155 other: part`${{ count: resolved.length }} resolved conversations`,
156 },
157 )}`;
158 return (
159 <>
160 {resolved.length > 0 ? (
161 <SharedTooltipTrigger
162 render={
163 <button
164 type="button"
165 data-resolved-threads
166 aria-label={label}
167 aria-expanded={expanded}
168 // Sits on the commented line, which is the row above this annotation.
169 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"
170 contentEditable={false}
171 onPointerDown={(event) => event.stopPropagation()}
172 onClick={() =>
173 setShown(new Set((expanded ? open : threads).map((thread) => thread.id)))
174 }
175 />
176 }
177 label={label}
178 side="left"
179 >
180 {[...authors].slice(0, 3).map(([login, author]) => (
181 <PullRequestActorAvatar key={login} actor={author} className="ring-1 ring-background" />
182 ))}
183 </SharedTooltipTrigger>
184 ) : null}
185 {threads.map((thread) => renderThread(thread, thread.isResolved && !shown.has(thread.id)))}
186 </>
187 );
189​
190export function ReviewThreadCard({
191 thread,
192 workspaceRoot,
193 canReply,
194 canResolve,
195 canReact,
196 environmentId,
197 reference,
198 completionScope,
199 pending,
200 fixPending,
201 fixLabel,
202 onFix,
203 onAddToChat,
204 onReply,
205 onLoadMore,
206 canEditComment,
207 onEditComment,
208 onToggleResolved,
209 onReacted,
210 hidden,
211}: {
212 thread: PullRequestReviewThread;
213 workspaceRoot: string;
214 canReply: boolean;
215 canResolve: boolean;
216 canReact: boolean;
217 environmentId: EnvironmentId;
218 reference: PullRequestRef;
219 completionScope: PullRequestCompletionScope | null;
220 pending: boolean;
221 fixPending?: boolean;
222 fixLabel?: string;
223 onFix?: () => void;
224 /**
225 * Absent where there is no composer beside the panel to add the conversation to. Handed the
226 * thread with every comment the reader has loaded, not only the first page.
227 */
228 onAddToChat?: (thread: PullRequestReviewThread) => void;
229 onReply: (body: string) => Promise<boolean>;
230 onLoadMore: (cursor: string) => Promise<PullRequestThreadCommentsResult | null>;
231 canEditComment: (comment: PullRequestThreadComment) => boolean;
232 onEditComment: (commentId: string, body: string) => Promise<boolean>;
233 onToggleResolved: () => void;
234 onReacted: () => void;
235 /** Set on a diff line. Hidden draws nothing but stays mounted, so an unsent reply survives. */
236 hidden?: boolean;
237}) {
238 const gt = useGT();
239 const [expanded, setExpanded] = useState(hidden !== undefined || !thread.isResolved);
240 const [replying, setReplying] = useState(false);
241 const [reply, setReply] = useState("");
242 const [editingId, setEditingId] = useState<string | null>(null);
243 const [savingEdit, setSavingEdit] = useState(false);
244 const sendingRef = useRef(false);
245 const replyRef = useRef<HTMLTextAreaElement>(null);
246 const [loadedPage, setLoadedPage] = useState<
247 (PullRequestThreadCommentsResult & { readonly threadId: string }) | null
248 >(null);
249 const [loadingMore, setLoadingMore] = useState(false);
250 const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null;
251 const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []);
252 const nextCommentsCursor =
253 currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor;
254 const commentCount = thread.commentCount ?? comments.length;
255​
256 const saveEdit = async (commentId: string, body: string) => {
257 if (savingEdit) return;
258 setSavingEdit(true);
259 const saved = await onEditComment(commentId, body);
260 setSavingEdit(false);
261 if (saved) {
262 setLoadedPage((previous) =>
263 previous?.threadId === thread.id
264 ? {
265 ...previous,
266 comments: editPullRequestThreadComment(previous.comments, commentId, body),
267 }
268 : previous,
269 );
270 setEditingId(null);
271 }
272 };
273​
274 const send = async (text: string) => {
275 const trimmed = text.trim();
276 if (trimmed.length === 0 || pending || sendingRef.current) return;
277 sendingRef.current = true;
278 const result = await settlePromise(() => onReply(trimmed));
279 sendingRef.current = false;
280 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
281 if (!result.value) return;
282 // Replies return no comment; retain loaded data and reopen pagination for a later read.
283 setLoadedPage((previous) =>
284 previous?.threadId === thread.id
285 ? {
286 ...previous,
287 nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null,
288 }
289 : previous,
290 );
291 setReply("");
292 setReplying(false);
293 };
294 const loadMore = async () => {
295 if (nextCommentsCursor === null || loadingMore) return;
296 setLoadingMore(true);
297 const result = await settlePromise(() => onLoadMore(nextCommentsCursor));
298 setLoadingMore(false);
299 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
300 const page = result.value;
301 if (page === null) return;
302 setLoadedPage((previous) => ({
303 threadId: thread.id,
304 comments: mergePullRequestThreadComments(
305 previous?.threadId === thread.id ? previous.comments : [],
306 page.comments,
307 ),
308 nextCursor: page.nextCursor,
309 }));
310 };
311​
312 if (hidden) return null;
313​
314 return (
315 <div
316 className={cn(CARD_CLASS, !expanded && "py-1")}
317 contentEditable={false}
318 onPointerDown={(event) => event.stopPropagation()}
319 >
320 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
321 {thread.isResolved ? (
322 <CircleCheckIcon className="size-3.5 text-success-foreground" />
323 ) : (
324 <CircleIcon className="size-3.5" />
325 )}
326 <button
327 type="button"
328 className="hover:text-foreground"
329 aria-expanded={expanded}
330 onClick={() => setExpanded((current) => !current)}
331 >
332 {thread.isResolved
333 ? gt({ context: "review thread state" })`Resolved`
334 : gt({ context: "review thread state" })`Open`}{" "}
335 ·{" "}
336 {gt`${plural(
337 { count: commentCount },
338 {
339 one: part`${{ count: commentCount }} comment`,
340 other: part`${{ count: commentCount }} comments`,
341 },
342 )}`}
343 </button>
344 {thread.isOutdated ? (
345 <span>
346 <T context="review thread state">Outdated</T>
347 </span>
348 ) : null}
349 {onFix ? (
350 <Button
351 size="compact"
352 variant="ghost"
353 className="ml-auto"
354 disabled={pending || fixPending}
355 onClick={onFix}
356 >
357 <HammerIcon className="size-3" />
358 {fixPending ? gt`Preparing...` : (fixLabel ?? gt`Fix in a thread`)}
359 </Button>
360 ) : null}
361 {onAddToChat && comments.some((comment) => visibleBody(comment.body) !== null) ? (
362 <Button
363 size="compact"
364 variant="ghost"
365 className={onFix ? undefined : "ml-auto"}
366 onClick={() => onAddToChat({ ...thread, comments })}
367 >
368 <MessageSquarePlusIcon className="size-3" />
369 <T>Add to chat</T>
370 </Button>
371 ) : null}
372 {canResolve ? (
373 <Button
374 size="compact"
375 variant="ghost"
376 className={onFix || onAddToChat ? undefined : "ml-auto"}
377 disabled={pending}
378 onClick={onToggleResolved}
379 >
380 {thread.isResolved ? gt`Unresolve` : gt`Resolve`}
381 </Button>
382 ) : null}
383 </div>
384​
385 {expanded ? (
386 <>
387 <div className="mt-2 space-y-3">
388 {comments.map((comment) => (
389 <article key={comment.id} className="group min-w-0">
390 <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
391 <PullRequestActorLabel actor={comment.author} />
392 <span>
393 <RelativeTime timestamp={comment.createdAt} />
394 </span>
395 <PullRequestReactionBar
396 className="ml-auto justify-end"
397 reactions={comment.reactions ?? []}
398 canReact={canReact}
399 subjectId={comment.id}
400 environmentId={environmentId}
401 reference={reference}
402 onRefresh={onReacted}
403 />
404 </div>
405 {editingId === comment.id ? (
406 <PullRequestMarkdownEditor
407 className="mt-1"
408 value={comment.body}
409 cwd={workspaceRoot}
410 environmentId={environmentId}
411 completionScope={completionScope}
412 label={gt`Edit comment`}
413 saving={savingEdit}
414 onSave={(body) => void saveEdit(comment.id, body)}
415 onCancel={() => setEditingId(null)}
416 />
417 ) : (
418 <div className="mt-1 flex items-start gap-1">
419 <PullRequestMarkdown
420 className="min-w-0 flex-1 text-sm"
421 text={comment.body}
422 cwd={workspaceRoot}
423 environmentId={environmentId}
424 />
425 {canEditComment(comment) ? (
426 <PullRequestEditButton
427 aria-label={gt`Edit comment`}
428 onClick={() => setEditingId(comment.id)}
429 />
430 ) : null}
431 </div>
432 )}
433 </article>
434 ))}
435 </div>
436 {nextCommentsCursor !== null ? (
437 <div className="mt-2">
438 <Button
439 size="xs"
440 variant="ghost"
441 disabled={loadingMore}
442 onClick={() => void loadMore()}
443 >
444 {loadingMore ? gt`Loading...` : gt`Load more comments`}
445 </Button>
446 </div>
447 ) : null}
448​
449 {canReply ? (
450 replying ? (
451 <SpeechTextField
452 environmentId={environmentId}
453 projectId={reference.projectId}
454 ownerKey={JSON.stringify(["pr-reply", environmentId, reference, thread.id])}
455 text={reply}
456 textareaRef={replyRef}
457 onTextChange={setReply}
458 disabled={pending}
459 >
460 {(speech) => (
461 <div className="mt-2">
462 <PullRequestMarkdownTextarea
463 ref={replyRef}
464 readOnly={speech.freezesEditor}
465 autoFocus
466 size="sm"
467 completionScope={completionScope}
468 value={reply}
469 placeholder={gt({ context: "noun, placeholder" })`Reply`}
470 aria-label={gt`Reply to this conversation`}
471 onValueChange={setReply}
472 onKeyDown={submitKeys({
473 value: reply,
474 pending,
475 allowEmpty: speech.blocksSubmission,
476 onSubmit: () => speech.submitAfterDictation((text) => void send(text)),
477 onCancel: () =>
478 speech.state.phase === "idle" ? setReplying(false) : speech.cancel(),
479 })}
480 />
481 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
482 <TextFieldSpeechControls speech={speech} disabled={pending} />
483 <Button size="xs" variant="ghost" onClick={() => setReplying(false)}>
484 <T>Cancel</T>
485 </Button>
486 <Button
487 size="xs"
488 disabled={
489 speech.preparing ||
490 pending ||
491 (!speech.blocksSubmission && reply.trim().length === 0)
492 }
493 onClick={() => speech.submitAfterDictation((text) => void send(text))}
494 >
495 <T context="verb, button">Reply</T>
496 </Button>
497 </div>
498 </div>
499 )}
500 </SpeechTextField>
501 ) : (
502 <Button size="xs" variant="ghost" className="mt-2" onClick={() => setReplying(true)}>
503 <T context="verb, button">Reply</T>
504 </Button>
505 )
506 ) : null}
507 </>
508 ) : null}
509 </div>
510 );