Open History to see the last commit
1import { useAtomCommand } from "~/state/use-atom-command";
2import type {
3 EnvironmentId,
4 PullRequestActor,
5 PullRequestComment,
6 PullRequestDetailView,
7 PullRequestRef,
8 ScopedThreadRef,
9} from "@t3tools/contracts";
10import {
11 ChevronDownIcon,
12 CircleCheckIcon,
13 ExternalLinkIcon,
14 FileCode2Icon,
15 GitCommitHorizontalIcon,
16 MessageSquareIcon,
17} from "lucide-react";
18import { useState, type ReactNode } from "react";
19
20import { cn } from "~/lib/utils";
21import { readLocalApi } from "~/localApi";
22import { pullRequestEnvironment } from "~/state/pullRequests";
23import { RelativeTime } from "~/components/RelativeTime";
24
25import { Button } from "../ui/button";
26import { PullRequestEditButton } from "./PullRequestEditButton";
27import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
28import { toastManager } from "../ui/toast";
29import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30import {
31 buildPullRequestTimeline,
32 groupPullRequestTimelineConversations,
33 isPullRequestVerdictStale,
34 newestPullRequestCommitAt,
35 pullRequestReviewOutcome,
36 type PullRequestReviewOutcome,
37 type PullRequestTimelineEvent,
38 type PullRequestTimelineThread,
39} from "./pullRequestDetail.logic";
40import { canEditPullRequestComment } from "./pullRequestEditing.logic";
41import { PullRequestMarkdown } from "./PullRequestMarkdown";
42import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
43import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
44import { PullRequestReactionBar } from "./PullRequestReactions";
45import {
46 PullRequestActorAvatar,
47 PullRequestDiffStat,
48 PullRequestMetaLine,
49 PullRequestReviewOutcomeIcon,
50 pullRequestReviewOutcomeLabel,
51 pullRequestReviewOutcomeStaleLabel,
52 pullRequestReviewOutcomeToneClassName,
53} from "./pullRequestPresentation";
54import { PullRequestGlyph } from "./pullRequestIcons";
55
56interface ReactionSurface {
57 readonly canReact: boolean;
58 readonly environmentId: EnvironmentId;
59 readonly threadRef: ScopedThreadRef | null;
60 readonly reference: PullRequestRef;
61 readonly onRefresh: () => void;
62}
63
64function TimelineBody({
65 body,
66 markdown,
67 cwd,
68 environmentId,
69 threadRef,
70}: {
71 body: string;
72 markdown: boolean;
73 cwd: string;
74 environmentId: EnvironmentId;
75 threadRef: ScopedThreadRef | null;
76}) {
77 return (
78 <div className="mt-3">
79 {markdown ? (
80 <PullRequestMarkdown
81 text={body}
82 cwd={cwd}
83 environmentId={environmentId}
84 threadRef={threadRef}
85 />
86 ) : (
87 <p className="whitespace-pre-wrap text-xs text-muted-foreground">{body}</p>
88 )}
89 </div>
90 );
91}
92
93function ActorName({ actor }: { actor: PullRequestActor | null }) {
94 return <span className="font-semibold text-foreground">{actor?.login ?? "ghost"}</span>;
95}
96
97function TimelineMarker({
98 children,
99 className,
100}: {
101 children: ReactNode;
102 className?: string | undefined;
103}) {
104 return (
105 <span
106 className={cn(
107 "absolute left-0 top-1/2 z-10 flex size-8 -translate-y-1/2 items-center justify-center bg-background",
108 className,
109 )}
110 >
111 {children}
112 </span>
113 );
114}
115
116function IconMarker({ icon, className }: { icon: ReactNode; className?: string | undefined }) {
117 return (
118 <TimelineMarker className={className}>
119 <span className="flex size-7 items-center justify-center bg-background text-muted-foreground">
120 {icon}
121 </span>
122 </TimelineMarker>
123 );
124}
125
126function ActorTimelineMarker({
127 actors,
128 className,
129 fallback,
130 muted = false,
131}: {
132 actors: ReadonlyArray<PullRequestActor>;
133 className?: string | undefined;
134 fallback: ReactNode;
135 muted?: boolean;
136}) {
137 const actor = actors[0];
138 return actor === undefined ? (
139 <IconMarker className={className} icon={fallback} />
140 ) : (
141 <TimelineMarker className={className}>
142 <PullRequestActorAvatar
143 actor={actor}
144 className={cn(
145 "size-7 bg-muted text-3xs transition-opacity",
146 muted && "opacity-45 grayscale",
147 )}
148 />
149 </TimelineMarker>
150 );
151}
152
153function friendlyReviewState(value: string): string {
154 const words = value.toLowerCase().replaceAll("_", " ").replaceAll("-", " ");
155 return words.replace(/^\w/u, (letter) => letter.toUpperCase());
156}
157
158function ReviewStateBadge({ state }: { state: string }) {
159 return (
160 <span className="text-3xs font-medium text-muted-foreground">{friendlyReviewState(state)}</span>
161 );
162}
163
164function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
165 return url === null ? null : (
166 <Button
167 size="icon-xs"
168 variant="ghost-muted"
169 className="-mr-1 -mt-1 shrink-0"
170 aria-label="Open activity on host"
171 onClick={() => onOpen(url)}
172 >
173 <ExternalLinkIcon className="size-3" />
174 </Button>
175 );
176}
177
178function ConversationCard({
179 event,
180 editable,
181 cwd,
182 onOpen,
183 reactions,
184 showPath = true,
185}: {
186 event: PullRequestTimelineEvent;
187 editable: PullRequestComment | null;
188 cwd: string;
189 onOpen: (url: string) => void;
190 reactions: ReactionSurface;
191 showPath?: boolean;
192}) {
193 const [editing, setEditing] = useState(false);
194 const [saving, setSaving] = useState(false);
195 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
196 reportFailure: false,
197 });
198
199 const save = async (body: string) => {
200 // A review's own summary is not a kind any host rewrites, which is why `editable` is never
201 // one; the check is here because the comment's own type still allows it.
202 if (editable === null || saving || editable.kind === "review") return;
203 setSaving(true);
204 const result = await updateComment({
205 environmentId: reactions.environmentId,
206 input: { ...reactions.reference, commentId: editable.id, kind: editable.kind, body },
207 });
208 setSaving(false);
209 if (result._tag === "Failure") {
210 toastManager.add({ type: "error", title: "Could not save the comment" });
211 return;
212 }
213 setEditing(false);
214 reactions.onRefresh();
215 };
216
217 return (
218 <article className="group py-2">
219 <div className="px-2">
220 <div className="flex min-w-0 flex-wrap items-start gap-2">
221 <div className="min-w-0 flex-1">
222 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
223 <ActorName actor={event.actor} />
224 <span className="text-muted-foreground">{event.title}</span>
225 {event.reviewState ? <ReviewStateBadge state={event.reviewState} /> : null}
226 </div>
227 <PullRequestMetaLine className="mt-1 flex-wrap text-2xs text-muted-foreground">
228 <span>
229 <RelativeTime timestamp={event.at} />
230 </span>
231 {showPath && event.path ? (
232 <span className="inline-flex min-w-0 items-center gap-1">
233 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
234 <span className="truncate">{event.path}</span>
235 </span>
236 ) : null}
237 </PullRequestMetaLine>
238 </div>
239 {editable !== null && !editing ? (
240 <PullRequestEditButton
241 className="-mt-1"
242 aria-label="Edit comment"
243 onClick={() => setEditing(true)}
244 />
245 ) : null}
246 {reactions.canReact || event.reactions.length > 0 ? (
247 <PullRequestReactionBar
248 className="ml-auto justify-end"
249 reactions={event.reactions}
250 canReact={reactions.canReact}
251 subjectId={event.id}
252 environmentId={reactions.environmentId}
253 reference={reactions.reference}
254 onRefresh={reactions.onRefresh}
255 />
256 ) : null}
257 <OpenOnHostButton url={event.url} onOpen={onOpen} />
258 </div>
259 </div>
260 {editing && editable !== null ? (
261 <div className="px-2 pb-2 pt-3">
262 <PullRequestMarkdownEditor
263 value={editable.body}
264 cwd={cwd}
265 environmentId={reactions.environmentId}
266 threadRef={reactions.threadRef}
267 label="Edit comment"
268 saving={saving}
269 onSave={(body) => void save(body)}
270 onCancel={() => setEditing(false)}
271 />
272 </div>
273 ) : event.body ? (
274 <div className="px-2 pb-2">
275 <TimelineBody
276 body={event.body}
277 markdown={event.markdown}
278 cwd={cwd}
279 environmentId={reactions.environmentId}
280 threadRef={reactions.threadRef}
281 />
282 </div>
283 ) : null}
284 </article>
285 );
286}
287
288function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
289 const actors = new Map<string, PullRequestActor>();
290 for (const event of events) {
291 const actor = event.actor;
292 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
293 }
294 return [...actors.values()];
295}
296
297function ConversationGroup({
298 events,
299 editable,
300 cwd,
301 onOpen,
302 reactions,
303}: {
304 events: ReadonlyArray<PullRequestTimelineEvent>;
305 editable: ReadonlyMap<string, PullRequestComment>;
306 cwd: string;
307 onOpen: (url: string) => void;
308 reactions: ReactionSurface;
309}) {
310 const [open, setOpen] = useState(false);
311 const actors = uniqueConversationActors(events);
312 const first = events[0];
313 if (first === undefined) return null;
314
315 return (
316 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
317 <ActorTimelineMarker
318 actors={actors}
319 className="top-6"
320 fallback={<MessageSquareIcon className="size-3.5" />}
321 muted={!open}
322 />
323 <Collapsible open={open} onOpenChange={setOpen}>
324 <div>
325 <CollapsibleTrigger
326 className={cn(
327 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
328 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
329 )}
330 >
331 <span className="min-w-0 flex-1">
332 <span className="block text-xs font-semibold">
333 {events.length.toLocaleString()} {events.length === 1 ? "comment" : "comments"}
334 </span>
335 <span className="block truncate text-3xs text-muted-foreground">
336 {actors.length.toLocaleString()} {actors.length === 1 ? "author" : "authors"} ·{" "}
337 <RelativeTime timestamp={first.at} />
338 </span>
339 </span>
340 <ChevronDownIcon
341 aria-hidden
342 className={cn(
343 "size-3.5 shrink-0 text-muted-foreground transition-transform",
344 open && "rotate-180",
345 )}
346 />
347 </CollapsibleTrigger>
348 <CollapsiblePanel>
349 {open ? (
350 <div className="mt-1 space-y-1">
351 {events.map((event) => (
352 <ConversationCard
353 // Named with the pull request too: a remark's id is the host's own, and two
354 // pull requests can hand out the same one — which would leave one card's open
355 // editor standing over the other's remark.
356 key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
357 event={event}
358 editable={editable.get(event.id) ?? null}
359 cwd={cwd}
360 onOpen={onOpen}
361 reactions={reactions}
362 />
363 ))}
364 </div>
365 ) : null}
366 </CollapsiblePanel>
367 </div>
368 </Collapsible>
369 </div>
370 );
371}
372
373function ReviewThreadEvent({
374 event,
375 thread,
376 editable,
377 cwd,
378 onOpen,
379 reactions,
380}: {
381 event: PullRequestTimelineEvent;
382 thread: PullRequestTimelineThread;
383 editable: ReadonlyMap<string, PullRequestComment>;
384 cwd: string;
385 onOpen: (url: string) => void;
386 reactions: ReactionSurface;
387}) {
388 const dismissed = pullRequestReviewOutcome(event.reviewState) === "dismissed";
389 const [expanded, setExpanded] = useState(!thread.isResolved && !dismissed);
390 const replyCount = thread.replies.length + thread.moreReplies;
391
392 return (
393 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
394 <ActorTimelineMarker
395 actors={event.actor ? [event.actor] : []}
396 className="top-6"
397 fallback={<MessageSquareIcon className="size-3.5" />}
398 muted={!expanded}
399 />
400 <button
401 type="button"
402 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"
403 aria-expanded={expanded}
404 onClick={() => setExpanded((current) => !current)}
405 >
406 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
407 <span className="min-w-0 truncate font-mono">
408 {thread.line === null ? thread.path : `${thread.path}:${thread.line}`}
409 </span>
410 {thread.isResolved ? (
411 <span className="inline-flex shrink-0 items-center gap-1 font-medium text-success-foreground">
412 <CircleCheckIcon aria-hidden className="size-3" />
413 Resolved
414 </span>
415 ) : null}
416 {dismissed ? <span className="shrink-0 font-medium">Review dismissed</span> : null}
417 {thread.isOutdated ? <span className="shrink-0 font-medium">Outdated</span> : null}
418 {expanded ? null : (
419 <span className="shrink-0">
420 · {event.actor?.login ?? "ghost"}
421 {replyCount > 0 ? (
422 <>
423 {" "}
424 · {replyCount.toLocaleString()} {replyCount === 1 ? "reply" : "replies"}
425 </>
426 ) : null}
427 </span>
428 )}
429 <ChevronDownIcon
430 aria-hidden
431 className={cn("ml-auto size-3.5 shrink-0 transition-transform", expanded && "rotate-180")}
432 />
433 </button>
434 {expanded ? (
435 <>
436 <ConversationCard
437 event={event}
438 editable={editable.get(event.id) ?? null}
439 cwd={cwd}
440 onOpen={onOpen}
441 reactions={reactions}
442 showPath={false}
443 />
444 {thread.replies.length > 0 ? (
445 <div className="ml-2 space-y-1 border-l border-border/60 pl-3">
446 {thread.replies.map((reply) => (
447 <ConversationCard
448 key={reply.id}
449 event={reply}
450 editable={editable.get(reply.id) ?? null}
451 cwd={cwd}
452 onOpen={onOpen}
453 reactions={reactions}
454 showPath={false}
455 />
456 ))}
457 </div>
458 ) : null}
459 </>
460 ) : null}
461 {thread.hasMoreReplies ? (
462 <div className="px-2">
463 <PullRequestMoreReplies {...thread} />
464 </div>
465 ) : null}
466 </div>
467 );
468}
469
470function CommitEvent({
471 event,
472 onOpen,
473}: {
474 event: PullRequestTimelineEvent;
475 onOpen: (oid: string) => void;
476}) {
477 return (
478 <button
479 type="button"
480 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"
481 aria-label={`View commit ${event.id}`}
482 onClick={() => onOpen(event.id)}
483 >
484 <ActorTimelineMarker
485 actors={event.commitAuthors}
486 fallback={<GitCommitHorizontalIcon className="size-3.5" />}
487 />
488 <div className="flex min-w-0 items-center gap-2.5 py-1.5">
489 <div className="min-w-0 flex-1">
490 <div className="truncate text-xs font-semibold text-foreground transition-colors group-hover:text-primary">
491 {event.body ?? "Untitled commit"}
492 </div>
493 <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-3xs text-muted-foreground">
494 <code className="font-mono">{event.id.slice(0, 7)}</code>
495 <span>
496 <RelativeTime timestamp={event.at} />
497 </span>
498 </div>
499 </div>
500 {event.additions !== null && event.deletions !== null ? (
501 <PullRequestDiffStat
502 additions={event.additions}
503 deletions={event.deletions}
504 className="ml-auto shrink-0 font-mono text-3xs"
505 />
506 ) : null}
507 </div>
508 </button>
509 );
510}
511
512function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
513 const presentation =
514 event.kind === "opened"
515 ? {
516 icon: <PullRequestGlyph.pullRequest className="size-3.5" />,
517 label: "Pull request opened",
518 }
519 : event.kind === "merged"
520 ? {
521 icon: <PullRequestGlyph.merged className="size-3.5" />,
522 label: "Pull request merged",
523 }
524 : {
525 icon: <PullRequestGlyph.closed className="size-3.5" />,
526 label: "Pull request closed",
527 };
528
529 return (
530 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
531 <IconMarker icon={presentation.icon} />
532 <div className="py-1.5 text-xs">
533 <div className="flex flex-wrap items-center gap-1.5">
534 {event.actor ? <ActorName actor={event.actor} /> : null}
535 <span className="font-semibold text-foreground">{presentation.label}</span>
536 </div>
537 <div className="mt-0.5 text-2xs text-muted-foreground">
538 <RelativeTime timestamp={event.at} />
539 </div>
540 </div>
541 </div>
542 );
543}
544
545function ReviewVerdictEvent({
546 event,
547 outcome,
548 stale,
549 cwd,
550 onOpen,
551 reactions,
552}: {
553 event: PullRequestTimelineEvent;
554 outcome: PullRequestReviewOutcome;
555 stale: boolean;
556 cwd: string;
557 onOpen: (url: string) => void;
558 reactions: ReactionSurface;
559}) {
560 return (
561 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
562 <ActorTimelineMarker
563 actors={event.actor ? [event.actor] : []}
564 className="top-6"
565 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
566 />
567 <div className="flex min-w-0 flex-wrap items-start gap-2 py-1.5">
568 <div className="min-w-0 flex-1">
569 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
570 <ActorName actor={event.actor} />
571 <Tooltip disabled={!stale}>
572 <TooltipTrigger
573 render={
574 <span
575 className={cn(
576 "font-medium lowercase",
577 stale
578 ? "text-muted-foreground opacity-70"
579 : pullRequestReviewOutcomeToneClassName(outcome),
580 )}
581 />
582 }
583 >
584 {pullRequestReviewOutcomeLabel(outcome)}
585 {stale ? <span className="sr-only">, before the latest commits</span> : null}
586 </TooltipTrigger>
587 <TooltipPopup>{pullRequestReviewOutcomeStaleLabel(outcome)}</TooltipPopup>
588 </Tooltip>
589 </div>
590 <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
591 <PullRequestMetaLine className="flex-wrap text-2xs text-muted-foreground">
592 <span>
593 <RelativeTime timestamp={event.at} />
594 </span>
595 {event.path ? (
596 <span className="inline-flex min-w-0 items-center gap-1">
597 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
598 <span className="truncate">{event.path}</span>
599 </span>
600 ) : null}
601 </PullRequestMetaLine>
602 </div>
603 </div>
604 {reactions.canReact || event.reactions.length > 0 ? (
605 <PullRequestReactionBar
606 className="ml-auto justify-end"
607 reactions={event.reactions}
608 canReact={reactions.canReact}
609 subjectId={event.id}
610 environmentId={reactions.environmentId}
611 reference={reactions.reference}
612 onRefresh={reactions.onRefresh}
613 />
614 ) : null}
615 <OpenOnHostButton url={event.url} onOpen={onOpen} />
616 </div>
617 {event.body ? (
618 <TimelineBody
619 body={event.body}
620 markdown={event.markdown}
621 cwd={cwd}
622 environmentId={reactions.environmentId}
623 threadRef={reactions.threadRef}
624 />
625 ) : null}
626 </div>
627 );
628}
629
630export function PullRequestTimelineTab({
631 scrollerRef,
632 detail,
633 environmentId,
634 threadRef = null,
635 reference,
636 order,
637 onOpenCommit,
638 onRefresh,
639}: {
640 scrollerRef: (node: HTMLDivElement | null) => void;
641 detail: PullRequestDetailView;
642 environmentId: EnvironmentId;
643 threadRef?: ScopedThreadRef | null;
644 reference: PullRequestRef;
645 order: "newest" | "oldest";
646 onOpenCommit: (oid: string) => void;
647 onRefresh: () => void;
648}) {
649 const events = buildPullRequestTimeline(detail);
650 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
651 const reactions: ReactionSurface = {
652 canReact: detail.capabilities.reactions === true,
653 environmentId,
654 threadRef,
655 reference,
656 onRefresh,
657 };
658 const editable = new Map(
659 events
660 .flatMap((event) => [event, ...(event.thread?.replies ?? [])])
661 .flatMap((event) => (event.comment ? [event.comment] : []))
662 .filter((comment) => canEditPullRequestComment(detail, comment))
663 .map((comment) => [comment.id, comment] as const),
664 );
665 const orderedEvents = order === "newest" ? events : events.toReversed();
666 const rows = groupPullRequestTimelineConversations(orderedEvents);
667 const openOnHost = (url: string) => {
668 void readLocalApi()?.shell.openExternal(url);
669 };
670
671 return (
672 <div ref={scrollerRef} className="scrollbar-gutter-both h-full overflow-y-auto px-4 py-5">
673 <div className="mx-auto max-w-3xl">
674 <div className="relative">
675 <span aria-hidden className="absolute bottom-5 left-[15px] top-1 w-px bg-border/45" />
676 {rows.map((row) => {
677 if (row.kind === "comments") {
678 return (
679 <ConversationGroup
680 key={`comments:${row.events[0]?.id ?? "empty"}`}
681 events={row.events}
682 editable={editable}
683 cwd={detail.workspaceRoot}
684 onOpen={openOnHost}
685 reactions={reactions}
686 />
687 );
688 }
689 const event = row.event;
690 if (event.thread !== undefined) {
691 return (
692 <ReviewThreadEvent
693 key={`${reactions.reference.projectId}#${reactions.reference.number}:thread:${event.id}:${event.thread.isResolved}:${pullRequestReviewOutcome(event.reviewState) === "dismissed"}`}
694 event={event}
695 thread={event.thread}
696 editable={editable}
697 cwd={detail.workspaceRoot}
698 onOpen={openOnHost}
699 reactions={reactions}
700 />
701 );
702 }
703 if (event.kind === "commit") {
704 return <CommitEvent key={event.id} event={event} onOpen={onOpenCommit} />;
705 }
706 const outcome = pullRequestReviewOutcome(event.reviewState);
707 if (outcome !== null) {
708 return (
709 <ReviewVerdictEvent
710 key={event.id}
711 event={event}
712 outcome={outcome}
713 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
714 cwd={detail.workspaceRoot}
715 onOpen={openOnHost}
716 reactions={reactions}
717 />
718 );
719 }
720 return <LifecycleEvent key={event.id} event={event} />;
721 })}
722 </div>
723
724 {events.length === 0 ? (
725 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
726 <PullRequestGlyph.pullRequest className="mb-2 size-5" />
727 <p className="text-xs">No activity yet.</p>
728 </div>
729 ) : null}
730 </div>
731 </div>
732 );
733}