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

PullRequestReviewAnnotation.tsx

413 lines14.2 KB

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