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

RightPanelTabs.tsx

610 lines21.5 KB

1import type { ContextMenuItem, PreviewSessionSnapshot, PullRequestState } from "@t3tools/contracts";
2import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
3import {
4 Bot,
5 FileDiff,
6 Files,
7 GitPullRequest,
8 Globe2,
9 Plus,
10 TerminalSquare,
11 X,
12} from "lucide-react";
13import {
14 type MouseEvent as ReactMouseEvent,
15 type ReactElement,
16 type ReactNode,
17 useCallback,
18 useEffect,
19 useRef,
20 useState,
21} from "react";
22​
23import { isElectron } from "~/env";
24import type { RightPanelSurface } from "~/rightPanelStore";
25import { cn } from "~/lib/utils";
26import { readLocalApi } from "~/localApi";
27import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
28import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
29import { ScrollArea } from "~/components/ui/scroll-area";
30import { faviconUrlForOrigin } from "~/lib/favicon";
31import { useTheme } from "~/hooks/useTheme";
32import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
33​
34import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
35import { PierreEntryIcon } from "./chat/PierreEntryIcon";
36​
37interface RightPanelTabsProps {
38 mode: PreviewPanelMode;
39 maximized?: boolean;
40 /** Forwarded to PreviewPanelShell so this surface persists its own width. */
41 widthStorageKey?: string;
42 /** Forwarded to PreviewPanelShell as the initial width before a user resize. */
43 defaultWidth?: number;
44 layoutControls?: ReactNode;
45 surfaces: readonly RightPanelSurface[];
46 activeSurfaceId: string | null;
47 pendingSurfaceIds: ReadonlySet<string>;
48 previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
49 terminalLabelsById: ReadonlyMap<string, string>;
50 onActivate: (surface: RightPanelSurface) => void;
51 onCloseSurface: (surface: RightPanelSurface) => void;
52 onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
53 onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
54 onCloseAllSurfaces: () => void;
55 onCopyFilePath: (relativePath: string) => void;
56 onAddBrowser: () => void;
57 onAddTerminal: () => void;
58 onAddDiff: () => void;
59 onAddFiles: () => void;
60 onAddPullRequest: () => void;
61 onAddAgents: () => void;
62 browserAvailable: boolean;
63 terminalAvailable: boolean;
64 diffAvailable: boolean;
65 filesAvailable: boolean;
66 pullRequestAvailable: boolean;
67 agentsAvailable: boolean;
68 pullRequestStatuses?: Readonly<Record<string, PullRequestTabStatus>>;
69 /** Running + waiting subagents; badges the Agents card in the empty state. */
70 liveAgentCount: number;
71 children: ReactNode;
73​
74export interface PullRequestTabStatus {
75 projectId: string;
76 repository: string;
77 number: number;
78 state: PullRequestState;
79 isDraft: boolean;
81​
82const SURFACE_DISABLED_REASONS = {
83 browser: "Browser previews are only available in the T3 Code desktop app.",
84 terminal: "Terminal surfaces are only available from a project thread.",
85 files: "Files are only available when a project is open.",
86 diff: "Diff is only available for server threads in Git repositories.",
87 pullRequest: "This thread's branch has no pull request yet.",
88 agents: "Agents are only available from a thread.",
89} as const;
90​
91type TabContextMenuAction = "copy-path" | "close" | "close-others" | "close-to-right" | "close-all";
92​
93function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
94 return (
95 <Tooltip>
96 <TooltipTrigger render={props.trigger} />
97 <TooltipPopup side="top">{props.reason}</TooltipPopup>
98 </Tooltip>
99 );
101​
102function SurfaceMenuItem(props: {
103 available: boolean;
104 disabledReason?: string;
105 onClick: () => void;
106 children: ReactNode;
107}) {
108 const item = (
109 <MenuItem
110 className={!props.available ? "data-disabled:pointer-events-auto" : undefined}
111 onClick={props.onClick}
112 disabled={!props.available}
113 >
114 {props.children}
115 </MenuItem>
116 );
117 if (props.available || !props.disabledReason) return item;
118 return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
120​
121function RightPanelEmptyState(props: {
122 onAddBrowser: () => void;
123 onAddTerminal: () => void;
124 onAddDiff: () => void;
125 onAddFiles: () => void;
126 onAddPullRequest: () => void;
127 onAddAgents: () => void;
128 browserAvailable: boolean;
129 terminalAvailable: boolean;
130 diffAvailable: boolean;
131 filesAvailable: boolean;
132 pullRequestAvailable: boolean;
133 agentsAvailable: boolean;
134 liveAgentCount: number;
135}) {
136 const actions = [
137 {
138 label: "Browser",
139 description: "Open a local app or URL.",
140 icon: Globe2,
141 available: props.browserAvailable,
142 disabledReason: SURFACE_DISABLED_REASONS.browser,
143 onClick: props.onAddBrowser,
144 badgeCount: 0,
145 },
146 {
147 label: "Terminal",
148 description: "Start a shell in this workspace.",
149 icon: TerminalSquare,
150 available: props.terminalAvailable,
151 disabledReason: SURFACE_DISABLED_REASONS.terminal,
152 onClick: props.onAddTerminal,
153 badgeCount: 0,
154 },
155 {
156 label: "Files",
157 description: "Browse and read workspace files.",
158 icon: Files,
159 available: props.filesAvailable,
160 disabledReason: SURFACE_DISABLED_REASONS.files,
161 onClick: props.onAddFiles,
162 badgeCount: 0,
163 },
164 {
165 label: "Diff",
166 description: "Review changes in this thread.",
167 icon: FileDiff,
168 available: props.diffAvailable,
169 disabledReason: SURFACE_DISABLED_REASONS.diff,
170 onClick: props.onAddDiff,
171 badgeCount: 0,
172 },
173 {
174 label: "Pull request",
175 description: "Open the pull request for this thread's branch.",
176 icon: GitPullRequest,
177 available: props.pullRequestAvailable,
178 disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
179 onClick: props.onAddPullRequest,
180 badgeCount: 0,
181 },
182 {
183 label: "Agents",
184 description: "Watch subagents and workflows run.",
185 icon: Bot,
186 available: props.agentsAvailable,
187 disabledReason: SURFACE_DISABLED_REASONS.agents,
188 onClick: props.onAddAgents,
189 badgeCount: props.liveAgentCount,
190 },
191 ] as const;
192​
193 return (
194 <div className="flex min-h-0 flex-1 items-center justify-center p-6">
195 <div className="w-full max-w-xl">
196 <div className="mb-5 text-center">
197 <h3 className="text-sm font-medium text-foreground">Open a surface</h3>
198 <p className="mt-1 text-xs text-muted-foreground">
199 Choose what to show in the right panel.
200 </p>
201 </div>
202 <div className="grid grid-cols-2 gap-2">
203 {actions.map((action) => {
204 const Icon = action.icon;
205 const content = (
206 <>
207 <span className="relative mb-3 inline-flex">
208 <Icon className="size-5" />
209 {action.badgeCount > 0 ? (
210 <span
211 aria-hidden
212 className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
213 >
214 {action.badgeCount}
215 </span>
216 ) : null}
217 </span>
218 <span className="text-sm font-medium">{action.label}</span>
219 <span className="mt-1 text-xs leading-relaxed text-muted-foreground">
220 {action.description}
221 </span>
222 </>
223 );
224 if (action.available) {
225 return (
226 <button
227 key={action.label}
228 type="button"
229 onClick={action.onClick}
230 className="cursor-pointer flex min-h-28 w-full flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left transition hover:border-border hover:bg-accent/60 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
231 >
232 {content}
233 </button>
234 );
235 }
236 const disabledCard = (
237 <button
238 type="button"
239 className="flex min-h-28 w-full cursor-not-allowed flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left opacity-40 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
240 aria-disabled="true"
241 >
242 {content}
243 </button>
244 );
245 return (
246 <DisabledReasonTooltip
247 key={action.label}
248 reason={action.disabledReason}
249 trigger={disabledCard}
250 />
251 );
252 })}
253 </div>
254 </div>
255 </div>
256 );
258​
259function surfaceTitle(
260 surface: RightPanelSurface,
261 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
262 terminalLabelsById: ReadonlyMap<string, string>,
263): string {
264 switch (surface.kind) {
265 case "diff":
266 return "Diff";
267 case "files":
268 return "Files";
269 case "file":
270 return surface.relativePath.slice(surface.relativePath.lastIndexOf("/") + 1);
271 case "terminal":
272 return (
273 terminalLabelsById.get(surface.activeTerminalId) ??
274 getTerminalLabel(surface.activeTerminalId)
275 );
276 case "pull-request":
277 return `#${surface.number}`;
278 case "agents":
279 return "Agents";
280 case "preview": {
281 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
282 if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
283 if (snapshot.navStatus.title.trim().length > 0) return snapshot.navStatus.title;
284 try {
285 return new URL(snapshot.navStatus.url).host || "Browser";
286 } catch {
287 return "Browser";
288 }
289 }
290 }
292​
293function PreviewFavicon({ url }: { url: string | null }) {
294 const faviconUrl = faviconUrlForOrigin(url, 32);
295 const [failedUrl, setFailedUrl] = useState<string | null>(null);
296 if (!faviconUrl || failedUrl === faviconUrl) return <Globe2 className="size-3 shrink-0" />;
297 return (
298 <img
299 src={faviconUrl}
300 alt=""
301 aria-hidden
302 draggable={false}
303 className="size-3 shrink-0 rounded-sm"
304 onError={() => setFailedUrl(faviconUrl)}
305 />
306 );
308​
309function SurfaceIcon({
310 surface,
311 sessions,
312 theme,
313 pullRequestStatuses,
314}: {
315 surface: RightPanelSurface;
316 sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
317 theme: "light" | "dark";
318 pullRequestStatuses: Readonly<Record<string, PullRequestTabStatus>> | undefined;
319}) {
320 switch (surface.kind) {
321 case "preview": {
322 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
323 const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
324 return <PreviewFavicon url={url} />;
325 }
326 case "diff":
327 return <FileDiff className="size-3 shrink-0" />;
328 case "files":
329 return <Files className="size-3 shrink-0" />;
330 case "file":
331 return (
332 <PierreEntryIcon
333 pathValue={surface.relativePath}
334 kind="file"
335 theme={theme}
336 className="size-3"
337 />
338 );
339 case "terminal":
340 return <TerminalSquare className="size-3 shrink-0" />;
341 case "pull-request": {
342 const status = pullRequestStatuses?.[surface.id] ?? null;
343 const toneClassName =
344 status?.state === "merged"
345 ? "text-violet-600 dark:text-violet-300/90"
346 : status?.state === "closed"
347 ? "text-red-600 dark:text-red-300/90"
348 : status?.isDraft
349 ? "text-zinc-500 dark:text-zinc-400/80"
350 : status?.state === "open"
351 ? "text-emerald-600 dark:text-emerald-300/90"
352 : "text-muted-foreground";
353 return <GitPullRequest className={cn("size-3 shrink-0", toneClassName)} />;
354 }
355 case "agents":
356 return <Bot className="size-3 shrink-0" />;
357 }
359​
360export function RightPanelTabs(props: RightPanelTabsProps) {
361 const ownsDesktopTitleBar = isElectron && props.mode === "inline";
362 const { resolvedTheme } = useTheme();
363 const tabListRef = useRef<HTMLDivElement>(null);
364​
365 const handleTabContextMenu = useCallback(
366 async (event: ReactMouseEvent, surface: RightPanelSurface) => {
367 event.preventDefault();
368 event.stopPropagation();
369​
370 const api = readLocalApi();
371 if (!api) return;
372​
373 const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
374 if (surfaceIndex < 0) return;
375​
376 const items: ContextMenuItem<TabContextMenuAction>[] = [];
377 if (surface.kind === "file") {
378 items.push({ id: "copy-path", label: "Copy path" });
379 }
380 items.push(
381 { id: "close", label: "Close" },
382 {
383 id: "close-others",
384 label: "Close others",
385 disabled: props.surfaces.length <= 1,
386 },
387 {
388 id: "close-to-right",
389 label: "Close to the right",
390 disabled: surfaceIndex >= props.surfaces.length - 1,
391 },
392 {
393 id: "close-all",
394 label: "Close all",
395 disabled: props.surfaces.length === 0,
396 },
397 );
398​
399 const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
400 switch (action) {
401 case "copy-path":
402 if (surface.kind === "file") props.onCopyFilePath(surface.relativePath);
403 break;
404 case "close":
405 props.onCloseSurface(surface);
406 break;
407 case "close-others":
408 props.onCloseOtherSurfaces(surface);
409 break;
410 case "close-to-right":
411 props.onCloseSurfacesToRight(surface);
412 break;
413 case "close-all":
414 props.onCloseAllSurfaces();
415 break;
416 case null:
417 break;
418 }
419 },
420 [props],
421 );
422 const handleTabMouseDown = useCallback((event: ReactMouseEvent) => {
423 if (event.button !== 1) return;
424 event.preventDefault();
425 }, []);
426 const handleTabAuxClick = useCallback(
427 (event: ReactMouseEvent, surface: RightPanelSurface) => {
428 if (event.button !== 1) return;
429 event.preventDefault();
430 event.stopPropagation();
431 props.onCloseSurface(surface);
432 },
433 [props],
434 );
435​
436 useEffect(() => {
437 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
438 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
439 }, [props.activeSurfaceId]);
440​
441 return (
442 <PreviewPanelShell
443 mode={props.mode}
444 {...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
445 {...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
446 {...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
447 >
448 <div
449 className={cn(
450 "workspace-topbar gap-1 pl-2",
451 props.mode !== "inline" && "[--workspace-topbar-height:--spacing(11)]",
452 props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
453 ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
454 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
455 )}
456 data-right-panel-tabbar
457 >
458 <ScrollArea
459 ref={tabListRef}
460 hideScrollbars
461 scrollFade
462 className={cn("min-w-0 flex-1 rounded-none", ownsDesktopTitleBar && "drag-region")}
463 data-right-panel-tab-list
464 >
465 <div className="flex h-full w-max min-w-full items-center gap-1">
466 {props.surfaces.map((surface) => {
467 const active = surface.id === props.activeSurfaceId;
468 const pending = props.pendingSurfaceIds.has(surface.id);
469 const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
470 return (
471 <div
472 key={surface.id}
473 data-active-tab={active}
474 onMouseDown={handleTabMouseDown}
475 onAuxClick={(event) => handleTabAuxClick(event, surface)}
476 onContextMenu={(event) => void handleTabContextMenu(event, surface)}
477 className={cn(
478 "cursor-pointer group/tab flex h-6 max-w-36 shrink-0 items-center gap-0.5 rounded-md pr-2 pl-1.5 text-xs",
479 active
480 ? "bg-accent text-foreground"
481 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
482 )}
483 >
484 <button
485 type="button"
486 className="cursor-pointer group/close relative flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
487 aria-label={`Close ${title}`}
488 onClick={() => props.onCloseSurface(surface)}
489 >
490 <span className="relative flex size-3 items-center justify-center group-hover/tab:hidden group-focus-visible/close:hidden">
491 <SurfaceIcon
492 surface={surface}
493 sessions={props.previewSessions}
494 theme={resolvedTheme}
495 pullRequestStatuses={props.pullRequestStatuses}
496 />
497 {pending ? (
498 <span
499 className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
500 aria-hidden
501 />
502 ) : null}
503 </span>
504 <X className="hidden size-3 group-hover/tab:block group-focus-visible/close:block" />
505 </button>
506 <Tooltip>
507 <TooltipTrigger
508 render={
509 <button
510 type="button"
511 className="cursor-pointer flex min-w-0 items-center"
512 onClick={() => props.onActivate(surface)}
513 >
514 <span className="truncate">{title}</span>
515 </button>
516 }
517 />
518 <TooltipPopup>{title}</TooltipPopup>
519 </Tooltip>
520 </div>
521 );
522 })}
523 {props.surfaces.length > 0 ? (
524 <Menu>
525 <MenuTrigger
526 className="cursor-pointer relative inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
527 aria-label="Add panel surface"
528 >
529 <Plus className="size-3.5" />
530 </MenuTrigger>
531 <MenuPopup align="start" side="bottom" sideOffset={6} className="min-w-44">
532 <SurfaceMenuItem
533 available={props.browserAvailable}
534 disabledReason={SURFACE_DISABLED_REASONS.browser}
535 onClick={props.onAddBrowser}
536 >
537 <Globe2 />
538 Browser
539 </SurfaceMenuItem>
540 <SurfaceMenuItem
541 available={props.terminalAvailable}
542 disabledReason={SURFACE_DISABLED_REASONS.terminal}
543 onClick={props.onAddTerminal}
544 >
545 <TerminalSquare />
546 Terminal
547 </SurfaceMenuItem>
548 <SurfaceMenuItem
549 available={props.filesAvailable}
550 disabledReason={SURFACE_DISABLED_REASONS.files}
551 onClick={props.onAddFiles}
552 >
553 <Files />
554 Files
555 </SurfaceMenuItem>
556 <SurfaceMenuItem
557 available={props.diffAvailable}
558 disabledReason={SURFACE_DISABLED_REASONS.diff}
559 onClick={props.onAddDiff}
560 >
561 <FileDiff />
562 Diff
563 </SurfaceMenuItem>
564 <SurfaceMenuItem
565 available={props.pullRequestAvailable}
566 disabledReason={SURFACE_DISABLED_REASONS.pullRequest}
567 onClick={props.onAddPullRequest}
568 >
569 <GitPullRequest />
570 Pull request
571 </SurfaceMenuItem>
572 <SurfaceMenuItem
573 available={props.agentsAvailable}
574 disabledReason={SURFACE_DISABLED_REASONS.agents}
575 onClick={props.onAddAgents}
576 >
577 <Bot />
578 Agents
579 </SurfaceMenuItem>
580 </MenuPopup>
581 </Menu>
582 ) : null}
583 </div>
584 </ScrollArea>
585 {props.layoutControls}
586 </div>
587 <div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
588 {props.activeSurfaceId === null ? (
589 <RightPanelEmptyState
590 onAddBrowser={props.onAddBrowser}
591 onAddTerminal={props.onAddTerminal}
592 onAddDiff={props.onAddDiff}
593 onAddFiles={props.onAddFiles}
594 onAddPullRequest={props.onAddPullRequest}
595 onAddAgents={props.onAddAgents}
596 browserAvailable={props.browserAvailable}
597 terminalAvailable={props.terminalAvailable}
598 diffAvailable={props.diffAvailable}
599 filesAvailable={props.filesAvailable}
600 pullRequestAvailable={props.pullRequestAvailable}
601 agentsAvailable={props.agentsAvailable}
602 liveAgentCount={props.liveAgentCount}
603 />
604 ) : (
605 props.children
606 )}
607 </div>
608 </PreviewPanelShell>
609 );