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

ThreadStatusIndicators.tsx

605 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`
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 linkedCount !== null
174 ? "text-secondary-label"
175 : isStack
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<NonNullable<ThreadPr>["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};
284​
285export function settledPrHoverColorClass(
286 state: NonNullable<ThreadPr>["state"],
287 isDraft = false,
288): string {
289 switch (state) {
290 case "open":
291 if (isDraft) {
292 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
293 }
294 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
295 case "merged":
296 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
297 case "closed":
298 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
299 }
301​
302export function prStatusIndicator(
303 pr: ThreadPr,
304 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
305): PrStatusIndicator | null {
306 function formatPrState(pr: NonNullable<ThreadPr>): string {
307 if (pr.state === "open" && pr.isDraft === true) return "Draft";
308 return pr.state.charAt(0).toUpperCase() + pr.state.slice(1);
309 }
310​
311 function formatPrStatusLead(pr: NonNullable<ThreadPr>, changeRequestShortName: string): string {
312 return `${changeRequestShortName} #${pr.number} - ${formatPrState(pr)}`;
313 }
314 if (!pr) return null;
315 const presentation = resolveChangeRequestPresentation(provider);
316​
317 const tooltipLead = formatPrStatusLead(pr, presentation.shortName);
318 const tooltip = `${tooltipLead}: ${pr.title}`;
319​
320 if (pr.state === "open") {
321 const isDraft = pr.isDraft === true;
322 return {
323 label: `${presentation.shortName} ${isDraft ? "draft" : "open"}`,
324 colorClass: isDraft
325 ? "text-zinc-500 dark:text-zinc-400/80"
326 : "text-emerald-600 dark:text-emerald-300/90",
327 tooltip,
328 tooltipLead,
329 tooltipTitle: pr.title,
330 url: pr.url,
331 };
332 }
333 if (pr.state === "closed") {
334 return {
335 label: `${presentation.shortName} closed`,
336 colorClass: "text-red-600 dark:text-red-300/90",
337 tooltip,
338 tooltipLead,
339 tooltipTitle: pr.title,
340 url: pr.url,
341 };
342 }
343 if (pr.state === "merged") {
344 return {
345 label: `${presentation.shortName} merged`,
346 colorClass: "text-violet-600 dark:text-violet-300/90",
347 tooltip,
348 tooltipLead,
349 tooltipTitle: pr.title,
350 url: pr.url,
351 };
352 }
353 return null;
355​
356export function ChangeRequestStatusIcon({
357 state,
358 isDraft = false,
359 className,
360}: Pick<NonNullable<ThreadPr>, "state"> & {
361 readonly isDraft?: boolean | undefined;
362 readonly className?: string | undefined;
363}) {
364 const presentation = resolvePullRequestState({ state, isDraft });
365 return <presentation.Icon className={className} />;
367​
368export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
369 return (
370 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
371 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
372 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
373 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
374 </span>
375 );
377​
378export function terminalStatusFromRunningIds(
379 runningTerminalIds: ReadonlyArray<string>,
380): TerminalStatusIndicator | null {
381 if (runningTerminalIds.length === 0) {
382 return null;
383 }
384 return {
385 label: "Terminal process running",
386 colorClass: "text-teal-600 dark:text-teal-300/90",
387 pulse: true,
388 };
390​
391export function ThreadWorktreeIndicator({
392 thread,
393}: {
394 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
395}) {
396 const worktreePath = thread.worktreePath?.trim();
397 if (!worktreePath) {
398 return null;
399 }
400​
401 const displayPath = formatWorktreePathForDisplay(worktreePath);
402 const tooltip = thread.branch
403 ? `Worktree: ${displayPath} (${thread.branch})`
404 : `Worktree: ${displayPath}`;
405​
406 return (
407 <Tooltip>
408 <TooltipTrigger
409 render={
410 <span
411 role="img"
412 aria-label={tooltip}
413 data-testid={`thread-worktree-${thread.id}`}
414 className="inline-flex items-center justify-center"
415 />
416 }
417 >
418 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
419 </TooltipTrigger>
420 <TooltipPopup side="top">{tooltip}</TooltipPopup>
421 </Tooltip>
422 );
424​
425export function ThreadStatusLabel({
426 status,
427 compact = false,
428}: {
429 status: ThreadStatusPill;
430 compact?: boolean;
431}) {
432 if (compact) {
433 return (
434 <Tooltip>
435 <TooltipTrigger
436 render={
437 <span
438 aria-label={status.label}
439 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
440 />
441 }
442 >
443 <span
444 className={`size-[9px] rounded-full ${status.dotClass} ${
445 status.pulse ? "animate-status-pulse" : ""
446 }`}
447 />
448 </TooltipTrigger>
449 <TooltipPopup side="top">{status.label}</TooltipPopup>
450 </Tooltip>
451 );
452 }
453​
454 return (
455 <Tooltip>
456 <TooltipTrigger
457 render={
458 <span
459 aria-label={status.label}
460 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
461 />
462 }
463 >
464 <span
465 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
466 status.pulse ? "animate-status-pulse" : ""
467 }`}
468 />
469 <span className="hidden md:inline">{status.label}</span>
470 </TooltipTrigger>
471 <TooltipPopup side="top">{status.label}</TooltipPopup>
472 </Tooltip>
473 );
475​
476/**
477 * Non-interactive leading status icons for a thread row in compact contexts
478 * like the command palette. Shows the change request state icon (if present) and the
479 * thread status dot, matching the sidebar's leading indicators.
480 */
481export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
482 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
483 const lastVisitedAt = useUiStateStore(
484 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
485 );
486 const pullRequest = useLinkedThreadPullRequest(
487 thread.environmentId,
488 thread.linkedPullRequest,
489 true,
490 thread.pullRequests,
491 thread.branchPullRequest,
492 );
493 const pr = pullRequest?.pr ?? null;
494 const prStatus = prStatusIndicator(pr, pullRequest?.sourceControlProvider);
495 const threadStatus = resolveThreadStatusPill({
496 thread: {
497 ...thread,
498 lastVisitedAt,
499 },
500 });
501​
502 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
503 const pendingLink =
504 pr === null && supportsMultiplePullRequests
505 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
506 : null;
507 if (!prStatus && !threadStatus && !pendingLink) {
508 return null;
509 }
510​
511 return (
512 <span className="inline-flex shrink-0 items-center gap-1.5">
513 {prStatus && pr ? (
514 <Tooltip>
515 <TooltipTrigger
516 render={
517 <span
518 aria-label={prStatus.tooltip}
519 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
520 />
521 }
522 >
523 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
524 </TooltipTrigger>
525 <TooltipPopup side="top">
526 <PrStatusTooltipContent status={prStatus} />
527 </TooltipPopup>
528 </Tooltip>
529 ) : null}
530 {pendingLink ? (
531 <GitPullRequestArrowIcon
532 className="size-3 text-muted-foreground"
533 aria-label={`PR #${pendingLink.number}, status pending`}
534 />
535 ) : null}
536 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
537 </span>
538 );
540​
541/**
542 * Non-interactive trailing status icons for a thread row in compact contexts
543 * like the command palette. Shows a terminal-running indicator and a remote
544 * environment indicator, matching the sidebar's trailing indicators.
545 */
546export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
547 const runningTerminalIds = useThreadRunningTerminalIds({
548 environmentId: thread.environmentId,
549 threadId: thread.id,
550 });
551 const environment = useEnvironment(thread.environmentId);
552 const primaryEnvironmentId = usePrimaryEnvironmentId();
553 // No primary (the hosted app) means every thread is remote, and the machine
554 // glyph is what tells the environments apart.
555 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
556 const remoteEnvLabel = environment?.label ?? null;
557 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
558 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
559 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
560​
561 if (!terminalStatus && !isRemoteThread) {
562 return null;
563 }
564​
565 return (
566 <span className="inline-flex shrink-0 items-center gap-1.5">
567 {terminalStatus ? (
568 <Tooltip>
569 <TooltipTrigger
570 render={
571 <span
572 role="img"
573 aria-label={terminalStatus.label}
574 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
575 />
576 }
577 >
578 <TerminalIcon
579 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
580 />
581 </TooltipTrigger>
582 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
583 </Tooltip>
584 ) : null}
585 {isRemoteThread ? (
586 <Tooltip>
587 <TooltipTrigger
588 render={
589 <span
590 aria-label={threadEnvironmentLabel ?? "Remote"}
591 className="inline-flex items-center justify-center"
592 />
593 }
594 >
595 <EnvironmentMachineIcon
596 kind={remoteMachine}
597 className="size-3 text-muted-foreground/60"
598 />
599 </TooltipTrigger>
600 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
601 </Tooltip>
602 ) : null}
603 </span>
604 );