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