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

PullRequestTimelineTab.tsx

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