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