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

ThreadDetailsPrRow.tsx

452 lines16.6 KB

1import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
2/**
3 * The thread details panel's pull request row: what the thread's pull request is, and the one
4 * thing worth doing to it right now.
5 *
6 * The row itself opens the pull request in the right panel, exactly as it always has. Around
7 * that, the host's richer answer collapses into a single trailing slot, ranked by what unblocks
8 * the merge next: "Resolve" on conflicts, "Ready" on a draft, "Fix" under failing checks, and
9 * "Merge" only once the branch is clean and its checks pass. While checks run the slot reports
10 * that instead — a merge offered mid-run would race the very runs that gate it. Everything else
11 * the host knows (title, state, checks tally, diff size) lives in the row's tooltip, so a hover
12 * answers what previously took opening the panel.
13 *
14 * Until the detail arrives — or where pull requests are not supported at all — the row renders
15 * from the linked snapshot or branch summary, or just the link when status is unavailable.
16 */
17import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
18import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
19import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
20import { ArrowUpRightIcon, FileDiffIcon, GitBranchIcon, TriangleAlertIcon } from "lucide-react";
21import { useState, type MouseEvent as ReactMouseEvent } from "react";
22​
23import { useLiveRefresh } from "~/hooks/useLiveRefresh";
24import { cn } from "~/lib/utils";
25import { useServerConfigs } from "~/state/entities";
26import { pullRequestEnvironment } from "~/state/pullRequests";
27import { useEnvironmentQuery } from "~/state/query";
28​
29import {
30 buildFixFindingsHandoff,
31 buildResolveConflictsPrompt,
32 classifyPullRequestChecks,
33 describePullRequestChecks,
34 isPullRequestConflicting,
35 resolveSelectedMergeMethod,
36 allowedPullRequestMergeMethods,
37 resolveThreadPanelPullRequestAction,
38} from "../pullRequest/pullRequestDetail.logic";
39import { PullRequestChecksPopover } from "../pullRequest/PullRequestChecksPopover";
40import {
41 pullRequestChecksState,
42 PullRequestCheckStatusIcon,
43 PullRequestDiffStat,
44 resolvePullRequestState,
45} from "../pullRequest/pullRequestPresentation";
46import {
47 usePullRequestActionRunner,
48 usePullRequestHandoffs,
49} from "../pullRequest/usePullRequestActions";
50import {
51 ChangeRequestStatusIcon,
52 type PrStatusIndicator,
53 type ThreadPr,
54} from "../ThreadStatusIndicators";
55import {
56 AlertDialog,
57 AlertDialogClose,
58 AlertDialogDescription,
59 AlertDialogFooter,
60 AlertDialogHeader,
61 AlertDialogPopup,
62 AlertDialogTitle,
63} from "../ui/alert-dialog";
64import { Button } from "../ui/button";
65import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
66import {
67 THREAD_DETAILS_PANEL_ICON_CLASS,
68 THREAD_DETAILS_PANEL_LINK_SPLIT_ACTION_CLASS,
69 THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS,
70 THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS,
71 THREAD_DETAILS_PANEL_ROW_CLASS,
72 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
73} from "./threadDetailsPanelStyles";
74​
75export function ThreadDetailsPrRow({
76 environmentId,
77 pr,
78 number,
79 reference: linkedReference,
80 status,
81 project,
82 label,
83 openAriaLabel,
84 onOpen,
85 onActed,
86}: {
87 environmentId: EnvironmentId;
88 pr: ThreadPr;
89 number: number;
90 reference?: Pick<PullRequestRef, "host" | "repository" | "number"> | null;
91 status: PrStatusIndicator | null;
92 /** The thread's project, which is what the pull request is read through on the host. */
93 project: EnvironmentProject | null;
94 label: string;
95 openAriaLabel: string;
96 onOpen: (event: ReactMouseEvent<HTMLElement>) => void;
97 /** An action changed the pull request on the host, so the vcs status behind the row is stale. */
98 onActed?: () => void;
99}) {
100 const serverConfigs = useServerConfigs();
101 const supportsPullRequests =
102 serverConfigs.get(environmentId)?.environment.capabilities.pullRequests === true;
103 const repository = sourceControlRepositorySelector(project?.repositoryIdentity);
104 const reference: PullRequestRef | null =
105 supportsPullRequests && project !== null
106 ? linkedReference
107 ? { ...linkedReference, projectId: project.id as ProjectId }
108 : repository !== null
109 ? { projectId: project.id as ProjectId, repository, number }
110 : null
111 : null;
112 const detailQuery = useEnvironmentQuery(
113 reference === null
114 ? null
115 : pullRequestEnvironment.detail({
116 environmentId,
117 input: { ...reference, allowStale: false },
118 }),
119 );
120 const supportsChecks =
121 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
122 const checksQuery = useEnvironmentQuery(
123 supportsChecks && reference !== null && detailQuery.data !== null
124 ? pullRequestEnvironment.checks({ environmentId, input: reference })
125 : null,
126 );
127 const detail =
128 detailQuery.data === null
129 ? null
130 : checksQuery.data !== null && checksQuery.dataUpdatedAt >= detailQuery.dataUpdatedAt
131 ? { ...detailQuery.data, ...checksQuery.data }
132 : detailQuery.data;
133 const open = reference !== null && (detail?.state ?? pr?.state) === "open";
134 const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
135 useLiveRefresh(detailQuery.isPending ? null : detailQuery.refresh, {
136 enabled: open,
137 key: `workspace-pr:${refreshKey}`,
138 intervalMs: 10 * 60_000,
139 });
140 useLiveRefresh(checksQuery.isPending || detailQuery.isPending ? null : checksQuery.refresh, {
141 enabled: open && supportsChecks && !(checksQuery.isSuccess && checksQuery.data === null),
142 key: `workspace-pr-checks:${refreshKey}`,
143 intervalMs: 45_000,
144 });
145​
146 const { actionPending, perform } = usePullRequestActionRunner({
147 environmentId,
148 reference,
149 onSuccess: () => {
150 detailQuery.refresh();
151 checksQuery.refresh();
152 onActed?.();
153 },
154 });
155 const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail });
156 const [confirmingMerge, setConfirmingMerge] = useState(false);
157​
158 const rowAction = resolveThreadPanelPullRequestAction(detail);
159 if (confirmingMerge && rowAction !== "merge") {
160 setConfirmingMerge(false);
161 }
162 const conflicting = isPullRequestConflicting(detail);
163 const checksState = detail === null ? "none" : classifyPullRequestChecks(detail.checks);
164 const checksRollup = detail === null ? null : pullRequestChecksState(detail.checks);
165 const selectedMergeMethod = resolveSelectedMergeMethod(
166 allowedPullRequestMergeMethods(detail),
167 "merge",
168 );
169​
170 const startResolveConflicts = () => {
171 if (detail === null) return;
172 void startHandoff("conflicts", {
173 prompt: buildResolveConflictsPrompt({
174 number: detail.number,
175 url: detail.url,
176 headBranch: detail.headBranch,
177 baseBranch: detail.baseBranch,
178 }),
179 });
180 };
181​
182 const startFixChecks = () => {
183 if (detail === null) return;
184 // The compact row fetches no conversation, so the handoff carries the failing checks alone;
185 // review threads keep arriving through the full panel's richer version of this action.
186 void startHandoff(
187 "findings",
188 buildFixFindingsHandoff({
189 number: detail.number,
190 title: detail.title,
191 url: detail.url,
192 headBranch: detail.headBranch,
193 baseBranch: detail.baseBranch,
194 reviewThreads: [],
195 comments: [],
196 checks: detail.checks,
197 commentsTruncated: false,
198 }),
199 );
200 };
201​
202 // Host details distinguish drafts; all panels share the same PR-state glyph.
203 const statePresentation =
204 detail === null
205 ? null
206 : resolvePullRequestState({
207 state: detail.state,
208 isDraft: detail.isDraft,
209 });
210 const icon = statePresentation ? (
211 <statePresentation.Icon
212 aria-hidden
213 className={cn("-mx-0.5 size-4 shrink-0", statePresentation.toneClassName)}
214 />
215 ) : pr && status ? (
216 <ChangeRequestStatusIcon
217 state={pr.state}
218 className={cn(THREAD_DETAILS_PANEL_ICON_CLASS, status.colorClass)}
219 />
220 ) : (
221 <PullRequestGlyph.pullRequest className={THREAD_DETAILS_PANEL_ICON_CLASS} />
222 );
223​
224 // Everything the host reported, at a glance. The row stays one line; the tooltip is where the
225 // rest of the answer lives — styled like the sidebar's thread tooltip, title above icon-led
226 // detail rows, so the two read as one family.
227 const rowTooltip =
228 detail === null || statePresentation === null ? (
229 <TooltipPopup side="top">{status?.tooltip ?? `Pull request #${number}`}</TooltipPopup>
230 ) : (
231 <TooltipPopup
232 side="top"
233 align="start"
234 sideOffset={4}
235 variant="glass"
236 className="max-w-80 text-left whitespace-normal [&_[data-slot=tooltip-viewport]]:p-0"
237 >
238 <div className="flex min-w-0 max-w-80 flex-col gap-2 p-[var(--floating-content-inset)]">
239 <div className="flex min-w-0 items-baseline gap-1.5 text-xs leading-none">
240 <span className="min-w-0 truncate font-medium text-foreground">{detail.title}</span>
241 <span className="shrink-0 text-muted-foreground">#{detail.number}</span>
242 </div>
243 <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
244 <div className="flex min-w-0 items-center gap-2">
245 <statePresentation.Icon
246 aria-hidden
247 className={cn("size-3 shrink-0", statePresentation.toneClassName)}
248 />
249 <div className="min-w-0 truncate text-foreground/75">{statePresentation.label}</div>
250 </div>
251 <div className="flex min-w-0 items-center gap-2">
252 <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
253 <div className="min-w-0 truncate text-foreground/75">
254 {detail.baseBranch} ← {detail.headBranch}
255 </div>
256 </div>
257 {detail.state === "open" && checksState !== "none" ? (
258 <div className="flex min-w-0 items-center gap-2">
259 <PullRequestCheckStatusIcon
260 status={
261 checksState === "failing"
262 ? "failure"
263 : checksState === "pending"
264 ? "pending"
265 : "success"
266 }
267 />
268 <div className="min-w-0 truncate text-foreground/75">
269 {describePullRequestChecks(detail.checks)}
270 </div>
271 </div>
272 ) : null}
273 {detail.isDraft && conflicting ? (
274 <div className="flex min-w-0 items-start gap-2 text-destructive">
275 <TriangleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
276 <div className="min-w-0 flex-1 wrap-break-word leading-5">
277 Merge conflicts with {detail.baseBranch}
278 </div>
279 </div>
280 ) : null}
281 <div className="flex min-w-0 items-center gap-2">
282 <FileDiffIcon className="size-3 shrink-0 stroke-muted-foreground" />
283 <div className="min-w-0 flex items-baseline gap-1 truncate text-foreground/75">
284 {detail.changedFiles.toLocaleString()}{" "}
285 {detail.changedFiles === 1 ? "file" : "files"}
286 <PullRequestDiffStat additions={detail.additions} deletions={detail.deletions} />
287 </div>
288 </div>
289 </div>
290 </div>
291 </TooltipPopup>
292 );
293​
294 const trailingAction =
295 rowAction === "resolve"
296 ? {
297 label: "Resolve",
298 pendingLabel: "Preparing...",
299 pending: handoff === "conflicts",
300 destructive: true,
301 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
302 tooltip: "Check the branch out and resolve the conflicts in a new thread",
303 onClick: startResolveConflicts,
304 }
305 : rowAction === "ready"
306 ? {
307 label: "Ready",
308 pendingLabel: "Marking...",
309 pending: actionPending,
310 destructive: false,
311 suffix: null,
312 tooltip: "Mark this pull request as ready for review",
313 onClick: () => void perform("ready"),
314 }
315 : rowAction === "fix"
316 ? {
317 label: "Fix",
318 pendingLabel: "Preparing...",
319 pending: handoff === "findings",
320 destructive: true,
321 suffix: <ArrowUpRightIcon aria-hidden className="size-3 shrink-0" />,
322 tooltip: "Fix the failing checks in a new thread",
323 onClick: startFixChecks,
324 }
325 : rowAction === "merge"
326 ? {
327 label: "Merge",
328 pendingLabel: "Merging...",
329 pending: actionPending,
330 destructive: false,
331 suffix: null,
332 tooltip: `Merge this pull request (${selectedMergeMethod})`,
333 onClick: () => setConfirmingMerge(true),
334 }
335 : null;
336​
337 const rowContent = (
338 <>
339 {icon}
340 <span className="min-w-0 flex-1 truncate text-left">{label}</span>
341 </>
342 );
343​
344 return (
345 <>
346 {detail ? (
347 <div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
348 <Tooltip>
349 <TooltipTrigger
350 render={
351 <Button
352 type="button"
353 variant="ghost"
354 size="sm"
355 className={THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS}
356 aria-label={openAriaLabel}
357 onClick={onOpen}
358 />
359 }
360 >
361 {rowContent}
362 </TooltipTrigger>
363 {rowTooltip}
364 </Tooltip>
365 {checksRollup !== null && !conflicting && !detail.isDraft ? (
366 <>
367 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
368 <PullRequestChecksPopover
369 checksState={checksRollup}
370 checks={detail.checks}
371 variant="count"
372 className="text-[13px] sm:text-[13px]"
373 />
374 </>
375 ) : null}
376 {trailingAction ? (
377 <>
378 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
379 <Tooltip>
380 <TooltipTrigger
381 render={
382 <Button
383 type="button"
384 variant="ghost"
385 size="sm"
386 className={cn(
387 THREAD_DETAILS_PANEL_LINK_SPLIT_ACTION_CLASS,
388 trailingAction.destructive &&
389 "text-destructive hover:text-destructive data-pressed:text-destructive",
390 )}
391 disabled={actionPending || handoff !== null}
392 onClick={trailingAction.onClick}
393 />
394 }
395 >
396 {trailingAction.pending ? trailingAction.pendingLabel : trailingAction.label}
397 {trailingAction.suffix}
398 </TooltipTrigger>
399 <TooltipPopup side="top">{trailingAction.tooltip}</TooltipPopup>
400 </Tooltip>
401 </>
402 ) : null}
403 </div>
404 ) : (
405 <Tooltip>
406 <TooltipTrigger
407 render={
408 <Button
409 type="button"
410 variant="ghost"
411 size="sm"
412 className={THREAD_DETAILS_PANEL_ROW_CLASS}
413 aria-label={openAriaLabel}
414 onClick={onOpen}
415 />
416 }
417 >
418 {rowContent}
419 </TooltipTrigger>
420 {rowTooltip}
421 </Tooltip>
422 )}
423 {rowAction === "merge" ? (
424 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
425 <AlertDialogPopup>
426 <AlertDialogHeader>
427 <AlertDialogTitle>Merge pull request?</AlertDialogTitle>
428 <AlertDialogDescription>
429 This merges #{number} using {selectedMergeMethod}.
430 </AlertDialogDescription>
431 </AlertDialogHeader>
432 <AlertDialogFooter>
433 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
434 Cancel
435 </AlertDialogClose>
436 <Button
437 size="sm"
438 disabled={actionPending}
439 onClick={() => {
440 setConfirmingMerge(false);
441 void perform("merge", selectedMergeMethod);
442 }}
443 >
444 Merge
445 </Button>
446 </AlertDialogFooter>
447 </AlertDialogPopup>
448 </AlertDialog>
449 ) : null}
450 </>
451 );