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

PullRequestTimelineTab.tsx

602 lines20.7 KB

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