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

ThreadDetailsPrRow.tsx

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