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