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

PullRequestSummaryTab.tsx

463 lines18.2 KB

1import type { EnvironmentId, PullRequestDetailView, PullRequestRef } from "@t3tools/contracts";
2import {
3 ArrowDownUpIcon,
4 ChevronRightIcon,
5 HammerIcon,
6 MessageSquareIcon,
7 SendIcon,
8 UsersIcon,
9} from "lucide-react";
10import { useState, type ReactNode } from "react";
11​
12import { useAtomCommand } from "~/state/use-atom-command";
13import { pullRequestEnvironment } from "~/state/pullRequests";
14import { cn } from "~/lib/utils";
15import { readLocalApi } from "~/localApi";
16import { formatRelativeTimeLabel } from "~/timestampFormat";
17​
18import { Button } from "../ui/button";
19import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
20import { Textarea } from "../ui/textarea";
21import { toastManager } from "../ui/toast";
22import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
23import {
24 PullRequestActorLabel,
25 PullRequestCheckStatusIcon,
26 PullRequestMetaLine,
27 pullRequestCheckStatusLabel,
28} from "./pullRequestPresentation";
29import { PullRequestReviewerPicker } from "./PullRequestReviewerPicker";
30import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
31import {
32 orderPullRequestComments,
33 pullRequestFindingKey,
34 type PullRequestFinding,
35} from "./pullRequestDetail.logic";
36import { PullRequestMarkdown } from "./PullRequestMarkdown";
37import { PullRequestConversationGhost } from "./PullRequestGhosts";
38​
39function MetaRow({
40 icon,
41 label,
42 children,
43}: {
44 icon: ReactNode;
45 label: string;
46 children: ReactNode;
47}) {
48 return (
49 <div className="flex items-center gap-2 py-1.5 text-xs">
50 <span className="flex w-24 shrink-0 items-center gap-1.5 text-muted-foreground">
51 {icon}
52 {label}
53 </span>
54 <span className="min-w-0 flex-1 text-foreground">{children}</span>
55 </div>
56 );
58​
59function Section({
60 title,
61 count,
62 defaultOpen = true,
63 actions,
64 children,
65}: {
66 title: string;
67 count?: number;
68 defaultOpen?: boolean;
69 /** Controls riding on the heading row itself. A sibling of the trigger, not a child of it —
70 a button cannot hold a button — and only while open, since they act on what is shown. */
71 actions?: ReactNode;
72 children: ReactNode;
73}) {
74 const [open, setOpen] = useState(defaultOpen);
75 return (
76 <Collapsible open={open} onOpenChange={setOpen}>
77 <div className="flex w-full items-center border-t border-border/60 pr-4">
78 {/* Title first, chevron riding to its right, count last: the row reads as a heading
79 with an affordance rather than a tree node. */}
80 <CollapsibleTrigger className="flex min-w-0 flex-1 items-center gap-1.5 px-4 py-3 text-left text-sm font-medium">
81 <span>{title}</span>
82 <ChevronRightIcon
83 aria-hidden
84 className={cn(
85 "size-3.5 text-muted-foreground transition-transform",
86 open && "rotate-90",
87 )}
88 />
89 {count === undefined ? null : (
90 <span className="text-xs tabular-nums text-muted-foreground">{count}</span>
91 )}
92 </CollapsibleTrigger>
93 {open ? actions : null}
94 </div>
95 <CollapsiblePanel>
96 <div className="px-4 pb-4">{children}</div>
97 </CollapsiblePanel>
98 </Collapsible>
99 );
101​
102function CommentComposer({
103 environmentId,
104 detail,
105 onCommented,
106}: {
107 environmentId: EnvironmentId;
108 detail: PullRequestDetailView;
109 onCommented: () => void;
110}) {
111 const [body, setBody] = useState("");
112 const [posting, setPosting] = useState(false);
113 const postComment = useAtomCommand(pullRequestEnvironment.comment, { reportFailure: false });
114​
115 const submit = async () => {
116 const trimmed = body.trim();
117 if (trimmed.length === 0 || posting) return;
118 setPosting(true);
119 const result = await postComment({
120 environmentId,
121 input: {
122 projectId: detail.projectId,
123 repository: detail.repository,
124 number: detail.number,
125 body: trimmed,
126 },
127 });
128 setPosting(false);
129 if (result._tag === "Failure") {
130 toastManager.add({ type: "error", title: "Could not post the comment" });
131 return;
132 }
133 setBody("");
134 onCommented();
135 };
136​
137 return (
138 <div className="mt-3 space-y-2">
139 <Textarea
140 // Locked while posting: the body is cleared on success, which would otherwise throw
141 // away a new draft typed while the request was still in flight.
142 disabled={posting}
143 value={body}
144 rows={3}
145 placeholder="Leave a comment"
146 aria-label="Comment on this pull request"
147 onChange={(event) => setBody(event.target.value)}
148 />
149 <div className="flex justify-end">
150 <Button
151 size="xs"
152 variant="outline"
153 disabled={body.trim().length === 0 || posting}
154 onClick={() => void submit()}
155 >
156 <SendIcon className="size-3.5" />
157 {posting ? "Posting..." : "Comment"}
158 </Button>
159 </div>
160 </div>
161 );
163​
164/**
165 * What a first render of the conversation carries. A pull request with two hundred comments is
166 * two hundred markdown documents, and the ones worth arriving for are the recent ones.
167 */
168const COMMENT_PAGE = 30;
169​
170export function PullRequestSummaryTab({
171 environmentId,
172 reference,
173 detail,
174 activityPending,
175 activityError,
176 pendingFinding,
177 onFixFinding,
178 onRefresh,
179}: {
180 environmentId: EnvironmentId;
181 reference: PullRequestRef;
182 detail: PullRequestDetailView;
183 activityPending: boolean;
184 activityError: string | null;
185 /** The hand-off currently preparing, if any, so only the finding it belongs to says so. */
186 pendingFinding?: string | null;
187 onFixFinding?: (finding: PullRequestFinding) => void;
188 onRefresh: () => void;
189}) {
190 // Keyed by the pull request, so opening another one starts at the end of its conversation
191 // rather than wherever the last one had been read back to.
192 const [shown, setShown] = useState({ url: detail.url, count: COMMENT_PAGE });
193 const shownComments = shown.url === detail.url ? shown.count : COMMENT_PAGE;
194 // Windowed by recency regardless of display order: expanding always reaches further back in
195 // time, whether the newest comment currently reads first or last.
196 const recentComments = detail.comments.slice(Math.max(0, detail.comments.length - shownComments));
197 const hiddenCommentCount = detail.comments.length - recentComments.length;
198 const [commentOrder, setCommentOrder] = useState<"newest" | "oldest">("newest");
199 const visibleComments = orderPullRequestComments(recentComments, commentOrder);
200​
201 // A comment that already lives on a review thread is that thread: the thread carries the line
202 // and side the bare comment has lost, and a resolved one is finished work nobody should be
203 // invited to fix again — the same call the whole-review hand-off makes.
204 const threadByCommentId = new Map(
205 detail.reviewThreads.flatMap((thread) =>
206 thread.comments.map((comment) => [comment.id, thread] as const),
207 ),
208 );
209​
210 const openCheck = (url: string) => {
211 void readLocalApi()?.shell.openExternal(url);
212 };
213​
214 return (
215 <div className="h-full overflow-y-auto">
216 <section className="px-4 py-3">
217 <div>
218 <MetaRow icon={<UsersIcon className="size-3.5" />} label="Reviewers">
219 <span className="flex min-w-0 flex-wrap items-center gap-1.5">
220 {detail.reviewers.length === 0 ? (
221 <span className="text-muted-foreground">None</span>
222 ) : (
223 <span className="flex items-center -space-x-1">
224 {detail.reviewers.map((actor) => (
225 <Tooltip key={actor.login}>
226 <TooltipTrigger
227 render={
228 <span
229 className="relative rounded-full hover:z-10"
230 aria-label={actor.name ?? actor.login}
231 />
232 }
233 >
234 <PullRequestActorLabel
235 actor={actor}
236 className="gap-0 [&>img]:ring-2 [&>img]:ring-background [&>span:first-child]:ring-2 [&>span:first-child]:ring-background [&>span:last-child]:sr-only"
237 />
238 </TooltipTrigger>
239 <TooltipPopup side="bottom">
240 {actor.name && actor.name !== actor.login
241 ? `${actor.name} (@${actor.login})`
242 : actor.login}
243 </TooltipPopup>
244 </Tooltip>
245 ))}
246 </span>
247 )}
248 {/* Shown wherever the host can take a review request at all, and disabled with the
249 reason where this account may not make one: a control that vanishes teaches
250 nobody why, and "you need write access" is the answer to the question a reader
251 actually has. Azure DevOps is the exception — it takes a reviewer but will not
252 say who could be one, so there is nothing to open. */}
253 {detail.capabilities.reviewers.request &&
254 detail.capabilities.reviewers.listCandidates ? (
255 <PullRequestReviewerPicker
256 environmentId={environmentId}
257 reference={reference}
258 allowed={detail.viewerPermissions.requestReviewers}
259 onRequested={onRefresh}
260 />
261 ) : null}
262 </span>
263 </MetaRow>
264 <MetaRow icon={<MessageSquareIcon className="size-3.5" />} label="Comments">
265 {activityPending
266 ? "Loading conversation…"
267 : activityError
268 ? "Conversation unavailable"
269 : detail.commentCount === 1
270 ? "1 comment"
271 : `${detail.commentCount} comments`}
272 </MetaRow>
273 </div>
274 </section>
275​
276 <Section title="Description">
277 <PullRequestMarkdown
278 text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}
279 cwd={detail.workspaceRoot}
280 />
281 </Section>
282​
283 <Section title="Checks" count={detail.checks.length}>
284 {detail.checks.length === 0 ? (
285 <p className="text-xs text-muted-foreground">No checks reported.</p>
286 ) : (
287 <div className="space-y-0.5">
288 {detail.checks.map((check) => {
289 const finding = { kind: "check", check } as const;
290 const failing = check.status === "failure" || check.status === "cancelled";
291 return (
292 <div
293 key={`${check.name}:${check.url ?? ""}`}
294 className="group flex items-center gap-1 rounded-md pr-1 hover:bg-accent/60"
295 >
296 <button
297 type="button"
298 disabled={!check.url}
299 onClick={() => check.url && openCheck(check.url)}
300 className={cn(
301 "flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",
302 check.url ? undefined : "cursor-default",
303 )}
304 >
305 <PullRequestCheckStatusIcon status={check.status} />
306 <span className="min-w-0 flex-1 truncate">{check.name}</span>
307 <span className="shrink-0 text-muted-foreground">
308 {pullRequestCheckStatusLabel(check.status)}
309 </span>
310 </button>
311 {/* Only where there is something to fix. A passing check has no failure to
312 reproduce, and the button would be an invitation to waste a thread. */}
313 {onFixFinding && failing ? (
314 <Button
315 size="xs"
316 variant="ghost"
317 className="shrink-0"
318 disabled={pendingFinding !== null && pendingFinding !== undefined}
319 onClick={() => onFixFinding(finding)}
320 >
321 <HammerIcon className="size-3" />
322 {pendingFinding === pullRequestFindingKey(finding) ? "Preparing..." : "Fix"}
323 </Button>
324 ) : null}
325 </div>
326 );
327 })}
328 </div>
329 )}
330 </Section>
331​
332 <Section
333 title="Comments"
334 {...(activityPending || activityError ? {} : { count: detail.commentCount })}
335 actions={
336 !activityPending && !activityError && detail.comments.length > 0 ? (
337 <Button
338 size="xs"
339 variant="ghost"
340 className="h-7 shrink-0 px-2 text-[10px] text-muted-foreground"
341 aria-label={
342 commentOrder === "newest"
343 ? "Show oldest comments first"
344 : "Show newest comments first"
345 }
346 onClick={() => setCommentOrder((value) => (value === "newest" ? "oldest" : "newest"))}
347 >
348 <ArrowDownUpIcon aria-hidden className="size-3" />
349 {commentOrder === "newest" ? "Newest first" : "Oldest first"}
350 </Button>
351 ) : null
352 }
353 >
354 {activityPending ? (
355 <PullRequestConversationGhost />
356 ) : activityError ? (
357 <PullRequestActivityUnavailableState compact error={activityError} onRetry={onRefresh} />
358 ) : (
359 <>
360 {detail.commentsTruncated ? (
361 <p className="mb-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-2 py-1.5 text-xs">
362 This conversation is longer than this page reads in one go. The most recent{" "}
363 {detail.comments.length} are here; open it on the host to read the rest.
364 </p>
365 ) : null}
366 {detail.comments.length === 0 ? (
367 <p className="py-2 text-xs text-muted-foreground">No comments yet.</p>
368 ) : (
369 <div className="space-y-3">
370 {hiddenCommentCount > 0 ? (
371 // Hundreds of comments are hundreds of markdown renders, and the ones worth
372 // opening a pull request for are the recent ones. The rest are one press away and
373 // stay rendered once asked for.
374 <Button
375 size="sm"
376 variant="outline"
377 className="w-full"
378 onClick={() =>
379 setShown({ url: detail.url, count: shownComments + COMMENT_PAGE })
380 }
381 >
382 Show {Math.min(hiddenCommentCount, COMMENT_PAGE)} earlier{" "}
383 {hiddenCommentCount === 1 ? "comment" : "comments"}
384 </Button>
385 ) : null}
386 {visibleComments.map((comment) => {
387 const thread = threadByCommentId.get(comment.id);
388 const finding: PullRequestFinding | null =
389 comment.kind !== "review" && comment.kind !== "review-comment"
390 ? null
391 : thread === undefined
392 ? { kind: "comment", comment }
393 : thread.isResolved
394 ? null
395 : { kind: "thread", thread };
396 return (
397 <article
398 key={comment.id}
399 // Offscreen comments skip style, layout and paint. Bot comments carry pages of
400 // highlighted code, and the conversation is below the description either way.
401 className="rounded-lg border border-border/60 p-3 [contain-intrinsic-block-size:120px] [content-visibility:auto]"
402 >
403 <div className="flex items-start gap-2">
404 <PullRequestMetaLine className="min-w-0 flex-1 text-xs text-muted-foreground">
405 <PullRequestActorLabel
406 actor={comment.author}
407 className="font-medium text-foreground"
408 />
409 <span>{formatRelativeTimeLabel(comment.createdAt)}</span>
410 {comment.reviewState ? (
411 <span>{comment.reviewState.toLowerCase()}</span>
412 ) : null}
413 </PullRequestMetaLine>
414 {/* Review remarks only. A plain conversation comment is talk, not a finding,
415 and offering to fix one would promise more than it says. */}
416 {onFixFinding && finding ? (
417 <Button
418 size="xs"
419 variant="ghost"
420 className="-mt-1 shrink-0"
421 disabled={pendingFinding !== null && pendingFinding !== undefined}
422 onClick={() => onFixFinding(finding)}
423 >
424 <HammerIcon className="size-3" />
425 {pendingFinding === pullRequestFindingKey(finding)
426 ? "Preparing..."
427 : "Fix in a thread"}
428 </Button>
429 ) : null}
430 </div>
431 {comment.path ? (
432 <p
433 className="mt-1 truncate text-xs text-muted-foreground"
434 title={comment.path}
435 >
436 {comment.path}
437 </p>
438 ) : null}
439 <PullRequestMarkdown
440 className="mt-2"
441 text={comment.body}
442 cwd={detail.workspaceRoot}
443 />
444 </article>
445 );
446 })}
447 </div>
448 )}
449 </>
450 )}
451 {/* Posting is a core capability and remains usable even if the activity read failed. */}
452 {detail.capabilities.comment && detail.viewerPermissions.comment ? (
453 <CommentComposer
454 key={`${environmentId}:${detail.projectId}/${detail.repository}#${detail.number}`}
455 environmentId={environmentId}
456 detail={detail}
457 onCommented={onRefresh}
458 />
459 ) : null}
460 </Section>
461 </div>
462 );