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

ThreadDetailsPrRow.tsx

449 lines16.4 KB

1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
3/**
4 * The thread details panel's pull request row: what the thread's pull request is, and the one
5 * thing worth doing to it right now.
6 *
7 * The row itself opens the pull request in the right panel, exactly as it always has. Around
8 * that, the host's richer answer collapses into a single trailing slot, ranked by what unblocks
9 * the merge next: "Resolve" on conflicts, "Ready" on a draft, "Fix" under failing checks, and
10 * "Merge" only once the branch is clean and its checks pass. While checks run the slot reports
11 * that instead — a merge offered mid-run would race the very runs that gate it. Everything else
12 * the host knows (title, state, checks tally, diff size) lives in the row's tooltip, so a hover
13 * answers what previously took opening the panel.
14 *
15 * Until the detail arrives — or where pull requests are not supported at all — the row renders
16 * from the linked snapshot or branch summary, or just the link when status is unavailable.
17 */
18import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
19import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";
20import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
21import { ArrowUpRightIcon, FileDiffIcon, GitBranchIcon, TriangleAlertIcon } from "lucide-react";
22import { useState, type MouseEvent as ReactMouseEvent } from "react";
23​
24import { useLiveRefresh } from "~/hooks/useLiveRefresh";
25import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
26import { cn } from "~/lib/utils";
27import { useServerConfigs } from "~/state/entities";
28import { pullRequestEnvironment } from "~/state/pullRequests";
29import { useEnvironmentQuery } from "~/state/query";
30​
31import {
32 buildFixFindingsHandoff,
33 buildResolveConflictsPrompt,
34 classifyPullRequestChecks,
35 describePullRequestChecks,
36 isPullRequestConflicting,
37 resolveSelectedMergeMethod,
38 allowedPullRequestMergeMethods,
39 resolveThreadPanelPullRequestAction,
40} from "../pullRequest/pullRequestDetail.logic";
41import { PullRequestChecksPopover } from "../pullRequest/PullRequestChecksPopover";
42import {
43 pullRequestChecksState,
44 PullRequestCheckStatusIcon,
45 PullRequestDiffStat,
46 resolvePullRequestState,
47} from "../pullRequest/pullRequestPresentation";
48import {
49 usePullRequestActionRunner,
50 usePullRequestHandoffs,
51} from "../pullRequest/usePullRequestActions";
52import {
53 ChangeRequestStatusIcon,
54 type PrStatusIndicator,
55 type ThreadPr,
56} from "../ThreadStatusIndicators";
57import {
58 AlertDialog,
59 AlertDialogClose,
60 AlertDialogDescription,
61 AlertDialogFooter,
62 AlertDialogHeader,
63 AlertDialogPopup,
64 AlertDialogTitle,
65} from "../ui/alert-dialog";
66import { Button } from "../ui/button";
67import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
68import {
69 THREAD_DETAILS_PANEL_ICON_CLASS,
70 THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS,
71 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
72} from "./threadDetailsPanelStyles";
73​
74export function ThreadDetailsPrRow({
75 environmentId,
76 pr,
77 number,
78 reference: linkedReference,
79 status,
80 project,
81 label,
82 openAriaLabel,
83 onOpen,
84 onActed,
85}: {
86 environmentId: EnvironmentId;
87 pr: ThreadPr;
88 number: number;
89 reference?: Pick<PullRequestRef, "host" | "repository" | "number"> | null;
90 status: PrStatusIndicator | null;
91 /** The thread's project, which is what the pull request is read through on the host. */
92 project: EnvironmentProject | null;
93 label: string;
94 openAriaLabel: string;
95 onOpen: (event: ReactMouseEvent<HTMLElement>) => void;
96 /** An action changed the pull request on the host, so the vcs status behind the row is stale. */
97 onActed?: () => void;
98}) {
99 const serverConfigs = useServerConfigs();
100 const supportsPullRequests =
101 serverConfigs.get(environmentId)?.environment.capabilities.pullRequests === true;
102 const repository = sourceControlRepositorySelector(project?.repositoryIdentity);
103 const reference: PullRequestRef | null =
104 supportsPullRequests && project !== null
105 ? linkedReference
106 ? { ...linkedReference, projectId: project.id as ProjectId }
107 : repository !== null
108 ? { projectId: project.id as ProjectId, repository, number }
109 : null
110 : null;
111 const detailQuery = useEnvironmentQuery(
112 reference === null
113 ? null
114 : pullRequestEnvironment.detail({
115 environmentId,
116 input: { ...reference, allowStale: false },
117 }),
118 );
119 const supportsChecks =
120 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
121 const checksQuery = useEnvironmentQuery(
122 supportsChecks && reference !== null && detailQuery.data !== null
123 ? pullRequestEnvironment.checks({ environmentId, input: reference })
124 : null,
125 );
126 const detail =
127 detailQuery.data === null
128 ? null
129 : checksQuery.data !== null && checksQuery.dataUpdatedAt >= detailQuery.dataUpdatedAt
130 ? { ...detailQuery.data, ...checksQuery.data }
131 : detailQuery.data;
132 const open = reference !== null && (detail?.state ?? pr?.state) === "open";
133 const refreshKey = `${environmentId}:${project?.id}:${reference?.host}:${reference?.repository}:${number}`;
134 useLiveRefresh(detailQuery.isPending ? null : detailQuery.refresh, {
135 enabled: open,
136 key: `workspace-pr:${refreshKey}`,
137 intervalMs: 10 * 60_000,
138 });
139 usePullRequestChecksRefresh({
140 refresh: checksQuery.isPending || detailQuery.isPending ? null : checksQuery.refresh,
141 enabled: open && supportsChecks && !(checksQuery.isSuccess && checksQuery.data === null),
142 key: `workspace-pr-checks:${refreshKey}`,
143 checks: detail?.checks ?? [],
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("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"
237 >
238 <div className="flex min-w-0 max-w-80 flex-col gap-2 px-1 py-2">
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 <ThreadDetailsControl
352 type="button"
353 variant="ghost"
354 size="sm"
355 part="link-primary"
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 render={<ThreadDetailsControl part="checks" />}
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 <ThreadDetailsControl
383 type="button"
384 variant="ghost"
385 size="sm"
386 part="action"
387 tone={trailingAction.destructive ? "destructive" : "default"}
388 disabled={actionPending || handoff !== null}
389 onClick={trailingAction.onClick}
390 />
391 }
392 >
393 {trailingAction.pending ? trailingAction.pendingLabel : trailingAction.label}
394 {trailingAction.suffix}
395 </TooltipTrigger>
396 <TooltipPopup side="top">{trailingAction.tooltip}</TooltipPopup>
397 </Tooltip>
398 </>
399 ) : null}
400 </div>
401 ) : (
402 <Tooltip>
403 <TooltipTrigger
404 render={
405 <ThreadDetailsControl
406 type="button"
407 variant="ghost"
408 size="sm"
409 part="row"
410 aria-label={openAriaLabel}
411 onClick={onOpen}
412 />
413 }
414 >
415 {rowContent}
416 </TooltipTrigger>
417 {rowTooltip}
418 </Tooltip>
419 )}
420 {rowAction === "merge" ? (
421 <AlertDialog open={confirmingMerge} onOpenChange={(open) => setConfirmingMerge(open)}>
422 <AlertDialogPopup>
423 <AlertDialogHeader>
424 <AlertDialogTitle>Merge pull request?</AlertDialogTitle>
425 <AlertDialogDescription>
426 This merges #{number} using {selectedMergeMethod}.
427 </AlertDialogDescription>
428 </AlertDialogHeader>
429 <AlertDialogFooter>
430 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
431 Cancel
432 </AlertDialogClose>
433 <Button
434 size="sm"
435 disabled={actionPending}
436 onClick={() => {
437 setConfirmingMerge(false);
438 void perform("merge", selectedMergeMethod);
439 }}
440 >
441 Merge
442 </Button>
443 </AlertDialogFooter>
444 </AlertDialogPopup>
445 </AlertDialog>
446 ) : null}
447 </>
448 );