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

RightPanelTabs.tsx

512 lines17.5 KB

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