Open History to see the last commit
1import { pullRequestCommentPreview } from "./pullRequestMarkdown.logic";
2import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
3import { holdLinkedNodeInView, holdScrollTop } from "./holdLinkedNodeInView";
4import { useAtomValue } from "@effect/atom-react";
5import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
6import { useAtomCommand } from "~/state/use-atom-command";
7import {
8 type EnvironmentId,
9 type PullRequestComment,
10 type PullRequestDetailView,
11 type PullRequestRef,
12 type PullRequestConversationThread,
13 type ScopedThreadRef,
14 pullRequestConversationThreads,
15} from "@t3tools/contracts";
16import {
17 ArrowDownUpIcon,
18 ChevronDownIcon,
19 ChevronRightIcon,
20 HammerIcon,
21 ListFilterIcon,
22 MessageSquarePlusIcon,
23 TagIcon,
24 UsersIcon,
25} from "lucide-react";
26import * as Schema from "effect/Schema";
27import { msg, T, useGT, useMessages, Var } from "gt-react";
28import {
29 memo,
30 useEffect,
31 useEffectEvent,
32 useLayoutEffect,
33 useRef,
34 useState,
35 type ReactNode,
36} from "react";
37
38import { m, type MessageResolver } from "~/i18n/messages";
39
40import { pullRequestEnvironment } from "~/state/pullRequests";
41import { useLocalStorage } from "~/hooks/useLocalStorage";
42import { cn } from "~/lib/utils";
43import { useOpenLink } from "~/browser/useOpenLink";
44import { RelativeTime } from "~/components/RelativeTime";
45import { useClientSettings } from "~/hooks/useSettings";
46import { formatFullTimestamp } from "~/timestampFormat";
47
48import { Button } from "../ui/button";
49import { PullRequestEditButton } from "./PullRequestEditButton";
50import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
51import {
52 Menu,
53 MenuCheckboxItem,
54 MenuGroup,
55 MenuGroupLabel,
56 MenuPopup,
57 MenuTrigger,
58} from "../ui/menu";
59import { toastManager } from "../ui/toast";
60import { SharedTooltipTrigger } from "../ui/shared-tooltip";
61import {
62 PullRequestActorLabel,
63 PullRequestCheckStatusIcon,
64 pullRequestCheckStatusLabel,
65 PullRequestLabelChip,
66 PullRequestReviewOutcomeBadge,
67 pullRequestReviewOutcomeLabel,
68 PullRequestReviewOutcomeAvatarBadge,
69 pullRequestReviewOutcomeRingClassName,
70 pullRequestReviewOutcomeStaleLabel,
71} from "./pullRequestPresentation";
72import { PullRequestLabelPicker } from "./PullRequestLabelPicker";
73import { PullRequestReviewerPicker } from "./PullRequestReviewerPicker";
74import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
75import {
76 filterPullRequestConversationItems,
77 isPullRequestCommentFinished,
78 latestPullRequestReviewOutcomes,
79 orderPullRequestComments,
80 pagePullRequestConversationItems,
81 pullRequestConversationItemComments,
82 pullRequestConversationItems,
83 pullRequestFindingKey,
84 pullRequestReviewOutcome,
85 visibleBody,
86 type PullRequestChatSubject,
87 type PullRequestConversationItem,
88 type PullRequestFinding,
89} from "./pullRequestDetail.logic";
90import {
91 canEditPullRequestChangeRequest,
92 canEditPullRequestComment,
93 descriptionDraftInForce,
94 settleDescriptionSave,
95 startDescriptionSave,
96 type DescriptionDraft,
97} from "@t3tools/client-runtime/pull-request-editing";
98import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits";
99import { PullRequestMarkdown } from "./PullRequestMarkdown";
100import { PullRequestCommentBody } from "./PullRequestCommentBody";
101import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
102import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
103import {
104 type PullRequestCompletionScope,
105 pullRequestCompletionScope,
106} from "./PullRequestMarkdownTextarea";
107import { PullRequestReactionBar } from "./PullRequestReactions";
108import { canReactPullRequestComment } from "@t3tools/client-runtime/pull-request-reactions";
109import { PullRequestResolveThreadButton } from "./PullRequestResolveThreadButton";
110import { PullRequestConversationGhost } from "./PullRequestGhosts";
111import { sectionCollapseAnchorScrollTop } from "./pullRequestSummaryScroll.logic";
112
113import { changeRequestTermKind } from "./changeRequestTerm";
114import { WorkflowRunsAbout } from "../workflows/WorkflowRunsAbout";
115
116function reviewerKey(login: string): string {
117 return login.toLowerCase();
118}
119
120function CommentIdentity({
121 comment,
122 detail,
123 threadRef,
124}: {
125 comment: PullRequestComment;
126 detail: PullRequestDetailView;
127 threadRef: ScopedThreadRef | null;
128}) {
129 const gt = useGT();
130 const openLink = useOpenLink(threadRef);
131 const url = comment.url;
132 const timestampFormat = useClientSettings((settings) => settings.timestampFormat);
133 const actor = comment.author;
134 const profileUrl = actor
135 ? sourceControlClients.get(detail.provider).authorProfileUrl(actor.login, detail.url)
136 : null;
137 return (
138 <h2 className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-1 text-xs">
139 <PullRequestActorLabel
140 actor={actor}
141 profileUrl={profileUrl}
142 threadRef={threadRef}
143 className="max-w-full"
144 />
145 <SharedTooltipTrigger
146 render={
147 url ? (
148 <a
149 href={url}
150 target="_blank"
151 rel="noopener noreferrer"
152 className="text-muted-foreground hover:text-foreground hover:underline"
153 onClick={(event) => {
154 event.preventDefault();
155 void openLink(url, { event }).catch(console.error);
156 }}
157 />
158 ) : (
159 <span className="text-muted-foreground" />
160 )
161 }
162 label={
163 <>
164 {formatFullTimestamp(comment.createdAt, timestampFormat)}
165 {url ? ` · ${gt("Open comment on host")}` : ""}
166 </>
167 }
168 >
169 <time dateTime={comment.createdAt}>
170 <RelativeTime timestamp={comment.createdAt} />
171 </time>
172 </SharedTooltipTrigger>
173 </h2>
174 );
175}
176
177function CommentLocation({
178 comment,
179 thread,
180}: {
181 comment: PullRequestComment;
182 thread: PullRequestConversationThread | undefined;
183}) {
184 const path = thread?.path ?? comment.path;
185 if (!path) return null;
186 const label = `${path}${thread?.line ? `:${thread.line}` : ""}`;
187 return (
188 <div className="mt-2 flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
189 <SharedTooltipTrigger render={<span className="truncate font-mono" />} label={label}>
190 {label}
191 </SharedTooltipTrigger>
192 {thread?.isOutdated ? (
193 <span className="shrink-0">
194 <T context="review thread state">Outdated</T>
195 </span>
196 ) : null}
197 </div>
198 );
199}
200
201const REVIEW_STATE_LABELS: Partial<Record<string, string>> = {
202 commented: msg("Commented", { $context: "review state" }),
203 pending: msg("Pending", { $context: "review state" }),
204};
205
206function reviewStateLabel(state: string, resolve: MessageResolver): string {
207 const known = REVIEW_STATE_LABELS[state.trim().toLowerCase()];
208 if (known) return resolve(known);
209 const words = state.toLowerCase().replace(/_/g, " ");
210 return words.charAt(0).toUpperCase() + words.slice(1);
211}
212
213interface CommentEditing {
214 readonly cwd: string;
215 readonly environmentId: EnvironmentId;
216 readonly completionScope: PullRequestCompletionScope | null;
217 readonly threadRef: ScopedThreadRef | null;
218 readonly canEdit: (comment: PullRequestComment) => boolean;
219 readonly editingId: string | null;
220 readonly saving: boolean;
221 readonly onEdit: (comment: PullRequestComment | null) => void;
222 readonly onSave: (comment: PullRequestComment, body: string) => void;
223}
224
225function CommentBody({
226 comment,
227 editing,
228 className,
229}: {
230 comment: PullRequestComment;
231 editing: CommentEditing;
232 className?: string | undefined;
233}) {
234 const gt = useGT();
235 if (editing.editingId === comment.id) {
236 return (
237 <PullRequestMarkdownEditor
238 className={className}
239 value={comment.body}
240 cwd={editing.cwd}
241 environmentId={editing.environmentId}
242 completionScope={editing.completionScope}
243 threadRef={editing.threadRef}
244 label={gt("Edit comment")}
245 saving={editing.saving}
246 onSave={(body) => editing.onSave(comment, body)}
247 onCancel={() => editing.onEdit(null)}
248 />
249 );
250 }
251 return (
252 <div className={cn("flex items-start gap-1", className)}>
253 <PullRequestCommentBody
254 key={comment.id}
255 className="min-w-0 flex-1"
256 text={comment.body}
257 cwd={editing.cwd}
258 environmentId={editing.environmentId}
259 threadRef={editing.threadRef}
260 />
261 {editing.canEdit(comment) ? (
262 <PullRequestEditButton
263 aria-label={gt("Edit comment")}
264 onClick={() => editing.onEdit(comment)}
265 />
266 ) : null}
267 </div>
268 );
269}
270
271/**
272 * What Add to chat hands over for a remark: a remark on a line goes as its whole conversation,
273 * the way fixing one does. Null when there are no words in it to talk about.
274 */
275function chatSubject(
276 comment: PullRequestComment,
277 thread: PullRequestConversationThread | undefined,
278): PullRequestChatSubject | null {
279 // An overview thread has no line to attach, so it goes as its opening remark, as fixing it does.
280 if (thread !== undefined && thread.path !== null) {
281 return thread.comments.some((entry) => visibleBody(entry.body) !== null)
282 ? { kind: "thread", thread }
283 : null;
284 }
285 return visibleBody(comment.body) === null ? null : { kind: "comment", comment };
286}
287
288function AddToChatButton({ onClick }: { onClick: () => void }) {
289 return (
290 <Button size="xs" variant="ghost" className="shrink-0" onClick={onClick}>
291 {/* Wrapped like Fix's label so both sit on the header's baseline. */}
292 <span className="inline-flex items-baseline gap-1">
293 <MessageSquarePlusIcon className="size-3 self-center" />
294 <span>
295 <T>Add to chat</T>
296 </span>
297 </span>
298 </Button>
299 );
300}
301
302function CollapsedComment({
303 comment,
304 editing,
305 label,
306 body,
307 reactionBar,
308 resolveButton,
309 detail,
310 thread,
311 replyCount = 0,
312 replies = null,
313 moreReplies = null,
314 onAddToChat,
315}: {
316 comment: PullRequestComment;
317 editing: CommentEditing;
318 label: string;
319 body: string | null;
320 reactionBar: ReactNode;
321 resolveButton: ReactNode;
322 detail: PullRequestDetailView;
323 thread: PullRequestConversationThread | undefined;
324 replyCount?: number;
325 replies?: ReactNode;
326 moreReplies?: ReactNode;
327 onAddToChat?: (() => void) | undefined;
328}) {
329 const gt = useGT();
330 const [open, setOpen] = useState(false);
331 const statusTriggerRef = useRef<HTMLButtonElement>(null);
332 return (
333 <Collapsible open={open} onOpenChange={setOpen}>
334 <article className="group rounded-lg border border-border/60 [contain-intrinsic-block-size:44px] [content-visibility:auto]">
335 <div className="p-3">
336 <div className="flex flex-wrap items-baseline gap-2">
337 <CommentIdentity comment={comment} detail={detail} threadRef={editing.threadRef} />
338 {replyCount > 0 ? (
339 <span className="shrink-0 py-1 text-xs text-muted-foreground">
340 {gt("{count, plural, one {{count} reply} other {{count} replies}}", {
341 count: replyCount,
342 })}
343 </span>
344 ) : null}
345 {/* Collapsed, the status label already says "Resolved". It goes before the
346 trigger so opening doesn't shift the trigger out from under the cursor. */}
347 {open ? resolveButton : null}
348 <CollapsibleTrigger
349 ref={statusTriggerRef}
350 className="flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground"
351 >
352 {label}
353 <ChevronDownIcon
354 aria-hidden
355 className={cn("size-3.5 transition-transform", open && "rotate-180")}
356 />
357 </CollapsibleTrigger>
358 {onAddToChat ? <AddToChatButton onClick={onAddToChat} /> : null}
359 {reactionBar}
360 </div>
361 <CommentLocation comment={comment} thread={thread} />
362 {!open && body ? (
363 <CollapsibleTrigger
364 className="mt-2 block w-full truncate text-left text-xs text-muted-foreground hover:text-foreground"
365 onClick={() => statusTriggerRef.current?.focus({ preventScroll: true })}
366 >
367 {pullRequestCommentPreview(body, detail.provider)}
368 </CollapsibleTrigger>
369 ) : null}
370 </div>
371 <CollapsiblePanel>
372 {open ? (
373 <div className="px-3 pb-3">
374 {body === null && !editing.canEdit(comment) ? null : (
375 <CommentBody className="mt-2" comment={comment} editing={editing} />
376 )}
377 {replies ? <div className="mt-3">{replies}</div> : null}
378 </div>
379 ) : null}
380 </CollapsiblePanel>
381 {moreReplies ? <div className="px-3 pb-3">{moreReplies}</div> : null}
382 </article>
383 </Collapsible>
384 );
385}
386
387export function PullRequestMetaRow({
388 icon,
389 label,
390 children,
391}: {
392 icon: ReactNode;
393 label: string;
394 children: ReactNode;
395}) {
396 return (
397 <div className="grid min-h-7 min-w-0 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2 text-xs sm:min-h-6">
398 <span className="flex items-center gap-1.5 text-muted-foreground">
399 {icon}
400 {label}
401 </span>
402 <span className="min-w-0 text-foreground">{children}</span>
403 </div>
404 );
405}
406
407export function PullRequestSection({
408 title,
409 name,
410 defaultOpen = true,
411 keepMounted = false,
412 revealCount = 0,
413 actions,
414 children,
415}: {
416 title: string;
417 /** Stable key for links that reveal this section, since the title is translated. */
418 name?: string;
419 defaultOpen?: boolean;
420 keepMounted?: boolean;
421 /** Reopens the section each time a link reveals it. */
422 revealCount?: number;
423 actions?: ReactNode;
424 children: ReactNode;
425}) {
426 // A reveal opens at once: the opening animation would move what was just scrolled to.
427 const [open, setOpen] = useState<boolean | "revealed">(
428 revealCount > 0 ? "revealed" : defaultOpen,
429 );
430 const [seenRevealCount, setSeenRevealCount] = useState(revealCount);
431 if (revealCount !== seenRevealCount) {
432 setSeenRevealCount(revealCount);
433 setOpen("revealed");
434 }
435 const headingRef = useRef<HTMLDivElement>(null);
436 const setOpenWithScrollAnchor = (nextOpen: boolean) => {
437 if (!nextOpen) {
438 const heading = headingRef.current;
439 const section = heading?.closest<HTMLElement>("[data-pull-request-summary-section]");
440 const scroller = heading?.closest<HTMLElement>("[data-pull-request-summary-scroll]");
441 if (heading && section && scroller) {
442 const target = sectionCollapseAnchorScrollTop({
443 scrollTop: scroller.scrollTop,
444 viewportTop: scroller.getBoundingClientRect().top,
445 sectionTop: section.getBoundingClientRect().top,
446 headingTop: heading.getBoundingClientRect().top,
447 });
448 // Adjust before paint to keep the collapsed heading in place.
449 if (target !== null) scroller.scrollTop = target;
450 }
451 }
452 setOpen(nextOpen);
453 };
454 return (
455 <Collapsible
456 open={open !== false}
457 onOpenChange={setOpenWithScrollAnchor}
458 render={<section aria-label={title} />}
459 data-pull-request-summary-section={name ?? ""}
460 >
461 <div
462 ref={headingRef}
463 className="sticky top-0 z-10 flex w-full items-center bg-background pr-4"
464 >
465 <CollapsibleTrigger className="flex min-w-0 flex-1 items-center gap-1.5 px-4 py-3 text-left text-xs font-medium text-muted-foreground hover:text-foreground">
466 <span>{title}</span>
467 <ChevronRightIcon
468 aria-hidden
469 className={cn(
470 "size-3.5 text-muted-foreground/60 transition-transform",
471 open && "rotate-90",
472 )}
473 />
474 </CollapsibleTrigger>
475 {actions}
476 </div>
477 <CollapsiblePanel keepMounted={keepMounted} animate={open !== "revealed"}>
478 <div className="px-4 pb-4">{children}</div>
479 </CollapsiblePanel>
480 </Collapsible>
481 );
482}
483
484const COMMENT_PAGE = 10;
485
486interface SummaryView {
487 readonly order: "newest" | "oldest";
488 readonly shown: number;
489 readonly scrollTop: number;
490}
491// Session-only: switching right-panel tabs unmounts the Summary, which comes back as it was left.
492const summaryViewByScopeKey = new Map<string, SummaryView>();
493
494const COMMENT_FILTER_STORAGE_KEY = "t3code:pull-request-comment-filter:v1";
495const CommentFilterSchema = Schema.Struct({ bots: Schema.Boolean, resolved: Schema.Boolean });
496const DEFAULT_COMMENT_FILTER: typeof CommentFilterSchema.Type = { bots: false, resolved: false };
497
498// Memoized: it renders every comment, and the panel re-renders on each query state change.
499export const PullRequestSummaryTab = memo(function PullRequestSummaryTab({
500 revealUrl,
501 onRevealSettled,
502 scrollerRef,
503 environmentId,
504 threadRef,
505 reference,
506 detail,
507 observedAt,
508 activityPending,
509 checksStale = false,
510 activityError,
511 pendingFinding,
512 fixFindingLabel: requestedFixFindingLabel,
513 fixCheckLabel: requestedFixCheckLabel,
514 onFixFinding,
515 onAddToChat,
516 onRefresh,
517 onRefreshChecks = onRefresh,
518}: {
519 /** A clicked link to scroll to, until onRevealSettled reports it shown. */
520 revealUrl?: string | undefined;
521 onRevealSettled?: ((revealUrl: string) => void) | undefined;
522 scrollerRef: (node: HTMLDivElement | null) => void;
523 environmentId: EnvironmentId;
524 threadRef: ScopedThreadRef | null;
525 reference: PullRequestRef;
526 detail: PullRequestDetailView;
527 /** When the detail was last read; the detail itself keeps its older stamp across refreshes. */
528 observedAt: number | undefined;
529 activityPending: boolean;
530 checksStale?: boolean;
531 activityError: string | null;
532 pendingFinding?: string | null;
533 fixFindingLabel?: string;
534 fixCheckLabel?: string;
535 onFixFinding?: (finding: PullRequestFinding) => void;
536 /** Absent where there is no composer beside the panel to add a remark to. */
537 onAddToChat?: (subject: PullRequestChatSubject) => void;
538 onRefresh: () => void;
539 onRefreshChecks?: () => void;
540}) {
541 const gt = useGT();
542 const resolve = useMessages();
543 const fixFindingLabel = requestedFixFindingLabel ?? gt("Fix in a thread");
544 const fixCheckLabel =
545 requestedFixCheckLabel ?? gt("Fix", { $context: "verb, fix a review finding" });
546 const terminology = sourceControlClients.get(detail.provider).changeRequest;
547 const viewKey = `${environmentId}:${detail.url}`;
548 const rememberView = (patch: Partial<SummaryView>) => {
549 const view = summaryViewByScopeKey.get(viewKey) ?? {
550 order: "newest",
551 shown: COMMENT_PAGE,
552 scrollTop: 0,
553 };
554 summaryViewByScopeKey.set(viewKey, { ...view, ...patch });
555 };
556 const [shown, setShownState] = useState(() => ({
557 url: detail.url,
558 count: summaryViewByScopeKey.get(viewKey)?.shown ?? COMMENT_PAGE,
559 }));
560 const setShown = (next: { url: string; count: number }) => {
561 setShownState(next);
562 rememberView({ shown: next.count });
563 };
564 const shownConversations = shown.url === detail.url ? shown.count : COMMENT_PAGE;
565 const [commentFilter, setCommentFilter] = useLocalStorage(
566 COMMENT_FILTER_STORAGE_KEY,
567 DEFAULT_COMMENT_FILTER,
568 CommentFilterSchema,
569 );
570 const items = pullRequestConversationItems(
571 detail.comments,
572 pullRequestConversationThreads(detail),
573 );
574 const filteredItems = filterPullRequestConversationItems(items, commentFilter);
575 const commentCount = items.reduce(
576 (count, item) => count + pullRequestConversationItemComments(item).length,
577 0,
578 );
579 const filteredOutCount =
580 commentCount -
581 filteredItems.reduce(
582 (count, item) => count + pullRequestConversationItemComments(item).length,
583 0,
584 );
585 const { shown: recentItems, hidden: hiddenConversationCount } = pagePullRequestConversationItems(
586 filteredItems,
587 shownConversations,
588 );
589 const [commentOrder, setCommentOrder] = useState(
590 () => summaryViewByScopeKey.get(viewKey)?.order ?? "newest",
591 );
592 const visibleItems = orderPullRequestComments(recentItems, commentOrder);
593 const showOldestCommentsButton =
594 hiddenConversationCount > 0 ? (
595 <Button
596 size="sm"
597 variant="outline"
598 className="w-full"
599 onClick={() => setShown({ url: detail.url, count: shownConversations + COMMENT_PAGE })}
600 >
601 {gt(
602 "{count, plural, one {Show {shown} older conversation ({count} hidden)} other {Show {shown} older conversations ({count} hidden)}}",
603 {
604 count: hiddenConversationCount,
605 shown: Math.min(hiddenConversationCount, COMMENT_PAGE),
606 },
607 )}
608 </Button>
609 ) : null;
610 // Verdicts outside the visible comment window still count.
611 const reviewOutcomes = latestPullRequestReviewOutcomes(detail.comments, detail.commits);
612 // Host login casing varies; normalize to preserve verdicts and deduplicate reviewers.
613 const outcomeByLogin = new Map(
614 reviewOutcomes.flatMap((entry) =>
615 entry.actor ? [[reviewerKey(entry.actor.login), entry] as const] : [],
616 ),
617 );
618 // Hosts remove reviewed actors from requests; include submitted verdicts.
619 const reviewerEntries = [
620 ...detail.reviewers.map((actor) => ({
621 key: actor.login,
622 actor,
623 outcome: outcomeByLogin.get(reviewerKey(actor.login))?.outcome ?? null,
624 stale: outcomeByLogin.get(reviewerKey(actor.login))?.stale ?? false,
625 })),
626 ...reviewOutcomes
627 .filter(
628 (entry) =>
629 !detail.reviewers.some(
630 (actor) =>
631 entry.actor !== null && reviewerKey(actor.login) === reviewerKey(entry.actor.login),
632 ),
633 )
634 .map((entry) => ({
635 key: entry.key,
636 actor: entry.actor,
637 outcome: entry.outcome,
638 stale: entry.stale,
639 })),
640 ];
641
642 const openLink = useOpenLink(threadRef);
643 const openCheck = (url: string) => {
644 void openLink(url).catch((error: unknown) => {
645 console.error(error);
646 toastManager.add({ type: "error", title: m(msg("Unable to open check details")) });
647 });
648 };
649
650 const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
651 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
652 reportFailure: false,
653 });
654 const canUpdate = useAtomValue(pullRequestEnvironment.update.permissionAtom(environmentId));
655 const canEditDescription = canUpdate && canEditPullRequestChangeRequest(detail);
656 // The editor keeps the body it opened from, so a failed save cannot reset what was typed.
657 const [bodyScope, setBodyScope] = useState<{
658 readonly url: string;
659 readonly body: string;
660 } | null>(null);
661 const [descriptionDraft, setDescriptionDraft] = useState<DescriptionDraft | null>(null);
662 const descriptionDraftKept = descriptionDraftInForce(descriptionDraft, detail.url, observedAt);
663 if (descriptionDraftKept !== descriptionDraft) setDescriptionDraft(descriptionDraftKept);
664 const description = descriptionDraftKept?.body ?? detail.body;
665 const descriptionSaving = (descriptionDraftKept?.saves ?? 0) > 0;
666 const descriptionSavesRunning = useRef(0);
667 // Hosts can reuse comment ids across pull requests.
668 const [commentScope, setCommentScope] = useState<{
669 readonly pullRequest: string;
670 readonly commentId: string;
671 } | null>(null);
672 const [commentSaving, setCommentSaving] = useState(false);
673 const editingCommentId = commentScope?.pullRequest === detail.url ? commentScope.commentId : null;
674
675 const scrollRef = useRef<HTMLDivElement | null>(null);
676 const location = parsePullRequestAnchor(revealUrl);
677 const [checksReveals, setChecksReveals] = useState(0);
678 const [descriptionReveals, setDescriptionReveals] = useState(0);
679 const [seenRevealUrl, setSeenRevealUrl] = useState<string | undefined>(undefined);
680 if (revealUrl !== seenRevealUrl) {
681 setSeenRevealUrl(revealUrl);
682 if (location?.kind === "checks") setChecksReveals((count) => count + 1);
683 if (location?.kind === "summary" && location.anchor !== "top") {
684 setDescriptionReveals((count) => count + 1);
685 }
686 }
687 const stopHolding = useRef<(() => void) | null>(null);
688 // A restore clamped by content still loading must not overwrite the saved position.
689 const restoringScroll = useRef(false);
690 const revealSummary = useEffectEvent(() => {
691 const root = scrollRef.current;
692 if (revealUrl === undefined || !root) return;
693 let target: HTMLElement | null | undefined;
694 if (location?.kind === "checks") {
695 target = root.querySelector<HTMLElement>('[data-pull-request-summary-section="checks"]');
696 } else if (location?.kind === "summary") {
697 if (location.anchor === "top") {
698 stopHolding.current?.();
699 root.scrollTop = 0;
700 return onRevealSettled?.(revealUrl);
701 }
702 target = /^issue-\d+$/.test(location.anchor)
703 ? root.querySelector<HTMLElement>("[data-pr-description]")
704 : [...root.querySelectorAll<HTMLElement>("[id]")].find(
705 (node) => node.id === location.anchor || node.id === `user-content-${location.anchor}`,
706 );
707 }
708 // A heading may still be rendering; the link stays pending until it appears.
709 if (!target) return;
710 stopHolding.current?.();
711 const heading = target.hasAttribute("data-pull-request-summary-section")
712 ? null
713 : target.closest("[data-pull-request-summary-section]")?.firstElementChild;
714 stopHolding.current = holdLinkedNodeInView(
715 target,
716 root,
717 () => (heading?.getBoundingClientRect().height ?? 0) + (heading ? 8 : 0),
718 );
719 onRevealSettled?.(revealUrl);
720 });
721 const editingDescription = bodyScope?.url === detail.url;
722 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls to a linked section, description or heading once it renders
723 useEffect(() => {
724 revealSummary();
725 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retries once the description markdown renders, including after its editor closes
726 }, [revealUrl, description, checksReveals, descriptionReveals, editingDescription]);
727 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- puts a remounted Summary back at the scroll position it left, before paint
728 useLayoutEffect(() => {
729 const scrollTop = summaryViewByScopeKey.get(viewKey)?.scrollTop ?? 0;
730 if (!scrollRef.current || scrollTop === 0) return;
731 restoringScroll.current = true;
732 stopHolding.current = holdScrollTop(scrollRef.current, scrollTop, () => {
733 restoringScroll.current = false;
734 });
735 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- restores once per mount
736 }, []);
737 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab
738 useEffect(() => () => stopHolding.current?.(), []);
739 // Checkbox ticks and the editor share one draft, so each starts from the other's latest body.
740 const saveDescription = async (body: string) => {
741 const key = detail.url;
742 // The shown detail keeps its older stamp across refreshes; the draft must use the live one.
743 setDescriptionDraft((draft) =>
744 startDescriptionSave(draft, { url: detail.url, observedAt }, body),
745 );
746 descriptionSavesRunning.current += 1;
747 const result = await update({ environmentId, input: { ...reference, body } });
748 descriptionSavesRunning.current -= 1;
749 const saved = result._tag === "Success";
750 setDescriptionDraft((draft) => settleDescriptionSave(draft, key, saved));
751 if (!saved) {
752 toastManager.add({ type: "error", title: m(msg("Could not save the description")) });
753 }
754 if (descriptionSavesRunning.current === 0) onRefresh();
755 return saved;
756 };
757 const saveBody = async (body: string) => {
758 if (descriptionSaving) return;
759 if (await saveDescription(body)) setBodyScope(null);
760 };
761 const toggleTask = ({ markerOffset, checked }: { markerOffset: number; checked: boolean }) => {
762 const body = setMarkdownTaskChecked(description, markerOffset, checked);
763 if (body !== description) void saveDescription(body);
764 };
765
766 const completionScope = pullRequestCompletionScope(detail, environmentId, reference);
767 const commentEditing: CommentEditing = {
768 cwd: detail.workspaceRoot,
769 environmentId,
770 completionScope,
771 threadRef,
772 canEdit: (comment) => canEditPullRequestComment(detail, comment),
773 editingId: editingCommentId,
774 saving: commentSaving,
775 onEdit: (comment) =>
776 setCommentScope(comment === null ? null : { pullRequest: detail.url, commentId: comment.id }),
777 onSave: async (comment, body) => {
778 if (commentSaving || comment.kind === "review") return;
779 setCommentSaving(true);
780 const result = await updateComment({
781 environmentId,
782 input: { ...reference, commentId: comment.id, kind: comment.kind, body },
783 });
784 setCommentSaving(false);
785 if (result._tag === "Failure") {
786 toastManager.add({ type: "error", title: m(msg("Could not save the comment")) });
787 return;
788 }
789 setCommentScope(null);
790 onRefresh();
791 },
792 };
793
794 const reactionBarFor = (comment: PullRequestComment) => (
795 <PullRequestReactionBar
796 className="ml-auto justify-end"
797 reactions={comment.reactions ?? []}
798 canReact={canReactPullRequestComment(detail, comment)}
799 subjectId={comment.id}
800 environmentId={environmentId}
801 reference={reference}
802 onRefresh={onRefresh}
803 />
804 );
805
806 const resolveButtonFor = (thread: PullRequestConversationThread | undefined) =>
807 thread === undefined ? null : (
808 <PullRequestResolveThreadButton
809 environmentId={environmentId}
810 reference={reference}
811 detail={detail}
812 thread={thread}
813 onRefresh={onRefresh}
814 />
815 );
816
817 const renderCommentCard = (
818 comment: PullRequestComment,
819 thread: PullRequestConversationThread | undefined,
820 { reply = false }: { reply?: boolean } = {},
821 ) => {
822 const body = visibleBody(comment.body);
823 const outcome = pullRequestReviewOutcome(comment.reviewState);
824 const finding: PullRequestFinding | null =
825 reply ||
826 (comment.kind !== "review" && comment.kind !== "review-comment") ||
827 outcome === "approved"
828 ? null
829 : thread === undefined || thread.path === null
830 ? body === null
831 ? null
832 : { kind: "comment", comment }
833 : { kind: "thread", thread };
834 // A reply goes with its conversation, from the card that heads it.
835 const chat = reply ? null : chatSubject(comment, thread);
836 return (
837 <article
838 key={`${detail.url}:${comment.id}`}
839 className="group rounded-lg border border-border/60 bg-background [contain-intrinsic-block-size:160px] [content-visibility:auto]"
840 >
841 <div className="flex flex-wrap items-baseline gap-2 rounded-t-lg bg-muted/25 px-3 py-2.5">
842 <div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-2 text-xs text-muted-foreground">
843 <CommentIdentity comment={comment} detail={detail} threadRef={threadRef} />
844 {outcome ? (
845 <PullRequestReviewOutcomeBadge outcome={outcome} />
846 ) : comment.reviewState ? (
847 <span>{reviewStateLabel(comment.reviewState, resolve)}</span>
848 ) : null}
849 </div>
850 {onFixFinding && finding ? (
851 <Button
852 size="xs"
853 variant="ghost"
854 className="shrink-0"
855 disabled={pendingFinding !== null && pendingFinding !== undefined}
856 onClick={() => onFixFinding(finding)}
857 >
858 <span className="inline-flex items-baseline gap-1">
859 <HammerIcon className="size-3 self-center" />
860 <span>
861 {pendingFinding === pullRequestFindingKey(finding)
862 ? gt("Preparing...")
863 : fixFindingLabel}
864 </span>
865 </span>
866 </Button>
867 ) : null}
868 {resolveButtonFor(thread)}
869 {onAddToChat && chat !== null ? (
870 <AddToChatButton onClick={() => onAddToChat(chat)} />
871 ) : null}
872 {reactionBarFor(comment)}
873 </div>
874 {reply ? null : (
875 <div className="px-3">
876 <CommentLocation comment={comment} thread={thread} />
877 </div>
878 )}
879 {body === null && !canEditPullRequestComment(detail, comment) ? null : (
880 <CommentBody className="px-3 py-3" comment={comment} editing={commentEditing} />
881 )}
882 </article>
883 );
884 };
885
886 const renderItem = (item: PullRequestConversationItem) => {
887 const comment = item.kind === "comment" ? item.comment : item.root;
888 const thread = item.kind === "thread" ? item.thread : undefined;
889 const replies =
890 item.kind === "thread" && item.replies.length > 0 ? (
891 <div className="ml-4 space-y-2 border-l-2 border-border/60 pl-3">
892 {item.replies.map((reply) => renderCommentCard(reply, undefined, { reply: true }))}
893 </div>
894 ) : null;
895 const moreReplies =
896 item.kind === "thread" && item.hasMoreReplies ? (
897 <PullRequestMoreReplies {...item} threadRef={threadRef} />
898 ) : null;
899 if (isPullRequestCommentFinished(comment, thread)) {
900 const chat = chatSubject(comment, thread);
901 return (
902 <CollapsedComment
903 key={`${detail.url}:${item.kind}:${item.id}`}
904 comment={comment}
905 editing={commentEditing}
906 detail={detail}
907 thread={thread}
908 label={
909 thread?.isResolved
910 ? gt("Resolved", { $context: "review thread state" })
911 : gt("Review dismissed")
912 }
913 body={visibleBody(comment.body)}
914 replyCount={item.kind === "thread" ? item.replies.length + item.moreReplies : 0}
915 replies={replies}
916 moreReplies={moreReplies}
917 onAddToChat={onAddToChat && chat !== null ? () => onAddToChat(chat) : undefined}
918 reactionBar={reactionBarFor(comment)}
919 resolveButton={resolveButtonFor(thread)}
920 />
921 );
922 }
923 if (item.kind === "comment") return renderCommentCard(comment, undefined);
924 return (
925 <div key={`${detail.url}:thread:${item.id}`} className="space-y-2">
926 {renderCommentCard(comment, thread)}
927 {replies}
928 {moreReplies}
929 </div>
930 );
931 };
932
933 return (
934 <div
935 ref={(node) => {
936 scrollRef.current = node;
937 scrollerRef(node);
938 }}
939 onScroll={(event) => {
940 if (!restoringScroll.current) rememberView({ scrollTop: event.currentTarget.scrollTop });
941 }}
942 tabIndex={-1}
943 data-workspace-focus-default
944 className="h-full overflow-y-auto outline-none"
945 data-pull-request-summary-scroll
946 >
947 <section className="px-4 pt-2.5 pb-1">
948 <div className="space-y-2">
949 <PullRequestMetaRow icon={<UsersIcon className="size-3.5" />} label={gt("Reviewers")}>
950 <span className="flex min-w-0 flex-wrap items-center gap-1.5">
951 {reviewerEntries.length === 0 ? (
952 <span className="text-muted-foreground">
953 <T context="no reviewers">None</T>
954 </span>
955 ) : (
956 <span className="flex items-center -space-x-1">
957 {reviewerEntries.map((entry) => {
958 const login = entry.actor?.login ?? "ghost";
959 const named =
960 entry.actor?.name && entry.actor.name !== login
961 ? `${entry.actor.name} (@${login})`
962 : login;
963 return (
964 <SharedTooltipTrigger
965 key={entry.key}
966 render={
967 <span
968 className={cn(
969 "relative rounded-full hover:z-10",
970 entry.outcome
971 ? pullRequestReviewOutcomeRingClassName(entry.outcome, entry.stale)
972 : undefined,
973 )}
974 />
975 }
976 label={
977 entry.outcome
978 ? `${named}: ${
979 entry.stale
980 ? pullRequestReviewOutcomeStaleLabel(entry.outcome, resolve)
981 : pullRequestReviewOutcomeLabel(entry.outcome, resolve)
982 }`
983 : named
984 }
985 side="bottom"
986 >
987 <PullRequestActorLabel
988 actor={entry.actor}
989 tooltip={false}
990 variant="avatar"
991 />
992 {entry.outcome ? (
993 <>
994 <PullRequestReviewOutcomeAvatarBadge
995 outcome={entry.outcome}
996 stale={entry.stale}
997 />
998 <span className="sr-only">
999 {entry.stale
1000 ? pullRequestReviewOutcomeStaleLabel(entry.outcome, resolve)
1001 : pullRequestReviewOutcomeLabel(entry.outcome, resolve)}
1002 </span>
1003 </>
1004 ) : null}
1005 </SharedTooltipTrigger>
1006 );
1007 })}
1008 </span>
1009 )}
1010 {/* Azure DevOps accepts reviewers but cannot list candidates. */}
1011 {detail.capabilities.reviewers.request &&
1012 detail.capabilities.reviewers.listCandidates ? (
1013 <PullRequestReviewerPicker
1014 searchable={detail.capabilities.reviewers.searchCandidates === true}
1015 environmentId={environmentId}
1016 reference={reference}
1017 allowed={detail.viewerPermissions.requestReviewers}
1018 />
1019 ) : null}
1020 </span>
1021 </PullRequestMetaRow>
1022 {detail.labels.length > 0 || detail.capabilities.labels === true ? (
1023 <PullRequestMetaRow icon={<TagIcon className="size-3.5" />} label={gt("Labels")}>
1024 <span className="flex min-w-0 flex-wrap items-center gap-1">
1025 {detail.labels.length === 0 ? (
1026 <span className="text-muted-foreground">
1027 <T context="no labels">None</T>
1028 </span>
1029 ) : (
1030 detail.labels.map((label) => (
1031 <PullRequestLabelChip
1032 key={label.name}
1033 label={label}
1034 size="default"
1035 className="max-w-48"
1036 focusable
1037 />
1038 ))
1039 )}
1040 {detail.capabilities.labels === true ? (
1041 <PullRequestLabelPicker
1042 environmentId={environmentId}
1043 reference={reference}
1044 allowed={detail.viewerPermissions.labels !== false}
1045 />
1046 ) : null}
1047 </span>
1048 </PullRequestMetaRow>
1049 ) : null}
1050 </div>
1051 <WorkflowRunsAbout
1052 environmentId={environmentId}
1053 item={{
1054 subject: detail.url,
1055 pullRequest: {
1056 projectId: reference.projectId,
1057 repository: reference.repository,
1058 number: reference.number,
1059 host:
1060 reference.host ??
1061 (URL.canParse(detail.url) ? new URL(detail.url).hostname : undefined),
1062 },
1063 }}
1064 />
1065 </section>
1066
1067 <PullRequestSection
1068 key={`description:${detail.url}`}
1069 title={gt("Description")}
1070 keepMounted
1071 revealCount={descriptionReveals}
1072 >
1073 <div className="group">
1074 {editingDescription ? (
1075 <PullRequestMarkdownEditor
1076 allowEmpty
1077 value={bodyScope.body}
1078 cwd={detail.workspaceRoot}
1079 environmentId={environmentId}
1080 completionScope={completionScope}
1081 threadRef={threadRef}
1082 label={gt(
1083 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} description",
1084 { term: changeRequestTermKind(terminology) },
1085 )}
1086 placeholder={gt(
1087 "Describe this {term, select, mr {merge request} cr {change request} other {pull request}}",
1088 { term: changeRequestTermKind(terminology) },
1089 )}
1090 saving={descriptionSaving}
1091 onSave={(body) => void saveBody(body)}
1092 onCancel={() => setBodyScope(null)}
1093 />
1094 ) : (
1095 <div className="flex items-start gap-1" data-pr-description>
1096 <PullRequestMarkdown
1097 className="min-w-0 flex-1"
1098 text={
1099 description.trim().length > 0 ? description : gt("_No description provided._")
1100 }
1101 cwd={detail.workspaceRoot}
1102 environmentId={environmentId}
1103 threadRef={threadRef}
1104 onTaskListChange={canEditDescription ? toggleTask : undefined}
1105 />
1106 {canEditDescription ? (
1107 <PullRequestEditButton
1108 aria-label={gt("Edit description")}
1109 onClick={() => setBodyScope({ url: detail.url, body: description })}
1110 />
1111 ) : null}
1112 </div>
1113 )}
1114 </div>
1115 </PullRequestSection>
1116
1117 <PullRequestSection
1118 key={`checks:${detail.url}`}
1119 title={gt("Checks", { $context: "CI checks section" })}
1120 name="checks"
1121 defaultOpen={false}
1122 revealCount={checksReveals}
1123 >
1124 {checksStale ? (
1125 <div className="flex items-center gap-2 text-xs text-muted-foreground">
1126 <span>
1127 <T>Check details are out of date.</T>
1128 </span>
1129 <Button size="xs" variant="ghost" onClick={onRefreshChecks}>
1130 <T context="verb, button">Refresh</T>
1131 </Button>
1132 </div>
1133 ) : detail.checks.length === 0 ? (
1134 <p className="text-xs text-muted-foreground">
1135 <T>No checks reported.</T>
1136 </p>
1137 ) : (
1138 detail.checks.map(
1139 (
1140 check,
1141 index,
1142 ) => /* oxlint-disable react/no-array-index-key -- Check names and URLs can repeat; these status rows have no local state. */ {
1143 const finding = { kind: "check", check } as const;
1144 const failing = check.status === "failure" || check.status === "cancelled";
1145 return (
1146 <div
1147 key={`${index}:${check.name}:${check.url ?? ""}`}
1148 className="group flex items-center gap-2 rounded-md pr-1 hover:bg-accent/60"
1149 >
1150 <button
1151 type="button"
1152 disabled={!check.url}
1153 onClick={() => check.url && openCheck(check.url)}
1154 className={cn(
1155 "flex min-w-0 flex-1 items-start gap-2 rounded-md px-2 py-2 text-left text-xs leading-5 [&>svg]:mt-0.5",
1156 check.url ? "cursor-pointer" : "cursor-default",
1157 )}
1158 >
1159 <PullRequestCheckStatusIcon status={check.status} />
1160 <span className="min-w-0 flex-1 wrap-anywhere">{check.name}</span>
1161 <span className="shrink-0 text-muted-foreground">
1162 {pullRequestCheckStatusLabel(check, resolve)}
1163 </span>
1164 </button>
1165 {onFixFinding && failing ? (
1166 <Button
1167 size="xs"
1168 variant="ghost"
1169 className="shrink-0"
1170 disabled={pendingFinding !== null && pendingFinding !== undefined}
1171 onClick={() => onFixFinding(finding)}
1172 >
1173 <HammerIcon className="size-3" />
1174 {pendingFinding === pullRequestFindingKey(finding)
1175 ? gt("Preparing...")
1176 : fixCheckLabel}
1177 </Button>
1178 ) : null}
1179 </div>
1180 );
1181 } /* oxlint-enable react/no-array-index-key */,
1182 )
1183 )}
1184 </PullRequestSection>
1185
1186 <PullRequestSection
1187 title={gt("Comments ({count})", { count: detail.commentCount })}
1188 actions={
1189 <div className="flex shrink-0 items-center gap-1">
1190 <Menu>
1191 <MenuTrigger
1192 render={<Button size="xs" variant="ghost-muted" />}
1193 aria-label={gt("Filter comments")}
1194 >
1195 <ListFilterIcon aria-hidden className="size-3" />
1196 {filteredOutCount > 0
1197 ? gt("{count, plural, one {{count} hidden} other {{count} hidden}}", {
1198 count: filteredOutCount,
1199 })
1200 : gt("Filter", { $context: "noun, filter menu" })}
1201 </MenuTrigger>
1202 <MenuPopup align="end">
1203 <MenuGroup>
1204 <MenuGroupLabel>
1205 <T context="which comments to show">Show</T>
1206 </MenuGroupLabel>
1207 <MenuCheckboxItem
1208 checked={commentFilter.bots}
1209 closeOnClick={false}
1210 onCheckedChange={(bots) => setCommentFilter((value) => ({ ...value, bots }))}
1211 >
1212 <T>Bot comments</T>
1213 </MenuCheckboxItem>
1214 <MenuCheckboxItem
1215 checked={commentFilter.resolved}
1216 closeOnClick={false}
1217 onCheckedChange={(resolved) =>
1218 setCommentFilter((value) => ({ ...value, resolved }))
1219 }
1220 >
1221 <T>Resolved or dismissed</T>
1222 </MenuCheckboxItem>
1223 </MenuGroup>
1224 </MenuPopup>
1225 </Menu>
1226 <Button
1227 size="xs"
1228 variant="ghost-muted"
1229 aria-label={
1230 commentOrder === "newest"
1231 ? gt("Show oldest comments first")
1232 : gt("Show newest comments first")
1233 }
1234 onClick={() => {
1235 const order = commentOrder === "newest" ? "oldest" : "newest";
1236 setCommentOrder(order);
1237 rememberView({ order });
1238 }}
1239 >
1240 <ArrowDownUpIcon aria-hidden className="size-3" />
1241 {commentOrder === "newest" ? gt("Newest first") : gt("Oldest first")}
1242 </Button>
1243 </div>
1244 }
1245 >
1246 {activityPending ? (
1247 <PullRequestConversationGhost terminology={terminology} />
1248 ) : activityError ? (
1249 <PullRequestActivityUnavailableState
1250 compact
1251 error={activityError}
1252 term={changeRequestTermKind(terminology)}
1253 onRetry={onRefresh}
1254 />
1255 ) : (
1256 <>
1257 {detail.commentsTruncated ? (
1258 <p className="mb-2 rounded-md border border-warning/30 bg-warning-surface px-2 py-1.5 text-xs">
1259 {gt(
1260 "{count, plural, one {This conversation is only partially loaded. {count} comment is loaded; open it on the host to read the rest.} other {This conversation is only partially loaded. {count} comments are loaded; open it on the host to read the rest.}}",
1261 { count: commentCount },
1262 )}
1263 </p>
1264 ) : null}
1265 {items.length === 0 ? (
1266 <p className="py-2 text-xs text-muted-foreground">
1267 <T>No comments yet.</T>
1268 </p>
1269 ) : filteredItems.length === 0 ? (
1270 <p className="py-2 text-xs text-muted-foreground">
1271 {filteredOutCount === 1
1272 ? gt("The only comment is hidden by the filter.")
1273 : gt(
1274 "{count, plural, one {All {count} comments are hidden by the filter.} other {All {count} comments are hidden by the filter.}}",
1275 {
1276 count: filteredOutCount,
1277 },
1278 )}
1279 </p>
1280 ) : (
1281 <div className="space-y-3">
1282 {commentOrder === "oldest" ? showOldestCommentsButton : null}
1283 {visibleItems.map(renderItem)}
1284 {commentOrder === "newest" ? showOldestCommentsButton : null}
1285 {shownConversations > COMMENT_PAGE ? (
1286 <Button
1287 size="sm"
1288 variant="ghost"
1289 className="w-full"
1290 onClick={() => setShown({ url: detail.url, count: COMMENT_PAGE })}
1291 >
1292 <T>
1293 Show only <Var>{COMMENT_PAGE}</Var> recent conversations
1294 </T>
1295 </Button>
1296 ) : null}
1297 </div>
1298 )}
1299 </>
1300 )}
1301 </PullRequestSection>
1302 </div>
1303 );
1304});