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

PullRequestTimelineTab.tsx

639 lines21.6 KB

1import type {
2 EnvironmentId,
3 PullRequestActor,
4 PullRequestComment,
5 PullRequestDetailView,
6 PullRequestRef,
7 ScopedThreadRef,
8} from "@t3tools/contracts";
9import {
10 ChevronDownIcon,
11 ExternalLinkIcon,
12 FileCode2Icon,
13 GitCommitHorizontalIcon,
14 GitMergeIcon,
15 GitPullRequestClosedIcon,
16 GitPullRequestIcon,
17 MessageSquareIcon,
18 PencilIcon,
19} from "lucide-react";
20import { useState, type ReactNode } from "react";
21​
22import { cn } from "~/lib/utils";
23import { readLocalApi } from "~/localApi";
24import { pullRequestEnvironment } from "~/state/pullRequests";
25import { useAtomCommand } from "~/state/use-atom-command";
26import { formatRelativeTimeLabel } from "~/timestampFormat";
27​
28import { Button } from "../ui/button";
29import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
30import { toastManager } from "../ui/toast";
31import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
32import {
33 buildPullRequestTimeline,
34 groupPullRequestTimelineConversations,
35 isPullRequestVerdictStale,
36 newestPullRequestCommitAt,
37 pullRequestReviewOutcome,
38 type PullRequestReviewOutcome,
39 type PullRequestTimelineEvent,
40} from "./pullRequestDetail.logic";
41import { canEditPullRequestComment } from "./pullRequestEditing.logic";
42import { PullRequestMarkdown } from "./PullRequestMarkdown";
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";
54​
55/** What every comment on the timeline needs to react; only the subject differs between them. */
56interface ReactionSurface {
57 readonly canReact: boolean;
58 readonly environmentId: EnvironmentId;
59 /** Thread the timeline is shown beside, so body links can open in its in-app browser. */
60 readonly threadRef: ScopedThreadRef | null;
61 readonly reference: PullRequestRef;
62 readonly onRefresh: () => void;
64​
65function TimelineBody({
66 body,
67 markdown,
68 cwd,
69 environmentId,
70 threadRef,
71}: {
72 body: string;
73 markdown: boolean;
74 cwd: string;
75 environmentId: EnvironmentId;
76 threadRef: ScopedThreadRef | null;
77}) {
78 return (
79 <div className="mt-3">
80 {markdown ? (
81 <PullRequestMarkdown
82 text={body}
83 cwd={cwd}
84 environmentId={environmentId}
85 threadRef={threadRef}
86 />
87 ) : (
88 <p className="whitespace-pre-wrap text-xs text-muted-foreground">{body}</p>
89 )}
90 </div>
91 );
93​
94function ActorName({ actor }: { actor: PullRequestActor | null }) {
95 return <span className="font-semibold text-foreground">{actor?.login ?? "ghost"}</span>;
97​
98function TimelineMarker({
99 children,
100 className,
101}: {
102 children: ReactNode;
103 className?: string | undefined;
104}) {
105 return (
106 <span
107 className={cn(
108 "absolute left-0 top-1/2 z-10 flex size-8 -translate-y-1/2 items-center justify-center bg-background",
109 className,
110 )}
111 >
112 {children}
113 </span>
114 );
116​
117function IconMarker({ icon, className }: { icon: ReactNode; className?: string | undefined }) {
118 return (
119 <TimelineMarker className={className}>
120 <span className="flex size-7 items-center justify-center bg-background text-muted-foreground">
121 {icon}
122 </span>
123 </TimelineMarker>
124 );
126​
127function ActorTimelineMarker({
128 actors,
129 className,
130 fallback,
131 muted = false,
132}: {
133 actors: ReadonlyArray<PullRequestActor>;
134 className?: string | undefined;
135 fallback: ReactNode;
136 muted?: boolean;
137}) {
138 const actor = actors[0];
139 return actor === undefined ? (
140 <IconMarker className={className} icon={fallback} />
141 ) : (
142 <TimelineMarker className={className}>
143 <PullRequestActorAvatar
144 actor={actor}
145 className={cn(
146 "size-7 bg-muted text-[9px] transition-opacity",
147 muted && "opacity-45 grayscale",
148 )}
149 />
150 </TimelineMarker>
151 );
153​
154function friendlyReviewState(value: string): string {
155 const words = value.toLowerCase().replaceAll("_", " ").replaceAll("-", " ");
156 return words.replace(/^\w/u, (letter) => letter.toUpperCase());
158​
159function ReviewStateBadge({ state }: { state: string }) {
160 return (
161 <span className="text-[10px] font-medium text-muted-foreground">
162 {friendlyReviewState(state)}
163 </span>
164 );
166​
167function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
168 return url === null ? null : (
169 <Button
170 size="icon-xs"
171 variant="ghost"
172 className="-mr-1 -mt-1 shrink-0 text-muted-foreground"
173 aria-label="Open activity on host"
174 onClick={() => onOpen(url)}
175 >
176 <ExternalLinkIcon className="size-3" />
177 </Button>
178 );
180​
181function ConversationCard({
182 event,
183 editable,
184 cwd,
185 onOpen,
186 reactions,
187}: {
188 event: PullRequestTimelineEvent;
189 /** The remark behind this entry, only where this reader may rewrite it. */
190 editable: PullRequestComment | null;
191 cwd: string;
192 onOpen: (url: string) => void;
193 reactions: ReactionSurface;
194}) {
195 const [editing, setEditing] = useState(false);
196 const [saving, setSaving] = useState(false);
197 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
198 reportFailure: false,
199 });
200​
201 const save = async (body: string) => {
202 // A review's own summary is not a kind any host rewrites, which is why `editable` is never
203 // one; the check is here because the comment's own type still allows it.
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 items-start 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-[11px] text-muted-foreground">
230 <span>{formatRelativeTimeLabel(event.at)}</span>
231 {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 <Button
241 size="icon-xs"
242 variant="ghost"
243 className="-mt-1 shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
244 aria-label="Edit comment"
245 onClick={() => setEditing(true)}
246 >
247 <PencilIcon className="size-3" />
248 </Button>
249 ) : null}
250 <OpenOnHostButton url={event.url} onOpen={onOpen} />
251 </div>
252 </div>
253 {editing && editable !== null ? (
254 <div className="px-2 pb-2 pt-3">
255 <PullRequestMarkdownEditor
256 value={editable.body}
257 cwd={cwd}
258 environmentId={reactions.environmentId}
259 threadRef={reactions.threadRef}
260 label="Edit comment"
261 saving={saving}
262 onSave={(body) => void save(body)}
263 onCancel={() => setEditing(false)}
264 />
265 </div>
266 ) : event.body ? (
267 <div className="px-2 pb-2">
268 <TimelineBody
269 body={event.body}
270 markdown={event.markdown}
271 cwd={cwd}
272 environmentId={reactions.environmentId}
273 threadRef={reactions.threadRef}
274 />
275 </div>
276 ) : null}
277 {reactions.canReact || event.reactions.length > 0 ? (
278 <div className="px-2 pb-2">
279 <PullRequestReactionBar
280 reactions={event.reactions}
281 canReact={reactions.canReact}
282 subjectId={event.id}
283 environmentId={reactions.environmentId}
284 reference={reactions.reference}
285 onRefresh={reactions.onRefresh}
286 />
287 </div>
288 ) : null}
289 </article>
290 );
292​
293function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
294 const actors = new Map<string, PullRequestActor>();
295 for (const event of events) {
296 const actor = event.actor;
297 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
298 }
299 return [...actors.values()];
301​
302function ConversationGroup({
303 events,
304 editable,
305 cwd,
306 onOpen,
307 reactions,
308}: {
309 events: ReadonlyArray<PullRequestTimelineEvent>;
310 editable: ReadonlyMap<string, PullRequestComment>;
311 cwd: string;
312 onOpen: (url: string) => void;
313 reactions: ReactionSurface;
314}) {
315 const [open, setOpen] = useState(false);
316 const actors = uniqueConversationActors(events);
317 const first = events[0];
318 if (first === undefined) return null;
319​
320 return (
321 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
322 <ActorTimelineMarker
323 actors={actors}
324 className="top-6"
325 fallback={<MessageSquareIcon className="size-3.5" />}
326 muted={!open}
327 />
328 <Collapsible open={open} onOpenChange={setOpen}>
329 <div>
330 <CollapsibleTrigger
331 className={cn(
332 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
333 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
334 )}
335 >
336 <span className="min-w-0 flex-1">
337 <span className="block text-xs font-semibold">
338 {events.length.toLocaleString()} {events.length === 1 ? "comment" : "comments"}
339 </span>
340 <span className="block truncate text-[10px] text-muted-foreground">
341 {actors.length.toLocaleString()} {actors.length === 1 ? "author" : "authors"} ·{" "}
342 {formatRelativeTimeLabel(first.at)}
343 </span>
344 </span>
345 <ChevronDownIcon
346 aria-hidden
347 className={cn(
348 "size-3.5 shrink-0 text-muted-foreground transition-transform",
349 open && "rotate-180",
350 )}
351 />
352 </CollapsibleTrigger>
353 <CollapsiblePanel>
354 {open ? (
355 <div className="mt-1 space-y-1">
356 {events.map((event) => (
357 <ConversationCard
358 // Named with the pull request too: a remark's id is the host's own, and two
359 // pull requests can hand out the same one — which would leave one card's open
360 // editor standing over the other's remark.
361 key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
362 event={event}
363 editable={editable.get(event.id) ?? null}
364 cwd={cwd}
365 onOpen={onOpen}
366 reactions={reactions}
367 />
368 ))}
369 </div>
370 ) : null}
371 </CollapsiblePanel>
372 </div>
373 </Collapsible>
374 </div>
375 );
377​
378function CommitEvent({
379 event,
380 onOpen,
381}: {
382 event: PullRequestTimelineEvent;
383 onOpen: (oid: string) => void;
384}) {
385 return (
386 <button
387 type="button"
388 className="group relative mb-5 block w-full rounded-sm pl-12 text-left outline-none [contain-intrinsic-block-size:48px] [content-visibility:auto] focus-visible:ring-2 focus-visible:ring-ring"
389 aria-label={`View commit ${event.id}`}
390 onClick={() => onOpen(event.id)}
391 >
392 <ActorTimelineMarker
393 actors={event.commitAuthors}
394 fallback={<GitCommitHorizontalIcon className="size-3.5" />}
395 />
396 <div className="flex min-w-0 items-center gap-2.5 py-1.5">
397 <div className="min-w-0 flex-1">
398 <div className="truncate text-xs font-semibold text-foreground transition-colors group-hover:text-primary">
399 {event.body ?? "Untitled commit"}
400 </div>
401 <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground">
402 <code className="font-mono">{event.id.slice(0, 7)}</code>
403 <span>{formatRelativeTimeLabel(event.at)}</span>
404 </div>
405 </div>
406 {event.additions !== null && event.deletions !== null ? (
407 <PullRequestDiffStat
408 additions={event.additions}
409 deletions={event.deletions}
410 className="ml-auto shrink-0 font-mono text-[10px]"
411 />
412 ) : null}
413 </div>
414 </button>
415 );
417​
418function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
419 const presentation =
420 event.kind === "opened"
421 ? {
422 icon: <GitPullRequestIcon className="size-3.5" />,
423 label: "Pull request opened",
424 }
425 : event.kind === "merged"
426 ? {
427 icon: <GitMergeIcon className="size-3.5" />,
428 label: "Pull request merged",
429 }
430 : {
431 icon: <GitPullRequestClosedIcon className="size-3.5" />,
432 label: "Pull request closed",
433 };
434​
435 return (
436 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
437 <IconMarker icon={presentation.icon} />
438 <div className="py-1.5 text-xs">
439 <div className="flex flex-wrap items-center gap-1.5">
440 {event.actor ? <ActorName actor={event.actor} /> : null}
441 <span className="font-semibold text-foreground">{presentation.label}</span>
442 </div>
443 <div className="mt-0.5 text-[11px] text-muted-foreground">
444 {formatRelativeTimeLabel(event.at)}
445 </div>
446 </div>
447 </div>
448 );
450​
451/**
452 * A verdict, as its own row rather than a line inside a collapsed conversation. It wears the
453 * reviewer's face on the rail and the verdict's own icon beside their name, so "approved" reads
454 * at a glance from the same place a merge or a commit does.
455 */
456function ReviewVerdictEvent({
457 event,
458 outcome,
459 stale,
460 cwd,
461 onOpen,
462 reactions,
463}: {
464 event: PullRequestTimelineEvent;
465 outcome: PullRequestReviewOutcome;
466 /** Commits landed after this verdict, so it speaks for code the branch no longer has. */
467 stale: boolean;
468 cwd: string;
469 onOpen: (url: string) => void;
470 reactions: ReactionSurface;
471}) {
472 return (
473 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
474 {/* Pinned rather than centred: this row grows with a body and a reaction bar, and a
475 centred avatar drifts down beside them instead of sitting by the name. */}
476 <ActorTimelineMarker
477 actors={event.actor ? [event.actor] : []}
478 className="top-6"
479 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
480 />
481 <div className="flex min-w-0 items-start gap-2 py-1.5">
482 <div className="min-w-0 flex-1">
483 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
484 <ActorName actor={event.actor} />
485 {/* The word alone, in the verdict's own colour — green for an approval, red for a
486 request for changes. A verdict overtaken by later commits keeps its word and
487 loses that colour: it still happened, and it no longer speaks for what is on the
488 branch. Lowercased in the styling rather than the string, so what a screen reader
489 announces stays the label every other surface uses. */}
490 <Tooltip disabled={!stale}>
491 <TooltipTrigger
492 render={
493 <span
494 className={cn(
495 "font-medium lowercase",
496 stale
497 ? "text-muted-foreground opacity-70"
498 : pullRequestReviewOutcomeToneClassName(outcome),
499 )}
500 />
501 }
502 >
503 {pullRequestReviewOutcomeLabel(outcome)}
504 {stale ? <span className="sr-only">, before the latest commits</span> : null}
505 </TooltipTrigger>
506 <TooltipPopup>{pullRequestReviewOutcomeStaleLabel(outcome)}</TooltipPopup>
507 </Tooltip>
508 </div>
509 {/* The reaction bar rides this line rather than taking one of its own. Its add button
510 is invisible until hovered but still occupies `h-6`, and under a verdict — usually a
511 single line with no body — a row of that reserved on its own reads as a hole. */}
512 <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
513 <PullRequestMetaLine className="flex-wrap text-[11px] text-muted-foreground">
514 <span>{formatRelativeTimeLabel(event.at)}</span>
515 {event.path ? (
516 <span className="inline-flex min-w-0 items-center gap-1">
517 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
518 <span className="truncate">{event.path}</span>
519 </span>
520 ) : null}
521 </PullRequestMetaLine>
522 {reactions.canReact || event.reactions.length > 0 ? (
523 <PullRequestReactionBar
524 reactions={event.reactions}
525 canReact={reactions.canReact}
526 subjectId={event.id}
527 environmentId={reactions.environmentId}
528 reference={reactions.reference}
529 onRefresh={reactions.onRefresh}
530 />
531 ) : null}
532 </div>
533 {/* An approval usually carries no words. When it does they are the review, so they stay
534 visible rather than being folded away with the ordinary conversation. */}
535 {event.body ? (
536 <TimelineBody
537 body={event.body}
538 markdown={event.markdown}
539 cwd={cwd}
540 environmentId={reactions.environmentId}
541 threadRef={reactions.threadRef}
542 />
543 ) : null}
544 </div>
545 <OpenOnHostButton url={event.url} onOpen={onOpen} />
546 </div>
547 </div>
548 );
550​
551export function PullRequestTimelineTab({
552 detail,
553 environmentId,
554 threadRef = null,
555 reference,
556 order,
557 onOpenCommit,
558 onRefresh,
559}: {
560 detail: PullRequestDetailView;
561 environmentId: EnvironmentId;
562 threadRef?: ScopedThreadRef | null;
563 reference: PullRequestRef;
564 order: "newest" | "oldest";
565 onOpenCommit: (oid: string) => void;
566 onRefresh: () => void;
567}) {
568 const events = buildPullRequestTimeline(detail);
569 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
570 const reactions: ReactionSurface = {
571 canReact: detail.capabilities.reactions === true,
572 environmentId,
573 threadRef,
574 reference,
575 onRefresh,
576 };
577 // A timeline entry keeps only what it draws, so the remarks this reader may rewrite are looked
578 // up here by the id the entry carries.
579 const editable = new Map(
580 detail.comments
581 .filter((comment) => canEditPullRequestComment(detail, comment))
582 .map((comment) => [comment.id, comment] as const),
583 );
584 const orderedEvents = order === "newest" ? events : events.toReversed();
585 const rows = groupPullRequestTimelineConversations(orderedEvents);
586 const openOnHost = (url: string) => {
587 void readLocalApi()?.shell.openExternal(url);
588 };
589​
590 return (
591 <div className="h-full overflow-y-auto px-4 py-5">
592 <div className="mx-auto max-w-3xl">
593 <div className="relative">
594 <span aria-hidden className="absolute bottom-5 left-[15px] top-1 w-px bg-border/45" />
595 {rows.map((row) => {
596 if (row.kind === "comments") {
597 return (
598 <ConversationGroup
599 key={`comments:${row.events[0]?.id ?? "empty"}`}
600 events={row.events}
601 editable={editable}
602 cwd={detail.workspaceRoot}
603 onOpen={openOnHost}
604 reactions={reactions}
605 />
606 );
607 }
608 const event = row.event;
609 if (event.kind === "commit") {
610 return <CommitEvent key={event.id} event={event} onOpen={onOpenCommit} />;
611 }
612 const outcome = pullRequestReviewOutcome(event.reviewState);
613 if (outcome !== null) {
614 return (
615 <ReviewVerdictEvent
616 key={event.id}
617 event={event}
618 outcome={outcome}
619 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
620 cwd={detail.workspaceRoot}
621 onOpen={openOnHost}
622 reactions={reactions}
623 />
624 );
625 }
626 return <LifecycleEvent key={event.id} event={event} />;
627 })}
628 </div>
629​
630 {events.length === 0 ? (
631 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
632 <GitPullRequestIcon className="mb-2 size-5" />
633 <p className="text-xs">No activity yet.</p>
634 </div>
635 ) : null}
636 </div>
637 </div>
638 );