Open History to see the last commit
1import {
2 parsePullRequestAnchor,
3 pullRequestAnchorMatchesUrl,
4 resolvePullRequestReviewAnchor,
5} from "@t3tools/shared/pullRequestAnchor";
6import { holdLinkedNodeInView } from "./holdLinkedNodeInView";
7import {
8 capitalizeTerm,
9 sourceControlClients,
10} from "@t3tools/client-runtime/source-control-clients";
11import { useAtomCommand } from "~/state/use-atom-command";
12import type {
13 EnvironmentId,
14 PullRequestActor,
15 PullRequestComment,
16 PullRequestDetailView,
17 PullRequestRef,
18 ScopedThreadRef,
19} from "@t3tools/contracts";
20import {
21 ChevronDownIcon,
22 CircleCheckIcon,
23 ExternalLinkIcon,
24 FileCode2Icon,
25 GitCommitHorizontalIcon,
26 MessageSquareIcon,
27 MessageSquarePlusIcon,
28} from "lucide-react";
29import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
30
31import { cn } from "~/lib/utils";
32import { readLocalApi } from "~/localApi";
33import { pullRequestEnvironment } from "~/state/pullRequests";
34import { RelativeTime } from "~/components/RelativeTime";
35
36import { Button } from "../ui/button";
37import { PullRequestEditButton } from "./PullRequestEditButton";
38import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
39import { toastManager } from "../ui/toast";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41import {
42 buildPullRequestTimeline,
43 groupPullRequestTimelineConversations,
44 pullRequestTimelineEventMatches,
45 type PullRequestTimelineRow,
46 isPullRequestVerdictStale,
47 newestPullRequestCommitAt,
48 pullRequestReviewOutcome,
49 type PullRequestChatSubject,
50 type PullRequestReviewOutcome,
51 type PullRequestTimelineEvent,
52 type PullRequestTimelineThread,
53} from "./pullRequestDetail.logic";
54import { canEditPullRequestComment } from "@t3tools/client-runtime/pull-request-editing";
55import { PullRequestMarkdown } from "./PullRequestMarkdown";
56import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
57import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
58import { PullRequestReactionBar } from "./PullRequestReactions";
59import { canReactPullRequestComment } from "@t3tools/client-runtime/pull-request-reactions";
60import { PullRequestResolveThreadButton } from "./PullRequestResolveThreadButton";
61import {
62 PullRequestActorAvatar,
63 PullRequestDiffStat,
64 PullRequestMetaLine,
65 PullRequestReviewOutcomeIcon,
66 pullRequestReviewOutcomeLabel,
67 pullRequestReviewOutcomeStaleLabel,
68 pullRequestReviewOutcomeToneClassName,
69} from "./pullRequestPresentation";
70import { PullRequestGlyph } from "./pullRequestIcons";
71import {
72 type PullRequestCompletionScope,
73 pullRequestCompletionScope,
74} from "./PullRequestMarkdownTextarea";
75import { LegendList, type LegendListRef } from "@legendapp/list/react";
76
77interface ReactionSurface {
78 revealAnchor?: string | null;
79 readonly canReact: (event: PullRequestTimelineEvent) => boolean;
80 /** Absent where there is no composer beside the panel to add a remark to. */
81 readonly onAddToChat?: ((comment: PullRequestComment) => void) | undefined;
82 readonly environmentId: EnvironmentId;
83 readonly threadRef: ScopedThreadRef | null;
84 readonly reference: PullRequestRef;
85 readonly completionScope: PullRequestCompletionScope | null;
86 readonly onRefresh: () => void;
87}
88
89function TimelineBody({
90 body,
91 markdown,
92 cwd,
93 environmentId,
94 threadRef,
95}: {
96 body: string;
97 markdown: boolean;
98 cwd: string;
99 environmentId: EnvironmentId;
100 threadRef: ScopedThreadRef | null;
101}) {
102 return (
103 <div className="mt-3">
104 {markdown ? (
105 <PullRequestMarkdown
106 text={body}
107 cwd={cwd}
108 environmentId={environmentId}
109 threadRef={threadRef}
110 />
111 ) : (
112 <p className="whitespace-pre-wrap text-xs text-muted-foreground">{body}</p>
113 )}
114 </div>
115 );
116}
117
118function ActorName({ actor }: { actor: PullRequestActor | null }) {
119 return <span className="font-semibold text-foreground">{actor?.login ?? "ghost"}</span>;
120}
121
122function TimelineMarker({
123 children,
124 className,
125}: {
126 children: ReactNode;
127 className?: string | undefined;
128}) {
129 return (
130 <span
131 className={cn(
132 "absolute left-0 top-1/2 z-10 flex size-8 -translate-y-1/2 items-center justify-center bg-background",
133 className,
134 )}
135 >
136 {children}
137 </span>
138 );
139}
140
141function IconMarker({ icon, className }: { icon: ReactNode; className?: string | undefined }) {
142 return (
143 <TimelineMarker className={className}>
144 <span className="flex size-7 items-center justify-center bg-background text-muted-foreground">
145 {icon}
146 </span>
147 </TimelineMarker>
148 );
149}
150
151function ActorTimelineMarker({
152 actors,
153 className,
154 fallback,
155 muted = false,
156}: {
157 actors: ReadonlyArray<PullRequestActor>;
158 className?: string | undefined;
159 fallback: ReactNode;
160 muted?: boolean;
161}) {
162 const actor = actors[0];
163 return actor === undefined ? (
164 <IconMarker className={className} icon={fallback} />
165 ) : (
166 <TimelineMarker className={className}>
167 <PullRequestActorAvatar
168 actor={actor}
169 className={cn(
170 "size-7 bg-muted text-3xs transition-opacity",
171 muted && "opacity-45 grayscale",
172 )}
173 />
174 </TimelineMarker>
175 );
176}
177
178function friendlyReviewState(value: string): string {
179 const words = value.toLowerCase().replaceAll("_", " ").replaceAll("-", " ");
180 return words.replace(/^\w/u, (letter) => letter.toUpperCase());
181}
182
183function ReviewStateBadge({ state }: { state: string }) {
184 return (
185 <span className="text-3xs font-medium text-muted-foreground">{friendlyReviewState(state)}</span>
186 );
187}
188
189function AddToChatButton({
190 comment,
191 reactions,
192}: {
193 comment: PullRequestComment;
194 reactions: ReactionSurface;
195}) {
196 const onAddToChat = reactions.onAddToChat;
197 return onAddToChat === undefined ? null : (
198 <Tooltip>
199 <TooltipTrigger
200 render={
201 <Button
202 size="icon-xs"
203 variant="ghost-muted"
204 className="-mt-1 shrink-0"
205 aria-label="Add to chat"
206 onClick={() => onAddToChat(comment)}
207 />
208 }
209 >
210 <MessageSquarePlusIcon className="size-3" />
211 </TooltipTrigger>
212 <TooltipPopup>Add to chat</TooltipPopup>
213 </Tooltip>
214 );
215}
216
217function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
218 return url === null ? null : (
219 <Button
220 size="icon-xs"
221 variant="ghost-muted"
222 className="-mr-1 shrink-0"
223 aria-label="Open activity on host"
224 onClick={() => onOpen(url)}
225 >
226 <ExternalLinkIcon className="size-3" />
227 </Button>
228 );
229}
230
231function ConversationCard({
232 event,
233 editable,
234 cwd,
235 onOpen,
236 reactions,
237 showPath = true,
238 reply = false,
239}: {
240 event: PullRequestTimelineEvent;
241 editable: PullRequestComment | null;
242 cwd: string;
243 onOpen: (url: string) => void;
244 reactions: ReactionSurface;
245 showPath?: boolean;
246 /** A reply goes with its conversation, from the card that heads it. */
247 reply?: boolean;
248}) {
249 const canReact = reactions.canReact(event);
250 const [editing, setEditing] = useState(false);
251 const [saving, setSaving] = useState(false);
252 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
253 reportFailure: false,
254 });
255
256 const save = async (body: string) => {
257 if (editable === null || saving || editable.kind === "review") return;
258 setSaving(true);
259 const result = await updateComment({
260 environmentId: reactions.environmentId,
261 input: { ...reactions.reference, commentId: editable.id, kind: editable.kind, body },
262 });
263 setSaving(false);
264 if (result._tag === "Failure") {
265 toastManager.add({ type: "error", title: "Could not save the comment" });
266 return;
267 }
268 setEditing(false);
269 reactions.onRefresh();
270 };
271
272 return (
273 <article
274 {...(reactions.revealAnchor != null &&
275 pullRequestAnchorMatchesUrl(reactions.revealAnchor, event.url)
276 ? {
277 "data-pr-link-target": true,
278 tabIndex: -1,
279 className: "group rounded-lg py-2 ring-1 ring-primary/40 outline-none",
280 }
281 : { className: "group py-2" })}
282 >
283 <div className="px-2">
284 <div className="flex min-w-0 flex-wrap items-center gap-2">
285 <div className="min-w-0 flex-1">
286 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
287 <ActorName actor={event.actor} />
288 <span className="text-muted-foreground">{event.title}</span>
289 {event.reviewState ? <ReviewStateBadge state={event.reviewState} /> : null}
290 </div>
291 <PullRequestMetaLine className="mt-1 flex-wrap text-2xs text-muted-foreground">
292 <span>
293 <RelativeTime timestamp={event.at} />
294 </span>
295 {showPath && event.path ? (
296 <span className="inline-flex min-w-0 items-center gap-1">
297 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
298 <span className="truncate">{event.path}</span>
299 </span>
300 ) : null}
301 </PullRequestMetaLine>
302 </div>
303 {editable !== null && !editing ? (
304 <PullRequestEditButton aria-label="Edit comment" onClick={() => setEditing(true)} />
305 ) : null}
306 {event.body && event.comment && !reply ? (
307 <AddToChatButton comment={event.comment} reactions={reactions} />
308 ) : null}
309 {canReact || event.reactions.length > 0 ? (
310 <PullRequestReactionBar
311 className="ml-auto justify-end"
312 reactions={event.reactions}
313 canReact={canReact}
314 subjectId={event.id}
315 environmentId={reactions.environmentId}
316 reference={reactions.reference}
317 onRefresh={reactions.onRefresh}
318 />
319 ) : null}
320 <OpenOnHostButton url={event.url} onOpen={onOpen} />
321 </div>
322 </div>
323 {editing && editable !== null ? (
324 <div className="px-2 pb-2 pt-3">
325 <PullRequestMarkdownEditor
326 value={editable.body}
327 cwd={cwd}
328 environmentId={reactions.environmentId}
329 completionScope={reactions.completionScope}
330 threadRef={reactions.threadRef}
331 label="Edit comment"
332 saving={saving}
333 onSave={(body) => void save(body)}
334 onCancel={() => setEditing(false)}
335 />
336 </div>
337 ) : event.body ? (
338 <div className="px-2 pb-2">
339 <TimelineBody
340 body={event.body}
341 markdown={event.markdown}
342 cwd={cwd}
343 environmentId={reactions.environmentId}
344 threadRef={reactions.threadRef}
345 />
346 </div>
347 ) : null}
348 </article>
349 );
350}
351
352function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
353 const actors = new Map<string, PullRequestActor>();
354 for (const event of events) {
355 const actor = event.actor;
356 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
357 }
358 return [...actors.values()];
359}
360
361function ConversationGroup({
362 revealAnchor,
363 events,
364 editable,
365 cwd,
366 onOpen,
367 reactions,
368}: {
369 revealAnchor?: string | null;
370 events: ReadonlyArray<PullRequestTimelineEvent>;
371 editable: ReadonlyMap<string, PullRequestComment>;
372 cwd: string;
373 onOpen: (url: string) => void;
374 reactions: ReactionSurface;
375}) {
376 const [open, setOpen] = useState(
377 () =>
378 revealAnchor != null &&
379 events.some((event) => pullRequestAnchorMatchesUrl(revealAnchor, event.url)),
380 );
381 const actors = uniqueConversationActors(events);
382 const first = events[0];
383 if (first === undefined) return null;
384
385 return (
386 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
387 <ActorTimelineMarker
388 actors={actors}
389 className="top-6"
390 fallback={<MessageSquareIcon className="size-3.5" />}
391 muted={!open}
392 />
393 <Collapsible open={open} onOpenChange={setOpen}>
394 <div>
395 <CollapsibleTrigger
396 className={cn(
397 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
398 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
399 )}
400 >
401 <span className="min-w-0 flex-1">
402 <span className="block text-xs font-semibold">
403 {events.length.toLocaleString()} {events.length === 1 ? "comment" : "comments"}
404 </span>
405 <span className="block truncate text-3xs text-muted-foreground">
406 {actors.length.toLocaleString()} {actors.length === 1 ? "author" : "authors"} ·{" "}
407 <RelativeTime timestamp={first.at} />
408 </span>
409 </span>
410 <ChevronDownIcon
411 aria-hidden
412 className={cn(
413 "size-3.5 shrink-0 text-muted-foreground transition-transform",
414 open && "rotate-180",
415 )}
416 />
417 </CollapsibleTrigger>
418 <CollapsiblePanel>
419 {open ? (
420 <div className="mt-1 space-y-1">
421 {events.map((event) => (
422 <ConversationCard
423 // Host comment ids can collide across pull requests.
424 key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
425 event={event}
426 editable={editable.get(event.id) ?? null}
427 cwd={cwd}
428 onOpen={onOpen}
429 reactions={reactions}
430 />
431 ))}
432 </div>
433 ) : null}
434 </CollapsiblePanel>
435 </div>
436 </Collapsible>
437 </div>
438 );
439}
440
441function ReviewThreadEvent({
442 revealAnchor,
443 event,
444 thread,
445 editable,
446 cwd,
447 onOpen,
448 reactions,
449 detail,
450}: {
451 revealAnchor?: string | null;
452 event: PullRequestTimelineEvent;
453 thread: PullRequestTimelineThread;
454 detail: PullRequestDetailView;
455 editable: ReadonlyMap<string, PullRequestComment>;
456 cwd: string;
457 onOpen: (url: string) => void;
458 reactions: ReactionSurface;
459}) {
460 const dismissed = pullRequestReviewOutcome(event.reviewState) === "dismissed";
461 const [expanded, setExpanded] = useState(
462 () =>
463 (revealAnchor != null &&
464 [event, ...thread.replies].some((item) =>
465 pullRequestAnchorMatchesUrl(revealAnchor, item.url),
466 )) ||
467 (!thread.isResolved && !dismissed),
468 );
469 const replyCount = thread.replies.length + thread.moreReplies;
470
471 return (
472 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
473 <ActorTimelineMarker
474 actors={event.actor ? [event.actor] : []}
475 className="top-4"
476 fallback={<MessageSquareIcon className="size-3.5" />}
477 muted={!expanded}
478 />
479 <div className="flex min-w-0 items-center gap-1">
480 <button
481 type="button"
482 className="flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left text-2xs text-muted-foreground hover:text-foreground"
483 aria-expanded={expanded}
484 onClick={() => setExpanded((current) => !current)}
485 >
486 {thread.path === null ? (
487 <span className="min-w-0 truncate">Overview</span>
488 ) : (
489 <>
490 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
491 <span className="min-w-0 truncate font-mono">
492 {thread.line === null ? thread.path : `${thread.path}:${thread.line}`}
493 </span>
494 </>
495 )}
496 {thread.isResolved ? (
497 <span className="inline-flex shrink-0 items-center gap-1 font-medium text-success-foreground">
498 <CircleCheckIcon aria-hidden className="size-3" />
499 Resolved
500 </span>
501 ) : null}
502 {dismissed ? <span className="shrink-0 font-medium">Review dismissed</span> : null}
503 {thread.isOutdated ? <span className="shrink-0 font-medium">Outdated</span> : null}
504 {expanded ? null : (
505 <span className="shrink-0">
506 · {event.actor?.login ?? "ghost"}
507 {replyCount > 0 ? (
508 <>
509 {" "}
510 · {replyCount.toLocaleString()} {replyCount === 1 ? "reply" : "replies"}
511 </>
512 ) : null}
513 </span>
514 )}
515 <ChevronDownIcon
516 aria-hidden
517 className={cn(
518 "ml-auto size-3.5 shrink-0 transition-transform",
519 expanded && "rotate-180",
520 )}
521 />
522 </button>
523 {expanded ? (
524 <PullRequestResolveThreadButton
525 environmentId={reactions.environmentId}
526 reference={reactions.reference}
527 detail={detail}
528 thread={thread}
529 onRefresh={reactions.onRefresh}
530 />
531 ) : null}
532 </div>
533 {expanded ? (
534 <>
535 <ConversationCard
536 event={event}
537 editable={editable.get(event.id) ?? null}
538 cwd={cwd}
539 onOpen={onOpen}
540 reactions={reactions}
541 showPath={false}
542 />
543 {thread.replies.length > 0 ? (
544 <div className="ml-2 space-y-1 border-l border-border/60 pl-3">
545 {thread.replies.map((reply) => (
546 <ConversationCard
547 key={reply.id}
548 event={reply}
549 editable={editable.get(reply.id) ?? null}
550 cwd={cwd}
551 onOpen={onOpen}
552 reactions={reactions}
553 showPath={false}
554 reply
555 />
556 ))}
557 </div>
558 ) : null}
559 </>
560 ) : null}
561 {thread.hasMoreReplies ? (
562 <div className="px-2">
563 <PullRequestMoreReplies {...thread} />
564 </div>
565 ) : null}
566 </div>
567 );
568}
569
570function CommitEvent({
571 event,
572 onOpen,
573}: {
574 event: PullRequestTimelineEvent;
575 onOpen: (oid: string) => void;
576}) {
577 return (
578 <button
579 type="button"
580 className="group relative mb-5 block w-full cursor-pointer rounded-sm pl-12 text-left outline-none [contain-intrinsic-block-size:48px] [content-visibility:auto] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
581 aria-label={`View commit ${event.id}`}
582 onClick={() => onOpen(event.id)}
583 >
584 <ActorTimelineMarker
585 actors={event.commitAuthors}
586 fallback={<GitCommitHorizontalIcon className="size-3.5" />}
587 />
588 <div className="flex min-w-0 items-center gap-2.5 py-1.5">
589 <div className="min-w-0 flex-1">
590 <div className="truncate text-xs font-semibold text-foreground transition-colors group-hover:text-primary">
591 {event.body ?? "Untitled commit"}
592 </div>
593 <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-3xs text-muted-foreground">
594 <code className="font-mono">{event.id.slice(0, 7)}</code>
595 <span>
596 <RelativeTime timestamp={event.at} />
597 </span>
598 </div>
599 </div>
600 {event.additions !== null && event.deletions !== null ? (
601 <PullRequestDiffStat
602 additions={event.additions}
603 deletions={event.deletions}
604 className="ml-auto shrink-0 font-mono text-3xs"
605 />
606 ) : null}
607 </div>
608 </button>
609 );
610}
611
612function LifecycleEvent({ event, term }: { event: PullRequestTimelineEvent; term: string }) {
613 const title = capitalizeTerm(term);
614 const presentation =
615 event.kind === "opened"
616 ? {
617 icon: <PullRequestGlyph.pullRequest className="size-3.5" />,
618 label: `${title} opened`,
619 }
620 : event.kind === "merged"
621 ? {
622 icon: <PullRequestGlyph.merged className="size-3.5" />,
623 label: `${title} merged`,
624 }
625 : {
626 icon: <PullRequestGlyph.closed className="size-3.5" />,
627 label: `${title} closed`,
628 };
629
630 return (
631 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
632 <IconMarker icon={presentation.icon} />
633 <div className="py-1.5 text-xs">
634 <div className="flex flex-wrap items-center gap-1.5">
635 {event.actor ? <ActorName actor={event.actor} /> : null}
636 <span className="font-semibold text-foreground">{presentation.label}</span>
637 </div>
638 <div className="mt-0.5 text-2xs text-muted-foreground">
639 <RelativeTime timestamp={event.at} />
640 </div>
641 </div>
642 </div>
643 );
644}
645
646function ReviewVerdictEvent({
647 event,
648 outcome,
649 stale,
650 cwd,
651 onOpen,
652 reactions,
653}: {
654 event: PullRequestTimelineEvent;
655 outcome: PullRequestReviewOutcome;
656 stale: boolean;
657 cwd: string;
658 onOpen: (url: string) => void;
659 reactions: ReactionSurface;
660}) {
661 const canReact = reactions.canReact(event);
662 return (
663 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
664 <ActorTimelineMarker
665 actors={event.actor ? [event.actor] : []}
666 className="top-6"
667 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
668 />
669 <div className="flex min-w-0 flex-wrap items-center gap-2 py-1.5">
670 <div className="min-w-0 flex-1">
671 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
672 <ActorName actor={event.actor} />
673 <Tooltip disabled={!stale}>
674 <TooltipTrigger
675 render={
676 <span
677 className={cn(
678 "font-medium lowercase",
679 stale
680 ? "text-muted-foreground opacity-70"
681 : pullRequestReviewOutcomeToneClassName(outcome),
682 )}
683 />
684 }
685 >
686 {pullRequestReviewOutcomeLabel(outcome)}
687 {stale ? <span className="sr-only">, before the latest commits</span> : null}
688 </TooltipTrigger>
689 <TooltipPopup>{pullRequestReviewOutcomeStaleLabel(outcome)}</TooltipPopup>
690 </Tooltip>
691 </div>
692 <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
693 <PullRequestMetaLine className="flex-wrap text-2xs text-muted-foreground">
694 <span>
695 <RelativeTime timestamp={event.at} />
696 </span>
697 {event.path ? (
698 <span className="inline-flex min-w-0 items-center gap-1">
699 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
700 <span className="truncate">{event.path}</span>
701 </span>
702 ) : null}
703 </PullRequestMetaLine>
704 </div>
705 </div>
706 {event.body && event.comment ? (
707 <AddToChatButton comment={event.comment} reactions={reactions} />
708 ) : null}
709 {canReact || event.reactions.length > 0 ? (
710 <PullRequestReactionBar
711 className="ml-auto justify-end"
712 reactions={event.reactions}
713 canReact={canReact}
714 subjectId={event.id}
715 environmentId={reactions.environmentId}
716 reference={reactions.reference}
717 onRefresh={reactions.onRefresh}
718 />
719 ) : null}
720 <OpenOnHostButton url={event.url} onOpen={onOpen} />
721 </div>
722 {event.body ? (
723 <TimelineBody
724 body={event.body}
725 markdown={event.markdown}
726 cwd={cwd}
727 environmentId={reactions.environmentId}
728 threadRef={reactions.threadRef}
729 />
730 ) : null}
731 </div>
732 );
733}
734
735export function PullRequestTimelineTab({
736 revealUrl,
737 onRevealSettled,
738 scrollerRef,
739 detail,
740 environmentId,
741 threadRef = null,
742 reference,
743 order,
744 onOpenCommit,
745 onAddToChat,
746 onRefresh,
747}: {
748 /** A clicked link to scroll to and mark, until onRevealSettled reports it shown. */
749 revealUrl?: string | undefined;
750 onRevealSettled?: ((revealUrl: string) => void) | undefined;
751 scrollerRef: (node: HTMLElement | null) => void;
752 detail: PullRequestDetailView;
753 environmentId: EnvironmentId;
754 threadRef?: ScopedThreadRef | null;
755 reference: PullRequestRef;
756 order: "newest" | "oldest";
757 onOpenCommit: (oid: string) => void;
758 onAddToChat?: (subject: PullRequestChatSubject) => void;
759 onRefresh: () => void;
760}) {
761 const events = buildPullRequestTimeline(detail);
762 const location = parsePullRequestAnchor(revealUrl);
763 const revealAnchor = location?.kind === "timeline" ? location.anchor : null;
764 // The linked item stays marked and open after it is shown, until another link replaces it.
765 const [linked, setLinked] = useState<{ readonly anchor: string; readonly count: number } | null>(
766 () => (revealAnchor === null ? null : { anchor: revealAnchor, count: 1 }),
767 );
768 const [seenRevealUrl, setSeenRevealUrl] = useState(revealUrl);
769 if (revealUrl !== seenRevealUrl) {
770 setSeenRevealUrl(revealUrl);
771 // Each click remounts the linked row, so it opens again even after the user closed it.
772 if (revealAnchor !== null) setLinked({ anchor: revealAnchor, count: (linked?.count ?? 0) + 1 });
773 }
774 const anchor = linked
775 ? resolvePullRequestReviewAnchor(linked.anchor, detail.comments, detail.reviewThreads)
776 : null;
777 const listRef = useRef<LegendListRef | null>(null);
778 const matches = (event: PullRequestTimelineEvent) =>
779 anchor !== null && pullRequestTimelineEventMatches(event, anchor);
780
781 const term = sourceControlClients.get(detail.provider).changeRequest.singular;
782 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
783 const reactions: ReactionSurface = {
784 revealAnchor: anchor,
785 canReact: (event) =>
786 event.comment !== undefined && canReactPullRequestComment(detail, event.comment),
787 onAddToChat: onAddToChat && ((comment) => onAddToChat({ kind: "comment", comment })),
788 environmentId,
789 threadRef,
790 reference,
791 completionScope: pullRequestCompletionScope(detail, environmentId, reference),
792 onRefresh,
793 };
794 const editable = new Map(
795 events
796 .flatMap((event) => [event, ...(event.thread?.replies ?? [])])
797 .flatMap((event) => (event.comment ? [event.comment] : []))
798 .filter((comment) => canEditPullRequestComment(detail, comment))
799 .map((comment) => [comment.id, comment] as const),
800 );
801 const orderedEvents = order === "newest" ? events : events.toReversed();
802 const rows = groupPullRequestTimelineConversations(orderedEvents);
803 const targetIndex = rows.findIndex((row) =>
804 row.kind === "comments" ? row.events.some(matches) : matches(row.event),
805 );
806 const stopHolding = useRef<(() => void) | null>(null);
807 const reveal = useEffectEvent(() => {
808 const list = listRef.current;
809 const url = revealUrl;
810 if (url === undefined || revealAnchor === null || targetIndex < 0 || !list) return;
811 stopHolding.current?.();
812 void list.scrollToIndex({ index: targetIndex, viewPosition: 0, animated: false }).then(() => {
813 const scroller = list.getScrollableNode();
814 const node = scroller?.querySelector<HTMLElement>("[data-pr-link-target=true]");
815 if (scroller && node) stopHolding.current = holdLinkedNodeInView(node, scroller, () => 16);
816 onRevealSettled?.(url);
817 });
818 });
819 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals a link destination after activity loading and virtual list mounting
820 useEffect(() => {
821 reveal();
822 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- runs for each clicked link and again when activity resolves its row
823 }, [revealUrl, targetIndex]);
824 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab
825 useEffect(() => () => stopHolding.current?.(), []);
826 const openOnHost = (url: string) => {
827 void readLocalApi()?.shell.openExternal(url);
828 };
829
830 const rowKey = (row: PullRequestTimelineRow) => {
831 if (row.kind === "comments")
832 return `comments:${row.events[0]?.id ?? "empty"}:${row.events.some(matches) ? (linked?.count ?? "") : ""}`;
833 const event = row.event;
834 // A thread's resolution or dismissal remounts it, so its disclosure starts in the new state.
835 return event.thread === undefined
836 ? `${event.id}:${matches(event) ? (linked?.count ?? "") : ""}`
837 : `thread:${event.id}:${matches(event) ? (linked?.count ?? "") : ""}:${event.thread.isResolved}:${pullRequestReviewOutcome(event.reviewState) === "dismissed"}`;
838 };
839 const renderRow = ({ item: row }: { item: PullRequestTimelineRow }) => {
840 if (row.kind === "comments") {
841 return (
842 <ConversationGroup
843 events={row.events}
844 revealAnchor={anchor}
845 editable={editable}
846 cwd={detail.workspaceRoot}
847 onOpen={openOnHost}
848 reactions={reactions}
849 />
850 );
851 }
852 const event = row.event;
853 if (event.thread !== undefined) {
854 return (
855 <ReviewThreadEvent
856 event={event}
857 thread={event.thread}
858 detail={detail}
859 revealAnchor={anchor}
860 editable={editable}
861 cwd={detail.workspaceRoot}
862 onOpen={openOnHost}
863 reactions={reactions}
864 />
865 );
866 }
867 if (event.kind === "commit") return <CommitEvent event={event} onOpen={onOpenCommit} />;
868 const outcome = pullRequestReviewOutcome(event.reviewState);
869 if (outcome !== null) {
870 return (
871 <ReviewVerdictEvent
872 event={event}
873 outcome={outcome}
874 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
875 cwd={detail.workspaceRoot}
876 onOpen={openOnHost}
877 reactions={reactions}
878 />
879 );
880 }
881 return <LifecycleEvent event={event} term={term} />;
882 };
883
884 if (events.length === 0) {
885 return (
886 <div ref={scrollerRef} className="scrollbar-gutter-both h-full overflow-y-auto px-4 py-5">
887 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
888 <PullRequestGlyph.pullRequest className="mb-2 size-5" />
889 <p className="text-xs">No activity yet.</p>
890 </div>
891 </div>
892 );
893 }
894
895 // Virtualized: a large pull request has thousands of events, and mounting every one stalls
896 // the page. The connector line is drawn by the content container, behind the rows.
897 return (
898 <LegendList<PullRequestTimelineRow>
899 ref={(list: LegendListRef | null) => {
900 listRef.current = list;
901 scrollerRef(list?.getScrollableNode() ?? null);
902 }}
903 data={rows}
904 extraData={{ editable, reactions, newestCommitAt }}
905 keyExtractor={rowKey}
906 renderItem={renderRow}
907 estimatedItemSize={140}
908 className="scrollbar-gutter-both h-full px-4"
909 contentContainerClassName="relative mx-auto w-full max-w-3xl before:absolute before:bottom-10 before:left-[15px] before:top-6 before:w-px before:bg-border/45"
910 ListHeaderComponent={
911 anchor !== null && targetIndex < 0 && revealUrl === undefined ? (
912 <p role="status" className="py-4 text-xs text-muted-foreground">
913 The linked item is not in the loaded activity.
914 </p>
915 ) : (
916 <div className="h-5" />
917 )
918 }
919 ListFooterComponent={<div className="h-5" />}
920 />
921 );
922}