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

ThreadStatusIndicators.tsx

604 lines20.1 KB

1import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
2import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
4import {
5 resolveEnvironmentMachineKind,
6 type EnvironmentId,
7 type ThreadLinkedPullRequest,
8 type ThreadPullRequestLink,
9 type VcsStatusResult,
10} from "@t3tools/contracts";
11import {
12 resolveThreadCurrentPullRequestLink,
13 resolveThreadPullRequestChains,
14 visibleThreadPullRequests,
15 type ThreadPullRequestBadge,
16} from "@t3tools/shared/threadPullRequests";
17import { FolderGit2Icon, GitPullRequestArrowIcon, LayersIcon, TerminalIcon } from "lucide-react";
18import { useMemo, type MouseEvent } from "react";
19import { buttonVariants, InlineButton } from "./ui/button";
20import { cn } from "../lib/utils";
21import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
22import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
23import { parseChangeRequestUrl } from "../lib/openPullRequestLink";
24import { useEnvironmentQuery } from "../state/query";
25import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
26import { useThreadRunningTerminalIds } from "../state/terminalSessions";
27import { useUiStateStore } from "../uiStateStore";
28import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
29import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
30import type { SidebarThreadSummary } from "../types";
31import { formatWorktreePathForDisplay } from "../worktreeCleanup";
32import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
33import { pullRequestListLines } from "./pullRequest/pullRequestListLines";
34import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
35​
36export interface PrStatusIndicator {
37 label: string;
38 colorClass: string;
39 tooltip: string;
40 tooltipLead: string;
41 tooltipTitle: string;
42 url: string;
44​
45export interface TerminalStatusIndicator {
46 label: "Terminal process running";
47 colorClass: string;
48 pulse: boolean;
50​
51export type ThreadPr = VcsStatusResult["pr"];
52​
53export interface LinkedThreadPullRequestStatus {
54 readonly pr: NonNullable<ThreadPr>;
55 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
57​
58/** Linked badges use persisted snapshots; only branch and legacy fallbacks lease summary reads. */
59export function useLinkedThreadPullRequest(
60 environmentId: EnvironmentId | null,
61 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
62 enabled = true,
63 pullRequests?: ReadonlyArray<ThreadPullRequestLink>,
64 branchPullRequest?: ThreadLinkedPullRequest | null,
65): LinkedThreadPullRequestStatus | null {
66 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
67 const current = useMemo(
68 () => (supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null),
69 [pullRequests, supportsLinks],
70 );
71 const fallback =
72 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
73 const host = fallback == null ? undefined : parseChangeRequestUrl(fallback.url)?.host;
74 const reference =
75 fallback == null ? null : { ...fallback, ...(host === undefined ? {} : { host }) };
76 const queried = useEnvironmentQuery(
77 !enabled || environmentId === null || reference === null
78 ? null
79 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
80 ).data;
81 const detail = useSharedPullRequestSummary(environmentId, reference, queried);
82​
83 return useMemo(() => {
84 if (current !== null) return linkedPullRequestSnapshotStatus(current);
85 return detail === null
86 ? null
87 : {
88 pr: pullRequestDetailToVcsStatus(detail),
89 sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" },
90 };
91 }, [current, detail]);
93​
94export function linkedPullRequestSnapshotStatus(
95 link: ThreadPullRequestLink,
96): LinkedThreadPullRequestStatus | null {
97 const snapshot = link.snapshot;
98 if (snapshot === null) return null;
99 const kind = link.url.includes("/-/merge_requests/")
100 ? "gitlab"
101 : link.url.includes("/pullrequest/")
102 ? "azure-devops"
103 : link.url.includes("/pull-requests/")
104 ? "bitbucket"
105 : "github";
106 return {
107 pr: {
108 number: link.number,
109 url: link.url,
110 title: snapshot.title,
111 state: snapshot.state,
112 isDraft: snapshot.isDraft,
113 headRef: snapshot.headBranch,
114 baseRef: snapshot.baseBranch,
115 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
116 },
117 sourceControlProvider: { kind, name: kind, baseUrl: "" },
118 };
120​
121export {
122 resolveThreadPullRequestBadge,
123 type ThreadPullRequestBadge,
124} from "@t3tools/shared/threadPullRequests";
125​
126/** The glyph a row's badge wears: the layers icon for a stack, the pull-request one otherwise. */
127function ThreadPullRequestBadgeIcon({
128 icon,
129 className,
130}: {
131 icon: "stack" | "pull-request";
132 className?: string | undefined;
133}) {
134 const Icon = icon === "stack" ? LayersIcon : GitPullRequestArrowIcon;
135 return <Icon aria-hidden className={cn("size-3 shrink-0", className)} />;
137​
138/** The complete linked-PR control shared by the sidebar and composer footer. */
139export function ThreadPullRequestBadgeControl({
140 variant,
141 badge,
142 number,
143 url,
144 status,
145 onOpenStack,
146 onOpenPullRequest,
147}: {
148 variant: "underline" | "ghost";
149 badge: ThreadPullRequestBadge | null;
150 number?: number | undefined;
151 url?: string | undefined;
152 status: PrStatusIndicator | null;
153 onOpenStack: () => void;
154 onOpenPullRequest: (event: MouseEvent<HTMLAnchorElement>) => void;
155}) {
156 const isStack = badge?.kind === "stack";
157 const linkedCount = badge?.kind === "pull-request" && badge.others > 0 ? badge.others + 1 : null;
158 if (!isStack && (number === undefined || url === undefined)) return null;
159 const label = isStack
160 ? `Stack of ${badge.layers} pull requests, ${badge.state}`
161 : `${status?.tooltip ?? `PR #${number}, status pending`}${
162 badge?.kind === "pull-request" && badge.others > 0
163 ? `, and ${badge.others} more linked; overall ${badge.state}`
164 : ""
165 }`;
166 const className = cn(
167 variant === "ghost"
168 ? buttonVariants({ variant: "ghost", size: "xs" })
169 : "inline-flex shrink-0 cursor-pointer items-center gap-0.5 whitespace-nowrap border-b border-transparent hover:border-current focus-visible:outline-2 focus-visible:outline-ring",
170 "text-xs tabular-nums",
171 variant === "ghost" &&
172 "font-normal text-xs! active:scale-100 [--control-icon-color:currentColor]",
173 badge !== null && (isStack || linkedCount !== null)
174 ? PR_STATE_COLOR_CLASS[badge.state]
175 : (status?.colorClass ?? "text-muted-foreground"),
176 );
177 const content = (
178 <>
179 <ThreadPullRequestBadgeIcon icon={badge?.kind ?? "pull-request"} />
180 {isStack ? badge.layers : linkedCount !== null ? `+${linkedCount}` : number}
181 </>
182 );
183 return (
184 <Tooltip>
185 <TooltipTrigger
186 render={
187 isStack ? (
188 <InlineButton
189 className={className}
190 aria-label={label}
191 onPointerDown={(event) => event.stopPropagation()}
192 onClick={(event) => {
193 event.preventDefault();
194 event.stopPropagation();
195 onOpenStack();
196 }}
197 />
198 ) : (
199 <a
200 href={url}
201 target="_blank"
202 rel="noopener noreferrer"
203 className={className}
204 aria-label={label}
205 onPointerDown={(event) => event.stopPropagation()}
206 onClick={onOpenPullRequest}
207 />
208 )
209 }
210 >
211 {content}
212 </TooltipTrigger>
213 <TooltipPopup side="top">{label}</TooltipPopup>
214 </Tooltip>
215 );
217​
218/**
219 * A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
220 * so the hover answers "what is in here" without opening the surface.
221 */
222export function ThreadPullRequestsMiniList({
223 pullRequests,
224}: {
225 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
226}) {
227 const lines = useMemo(
228 () =>
229 pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
230 [pullRequests],
231 );
232 if (lines.length === 0) return null;
233 return (
234 <ul className="flex flex-col gap-1">
235 {lines.map((line) => {
236 const snapshot = line.link.snapshot;
237 const presentation =
238 snapshot === null
239 ? null
240 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
241 return (
242 <li
243 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
244 className="flex min-w-0 items-center gap-2"
245 // Capped like the panel: past a few layers the indent only repeats "still in the
246 // stack", and sixteen of them would walk the titles off the popover.
247 style={{ paddingLeft: `${Math.min(line.depth, 3) * 0.75}rem` }}
248 >
249 {presentation ? (
250 <presentation.Icon
251 aria-hidden
252 className={cn("size-3 shrink-0", presentation.toneClassName)}
253 />
254 ) : (
255 <GitPullRequestArrowIcon
256 aria-hidden
257 className="size-3 shrink-0 stroke-muted-foreground"
258 />
259 )}
260 <span className="shrink-0 font-mono tabular-nums">#{line.link.number}</span>
261 <span className="min-w-0 truncate text-foreground/75">
262 {snapshot?.title ?? line.link.repository}
263 </span>
264 {line.stack ? (
265 <span className="ml-auto shrink-0 pl-1 text-[10px]">
266 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
267 </span>
268 ) : null}
269 </li>
270 );
271 })}
272 </ul>
273 );
275​
276/** The ink each pull-request state wears in the sidebar, shared by the number and stack badges. */
277const PR_STATE_COLOR_CLASS: Record<ThreadPullRequestBadge["state"], string> = {
278 open: "text-emerald-600 dark:text-emerald-300/90",
279 merged: "text-violet-600 dark:text-violet-300/90",
280 closed: "text-red-600 dark:text-red-300/90",
281 draft: "text-zinc-500 dark:text-zinc-400/80",
282};
283​
284export function settledPrHoverColorClass(
285 state: NonNullable<ThreadPr>["state"],
286 isDraft = false,
287): string {
288 switch (state) {
289 case "open":
290 if (isDraft) {
291 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
292 }
293 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
294 case "merged":
295 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
296 case "closed":
297 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
298 }
300​
301export function prStatusIndicator(
302 pr: ThreadPr,
303 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
304): PrStatusIndicator | null {
305 function formatPrState(pr: NonNullable<ThreadPr>): string {
306 if (pr.state === "open" && pr.isDraft === true) return "Draft";
307 return pr.state.charAt(0).toUpperCase() + pr.state.slice(1);
308 }
309​
310 function formatPrStatusLead(pr: NonNullable<ThreadPr>, changeRequestShortName: string): string {
311 return `${changeRequestShortName} #${pr.number} - ${formatPrState(pr)}`;
312 }
313 if (!pr) return null;
314 const presentation = resolveChangeRequestPresentation(provider);
315​
316 const tooltipLead = formatPrStatusLead(pr, presentation.shortName);
317 const tooltip = `${tooltipLead}: ${pr.title}`;
318​
319 if (pr.state === "open") {
320 const isDraft = pr.isDraft === true;
321 return {
322 label: `${presentation.shortName} ${isDraft ? "draft" : "open"}`,
323 colorClass: isDraft
324 ? "text-zinc-500 dark:text-zinc-400/80"
325 : "text-emerald-600 dark:text-emerald-300/90",
326 tooltip,
327 tooltipLead,
328 tooltipTitle: pr.title,
329 url: pr.url,
330 };
331 }
332 if (pr.state === "closed") {
333 return {
334 label: `${presentation.shortName} closed`,
335 colorClass: "text-red-600 dark:text-red-300/90",
336 tooltip,
337 tooltipLead,
338 tooltipTitle: pr.title,
339 url: pr.url,
340 };
341 }
342 if (pr.state === "merged") {
343 return {
344 label: `${presentation.shortName} merged`,
345 colorClass: "text-violet-600 dark:text-violet-300/90",
346 tooltip,
347 tooltipLead,
348 tooltipTitle: pr.title,
349 url: pr.url,
350 };
351 }
352 return null;
354​
355export function ChangeRequestStatusIcon({
356 state,
357 isDraft = false,
358 className,
359}: Pick<NonNullable<ThreadPr>, "state"> & {
360 readonly isDraft?: boolean | undefined;
361 readonly className?: string | undefined;
362}) {
363 const presentation = resolvePullRequestState({ state, isDraft });
364 return <presentation.Icon className={className} />;
366​
367export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
368 return (
369 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
370 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
371 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
372 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
373 </span>
374 );
376​
377export function terminalStatusFromRunningIds(
378 runningTerminalIds: ReadonlyArray<string>,
379): TerminalStatusIndicator | null {
380 if (runningTerminalIds.length === 0) {
381 return null;
382 }
383 return {
384 label: "Terminal process running",
385 colorClass: "text-teal-600 dark:text-teal-300/90",
386 pulse: true,
387 };
389​
390export function ThreadWorktreeIndicator({
391 thread,
392}: {
393 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
394}) {
395 const worktreePath = thread.worktreePath?.trim();
396 if (!worktreePath) {
397 return null;
398 }
399​
400 const displayPath = formatWorktreePathForDisplay(worktreePath);
401 const tooltip = thread.branch
402 ? `Worktree: ${displayPath} (${thread.branch})`
403 : `Worktree: ${displayPath}`;
404​
405 return (
406 <Tooltip>
407 <TooltipTrigger
408 render={
409 <span
410 role="img"
411 aria-label={tooltip}
412 data-testid={`thread-worktree-${thread.id}`}
413 className="inline-flex items-center justify-center"
414 />
415 }
416 >
417 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
418 </TooltipTrigger>
419 <TooltipPopup side="top">{tooltip}</TooltipPopup>
420 </Tooltip>
421 );
423​
424export function ThreadStatusLabel({
425 status,
426 compact = false,
427}: {
428 status: ThreadStatusPill;
429 compact?: boolean;
430}) {
431 if (compact) {
432 return (
433 <Tooltip>
434 <TooltipTrigger
435 render={
436 <span
437 aria-label={status.label}
438 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
439 />
440 }
441 >
442 <span
443 className={`size-[9px] rounded-full ${status.dotClass} ${
444 status.pulse ? "animate-status-pulse" : ""
445 }`}
446 />
447 </TooltipTrigger>
448 <TooltipPopup side="top">{status.label}</TooltipPopup>
449 </Tooltip>
450 );
451 }
452​
453 return (
454 <Tooltip>
455 <TooltipTrigger
456 render={
457 <span
458 aria-label={status.label}
459 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
460 />
461 }
462 >
463 <span
464 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
465 status.pulse ? "animate-status-pulse" : ""
466 }`}
467 />
468 <span className="hidden md:inline">{status.label}</span>
469 </TooltipTrigger>
470 <TooltipPopup side="top">{status.label}</TooltipPopup>
471 </Tooltip>
472 );
474​
475/**
476 * Non-interactive leading status icons for a thread row in compact contexts
477 * like the command palette. Shows the change request state icon (if present) and the
478 * thread status dot, matching the sidebar's leading indicators.
479 */
480export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
481 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
482 const lastVisitedAt = useUiStateStore(
483 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
484 );
485 const pullRequest = useLinkedThreadPullRequest(
486 thread.environmentId,
487 thread.linkedPullRequest,
488 true,
489 thread.pullRequests,
490 thread.branchPullRequest,
491 );
492 const pr = pullRequest?.pr ?? null;
493 const prStatus = prStatusIndicator(pr, pullRequest?.sourceControlProvider);
494 const threadStatus = resolveThreadStatusPill({
495 thread: {
496 ...thread,
497 lastVisitedAt,
498 },
499 });
500​
501 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
502 const pendingLink =
503 pr === null && supportsMultiplePullRequests
504 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
505 : null;
506 if (!prStatus && !threadStatus && !pendingLink) {
507 return null;
508 }
509​
510 return (
511 <span className="inline-flex shrink-0 items-center gap-1.5">
512 {prStatus && pr ? (
513 <Tooltip>
514 <TooltipTrigger
515 render={
516 <span
517 aria-label={prStatus.tooltip}
518 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
519 />
520 }
521 >
522 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
523 </TooltipTrigger>
524 <TooltipPopup side="top">
525 <PrStatusTooltipContent status={prStatus} />
526 </TooltipPopup>
527 </Tooltip>
528 ) : null}
529 {pendingLink ? (
530 <GitPullRequestArrowIcon
531 className="size-3 text-muted-foreground"
532 aria-label={`PR #${pendingLink.number}, status pending`}
533 />
534 ) : null}
535 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
536 </span>
537 );
539​
540/**
541 * Non-interactive trailing status icons for a thread row in compact contexts
542 * like the command palette. Shows a terminal-running indicator and a remote
543 * environment indicator, matching the sidebar's trailing indicators.
544 */
545export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
546 const runningTerminalIds = useThreadRunningTerminalIds({
547 environmentId: thread.environmentId,
548 threadId: thread.id,
549 });
550 const environment = useEnvironment(thread.environmentId);
551 const primaryEnvironmentId = usePrimaryEnvironmentId();
552 // No primary (the hosted app) means every thread is remote, and the machine
553 // glyph is what tells the environments apart.
554 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
555 const remoteEnvLabel = environment?.label ?? null;
556 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
557 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
558 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
559​
560 if (!terminalStatus && !isRemoteThread) {
561 return null;
562 }
563​
564 return (
565 <span className="inline-flex shrink-0 items-center gap-1.5">
566 {terminalStatus ? (
567 <Tooltip>
568 <TooltipTrigger
569 render={
570 <span
571 role="img"
572 aria-label={terminalStatus.label}
573 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
574 />
575 }
576 >
577 <TerminalIcon
578 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
579 />
580 </TooltipTrigger>
581 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
582 </Tooltip>
583 ) : null}
584 {isRemoteThread ? (
585 <Tooltip>
586 <TooltipTrigger
587 render={
588 <span
589 aria-label={threadEnvironmentLabel ?? "Remote"}
590 className="inline-flex items-center justify-center"
591 />
592 }
593 >
594 <EnvironmentMachineIcon
595 kind={remoteMachine}
596 className="size-3 text-muted-foreground/60"
597 />
598 </TooltipTrigger>
599 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
600 </Tooltip>
601 ) : null}
602 </span>
603 );