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 {
31 buildPullRequestTimeline,
32 groupPullRequestTimelineConversations,
33 type PullRequestTimelineEvent,
34} from "./pullRequestDetail.logic";
35import { canEditPullRequestComment } from "./pullRequestEditing.logic";
36import { PullRequestMarkdown } from "./PullRequestMarkdown";
37import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
38import { PullRequestReactionBar } from "./PullRequestReactions";
39import {
40 PullRequestActorAvatar,
41 PullRequestDiffStat,
42 PullRequestMetaLine,
43} from "./pullRequestPresentation";
44
45/** What every comment on the timeline needs to react; only the subject differs between them. */
46interface ReactionSurface {
47 readonly canReact: boolean;
48 readonly environmentId: EnvironmentId;
49 readonly reference: PullRequestRef;
50 readonly onRefresh: () => void;
51}
52
53function TimelineBody({ body, markdown, cwd }: { body: string; markdown: boolean; cwd: string }) {
54 return (
55 <div className="mt-3">
56 {markdown ? (
57 <PullRequestMarkdown text={body} cwd={cwd} />
58 ) : (
59 <p className="whitespace-pre-wrap text-xs text-muted-foreground">{body}</p>
60 )}
61 </div>
62 );
63}
64
65function ActorName({ actor }: { actor: PullRequestActor | null }) {
66 return <span className="font-semibold text-foreground">{actor?.login ?? "ghost"}</span>;
67}
68
69function TimelineMarker({
70 children,
71 className,
72}: {
73 children: ReactNode;
74 className?: string | undefined;
75}) {
76 return (
77 <span
78 className={cn(
79 "absolute left-0 top-1/2 z-10 flex size-8 -translate-y-1/2 items-center justify-center bg-background",
80 className,
81 )}
82 >
83 {children}
84 </span>
85 );
86}
87
88function IconMarker({ icon, className }: { icon: ReactNode; className?: string | undefined }) {
89 return (
90 <TimelineMarker className={className}>
91 <span className="flex size-7 items-center justify-center bg-background text-muted-foreground">
92 {icon}
93 </span>
94 </TimelineMarker>
95 );
96}
97
98function ActorTimelineMarker({
99 actors,
100 className,
101 fallback,
102 muted = false,
103}: {
104 actors: ReadonlyArray<PullRequestActor>;
105 className?: string | undefined;
106 fallback: ReactNode;
107 muted?: boolean;
108}) {
109 const actor = actors[0];
110 return actor === undefined ? (
111 <IconMarker className={className} icon={fallback} />
112 ) : (
113 <TimelineMarker className={className}>
114 <PullRequestActorAvatar
115 actor={actor}
116 className={cn(
117 "size-7 bg-muted text-[9px] transition-opacity",
118 muted && "opacity-45 grayscale",
119 )}
120 />
121 </TimelineMarker>
122 );
123}
124
125function friendlyReviewState(value: string): string {
126 const words = value.toLowerCase().replaceAll("_", " ").replaceAll("-", " ");
127 return words.replace(/^\w/u, (letter) => letter.toUpperCase());
128}
129
130function ReviewStateBadge({ state }: { state: string }) {
131 return (
132 <span className="text-[10px] font-medium text-muted-foreground">
133 {friendlyReviewState(state)}
134 </span>
135 );
136}
137
138function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
139 return url === null ? null : (
140 <Button
141 size="icon-xs"
142 variant="ghost"
143 className="-mr-1 -mt-1 shrink-0 text-muted-foreground"
144 aria-label="Open activity on host"
145 onClick={() => onOpen(url)}
146 >
147 <ExternalLinkIcon className="size-3" />
148 </Button>
149 );
150}
151
152function ConversationCard({
153 event,
154 editable,
155 cwd,
156 onOpen,
157 reactions,
158}: {
159 event: PullRequestTimelineEvent;
160 /** The remark behind this entry, only where this reader may rewrite it. */
161 editable: PullRequestComment | null;
162 cwd: string;
163 onOpen: (url: string) => void;
164 reactions: ReactionSurface;
165}) {
166 const [editing, setEditing] = useState(false);
167 const [saving, setSaving] = useState(false);
168 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
169 reportFailure: false,
170 });
171
172 const save = async (body: string) => {
173 // A review's own summary is not a kind any host rewrites, which is why `editable` is never
174 // one; the check is here because the comment's own type still allows it.
175 if (editable === null || saving || editable.kind === "review") return;
176 setSaving(true);
177 const result = await updateComment({
178 environmentId: reactions.environmentId,
179 input: { ...reactions.reference, commentId: editable.id, kind: editable.kind, body },
180 });
181 setSaving(false);
182 if (result._tag === "Failure") {
183 toastManager.add({ type: "error", title: "Could not save the comment" });
184 return;
185 }
186 setEditing(false);
187 reactions.onRefresh();
188 };
189
190 return (
191 <article className="group py-2">
192 <div className="px-2">
193 <div className="flex min-w-0 items-start gap-2">
194 <div className="min-w-0 flex-1">
195 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
196 <ActorName actor={event.actor} />
197 <span className="text-muted-foreground">{event.title}</span>
198 {event.reviewState ? <ReviewStateBadge state={event.reviewState} /> : null}
199 </div>
200 <PullRequestMetaLine className="mt-1 flex-wrap text-[11px] text-muted-foreground">
201 <span>{formatRelativeTimeLabel(event.at)}</span>
202 {event.path ? (
203 <span className="inline-flex min-w-0 items-center gap-1">
204 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
205 <span className="truncate">{event.path}</span>
206 </span>
207 ) : null}
208 </PullRequestMetaLine>
209 </div>
210 {editable !== null && !editing ? (
211 <Button
212 size="icon-xs"
213 variant="ghost"
214 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"
215 aria-label="Edit comment"
216 onClick={() => setEditing(true)}
217 >
218 <PencilIcon className="size-3" />
219 </Button>
220 ) : null}
221 <OpenOnHostButton url={event.url} onOpen={onOpen} />
222 </div>
223 </div>
224 {editing && editable !== null ? (
225 <div className="px-2 pb-2 pt-3">
226 <PullRequestMarkdownEditor
227 value={editable.body}
228 cwd={cwd}
229 label="Edit comment"
230 saving={saving}
231 onSave={(body) => void save(body)}
232 onCancel={() => setEditing(false)}
233 />
234 </div>
235 ) : event.body ? (
236 <div className="px-2 pb-2">
237 <TimelineBody body={event.body} markdown={event.markdown} cwd={cwd} />
238 </div>
239 ) : null}
240 {reactions.canReact || event.reactions.length > 0 ? (
241 <div className="px-2 pb-2">
242 <PullRequestReactionBar
243 reactions={event.reactions}
244 canReact={reactions.canReact}
245 subjectId={event.id}
246 environmentId={reactions.environmentId}
247 reference={reactions.reference}
248 onRefresh={reactions.onRefresh}
249 />
250 </div>
251 ) : null}
252 </article>
253 );
254}
255
256function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent>) {
257 const actors = new Map<string, PullRequestActor>();
258 for (const event of events) {
259 const actor = event.actor;
260 if (actor !== null && !actors.has(actor.login)) actors.set(actor.login, actor);
261 }
262 return [...actors.values()];
263}
264
265function ConversationGroup({
266 events,
267 editable,
268 cwd,
269 onOpen,
270 reactions,
271}: {
272 events: ReadonlyArray<PullRequestTimelineEvent>;
273 editable: ReadonlyMap<string, PullRequestComment>;
274 cwd: string;
275 onOpen: (url: string) => void;
276 reactions: ReactionSurface;
277}) {
278 const [open, setOpen] = useState(false);
279 const actors = uniqueConversationActors(events);
280 const first = events[0];
281 if (first === undefined) return null;
282
283 return (
284 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
285 <ActorTimelineMarker
286 actors={actors}
287 className="top-6"
288 fallback={<MessageSquareIcon className="size-3.5" />}
289 muted={!open}
290 />
291 <Collapsible open={open} onOpenChange={setOpen}>
292 <div>
293 <CollapsibleTrigger
294 className={cn(
295 "flex w-full min-w-0 items-center gap-3 py-2 text-left transition-opacity hover:opacity-100",
296 open ? "text-foreground opacity-100" : "text-muted-foreground opacity-55",
297 )}
298 >
299 <span className="min-w-0 flex-1">
300 <span className="block text-xs font-semibold">
301 {events.length.toLocaleString()} {events.length === 1 ? "comment" : "comments"}
302 </span>
303 <span className="block truncate text-[10px] text-muted-foreground">
304 {actors.length.toLocaleString()} {actors.length === 1 ? "author" : "authors"} ·{" "}
305 {formatRelativeTimeLabel(first.at)}
306 </span>
307 </span>
308 <ChevronDownIcon
309 aria-hidden
310 className={cn(
311 "size-3.5 shrink-0 text-muted-foreground transition-transform",
312 open && "rotate-180",
313 )}
314 />
315 </CollapsibleTrigger>
316 <CollapsiblePanel>
317 {open ? (
318 <div className="mt-1 space-y-1">
319 {events.map((event) => (
320 <ConversationCard
321 // Named with the pull request too: a remark's id is the host's own, and two
322 // pull requests can hand out the same one — which would leave one card's open
323 // editor standing over the other's remark.
324 key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
325 event={event}
326 editable={editable.get(event.id) ?? null}
327 cwd={cwd}
328 onOpen={onOpen}
329 reactions={reactions}
330 />
331 ))}
332 </div>
333 ) : null}
334 </CollapsiblePanel>
335 </div>
336 </Collapsible>
337 </div>
338 );
339}
340
341function CommitEvent({
342 event,
343 onOpen,
344}: {
345 event: PullRequestTimelineEvent;
346 onOpen: (oid: string) => void;
347}) {
348 return (
349 <button
350 type="button"
351 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"
352 aria-label={`View commit ${event.id}`}
353 onClick={() => onOpen(event.id)}
354 >
355 <ActorTimelineMarker
356 actors={event.commitAuthors}
357 fallback={<GitCommitHorizontalIcon className="size-3.5" />}
358 />
359 <div className="flex min-w-0 items-center gap-2.5 py-1.5">
360 <div className="min-w-0 flex-1">
361 <div className="truncate text-xs font-semibold text-foreground transition-colors group-hover:text-primary">
362 {event.body ?? "Untitled commit"}
363 </div>
364 <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground">
365 <code className="font-mono">{event.id.slice(0, 7)}</code>
366 <span>{formatRelativeTimeLabel(event.at)}</span>
367 </div>
368 </div>
369 {event.additions !== null && event.deletions !== null ? (
370 <PullRequestDiffStat
371 additions={event.additions}
372 deletions={event.deletions}
373 className="ml-auto shrink-0 font-mono text-[10px]"
374 />
375 ) : null}
376 </div>
377 </button>
378 );
379}
380
381function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
382 const presentation =
383 event.kind === "opened"
384 ? {
385 icon: <GitPullRequestIcon className="size-3.5" />,
386 label: "Pull request opened",
387 }
388 : event.kind === "merged"
389 ? {
390 icon: <GitMergeIcon className="size-3.5" />,
391 label: "Pull request merged",
392 }
393 : {
394 icon: <GitPullRequestClosedIcon className="size-3.5" />,
395 label: "Pull request closed",
396 };
397
398 return (
399 <div className="relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
400 <IconMarker icon={presentation.icon} />
401 <div className="py-1.5 text-xs">
402 <div className="flex flex-wrap items-center gap-1.5">
403 {event.actor ? <ActorName actor={event.actor} /> : null}
404 <span className="font-semibold text-foreground">{presentation.label}</span>
405 </div>
406 <div className="mt-0.5 text-[11px] text-muted-foreground">
407 {formatRelativeTimeLabel(event.at)}
408 </div>
409 </div>
410 </div>
411 );
412}
413
414export function PullRequestTimelineTab({
415 detail,
416 environmentId,
417 reference,
418 order,
419 onOpenCommit,
420 onRefresh,
421}: {
422 detail: PullRequestDetailView;
423 environmentId: EnvironmentId;
424 reference: PullRequestRef;
425 order: "newest" | "oldest";
426 onOpenCommit: (oid: string) => void;
427 onRefresh: () => void;
428}) {
429 const events = buildPullRequestTimeline(detail);
430 const reactions: ReactionSurface = {
431 canReact: detail.capabilities.reactions === true,
432 environmentId,
433 reference,
434 onRefresh,
435 };
436 // A timeline entry keeps only what it draws, so the remarks this reader may rewrite are looked
437 // up here by the id the entry carries.
438 const editable = new Map(
439 detail.comments
440 .filter((comment) => canEditPullRequestComment(detail, comment))
441 .map((comment) => [comment.id, comment] as const),
442 );
443 const orderedEvents = order === "newest" ? events : events.toReversed();
444 const rows = groupPullRequestTimelineConversations(orderedEvents);
445 const openOnHost = (url: string) => {
446 void readLocalApi()?.shell.openExternal(url);
447 };
448
449 return (
450 <div className="h-full overflow-y-auto px-4 py-5">
451 <div className="mx-auto max-w-3xl">
452 <div className="relative">
453 <span aria-hidden className="absolute bottom-5 left-[15px] top-1 w-px bg-border/45" />
454 {rows.map((row) => {
455 if (row.kind === "comments") {
456 return (
457 <ConversationGroup
458 key={`comments:${row.events[0]?.id ?? "empty"}`}
459 events={row.events}
460 editable={editable}
461 cwd={detail.workspaceRoot}
462 onOpen={openOnHost}
463 reactions={reactions}
464 />
465 );
466 }
467 const event = row.event;
468 if (event.kind === "commit") {
469 return <CommitEvent key={event.id} event={event} onOpen={onOpenCommit} />;
470 }
471 return <LifecycleEvent key={event.id} event={event} />;
472 })}
473 </div>
474
475 {events.length === 0 ? (
476 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
477 <GitPullRequestIcon className="mb-2 size-5" />
478 <p className="text-xs">No activity yet.</p>
479 </div>
480 ) : null}
481 </div>
482 </div>
483 );
484}