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} from "lucide-react";
16import { useState, type ReactNode } from "react";
17
18import { cn } from "~/lib/utils";
19import { readLocalApi } from "~/localApi";
20import { pullRequestEnvironment } from "~/state/pullRequests";
21import { useAtomCommand } from "~/state/use-atom-command";
22import { formatRelativeTimeLabel } from "~/timestampFormat";
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
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-muted"
170 className="-mr-1 -mt-1 shrink-0"
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 <PullRequestEditButton
239 className="-mt-1"
240 aria-label="Edit comment"
241 onClick={() => setEditing(true)}
242 />
243 ) : null}
244 {reactions.canReact || event.reactions.length > 0 ? (
245 <PullRequestReactionBar
246 className="ml-auto justify-end"
247 reactions={event.reactions}
248 canReact={reactions.canReact}
249 subjectId={event.id}
250 environmentId={reactions.environmentId}
251 reference={reactions.reference}
252 onRefresh={reactions.onRefresh}
253 />
254 ) : null}
255 <OpenOnHostButton url={event.url} onOpen={onOpen} />
256 </div>
257 </div>
258 {editing && editable !== null ? (
259 <div className="px-2 pb-2 pt-3">
260 <PullRequestMarkdownEditor
261 value={editable.body}
262 cwd={cwd}
263 environmentId={reactions.environmentId}
264 threadRef={reactions.threadRef}
265 label="Edit comment"
266 saving={saving}
267 onSave={(body) => void save(body)}
268 onCancel={() => setEditing(false)}
269 />
270 </div>
271 ) : event.body ? (
272 <div className="px-2 pb-2">
273 <TimelineBody
274 body={event.body}
275 markdown={event.markdown}
276 cwd={cwd}
277 environmentId={reactions.environmentId}
278 threadRef={reactions.threadRef}
279 />
280 </div>
281 ) : null}
282 </article>
283 );
284}
285
286function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
287 const actors = new Map<string, PullRequestActor>();
288 for (const event of events) {
289 const actor = event.actor;
290 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
291 }
292 return [...actors.values()];
293}
294
295function ConversationGroup({
296 events,
297 editable,
298 cwd,
299 onOpen,
300 reactions,
301}: {
302 events: ReadonlyArray<PullRequestTimelineEvent>;
303 editable: ReadonlyMap<string, PullRequestComment>;
304 cwd: string;
305 onOpen: (url: string) => void;
306 reactions: ReactionSurface;
307}) {
308 const [open, setOpen] = useState(false);
309 const actors = uniqueConversationActors(events);
310 const first = events[0];
311 if (first === undefined) return null;
312
313 return (
314 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
315 <ActorTimelineMarker
316 actors={actors}
317 className="top-6"
318 fallback={<MessageSquareIcon className="size-3.5" />}
319 muted={!open}
320 />
321 <Collapsible open={open} onOpenChange={setOpen}>
322 <div>
323 <CollapsibleTrigger
324 className={cn(
325 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
326 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
327 )}
328 >
329 <span className="min-w-0 flex-1">
330 <span className="block text-xs font-semibold">
331 {events.length.toLocaleString()} {events.length === 1 ? "comment" : "comments"}
332 </span>
333 <span className="block truncate text-[10px] text-muted-foreground">
334 {actors.length.toLocaleString()} {actors.length === 1 ? "author" : "authors"} ·{" "}
335 {formatRelativeTimeLabel(first.at)}
336 </span>
337 </span>
338 <ChevronDownIcon
339 aria-hidden
340 className={cn(
341 "size-3.5 shrink-0 text-muted-foreground transition-transform",
342 open && "rotate-180",
343 )}
344 />
345 </CollapsibleTrigger>
346 <CollapsiblePanel>
347 {open ? (
348 <div className="mt-1 space-y-1">
349 {events.map((event) => (
350 <ConversationCard
351 // Named with the pull request too: a remark's id is the host's own, and two
352 // pull requests can hand out the same one — which would leave one card's open
353 // editor standing over the other's remark.
354 key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
355 event={event}
356 editable={editable.get(event.id) ?? null}
357 cwd={cwd}
358 onOpen={onOpen}
359 reactions={reactions}
360 />
361 ))}
362 </div>
363 ) : null}
364 </CollapsiblePanel>
365 </div>
366 </Collapsible>
367 </div>
368 );
369}
370
371function CommitEvent({
372 event,
373 onOpen,
374}: {
375 event: PullRequestTimelineEvent;
376 onOpen: (oid: string) => void;
377}) {
378 return (
379 <button
380 type="button"
381 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"
382 aria-label={`View commit ${event.id}`}
383 onClick={() => onOpen(event.id)}
384 >
385 <ActorTimelineMarker
386 actors={event.commitAuthors}
387 fallback={<GitCommitHorizontalIcon className="size-3.5" />}
388 />
389 <div className="flex min-w-0 items-center gap-2.5 py-1.5">
390 <div className="min-w-0 flex-1">
391 <div className="truncate text-xs font-semibold text-foreground transition-colors group-hover:text-primary">
392 {event.body ?? "Untitled commit"}
393 </div>
394 <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground">
395 <code className="font-mono">{event.id.slice(0, 7)}</code>
396 <span>{formatRelativeTimeLabel(event.at)}</span>
397 </div>
398 </div>
399 {event.additions !== null && event.deletions !== null ? (
400 <PullRequestDiffStat
401 additions={event.additions}
402 deletions={event.deletions}
403 className="ml-auto shrink-0 font-mono text-[10px]"
404 />
405 ) : null}
406 </div>
407 </button>
408 );
409}
410
411function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
412 const presentation =
413 event.kind === "opened"
414 ? {
415 icon: <PullRequestGlyph.pullRequest className="size-3.5" />,
416 label: "Pull request opened",
417 }
418 : event.kind === "merged"
419 ? {
420 icon: <PullRequestGlyph.merged className="size-3.5" />,
421 label: "Pull request merged",
422 }
423 : {
424 icon: <PullRequestGlyph.closed className="size-3.5" />,
425 label: "Pull request closed",
426 };
427
428 return (
429 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
430 <IconMarker icon={presentation.icon} />
431 <div className="py-1.5 text-xs">
432 <div className="flex flex-wrap items-center gap-1.5">
433 {event.actor ? <ActorName actor={event.actor} /> : null}
434 <span className="font-semibold text-foreground">{presentation.label}</span>
435 </div>
436 <div className="mt-0.5 text-[11px] text-muted-foreground">
437 {formatRelativeTimeLabel(event.at)}
438 </div>
439 </div>
440 </div>
441 );
442}
443
444/**
445 * A verdict, as its own row rather than a line inside a collapsed conversation. It wears the
446 * reviewer's face on the rail and the verdict's own icon beside their name, so "approved" reads
447 * at a glance from the same place a merge or a commit does.
448 */
449function ReviewVerdictEvent({
450 event,
451 outcome,
452 stale,
453 cwd,
454 onOpen,
455 reactions,
456}: {
457 event: PullRequestTimelineEvent;
458 outcome: PullRequestReviewOutcome;
459 /** Commits landed after this verdict, so it speaks for code the branch no longer has. */
460 stale: boolean;
461 cwd: string;
462 onOpen: (url: string) => void;
463 reactions: ReactionSurface;
464}) {
465 return (
466 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
467 {/* Pinned rather than centred: this row grows with a body, and a
468 centred avatar drifts down beside it instead of sitting by the name. */}
469 <ActorTimelineMarker
470 actors={event.actor ? [event.actor] : []}
471 className="top-6"
472 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
473 />
474 <div className="flex min-w-0 flex-wrap items-start gap-2 py-1.5">
475 <div className="min-w-0 flex-1">
476 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
477 <ActorName actor={event.actor} />
478 {/* The word alone, in the verdict's own colour — green for an approval, red for a
479 request for changes. A verdict overtaken by later commits keeps its word and
480 loses that colour: it still happened, and it no longer speaks for what is on the
481 branch. Lowercased in the styling rather than the string, so what a screen reader
482 announces stays the label every other surface uses. */}
483 <Tooltip disabled={!stale}>
484 <TooltipTrigger
485 render={
486 <span
487 className={cn(
488 "font-medium lowercase",
489 stale
490 ? "text-muted-foreground opacity-70"
491 : pullRequestReviewOutcomeToneClassName(outcome),
492 )}
493 />
494 }
495 >
496 {pullRequestReviewOutcomeLabel(outcome)}
497 {stale ? <span className="sr-only">, before the latest commits</span> : null}
498 </TooltipTrigger>
499 <TooltipPopup>{pullRequestReviewOutcomeStaleLabel(outcome)}</TooltipPopup>
500 </Tooltip>
501 </div>
502 <div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
503 <PullRequestMetaLine className="flex-wrap text-[11px] text-muted-foreground">
504 <span>{formatRelativeTimeLabel(event.at)}</span>
505 {event.path ? (
506 <span className="inline-flex min-w-0 items-center gap-1">
507 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
508 <span className="truncate">{event.path}</span>
509 </span>
510 ) : null}
511 </PullRequestMetaLine>
512 </div>
513 </div>
514 {reactions.canReact || event.reactions.length > 0 ? (
515 <PullRequestReactionBar
516 className="ml-auto justify-end"
517 reactions={event.reactions}
518 canReact={reactions.canReact}
519 subjectId={event.id}
520 environmentId={reactions.environmentId}
521 reference={reactions.reference}
522 onRefresh={reactions.onRefresh}
523 />
524 ) : null}
525 <OpenOnHostButton url={event.url} onOpen={onOpen} />
526 </div>
527 {/* An approval usually carries no words. When it does they are the review, so they stay
528 visible rather than being folded away with the ordinary conversation. */}
529 {event.body ? (
530 <TimelineBody
531 body={event.body}
532 markdown={event.markdown}
533 cwd={cwd}
534 environmentId={reactions.environmentId}
535 threadRef={reactions.threadRef}
536 />
537 ) : null}
538 </div>
539 );
540}
541
542export function PullRequestTimelineTab({
543 detail,
544 environmentId,
545 threadRef = null,
546 reference,
547 order,
548 onOpenCommit,
549 onRefresh,
550}: {
551 detail: PullRequestDetailView;
552 environmentId: EnvironmentId;
553 threadRef?: ScopedThreadRef | null;
554 reference: PullRequestRef;
555 order: "newest" | "oldest";
556 onOpenCommit: (oid: string) => void;
557 onRefresh: () => void;
558}) {
559 const events = buildPullRequestTimeline(detail);
560 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
561 const reactions: ReactionSurface = {
562 canReact: detail.capabilities.reactions === true,
563 environmentId,
564 threadRef,
565 reference,
566 onRefresh,
567 };
568 // A timeline entry keeps only what it draws, so the remarks this reader may rewrite are looked
569 // up here by the id the entry carries.
570 const editable = new Map(
571 detail.comments
572 .filter((comment) => canEditPullRequestComment(detail, comment))
573 .map((comment) => [comment.id, comment] as const),
574 );
575 const orderedEvents = order === "newest" ? events : events.toReversed();
576 const rows = groupPullRequestTimelineConversations(orderedEvents);
577 const openOnHost = (url: string) => {
578 void readLocalApi()?.shell.openExternal(url);
579 };
580
581 return (
582 <div className="h-full overflow-y-auto px-4 py-5">
583 <div className="mx-auto max-w-3xl">
584 <div className="relative">
585 <span aria-hidden className="absolute bottom-5 left-[15px] top-1 w-px bg-border/45" />
586 {rows.map((row) => {
587 if (row.kind === "comments") {
588 return (
589 <ConversationGroup
590 key={`comments:${row.events[0]?.id ?? "empty"}`}
591 events={row.events}
592 editable={editable}
593 cwd={detail.workspaceRoot}
594 onOpen={openOnHost}
595 reactions={reactions}
596 />
597 );
598 }
599 const event = row.event;
600 if (event.kind === "commit") {
601 return <CommitEvent key={event.id} event={event} onOpen={onOpenCommit} />;
602 }
603 const outcome = pullRequestReviewOutcome(event.reviewState);
604 if (outcome !== null) {
605 return (
606 <ReviewVerdictEvent
607 key={event.id}
608 event={event}
609 outcome={outcome}
610 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
611 cwd={detail.workspaceRoot}
612 onOpen={openOnHost}
613 reactions={reactions}
614 />
615 );
616 }
617 return <LifecycleEvent key={event.id} event={event} />;
618 })}
619 </div>
620
621 {events.length === 0 ? (
622 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
623 <PullRequestGlyph.pullRequest className="mb-2 size-5" />
624 <p className="text-xs">No activity yet.</p>
625 </div>
626 ) : null}
627 </div>
628 </div>
629 );
630}