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

ThreadStatusIndicators.tsx

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