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