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

PullRequestTimelineTab.tsx

731 lines23.6 KB

1import {
2 capitalizeTerm,
3 sourceControlClients,
4} from "@t3tools/client-runtime/source-control-clients";
5import { useAtomCommand } from "~/state/use-atom-command";
6import type {
7 EnvironmentId,
8 PullRequestActor,
9 PullRequestComment,
10 PullRequestDetailView,
11 PullRequestRef,
12 ScopedThreadRef,
13} from "@t3tools/contracts";
14import {
15 ChevronDownIcon,
16 CircleCheckIcon,
17 ExternalLinkIcon,
18 FileCode2Icon,
19 GitCommitHorizontalIcon,
20 MessageSquareIcon,
21} from "lucide-react";
22import { useState, type ReactNode } from "react";
23​
24import { cn } from "~/lib/utils";
25import { readLocalApi } from "~/localApi";
26import { pullRequestEnvironment } from "~/state/pullRequests";
27import { RelativeTime } from "~/components/RelativeTime";
28​
29import { Button } from "../ui/button";
30import { PullRequestEditButton } from "./PullRequestEditButton";
31import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
32import { toastManager } from "../ui/toast";
33import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
34import {
35 buildPullRequestTimeline,
36 groupPullRequestTimelineConversations,
37 isPullRequestVerdictStale,
38 newestPullRequestCommitAt,
39 pullRequestReviewOutcome,
40 type PullRequestReviewOutcome,
41 type PullRequestTimelineEvent,
42 type PullRequestTimelineThread,
43} from "./pullRequestDetail.logic";
44import { canEditPullRequestComment } from "@t3tools/client-runtime/pull-request-editing";
45import { PullRequestMarkdown } from "./PullRequestMarkdown";
46import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
47import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
48import { PullRequestReactionBar } from "./PullRequestReactions";
49import {
50 PullRequestActorAvatar,
51 PullRequestDiffStat,
52 PullRequestMetaLine,
53 PullRequestReviewOutcomeIcon,
54 pullRequestReviewOutcomeLabel,
55 pullRequestReviewOutcomeStaleLabel,
56 pullRequestReviewOutcomeToneClassName,
57} from "./pullRequestPresentation";
58import { PullRequestGlyph } from "./pullRequestIcons";
59​
60interface ReactionSurface {
61 readonly canReact: boolean;
62 readonly environmentId: EnvironmentId;
63 readonly threadRef: ScopedThreadRef | null;
64 readonly reference: PullRequestRef;
65 readonly onRefresh: () => void;
67​
68function TimelineBody({
69 body,
70 markdown,
71 cwd,
72 environmentId,
73 threadRef,
74}: {
75 body: string;
76 markdown: boolean;
77 cwd: string;
78 environmentId: EnvironmentId;
79 threadRef: ScopedThreadRef | null;
80}) {
81 return (
82 <div className="mt-3">
83 {markdown ? (
84 <PullRequestMarkdown
85 text={body}
86 cwd={cwd}
87 environmentId={environmentId}
88 threadRef={threadRef}
89 />
90 ) : (
91 <p className="whitespace-pre-wrap text-xs text-muted-foreground">{body}</p>
92 )}
93 </div>
94 );
96​
97function ActorName({ actor }: { actor: PullRequestActor | null }) {
98 return <span className="font-semibold text-foreground">{actor?.login ?? "ghost"}</span>;
100​
101function TimelineMarker({
102 children,
103 className,
104}: {
105 children: ReactNode;
106 className?: string | undefined;
107}) {
108 return (
109 <span
110 className={cn(
111 "absolute left-0 top-1/2 z-10 flex size-8 -translate-y-1/2 items-center justify-center bg-background",
112 className,
113 )}
114 >
115 {children}
116 </span>
117 );
119​
120function IconMarker({ icon, className }: { icon: ReactNode; className?: string | undefined }) {
121 return (
122 <TimelineMarker className={className}>
123 <span className="flex size-7 items-center justify-center bg-background text-muted-foreground">
124 {icon}
125 </span>
126 </TimelineMarker>
127 );
129​
130function ActorTimelineMarker({
131 actors,
132 className,
133 fallback,
134 muted = false,
135}: {
136 actors: ReadonlyArray<PullRequestActor>;
137 className?: string | undefined;
138 fallback: ReactNode;
139 muted?: boolean;
140}) {
141 const actor = actors[0];
142 return actor === undefined ? (
143 <IconMarker className={className} icon={fallback} />
144 ) : (
145 <TimelineMarker className={className}>
146 <PullRequestActorAvatar
147 actor={actor}
148 className={cn(
149 "size-7 bg-muted text-3xs transition-opacity",
150 muted && "opacity-45 grayscale",
151 )}
152 />
153 </TimelineMarker>
154 );
156​
157function friendlyReviewState(value: string): string {
158 const words = value.toLowerCase().replaceAll("_", " ").replaceAll("-", " ");
159 return words.replace(/^\w/u, (letter) => letter.toUpperCase());
161​
162function ReviewStateBadge({ state }: { state: string }) {
163 return (
164 <span className="text-3xs font-medium text-muted-foreground">{friendlyReviewState(state)}</span>
165 );
167​
168function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
169 return url === null ? null : (
170 <Button
171 size="icon-xs"
172 variant="ghost-muted"
173 className="-mr-1 shrink-0"
174 aria-label="Open activity on host"
175 onClick={() => onOpen(url)}
176 >
177 <ExternalLinkIcon className="size-3" />
178 </Button>
179 );
181​
182function ConversationCard({
183 event,
184 editable,
185 cwd,
186 onOpen,
187 reactions,
188 showPath = true,
189}: {
190 event: PullRequestTimelineEvent;
191 editable: PullRequestComment | null;
192 cwd: string;
193 onOpen: (url: string) => void;
194 reactions: ReactionSurface;
195 showPath?: boolean;
196}) {
197 const [editing, setEditing] = useState(false);
198 const [saving, setSaving] = useState(false);
199 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
200 reportFailure: false,
201 });
202​
203 const save = async (body: string) => {
204 if (editable === null || saving || editable.kind === "review") return;
205 setSaving(true);
206 const result = await updateComment({
207 environmentId: reactions.environmentId,
208 input: { ...reactions.reference, commentId: editable.id, kind: editable.kind, body },
209 });
210 setSaving(false);
211 if (result._tag === "Failure") {
212 toastManager.add({ type: "error", title: "Could not save the comment" });
213 return;
214 }
215 setEditing(false);
216 reactions.onRefresh();
217 };
218​
219 return (
220 <article className="group py-2">
221 <div className="px-2">
222 <div className="flex min-w-0 flex-wrap items-center gap-2">
223 <div className="min-w-0 flex-1">
224 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
225 <ActorName actor={event.actor} />
226 <span className="text-muted-foreground">{event.title}</span>
227 {event.reviewState ? <ReviewStateBadge state={event.reviewState} /> : null}
228 </div>
229 <PullRequestMetaLine className="mt-1 flex-wrap text-2xs text-muted-foreground">
230 <span>
231 <RelativeTime timestamp={event.at} />
232 </span>
233 {showPath && event.path ? (
234 <span className="inline-flex min-w-0 items-center gap-1">
235 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
236 <span className="truncate">{event.path}</span>
237 </span>
238 ) : null}
239 </PullRequestMetaLine>
240 </div>
241 {editable !== null && !editing ? (
242 <PullRequestEditButton aria-label="Edit comment" onClick={() => setEditing(true)} />
243 ) : null}
244 {reactions.canReact || event.reactions.length > 0 ? (
245 <PullRequestReactionBar
246 className="ml-auto justify-end"
247 reactions={event.reactions}
248 canReact={reactions.canReact}
249 subjectId={event.id}
250 environmentId={reactions.environmentId}
251 reference={reactions.reference}
252 onRefresh={reactions.onRefresh}
253 />
254 ) : null}
255 <OpenOnHostButton url={event.url} onOpen={onOpen} />
256 </div>
257 </div>
258 {editing && editable !== null ? (
259 <div className="px-2 pb-2 pt-3">
260 <PullRequestMarkdownEditor
261 value={editable.body}
262 cwd={cwd}
263 environmentId={reactions.environmentId}
264 threadRef={reactions.threadRef}
265 label="Edit comment"
266 saving={saving}
267 onSave={(body) => void save(body)}
268 onCancel={() => setEditing(false)}
269 />
270 </div>
271 ) : event.body ? (
272 <div className="px-2 pb-2">
273 <TimelineBody
274 body={event.body}
275 markdown={event.markdown}
276 cwd={cwd}
277 environmentId={reactions.environmentId}
278 threadRef={reactions.threadRef}
279 />
280 </div>
281 ) : null}
282 </article>
283 );
285​
286function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
287 const actors = new Map<string, PullRequestActor>();
288 for (const event of events) {
289 const actor = event.actor;
290 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
291 }
292 return [...actors.values()];
294​
295function ConversationGroup({
296 events,
297 editable,
298 cwd,
299 onOpen,
300 reactions,
301}: {
302 events: ReadonlyArray<PullRequestTimelineEvent>;
303 editable: ReadonlyMap<string, PullRequestComment>;
304 cwd: string;
305 onOpen: (url: string) => void;
306 reactions: ReactionSurface;
307}) {
308 const [open, setOpen] = useState(false);
309 const actors = uniqueConversationActors(events);
310 const first = events[0];
311 if (first === undefined) return null;
312​
313 return (
314 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
315 <ActorTimelineMarker
316 actors={actors}
317 className="top-6"
318 fallback={<MessageSquareIcon className="size-3.5" />}
319 muted={!open}
320 />
321 <Collapsible open={open} onOpenChange={setOpen}>
322 <div>
323 <CollapsibleTrigger
324 className={cn(
325 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
326 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
327 )}
328 >
329 <span className="min-w-0 flex-1">
330 <span className="block text-xs font-semibold">
331 {events.length.toLocaleString()} {events.length === 1 ? "comment" : "comments"}
332 </span>
333 <span className="block truncate text-3xs text-muted-foreground">
334 {actors.length.toLocaleString()} {actors.length === 1 ? "author" : "authors"} ·{" "}
335 <RelativeTime timestamp={first.at} />
336 </span>
337 </span>
338 <ChevronDownIcon
339 aria-hidden
340 className={cn(
341 "size-3.5 shrink-0 text-muted-foreground transition-transform",
342 open && "rotate-180",
343 )}
344 />
345 </CollapsibleTrigger>
346 <CollapsiblePanel>
347 {open ? (
348 <div className="mt-1 space-y-1">
349 {events.map((event) => (
350 <ConversationCard
351 // Host comment ids can collide across pull requests.
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, term }: { event: PullRequestTimelineEvent; term: string }) {
509 const title = capitalizeTerm(term);
510 const presentation =
511 event.kind === "opened"
512 ? {
513 icon: <PullRequestGlyph.pullRequest className="size-3.5" />,
514 label: `${title} opened`,
515 }
516 : event.kind === "merged"
517 ? {
518 icon: <PullRequestGlyph.merged className="size-3.5" />,
519 label: `${title} merged`,
520 }
521 : {
522 icon: <PullRequestGlyph.closed className="size-3.5" />,
523 label: `${title} closed`,
524 };
525​
526 return (
527 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
528 <IconMarker icon={presentation.icon} />
529 <div className="py-1.5 text-xs">
530 <div className="flex flex-wrap items-center gap-1.5">
531 {event.actor ? <ActorName actor={event.actor} /> : null}
532 <span className="font-semibold text-foreground">{presentation.label}</span>
533 </div>
534 <div className="mt-0.5 text-2xs text-muted-foreground">
535 <RelativeTime timestamp={event.at} />
536 </div>
537 </div>
538 </div>
539 );
541​
542function ReviewVerdictEvent({
543 event,
544 outcome,
545 stale,
546 cwd,
547 onOpen,
548 reactions,
549}: {
550 event: PullRequestTimelineEvent;
551 outcome: PullRequestReviewOutcome;
552 stale: boolean;
553 cwd: string;
554 onOpen: (url: string) => void;
555 reactions: ReactionSurface;
556}) {
557 return (
558 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
559 <ActorTimelineMarker
560 actors={event.actor ? [event.actor] : []}
561 className="top-6"
562 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
563 />
564 <div className="flex min-w-0 flex-wrap items-center gap-2 py-1.5">
565 <div className="min-w-0 flex-1">
566 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
567 <ActorName actor={event.actor} />
568 <Tooltip disabled={!stale}>
569 <TooltipTrigger
570 render={
571 <span
572 className={cn(
573 "font-medium lowercase",
574 stale
575 ? "text-muted-foreground opacity-70"
576 : pullRequestReviewOutcomeToneClassName(outcome),
577 )}
578 />
579 }
580 >
581 {pullRequestReviewOutcomeLabel(outcome)}
582 {stale ? <span className="sr-only">, before the latest commits</span> : null}
583 </TooltipTrigger>
584 <TooltipPopup>{pullRequestReviewOutcomeStaleLabel(outcome)}</TooltipPopup>
585 </Tooltip>
586 </div>
587 <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
588 <PullRequestMetaLine className="flex-wrap text-2xs text-muted-foreground">
589 <span>
590 <RelativeTime timestamp={event.at} />
591 </span>
592 {event.path ? (
593 <span className="inline-flex min-w-0 items-center gap-1">
594 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
595 <span className="truncate">{event.path}</span>
596 </span>
597 ) : null}
598 </PullRequestMetaLine>
599 </div>
600 </div>
601 {reactions.canReact || event.reactions.length > 0 ? (
602 <PullRequestReactionBar
603 className="ml-auto justify-end"
604 reactions={event.reactions}
605 canReact={reactions.canReact}
606 subjectId={event.id}
607 environmentId={reactions.environmentId}
608 reference={reactions.reference}
609 onRefresh={reactions.onRefresh}
610 />
611 ) : null}
612 <OpenOnHostButton url={event.url} onOpen={onOpen} />
613 </div>
614 {event.body ? (
615 <TimelineBody
616 body={event.body}
617 markdown={event.markdown}
618 cwd={cwd}
619 environmentId={reactions.environmentId}
620 threadRef={reactions.threadRef}
621 />
622 ) : null}
623 </div>
624 );
626​
627export function PullRequestTimelineTab({
628 scrollerRef,
629 detail,
630 environmentId,
631 threadRef = null,
632 reference,
633 order,
634 onOpenCommit,
635 onRefresh,
636}: {
637 scrollerRef: (node: HTMLDivElement | null) => void;
638 detail: PullRequestDetailView;
639 environmentId: EnvironmentId;
640 threadRef?: ScopedThreadRef | null;
641 reference: PullRequestRef;
642 order: "newest" | "oldest";
643 onOpenCommit: (oid: string) => void;
644 onRefresh: () => void;
645}) {
646 const events = buildPullRequestTimeline(detail);
647 const term = sourceControlClients.get(detail.provider).changeRequest.singular;
648 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
649 const reactions: ReactionSurface = {
650 canReact: detail.capabilities.reactions === true,
651 environmentId,
652 threadRef,
653 reference,
654 onRefresh,
655 };
656 const editable = new Map(
657 events
658 .flatMap((event) => [event, ...(event.thread?.replies ?? [])])
659 .flatMap((event) => (event.comment ? [event.comment] : []))
660 .filter((comment) => canEditPullRequestComment(detail, comment))
661 .map((comment) => [comment.id, comment] as const),
662 );
663 const orderedEvents = order === "newest" ? events : events.toReversed();
664 const rows = groupPullRequestTimelineConversations(orderedEvents);
665 const openOnHost = (url: string) => {
666 void readLocalApi()?.shell.openExternal(url);
667 };
668​
669 return (
670 <div ref={scrollerRef} className="scrollbar-gutter-both h-full overflow-y-auto px-4 py-5">
671 <div className="mx-auto max-w-3xl">
672 <div className="relative">
673 <span aria-hidden className="absolute bottom-5 left-[15px] top-1 w-px bg-border/45" />
674 {rows.map((row) => {
675 if (row.kind === "comments") {
676 return (
677 <ConversationGroup
678 key={`comments:${row.events[0]?.id ?? "empty"}`}
679 events={row.events}
680 editable={editable}
681 cwd={detail.workspaceRoot}
682 onOpen={openOnHost}
683 reactions={reactions}
684 />
685 );
686 }
687 const event = row.event;
688 if (event.thread !== undefined) {
689 return (
690 <ReviewThreadEvent
691 key={`${reactions.reference.projectId}#${reactions.reference.number}:thread:${event.id}:${event.thread.isResolved}:${pullRequestReviewOutcome(event.reviewState) === "dismissed"}`}
692 event={event}
693 thread={event.thread}
694 editable={editable}
695 cwd={detail.workspaceRoot}
696 onOpen={openOnHost}
697 reactions={reactions}
698 />
699 );
700 }
701 if (event.kind === "commit") {
702 return <CommitEvent key={event.id} event={event} onOpen={onOpenCommit} />;
703 }
704 const outcome = pullRequestReviewOutcome(event.reviewState);
705 if (outcome !== null) {
706 return (
707 <ReviewVerdictEvent
708 key={event.id}
709 event={event}
710 outcome={outcome}
711 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
712 cwd={detail.workspaceRoot}
713 onOpen={openOnHost}
714 reactions={reactions}
715 />
716 );
717 }
718 return <LifecycleEvent key={event.id} event={event} term={term} />;
719 })}
720 </div>
721​
722 {events.length === 0 ? (
723 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
724 <PullRequestGlyph.pullRequest className="mb-2 size-5" />
725 <p className="text-xs">No activity yet.</p>
726 </div>
727 ) : null}
728 </div>
729 </div>
730 );