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