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

PullRequestTimelineTab.tsx

610 lines19.6 KB

1import { useAtomCommand } from "~/state/use-atom-command";
2import type {
3 EnvironmentId,
4 PullRequestActor,
5 PullRequestComment,
6 PullRequestDetailView,
7 PullRequestRef,
8 ScopedThreadRef,
9} from "@t3tools/contracts";
10import {
11 ChevronDownIcon,
12 ExternalLinkIcon,
13 FileCode2Icon,
14 GitCommitHorizontalIcon,
15 MessageSquareIcon,
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 { 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​
53interface ReactionSurface {
54 readonly canReact: boolean;
55 readonly environmentId: EnvironmentId;
56 readonly threadRef: ScopedThreadRef | null;
57 readonly reference: PullRequestRef;
58 readonly onRefresh: () => void;
60​
61function TimelineBody({
62 body,
63 markdown,
64 cwd,
65 environmentId,
66 threadRef,
67}: {
68 body: string;
69 markdown: boolean;
70 cwd: string;
71 environmentId: EnvironmentId;
72 threadRef: ScopedThreadRef | null;
73}) {
74 return (
75 <div className="mt-3">
76 {markdown ? (
77 <PullRequestMarkdown
78 text={body}
79 cwd={cwd}
80 environmentId={environmentId}
81 threadRef={threadRef}
82 />
83 ) : (
84 <p className="whitespace-pre-wrap text-xs text-muted-foreground">{body}</p>
85 )}
86 </div>
87 );
89​
90function ActorName({ actor }: { actor: PullRequestActor | null }) {
91 return <span className="font-semibold text-foreground">{actor?.login ?? "ghost"}</span>;
93​
94function TimelineMarker({
95 children,
96 className,
97}: {
98 children: ReactNode;
99 className?: string | undefined;
100}) {
101 return (
102 <span
103 className={cn(
104 "absolute left-0 top-1/2 z-10 flex size-8 -translate-y-1/2 items-center justify-center bg-background",
105 className,
106 )}
107 >
108 {children}
109 </span>
110 );
112​
113function IconMarker({ icon, className }: { icon: ReactNode; className?: string | undefined }) {
114 return (
115 <TimelineMarker className={className}>
116 <span className="flex size-7 items-center justify-center bg-background text-muted-foreground">
117 {icon}
118 </span>
119 </TimelineMarker>
120 );
122​
123function ActorTimelineMarker({
124 actors,
125 className,
126 fallback,
127 muted = false,
128}: {
129 actors: ReadonlyArray<PullRequestActor>;
130 className?: string | undefined;
131 fallback: ReactNode;
132 muted?: boolean;
133}) {
134 const actor = actors[0];
135 return actor === undefined ? (
136 <IconMarker className={className} icon={fallback} />
137 ) : (
138 <TimelineMarker className={className}>
139 <PullRequestActorAvatar
140 actor={actor}
141 className={cn(
142 "size-7 bg-muted text-3xs transition-opacity",
143 muted && "opacity-45 grayscale",
144 )}
145 />
146 </TimelineMarker>
147 );
149​
150function friendlyReviewState(value: string): string {
151 const words = value.toLowerCase().replaceAll("_", " ").replaceAll("-", " ");
152 return words.replace(/^\w/u, (letter) => letter.toUpperCase());
154​
155function ReviewStateBadge({ state }: { state: string }) {
156 return (
157 <span className="text-3xs font-medium text-muted-foreground">{friendlyReviewState(state)}</span>
158 );
160​
161function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
162 return url === null ? null : (
163 <Button
164 size="icon-xs"
165 variant="ghost-muted"
166 className="-mr-1 -mt-1 shrink-0"
167 aria-label="Open activity on host"
168 onClick={() => onOpen(url)}
169 >
170 <ExternalLinkIcon className="size-3" />
171 </Button>
172 );
174​
175function ConversationCard({
176 event,
177 editable,
178 cwd,
179 onOpen,
180 reactions,
181}: {
182 event: PullRequestTimelineEvent;
183 editable: PullRequestComment | null;
184 cwd: string;
185 onOpen: (url: string) => void;
186 reactions: ReactionSurface;
187}) {
188 const [editing, setEditing] = useState(false);
189 const [saving, setSaving] = useState(false);
190 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
191 reportFailure: false,
192 });
193​
194 const save = async (body: string) => {
195 // A review's own summary is not a kind any host rewrites, which is why `editable` is never
196 // one; the check is here because the comment's own type still allows it.
197 if (editable === null || saving || editable.kind === "review") return;
198 setSaving(true);
199 const result = await updateComment({
200 environmentId: reactions.environmentId,
201 input: { ...reactions.reference, commentId: editable.id, kind: editable.kind, body },
202 });
203 setSaving(false);
204 if (result._tag === "Failure") {
205 toastManager.add({ type: "error", title: "Could not save the comment" });
206 return;
207 }
208 setEditing(false);
209 reactions.onRefresh();
210 };
211​
212 return (
213 <article className="group py-2">
214 <div className="px-2">
215 <div className="flex min-w-0 flex-wrap items-start gap-2">
216 <div className="min-w-0 flex-1">
217 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
218 <ActorName actor={event.actor} />
219 <span className="text-muted-foreground">{event.title}</span>
220 {event.reviewState ? <ReviewStateBadge state={event.reviewState} /> : null}
221 </div>
222 <PullRequestMetaLine className="mt-1 flex-wrap text-2xs text-muted-foreground">
223 <span>{formatRelativeTimeLabel(event.at)}</span>
224 {event.path ? (
225 <span className="inline-flex min-w-0 items-center gap-1">
226 <FileCode2Icon aria-hidden className="size-3 shrink-0" />
227 <span className="truncate">{event.path}</span>
228 </span>
229 ) : null}
230 </PullRequestMetaLine>
231 </div>
232 {editable !== null && !editing ? (
233 <PullRequestEditButton
234 className="-mt-1"
235 aria-label="Edit comment"
236 onClick={() => setEditing(true)}
237 />
238 ) : null}
239 {reactions.canReact || event.reactions.length > 0 ? (
240 <PullRequestReactionBar
241 className="ml-auto justify-end"
242 reactions={event.reactions}
243 canReact={reactions.canReact}
244 subjectId={event.id}
245 environmentId={reactions.environmentId}
246 reference={reactions.reference}
247 onRefresh={reactions.onRefresh}
248 />
249 ) : null}
250 <OpenOnHostButton url={event.url} onOpen={onOpen} />
251 </div>
252 </div>
253 {editing && editable !== null ? (
254 <div className="px-2 pb-2 pt-3">
255 <PullRequestMarkdownEditor
256 value={editable.body}
257 cwd={cwd}
258 environmentId={reactions.environmentId}
259 threadRef={reactions.threadRef}
260 label="Edit comment"
261 saving={saving}
262 onSave={(body) => void save(body)}
263 onCancel={() => setEditing(false)}
264 />
265 </div>
266 ) : event.body ? (
267 <div className="px-2 pb-2">
268 <TimelineBody
269 body={event.body}
270 markdown={event.markdown}
271 cwd={cwd}
272 environmentId={reactions.environmentId}
273 threadRef={reactions.threadRef}
274 />
275 </div>
276 ) : null}
277 </article>
278 );
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()];
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-3xs 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 );
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 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-inset 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-3xs 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-3xs"
399 />
400 ) : null}
401 </div>
402 </button>
403 );
405​
406function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
407 const presentation =
408 event.kind === "opened"
409 ? {
410 icon: <PullRequestGlyph.pullRequest className="size-3.5" />,
411 label: "Pull request opened",
412 }
413 : event.kind === "merged"
414 ? {
415 icon: <PullRequestGlyph.merged className="size-3.5" />,
416 label: "Pull request merged",
417 }
418 : {
419 icon: <PullRequestGlyph.closed 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-2xs text-muted-foreground">
432 {formatRelativeTimeLabel(event.at)}
433 </div>
434 </div>
435 </div>
436 );
438​
439function ReviewVerdictEvent({
440 event,
441 outcome,
442 stale,
443 cwd,
444 onOpen,
445 reactions,
446}: {
447 event: PullRequestTimelineEvent;
448 outcome: PullRequestReviewOutcome;
449 stale: boolean;
450 cwd: string;
451 onOpen: (url: string) => void;
452 reactions: ReactionSurface;
453}) {
454 return (
455 <div className="group relative mb-5 pl-12 [contain-intrinsic-block-size:48px] [content-visibility:auto]">
456 <ActorTimelineMarker
457 actors={event.actor ? [event.actor] : []}
458 className="top-6"
459 fallback={<PullRequestReviewOutcomeIcon outcome={outcome} />}
460 />
461 <div className="flex min-w-0 flex-wrap items-start gap-2 py-1.5">
462 <div className="min-w-0 flex-1">
463 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs">
464 <ActorName actor={event.actor} />
465 <Tooltip disabled={!stale}>
466 <TooltipTrigger
467 render={
468 <span
469 className={cn(
470 "font-medium lowercase",
471 stale
472 ? "text-muted-foreground opacity-70"
473 : pullRequestReviewOutcomeToneClassName(outcome),
474 )}
475 />
476 }
477 >
478 {pullRequestReviewOutcomeLabel(outcome)}
479 {stale ? <span className="sr-only">, before the latest commits</span> : null}
480 </TooltipTrigger>
481 <TooltipPopup>{pullRequestReviewOutcomeStaleLabel(outcome)}</TooltipPopup>
482 </Tooltip>
483 </div>
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-2xs 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 </div>
495 </div>
496 {reactions.canReact || event.reactions.length > 0 ? (
497 <PullRequestReactionBar
498 className="ml-auto justify-end"
499 reactions={event.reactions}
500 canReact={reactions.canReact}
501 subjectId={event.id}
502 environmentId={reactions.environmentId}
503 reference={reactions.reference}
504 onRefresh={reactions.onRefresh}
505 />
506 ) : null}
507 <OpenOnHostButton url={event.url} onOpen={onOpen} />
508 </div>
509 {event.body ? (
510 <TimelineBody
511 body={event.body}
512 markdown={event.markdown}
513 cwd={cwd}
514 environmentId={reactions.environmentId}
515 threadRef={reactions.threadRef}
516 />
517 ) : null}
518 </div>
519 );
521​
522export function PullRequestTimelineTab({
523 scrollerRef,
524 detail,
525 environmentId,
526 threadRef = null,
527 reference,
528 order,
529 onOpenCommit,
530 onRefresh,
531}: {
532 scrollerRef: (node: HTMLDivElement | null) => void;
533 detail: PullRequestDetailView;
534 environmentId: EnvironmentId;
535 threadRef?: ScopedThreadRef | null;
536 reference: PullRequestRef;
537 order: "newest" | "oldest";
538 onOpenCommit: (oid: string) => void;
539 onRefresh: () => void;
540}) {
541 const events = buildPullRequestTimeline(detail);
542 const newestCommitAt = newestPullRequestCommitAt(detail.commits);
543 const reactions: ReactionSurface = {
544 canReact: detail.capabilities.reactions === true,
545 environmentId,
546 threadRef,
547 reference,
548 onRefresh,
549 };
550 const editable = new Map(
551 detail.comments
552 .filter((comment) => canEditPullRequestComment(detail, comment))
553 .map((comment) => [comment.id, comment] as const),
554 );
555 const orderedEvents = order === "newest" ? events : events.toReversed();
556 const rows = groupPullRequestTimelineConversations(orderedEvents);
557 const openOnHost = (url: string) => {
558 void readLocalApi()?.shell.openExternal(url);
559 };
560​
561 return (
562 <div ref={scrollerRef} className="scrollbar-gutter-both h-full overflow-y-auto px-4 py-5">
563 <div className="mx-auto max-w-3xl">
564 <div className="relative">
565 <span aria-hidden className="absolute bottom-5 left-[15px] top-1 w-px bg-border/45" />
566 {rows.map((row) => {
567 if (row.kind === "comments") {
568 return (
569 <ConversationGroup
570 key={`comments:${row.events[0]?.id ?? "empty"}`}
571 events={row.events}
572 editable={editable}
573 cwd={detail.workspaceRoot}
574 onOpen={openOnHost}
575 reactions={reactions}
576 />
577 );
578 }
579 const event = row.event;
580 if (event.kind === "commit") {
581 return <CommitEvent key={event.id} event={event} onOpen={onOpenCommit} />;
582 }
583 const outcome = pullRequestReviewOutcome(event.reviewState);
584 if (outcome !== null) {
585 return (
586 <ReviewVerdictEvent
587 key={event.id}
588 event={event}
589 outcome={outcome}
590 stale={isPullRequestVerdictStale(event.at, newestCommitAt)}
591 cwd={detail.workspaceRoot}
592 onOpen={openOnHost}
593 reactions={reactions}
594 />
595 );
596 }
597 return <LifecycleEvent key={event.id} event={event} />;
598 })}
599 </div>
600​
601 {events.length === 0 ? (
602 <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
603 <PullRequestGlyph.pullRequest className="mb-2 size-5" />
604 <p className="text-xs">No activity yet.</p>
605 </div>
606 ) : null}
607 </div>
608 </div>
609 );