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 } 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
338 aria-label={gt("Edit comment")}
339 onClick={() => setEditing(true)}
340 />
341 ) : null}
342 {resolveButton}
343 {event.body && event.comment && !reply ? (
344 <AddToChatButton comment={event.comment} reactions={reactions} />
345 ) : null}
346 {canReact || event.reactions.length > 0 ? (
347 <PullRequestReactionBar
348 className="ml-auto justify-end"
349 reactions={event.reactions}
350 canReact={canReact}
351 subjectId={event.id}
352 environmentId={reactions.environmentId}
353 reference={reactions.reference}
354 onRefresh={reactions.onRefresh}
355 />
356 ) : null}
357 <OpenOnHostButton url={event.url} onOpen={onOpen} />
358 </div>
359 </div>
360 {editing && editable !== null ? (
361 <div className="px-2 pb-2 pt-3">
362 <PullRequestMarkdownEditor
363 value={editable.body}
364 cwd={cwd}
365 environmentId={reactions.environmentId}
366 completionScope={reactions.completionScope}
367 threadRef={reactions.threadRef}
368 label={gt("Edit comment")}
369 saving={saving}
370 onSave={(body) => void save(body)}
371 onCancel={() => setEditing(false)}
372 />
373 </div>
374 ) : event.body ? (
375 <div className="px-2 pb-2">
376 <TimelineBody
377 body={event.body}
378 markdown={event.markdown}
379 cwd={cwd}
380 environmentId={reactions.environmentId}
381 threadRef={reactions.threadRef}
382 />
383 </div>
384 ) : null}
385 </article>
386 );
387}
388
389function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
390 const actors = new Map<string, PullRequestActor>();
391 for (const event of events) {
392 const actor = event.actor;
393 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
394 }
395 return [...actors.values()];
396}
397
398function ConversationGroup({
399 revealAnchor,
400 events,
401 editable,
402 cwd,
403 onOpen,
404 reactions,
405}: {
406 revealAnchor?: string | null;
407 events: ReadonlyArray<PullRequestTimelineEvent>;
408 editable: ReadonlyMap<string, PullRequestComment>;
409 cwd: string;
410 onOpen: OpenOnHost;
411 reactions: ReactionSurface;
412}) {
413 const [open, setOpen] = useState(
414 () =>
415 revealAnchor != null &&
416 events.some((event) => pullRequestAnchorMatchesUrl(revealAnchor, event.url)),
417 );
418 const gt = useGT();
419 const actors = uniqueConversationActors(events);
420 const first = events[0];
421 if (first === undefined) return null;
422
423 return (
424 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
425 <ActorTimelineMarker
426 actors={actors}
427 className="top-6"
428 fallback={<MessageSquareIcon className="size-3.5" />}
429 muted={!open}
430 />
431 <Collapsible open={open} onOpenChange={setOpen}>
432 <div>
433 <CollapsibleTrigger
434 className={cn(
435 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
436 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
437 )}
438 >
439 <span className="min-w-0 flex-1">
440 <span className="block text-xs font-semibold">
441 {gt("{count, plural, one {{formatted} comment} other {{formatted} comments}}", {
442 count: events.length,
443 formatted: events.length.toLocaleString(),
444 })}
445 </span>
446 <span className="block truncate text-3xs text-muted-foreground">
447 {gt("{count, plural, one {{formatted} author} other {{formatted} authors}}", {
448 count: actors.length,
449 formatted: actors.length.toLocaleString(),
450 })}{" "}
451 · <RelativeTime timestamp={first.at} />
452 </span>
453 </span>
454 <ChevronDownIcon
455 aria-hidden
456 className={cn(
457 "size-3.5 shrink-0 text-muted-foreground transition-transform",
458 open && "rotate-180",
459 )}
460 />
461 </CollapsibleTrigger>
462 <CollapsiblePanel>
463 {open ? (
464 <div className="mt-1 space-y-1">
465 {events.map((event) => (
466 <ConversationCard
467 // Host comment ids can collide across pull requests.
468 key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
469 event={event}
470 editable={editable.get(event.id) ?? null}
471 cwd={cwd}
472 onOpen={onOpen}
473 reactions={reactions}
474 />
475 ))}
476 </div>
477 ) : null}
478 </CollapsiblePanel>
479 </div>
480 </Collapsible>
481 </div>
482 );
483}
484
485function ReviewThreadEvent({
486 revealAnchor,
487 event,
488 thread,
489 editable,
490 cwd,
491 onOpen,
492 reactions,
493 detail,
494}: {
495 revealAnchor?: string | null;
496 event: PullRequestTimelineEvent;
497 thread: PullRequestTimelineThread;
498 detail: PullRequestDetailView;
499 editable: ReadonlyMap<string, PullRequestComment>;
500 cwd: string;
501 onOpen: OpenOnHost;
502 reactions: ReactionSurface;
503}) {
504 const gt = useGT();
505 const dismissed = pullRequestReviewOutcome(event.reviewState) === "dismissed";
506 const [expanded, setExpanded] = useState(
507 () =>
508 (revealAnchor != null &&
509 [event, ...thread.replies].some((item) =>
510 pullRequestAnchorMatchesUrl(revealAnchor, item.url),
511 )) ||
512 (!thread.isResolved && !dismissed),
513 );
514 const replyCount = thread.replies.length + thread.moreReplies;
515
516 return (
517 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
518 <ActorTimelineMarker
519 actors={event.actor ? [event.actor] : []}
520 className="top-4"
521 fallback={<MessageSquareIcon className="size-3.5" />}
522 muted={!expanded}
523 />
524 <button
525 type="button"
526 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"
527 aria-expanded={expanded}
528 onClick={() => setExpanded((current) => !current)}
529 >
530 {thread.path === null ? (
531 <span className="min-w-0 truncate">
532 <T context="review thread without a file">Overview</T>
533 </span>
534 ) : (
535 <>
536 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
537 <span className="min-w-0 truncate font-mono">
538 {thread.line === null ? thread.path : `${thread.path}:${thread.line}`}
539 </span>
540 </>
541 )}
542 {thread.isResolved ? (
543 <span className="inline-flex shrink-0 items-center gap-1 font-medium text-success-foreground">
544 <CircleCheckIcon aria-hidden className="size-3" />
545 <T context="review thread state">Resolved</T>
546 </span>
547 ) : null}
548 {dismissed ? (
549 <span className="shrink-0 font-medium">
550 <T>Review dismissed</T>
551 </span>
552 ) : null}
553 {thread.isOutdated ? (
554 <span className="shrink-0 font-medium">
555 <T context="review thread state">Outdated</T>
556 </span>
557 ) : null}
558 {expanded ? null : (
559 <span className="shrink-0">
560 · {event.actor?.login ?? "ghost"}
561 {replyCount > 0 ? (
562 <>
563 {" "}
564 ·{" "}
565 {gt("{count, plural, one {{formatted} reply} other {{formatted} replies}}", {
566 count: replyCount,
567 formatted: replyCount.toLocaleString(),
568 })}
569 </>
570 ) : null}
571 </span>
572 )}
573 <ChevronDownIcon
574 aria-hidden
575 className={cn("ml-auto size-3.5 shrink-0 transition-transform", expanded && "rotate-180")}
576 />
577 </button>
578 {expanded ? (
579 <>
580 <ConversationCard
581 event={event}
582 editable={editable.get(event.id) ?? null}
583 cwd={cwd}
584 onOpen={onOpen}
585 reactions={reactions}
586 showPath={false}
587 resolveButton={
588 <PullRequestResolveThreadButton
589 environmentId={reactions.environmentId}
590 reference={reactions.reference}
591 detail={detail}
592 thread={thread}
593 onRefresh={reactions.onRefresh}
594 />
595 }
596 />
597 {thread.replies.length > 0 ? (
598 <div className="ml-2 space-y-1 border-l border-border/60 pl-3">
599 {thread.replies.map((reply) => (
600 <ConversationCard
601 key={reply.id}
602 event={reply}
603 editable={editable.get(reply.id) ?? null}
604 cwd={cwd}
605 onOpen={onOpen}
606 reactions={reactions}
607 showPath={false}
608 reply
609 />
610 ))}
611 </div>
612 ) : null}
613 </>
614 ) : null}
615 {thread.hasMoreReplies ? (
616 <div className="px-2">
617 <PullRequestMoreReplies {...thread} threadRef={reactions.threadRef} />
618 </div>
619 ) : null}
620 </div>
621 );
622}
623
624function CommitEvent({
625 event,
626 onOpen,
627}: {
628 event: PullRequestTimelineEvent;
629 onOpen: (oid: string) => void;
630}) {
631 const gt = useGT();
632 return (
633 <button
634 type="button"
635 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"
636 aria-label={gt("View commit {sha}", { sha: event.id })}
637 onClick={() => onOpen(event.id)}
638 >
639 <ActorTimelineMarker
640 actors={event.commitAuthors}
641 fallback={<GitCommitHorizontalIcon className="size-3.5" />}
642 />
643 <div className="flex min-w-0 items-center gap-2.5 py-1.5">
644 <div className="min-w-0 flex-1">
645 <div className="truncate text-xs font-semibold text-foreground transition-colors group-hover:text-primary">
646 {event.body ?? gt("Untitled commit")}
647 </div>
648 <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-3xs text-muted-foreground">
649 <code className="font-mono">{event.id.slice(0, 7)}</code>
650 <span>
651 <RelativeTime timestamp={event.at} />
652 </span>
653 </div>
654 </div>
655 {event.additions !== null && event.deletions !== null ? (
656 <PullRequestDiffStat
657 additions={event.additions}
658 deletions={event.deletions}
659 className="ml-auto shrink-0 font-mono text-3xs"
660 />
661 ) : null}
662 </div>
663 </button>
664 );
665}
666
667function LifecycleEvent({
668 event,
669 term,
670}: {
671 event: PullRequestTimelineEvent;
672 term: ChangeRequestTermKind;
673}) {
674 const gt = useGT();
675 const presentation =
676 event.kind === "opened"
677 ? {
678 icon: <PullRequestGlyph.pullRequest className="size-3.5" />,
679 label: gt(
680 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} opened",
681 { term },
682 ),
683 }
684 : event.kind === "merged"
685 ? {
686 icon: <PullRequestGlyph.merged className="size-3.5" />,
687 label: gt(
688 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} merged",
689 { term },
690 ),
691 }
692 : {
693 icon: <PullRequestGlyph.closed className="size-3.5" />,
694 label: gt(
695 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} closed",
696 { term },
697 ),
698 };
699
700 return (
701 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
702 <IconMarker icon={presentation.icon} />
703 <div className="py-1.5 text-xs">
704 <div className="flex flex-wrap items-center gap-1.5">
705 {event.actor ? <ActorName actor={event.actor} /> : null}
706 <span className="font-semibold text-foreground">{presentation.label}</span>
707 </div>
708 <div className="mt-0.5 text-2xs text-muted-foreground">
709 <RelativeTime timestamp={event.at} />
710 </div>
711 </div>
712 </div>
713 );
714}
715
716function staleReviewOutcomeLabel(
717 outcome: PullRequestReviewOutcome,
718 gt: ReturnType<typeof useGT>,
719): string {
720 switch (outcome) {
721 case "approved":
722 return gt("Approved, before the latest commits");
723 case "changes-requested":
724 return gt("Changes requested, before the latest commits");
725 case "dismissed":
726 return gt("Review dismissed, before the latest commits");
727 }
728}
729
730function ReviewVerdictEvent({
731 event,
732 outcome,
733 stale,
734 cwd,
735 onOpen,
736 reactions,
737}: {
738 event: PullRequestTimelineEvent;
739 outcome: PullRequestReviewOutcome;
740 stale: boolean;
741 cwd: string;
742 onOpen: OpenOnHost;
743 reactions: ReactionSurface;
744}) {
745 const gt = useGT();
746 const resolve = useMessages();
747 const canReact = reactions.canReact(event);
748 return (
749 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
750 <ActorTimelineMarker
751 actors={event.actor ? [event.actor] : []}
752 className="top-6"
753 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
754 />
755 <div className="flex min-w-0 flex-wrap items-center gap-2 py-1.5">
756 <div className="min-w-0 flex-1">
757 <h2 className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
758 <ActorName actor={event.actor} />
759 <SharedTooltipTrigger
760 disabled={!stale}
761 render={
762 <span
763 className={cn(
764 "font-medium lowercase",
765 stale
766 ? "text-muted-foreground opacity-70"
767 : pullRequestReviewOutcomeToneClassName(outcome),
768 )}
769 />
770 }
771 label={pullRequestReviewOutcomeStaleLabel(outcome, resolve)}
772 >
773 {stale ? (
774 <>
775 <span aria-hidden>{pullRequestReviewOutcomeLabel(outcome, resolve)}</span>
776 <span className="sr-only">{staleReviewOutcomeLabel(outcome, gt)}</span>
777 </>
778 ) : (
779 pullRequestReviewOutcomeLabel(outcome, resolve)
780 )}
781 </SharedTooltipTrigger>
782 </h2>
783 <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
784 <PullRequestMetaLine className="flex-wrap text-2xs text-muted-foreground">
785 <span>
786 <RelativeTime timestamp={event.at} />
787 </span>
788 {event.path ? (
789 <span className="inline-flex min-w-0 items-center gap-1">
790 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
791 <span className="truncate">{event.path}</span>
792 </span>
793 ) : null}
794 </PullRequestMetaLine>
795 </div>
796 </div>
797 {event.body && event.comment ? (
798 <AddToChatButton comment={event.comment} reactions={reactions} />
799 ) : null}
800 {canReact || event.reactions.length > 0 ? (
801 <PullRequestReactionBar
802 className="ml-auto justify-end"
803 reactions={event.reactions}
804 canReact={canReact}
805 subjectId={event.id}
806 environmentId={reactions.environmentId}
807 reference={reactions.reference}
808 onRefresh={reactions.onRefresh}
809 />
810 ) : null}
811 <OpenOnHostButton url={event.url} onOpen={onOpen} />
812 </div>
813 {event.body ? (
814 <TimelineBody
815 body={event.body}
816 markdown={event.markdown}
817 cwd={cwd}
818 environmentId={reactions.environmentId}
819 threadRef={reactions.threadRef}
820 />
821 ) : null}
822 </div>
823 );
824}
825
826export function PullRequestTimelineTab({
827 revealUrl,
828 onRevealSettled,
829 scrollerRef,
830 detail,
831 environmentId,
832 threadRef = null,
833 reference,
834 order,
835 onOpenCommit,
836 onAddToChat,
837 onRefresh,
838}: {
839 /** A clicked link to scroll to and mark, until onRevealSettled reports it shown. */
840 revealUrl?: string | undefined;
841 onRevealSettled?: ((revealUrl: string) => void) | undefined;
842 scrollerRef: (node: HTMLElement | null) => void;
843 detail: PullRequestDetailView;
844 environmentId: EnvironmentId;
845 threadRef?: ScopedThreadRef | null;
846 reference: PullRequestRef;
847 order: "newest" | "oldest";
848 onOpenCommit: (oid: string) => void;
849 onAddToChat?: (subject: PullRequestChatSubject) => void;
850 onRefresh: () => void;
851}) {
852 const resolve = useMessages();
853 const events = buildPullRequestTimeline(detail, resolve);
854 const location = parsePullRequestAnchor(revealUrl);
855 const revealAnchor = location?.kind === "timeline" ? location.anchor : null;
856 // The linked item stays marked and open after it is shown, until another link replaces it.
857 const [linked, setLinked] = useState<{ readonly anchor: string; readonly count: number } | null>(
858 () => (revealAnchor === null ? null : { anchor: revealAnchor, count: 1 }),
859 );
860 const [seenRevealUrl, setSeenRevealUrl] = useState(revealUrl);
861 if (revealUrl !== seenRevealUrl) {
862 setSeenRevealUrl(revealUrl);
863 // Each click remounts the linked row, so it opens again even after the user closed it.
864 if (revealAnchor !== null) setLinked({ anchor: revealAnchor, count: (linked?.count ?? 0) + 1 });
865 }
866 const anchor = linked
867 ? resolvePullRequestReviewAnchor(linked.anchor, detail.comments, detail.reviewThreads)
868 : null;
869 const listRef = useRef<LegendListRef | null>(null);
870 const matches = (event: PullRequestTimelineEvent) =>
871 anchor !== null && pullRequestTimelineEventMatches(event, anchor);
872
873 const term = changeRequestTermKind(sourceControlClients.get(detail.provider).changeRequest);
874 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
875 const reactions: ReactionSurface = {
876 revealAnchor: anchor,
877 canReact: (event) =>
878 event.comment !== undefined && canReactPullRequestComment(detail, event.comment),
879 onAddToChat: onAddToChat && ((comment) => onAddToChat({ kind: "comment", comment })),
880 environmentId,
881 threadRef,
882 reference,
883 completionScope: pullRequestCompletionScope(detail, environmentId, reference),
884 onRefresh,
885 };
886 const editable = new Map(
887 events
888 .flatMap((event) => [event, ...(event.thread?.replies ?? [])])
889 .flatMap((event) => (event.comment ? [event.comment] : []))
890 .filter((comment) => canEditPullRequestComment(detail, comment))
891 .map((comment) => [comment.id, comment] as const),
892 );
893 const orderedEvents = order === "newest" ? events : events.toReversed();
894 const rows = groupPullRequestTimelineConversations(orderedEvents);
895 const targetIndex = rows.findIndex((row) =>
896 row.kind === "comments" ? row.events.some(matches) : matches(row.event),
897 );
898 const stopHolding = useRef<(() => void) | null>(null);
899 const reveal = useEffectEvent(() => {
900 const list = listRef.current;
901 const url = revealUrl;
902 if (url === undefined || revealAnchor === null || targetIndex < 0 || !list) return;
903 stopHolding.current?.();
904 void list.scrollToIndex({ index: targetIndex, viewPosition: 0, animated: false }).then(() => {
905 const scroller = list.getScrollableNode();
906 const node = scroller?.querySelector<HTMLElement>("[data-pr-link-target=true]");
907 if (scroller && node) stopHolding.current = holdLinkedNodeInView(node, scroller, () => 16);
908 onRevealSettled?.(url);
909 });
910 });
911 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals a link destination after activity loading and virtual list mounting
912 useEffect(() => {
913 reveal();
914 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- runs for each clicked link and again when activity resolves its row
915 }, [revealUrl, targetIndex]);
916 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab
917 useEffect(() => () => stopHolding.current?.(), []);
918 const openLink = useOpenLink(threadRef);
919 const openOnHost: OpenOnHost = (url, event) => {
920 void openLink(url, { event }).catch(console.error);
921 };
922
923 const rowKey = (row: PullRequestTimelineRow) => {
924 if (row.kind === "comments")
925 return `comments:${row.events[0]?.id ?? "empty"}:${row.events.some(matches) ? (linked?.count ?? "") : ""}`;
926 const event = row.event;
927 // A thread's resolution or dismissal remounts it, so its disclosure starts in the new state.
928 return event.thread === undefined
929 ? `${event.id}:${matches(event) ? (linked?.count ?? "") : ""}`
930 : `thread:${event.id}:${matches(event) ? (linked?.count ?? "") : ""}:${event.thread.isResolved}:${pullRequestReviewOutcome(event.reviewState) === "dismissed"}`;
931 };
932 const renderRow = ({ item: row }: { item: PullRequestTimelineRow }) => {
933 if (row.kind === "comments") {
934 return (
935 <ConversationGroup
936 events={row.events}
937 revealAnchor={anchor}
938 editable={editable}
939 cwd={detail.workspaceRoot}
940 onOpen={openOnHost}
941 reactions={reactions}
942 />
943 );
944 }
945 const event = row.event;
946 if (event.thread !== undefined) {
947 return (
948 <ReviewThreadEvent
949 event={event}
950 thread={event.thread}
951 detail={detail}
952 revealAnchor={anchor}
953 editable={editable}
954 cwd={detail.workspaceRoot}
955 onOpen={openOnHost}
956 reactions={reactions}
957 />
958 );
959 }
960 if (event.kind === "commit") return <CommitEvent event={event} onOpen={onOpenCommit} />;
961 const outcome = pullRequestReviewOutcome(event.reviewState);
962 if (outcome !== null) {
963 return (
964 <ReviewVerdictEvent
965 event={event}
966 outcome={outcome}
967 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
968 cwd={detail.workspaceRoot}
969 onOpen={openOnHost}
970 reactions={reactions}
971 />
972 );
973 }
974 return <LifecycleEvent event={event} term={term} />;
975 };
976
977 if (events.length === 0) {
978 return (
979 <div
980 ref={scrollerRef}
981 tabIndex={-1}
982 data-workspace-focus-default
983 className="scrollbar-gutter-both h-full overflow-y-auto px-4 py-5 outline-none"
984 >
985 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
986 <PullRequestGlyph.pullRequest className="mb-2 size-5" />
987 <p className="text-xs">
988 <T>No activity yet.</T>
989 </p>
990 </div>
991 </div>
992 );
993 }
994
995 // Virtualized: a large pull request has thousands of events, and mounting every one stalls
996 // the page. The connector line is drawn by the content container, behind the rows.
997 return (
998 <LegendList<PullRequestTimelineRow>
999 ref={(list: LegendListRef | null) => {
1000 listRef.current = list;
1001 scrollerRef(list?.getScrollableNode() ?? null);
1002 }}
1003 data={rows}
1004 extraData={{ editable, reactions, newestCommitAt }}
1005 keyExtractor={rowKey}
1006 renderItem={renderRow}
1007 estimatedItemSize={140}
1008 tabIndex={-1}
1009 data-workspace-focus-default
1010 className="scrollbar-gutter-both h-full px-4 outline-none"
1011 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"
1012 ListHeaderComponent={
1013 anchor !== null && targetIndex < 0 && revealUrl === undefined ? (
1014 <p role="status" className="py-4 text-xs text-muted-foreground">
1015 <T>The linked item is not in the loaded activity.</T>
1016 </p>
1017 ) : (
1018 <div className="h-5" />
1019 )
1020 }
1021 ListFooterComponent={<div className="h-5" />}
1022 />
1023 );
1024}