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