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