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

ThreadStatusIndicators.tsx

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