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