Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestTimelineTab.tsx

729 lines23.7 KB

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;
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 );
92​
93function ActorName({ actor }: { actor: PullRequestActor | null }) {
94 return <span className="font-semibold text-foreground">{actor?.login ?? "ghost"}</span>;
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 );
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 );
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 );
152​
153function friendlyReviewState(value: string): string {
154 const words = value.toLowerCase().replaceAll("_", " ").replaceAll("-", " ");
155 return words.replace(/^\w/u, (letter) => letter.toUpperCase());
157​
158function ReviewStateBadge({ state }: { state: string }) {
159 return (
160 <span className="text-3xs font-medium text-muted-foreground">{friendlyReviewState(state)}</span>
161 );
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 shrink-0"
170 aria-label="Open activity on host"
171 onClick={() => onOpen(url)}
172 >
173 <ExternalLinkIcon className="size-3" />
174 </Button>
175 );
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-center 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 aria-label="Edit comment" onClick={() => setEditing(true)} />
241 ) : null}
242 {reactions.canReact || event.reactions.length > 0 ? (
243 <PullRequestReactionBar
244 className="ml-auto justify-end"
245 reactions={event.reactions}
246 canReact={reactions.canReact}
247 subjectId={event.id}
248 environmentId={reactions.environmentId}
249 reference={reactions.reference}
250 onRefresh={reactions.onRefresh}
251 />
252 ) : null}
253 <OpenOnHostButton url={event.url} onOpen={onOpen} />
254 </div>
255 </div>
256 {editing && editable !== null ? (
257 <div className="px-2 pb-2 pt-3">
258 <PullRequestMarkdownEditor
259 value={editable.body}
260 cwd={cwd}
261 environmentId={reactions.environmentId}
262 threadRef={reactions.threadRef}
263 label="Edit comment"
264 saving={saving}
265 onSave={(body) => void save(body)}
266 onCancel={() => setEditing(false)}
267 />
268 </div>
269 ) : event.body ? (
270 <div className="px-2 pb-2">
271 <TimelineBody
272 body={event.body}
273 markdown={event.markdown}
274 cwd={cwd}
275 environmentId={reactions.environmentId}
276 threadRef={reactions.threadRef}
277 />
278 </div>
279 ) : null}
280 </article>
281 );
283​
284function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
285 const actors = new Map<string, PullRequestActor>();
286 for (const event of events) {
287 const actor = event.actor;
288 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
289 }
290 return [...actors.values()];
292​
293function ConversationGroup({
294 events,
295 editable,
296 cwd,
297 onOpen,
298 reactions,
299}: {
300 events: ReadonlyArray<PullRequestTimelineEvent>;
301 editable: ReadonlyMap<string, PullRequestComment>;
302 cwd: string;
303 onOpen: (url: string) => void;
304 reactions: ReactionSurface;
305}) {
306 const [open, setOpen] = useState(false);
307 const actors = uniqueConversationActors(events);
308 const first = events[0];
309 if (first === undefined) return null;
310​
311 return (
312 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
313 <ActorTimelineMarker
314 actors={actors}
315 className="top-6"
316 fallback={<MessageSquareIcon className="size-3.5" />}
317 muted={!open}
318 />
319 <Collapsible open={open} onOpenChange={setOpen}>
320 <div>
321 <CollapsibleTrigger
322 className={cn(
323 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
324 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
325 )}
326 >
327 <span className="min-w-0 flex-1">
328 <span className="block text-xs font-semibold">
329 {events.length.toLocaleString()} {events.length === 1 ? "comment" : "comments"}
330 </span>
331 <span className="block truncate text-3xs text-muted-foreground">
332 {actors.length.toLocaleString()} {actors.length === 1 ? "author" : "authors"} ·{" "}
333 <RelativeTime timestamp={first.at} />
334 </span>
335 </span>
336 <ChevronDownIcon
337 aria-hidden
338 className={cn(
339 "size-3.5 shrink-0 text-muted-foreground transition-transform",
340 open && "rotate-180",
341 )}
342 />
343 </CollapsibleTrigger>
344 <CollapsiblePanel>
345 {open ? (
346 <div className="mt-1 space-y-1">
347 {events.map((event) => (
348 <ConversationCard
349 // Named with the pull request too: a remark's id is the host's own, and two
350 // pull requests can hand out the same one — which would leave one card's open
351 // editor standing over the other's remark.
352 key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
353 event={event}
354 editable={editable.get(event.id) ?? null}
355 cwd={cwd}
356 onOpen={onOpen}
357 reactions={reactions}
358 />
359 ))}
360 </div>
361 ) : null}
362 </CollapsiblePanel>
363 </div>
364 </Collapsible>
365 </div>
366 );
368​
369function ReviewThreadEvent({
370 event,
371 thread,
372 editable,
373 cwd,
374 onOpen,
375 reactions,
376}: {
377 event: PullRequestTimelineEvent;
378 thread: PullRequestTimelineThread;
379 editable: ReadonlyMap<string, PullRequestComment>;
380 cwd: string;
381 onOpen: (url: string) => void;
382 reactions: ReactionSurface;
383}) {
384 const dismissed = pullRequestReviewOutcome(event.reviewState) === "dismissed";
385 const [expanded, setExpanded] = useState(!thread.isResolved && !dismissed);
386 const replyCount = thread.replies.length + thread.moreReplies;
387​
388 return (
389 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
390 <ActorTimelineMarker
391 actors={event.actor ? [event.actor] : []}
392 className="top-4"
393 fallback={<MessageSquareIcon className="size-3.5" />}
394 muted={!expanded}
395 />
396 <button
397 type="button"
398 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"
399 aria-expanded={expanded}
400 onClick={() => setExpanded((current) => !current)}
401 >
402 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
403 <span className="min-w-0 truncate font-mono">
404 {thread.line === null ? thread.path : `${thread.path}:${thread.line}`}
405 </span>
406 {thread.isResolved ? (
407 <span className="inline-flex shrink-0 items-center gap-1 font-medium text-success-foreground">
408 <CircleCheckIcon aria-hidden className="size-3" />
409 Resolved
410 </span>
411 ) : null}
412 {dismissed ? <span className="shrink-0 font-medium">Review dismissed</span> : null}
413 {thread.isOutdated ? <span className="shrink-0 font-medium">Outdated</span> : null}
414 {expanded ? null : (
415 <span className="shrink-0">
416 · {event.actor?.login ?? "ghost"}
417 {replyCount > 0 ? (
418 <>
419 {" "}
420 · {replyCount.toLocaleString()} {replyCount === 1 ? "reply" : "replies"}
421 </>
422 ) : null}
423 </span>
424 )}
425 <ChevronDownIcon
426 aria-hidden
427 className={cn("ml-auto size-3.5 shrink-0 transition-transform", expanded && "rotate-180")}
428 />
429 </button>
430 {expanded ? (
431 <>
432 <ConversationCard
433 event={event}
434 editable={editable.get(event.id) ?? null}
435 cwd={cwd}
436 onOpen={onOpen}
437 reactions={reactions}
438 showPath={false}
439 />
440 {thread.replies.length > 0 ? (
441 <div className="ml-2 space-y-1 border-l border-border/60 pl-3">
442 {thread.replies.map((reply) => (
443 <ConversationCard
444 key={reply.id}
445 event={reply}
446 editable={editable.get(reply.id) ?? null}
447 cwd={cwd}
448 onOpen={onOpen}
449 reactions={reactions}
450 showPath={false}
451 />
452 ))}
453 </div>
454 ) : null}
455 </>
456 ) : null}
457 {thread.hasMoreReplies ? (
458 <div className="px-2">
459 <PullRequestMoreReplies {...thread} />
460 </div>
461 ) : null}
462 </div>
463 );
465​
466function CommitEvent({
467 event,
468 onOpen,
469}: {
470 event: PullRequestTimelineEvent;
471 onOpen: (oid: string) => void;
472}) {
473 return (
474 <button
475 type="button"
476 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"
477 aria-label={`View commit ${event.id}`}
478 onClick={() => onOpen(event.id)}
479 >
480 <ActorTimelineMarker
481 actors={event.commitAuthors}
482 fallback={<GitCommitHorizontalIcon className="size-3.5" />}
483 />
484 <div className="flex min-w-0 items-center gap-2.5 py-1.5">
485 <div className="min-w-0 flex-1">
486 <div className="truncate text-xs font-semibold text-foreground transition-colors group-hover:text-primary">
487 {event.body ?? "Untitled commit"}
488 </div>
489 <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-3xs text-muted-foreground">
490 <code className="font-mono">{event.id.slice(0, 7)}</code>
491 <span>
492 <RelativeTime timestamp={event.at} />
493 </span>
494 </div>
495 </div>
496 {event.additions !== null && event.deletions !== null ? (
497 <PullRequestDiffStat
498 additions={event.additions}
499 deletions={event.deletions}
500 className="ml-auto shrink-0 font-mono text-3xs"
501 />
502 ) : null}
503 </div>
504 </button>
505 );
507​
508function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
509 const presentation =
510 event.kind === "opened"
511 ? {
512 icon: <PullRequestGlyph.pullRequest className="size-3.5" />,
513 label: "Pull request opened",
514 }
515 : event.kind === "merged"
516 ? {
517 icon: <PullRequestGlyph.merged className="size-3.5" />,
518 label: "Pull request merged",
519 }
520 : {
521 icon: <PullRequestGlyph.closed className="size-3.5" />,
522 label: "Pull request closed",
523 };
524​
525 return (
526 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
527 <IconMarker icon={presentation.icon} />
528 <div className="py-1.5 text-xs">
529 <div className="flex flex-wrap items-center gap-1.5">
530 {event.actor ? <ActorName actor={event.actor} /> : null}
531 <span className="font-semibold text-foreground">{presentation.label}</span>
532 </div>
533 <div className="mt-0.5 text-2xs text-muted-foreground">
534 <RelativeTime timestamp={event.at} />
535 </div>
536 </div>
537 </div>
538 );
540​
541function ReviewVerdictEvent({
542 event,
543 outcome,
544 stale,
545 cwd,
546 onOpen,
547 reactions,
548}: {
549 event: PullRequestTimelineEvent;
550 outcome: PullRequestReviewOutcome;
551 stale: boolean;
552 cwd: string;
553 onOpen: (url: string) => void;
554 reactions: ReactionSurface;
555}) {
556 return (
557 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
558 <ActorTimelineMarker
559 actors={event.actor ? [event.actor] : []}
560 className="top-6"
561 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
562 />
563 <div className="flex min-w-0 flex-wrap items-center gap-2 py-1.5">
564 <div className="min-w-0 flex-1">
565 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
566 <ActorName actor={event.actor} />
567 <Tooltip disabled={!stale}>
568 <TooltipTrigger
569 render={
570 <span
571 className={cn(
572 "font-medium lowercase",
573 stale
574 ? "text-muted-foreground opacity-70"
575 : pullRequestReviewOutcomeToneClassName(outcome),
576 )}
577 />
578 }
579 >
580 {pullRequestReviewOutcomeLabel(outcome)}
581 {stale ? <span className="sr-only">, before the latest commits</span> : null}
582 </TooltipTrigger>
583 <TooltipPopup>{pullRequestReviewOutcomeStaleLabel(outcome)}</TooltipPopup>
584 </Tooltip>
585 </div>
586 <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
587 <PullRequestMetaLine className="flex-wrap text-2xs text-muted-foreground">
588 <span>
589 <RelativeTime timestamp={event.at} />
590 </span>
591 {event.path ? (
592 <span className="inline-flex min-w-0 items-center gap-1">
593 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
594 <span className="truncate">{event.path}</span>
595 </span>
596 ) : null}
597 </PullRequestMetaLine>
598 </div>
599 </div>
600 {reactions.canReact || event.reactions.length > 0 ? (
601 <PullRequestReactionBar
602 className="ml-auto justify-end"
603 reactions={event.reactions}
604 canReact={reactions.canReact}
605 subjectId={event.id}
606 environmentId={reactions.environmentId}
607 reference={reactions.reference}
608 onRefresh={reactions.onRefresh}
609 />
610 ) : null}
611 <OpenOnHostButton url={event.url} onOpen={onOpen} />
612 </div>
613 {event.body ? (
614 <TimelineBody
615 body={event.body}
616 markdown={event.markdown}
617 cwd={cwd}
618 environmentId={reactions.environmentId}
619 threadRef={reactions.threadRef}
620 />
621 ) : null}
622 </div>
623 );
625​
626export function PullRequestTimelineTab({
627 scrollerRef,
628 detail,
629 environmentId,
630 threadRef = null,
631 reference,
632 order,
633 onOpenCommit,
634 onRefresh,
635}: {
636 scrollerRef: (node: HTMLDivElement | null) => void;
637 detail: PullRequestDetailView;
638 environmentId: EnvironmentId;
639 threadRef?: ScopedThreadRef | null;
640 reference: PullRequestRef;
641 order: "newest" | "oldest";
642 onOpenCommit: (oid: string) => void;
643 onRefresh: () => void;
644}) {
645 const events = buildPullRequestTimeline(detail);
646 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
647 const reactions: ReactionSurface = {
648 canReact: detail.capabilities.reactions === true,
649 environmentId,
650 threadRef,
651 reference,
652 onRefresh,
653 };
654 const editable = new Map(
655 events
656 .flatMap((event) => [event, ...(event.thread?.replies ?? [])])
657 .flatMap((event) => (event.comment ? [event.comment] : []))
658 .filter((comment) => canEditPullRequestComment(detail, comment))
659 .map((comment) => [comment.id, comment] as const),
660 );
661 const orderedEvents = order === "newest" ? events : events.toReversed();
662 const rows = groupPullRequestTimelineConversations(orderedEvents);
663 const openOnHost = (url: string) => {
664 void readLocalApi()?.shell.openExternal(url);
665 };
666​
667 return (
668 <div ref={scrollerRef} className="scrollbar-gutter-both h-full overflow-y-auto px-4 py-5">
669 <div className="mx-auto max-w-3xl">
670 <div className="relative">
671 <span aria-hidden className="absolute bottom-5 left-[15px] top-1 w-px bg-border/45" />
672 {rows.map((row) => {
673 if (row.kind === "comments") {
674 return (
675 <ConversationGroup
676 key={`comments:${row.events[0]?.id ?? "empty"}`}
677 events={row.events}
678 editable={editable}
679 cwd={detail.workspaceRoot}
680 onOpen={openOnHost}
681 reactions={reactions}
682 />
683 );
684 }
685 const event = row.event;
686 if (event.thread !== undefined) {
687 return (
688 <ReviewThreadEvent
689 key={`${reactions.reference.projectId}#${reactions.reference.number}:thread:${event.id}:${event.thread.isResolved}:${pullRequestReviewOutcome(event.reviewState) === "dismissed"}`}
690 event={event}
691 thread={event.thread}
692 editable={editable}
693 cwd={detail.workspaceRoot}
694 onOpen={openOnHost}
695 reactions={reactions}
696 />
697 );
698 }
699 if (event.kind === "commit") {
700 return <CommitEvent key={event.id} event={event} onOpen={onOpenCommit} />;
701 }
702 const outcome = pullRequestReviewOutcome(event.reviewState);
703 if (outcome !== null) {
704 return (
705 <ReviewVerdictEvent
706 key={event.id}
707 event={event}
708 outcome={outcome}
709 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
710 cwd={detail.workspaceRoot}
711 onOpen={openOnHost}
712 reactions={reactions}
713 />
714 );
715 }
716 return <LifecycleEvent key={event.id} event={event} />;
717 })}
718 </div>
719​
720 {events.length === 0 ? (
721 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
722 <PullRequestGlyph.pullRequest className="mb-2 size-5" />
723 <p className="text-xs">No activity yet.</p>
724 </div>
725 ) : null}
726 </div>
727 </div>
728 );