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 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"
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 p-4 text-left opacity-40 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
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 const handleTabMouseDown = useCallback((event: ReactMouseEvent) => {
337 if (event.button !== 1) return;
338 event.preventDefault();
339 }, []);
340 const handleTabAuxClick = useCallback(
341 (event: ReactMouseEvent, surface: RightPanelSurface) => {
342 if (event.button !== 1) return;
343 event.preventDefault();
344 event.stopPropagation();
345 props.onCloseSurface(surface);
346 },
347 [props],
348 );
349
350 useEffect(() => {
351 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
352 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
353 }, [props.activeSurfaceId]);
354
355 return (
356 <PreviewPanelShell
357 mode={props.mode}
358 {...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
359 {...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
360 >
361 <div
362 className={cn(
363 "workspace-topbar gap-1 pl-2",
364 !ownsDesktopTitleBar && "[--workspace-topbar-height:--spacing(11)]",
365 props.mode === "inline" ? "pr-28" : "pr-3",
366 ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
367 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
368 )}
369 data-right-panel-tabbar
370 >
371 <ScrollArea
372 ref={tabListRef}
373 hideScrollbars
374 scrollFade
375 className={cn("min-w-0 flex-1 rounded-none", ownsDesktopTitleBar && "drag-region")}
376 data-right-panel-tab-list
377 >
378 <div className="flex h-full w-max min-w-full items-center gap-1">
379 {props.surfaces.map((surface) => {
380 const active = surface.id === props.activeSurfaceId;
381 const pending = props.pendingSurfaceIds.has(surface.id);
382 const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
383 return (
384 <div
385 key={surface.id}
386 data-active-tab={active}
387 onMouseDown={handleTabMouseDown}
388 onAuxClick={(event) => handleTabAuxClick(event, surface)}
389 onContextMenu={(event) => void handleTabContextMenu(event, surface)}
390 className={cn(
391 "group flex h-7 min-w-25 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm",
392 active
393 ? "bg-accent text-foreground"
394 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
395 )}
396 >
397 <Tooltip>
398 <TooltipTrigger
399 render={
400 <button
401 type="button"
402 className="flex min-w-0 flex-1 items-center gap-1.5"
403 onClick={() => props.onActivate(surface)}
404 >
405 <SurfaceIcon
406 surface={surface}
407 sessions={props.previewSessions}
408 theme={resolvedTheme}
409 />
410 <span className="truncate">{title}</span>
411 </button>
412 }
413 />
414 <TooltipPopup>{title}</TooltipPopup>
415 </Tooltip>
416 <button
417 type="button"
418 className={cn(
419 "relative flex size-4 shrink-0 items-center justify-center rounded hover:bg-muted focus:opacity-100",
420 pending ? "opacity-100" : "opacity-0 group-hover:opacity-100",
421 )}
422 aria-label={`Close ${title}`}
423 onClick={() => props.onCloseSurface(surface)}
424 >
425 {pending ? (
426 <>
427 <span
428 className="size-2 rounded-full bg-current group-hover:hidden"
429 aria-hidden
430 />
431 <X className="hidden size-3 group-hover:block" />
432 </>
433 ) : (
434 <X className="size-3" />
435 )}
436 </button>
437 </div>
438 );
439 })}
440 {props.surfaces.length > 0 ? (
441 <Menu>
442 <MenuTrigger
443 className="relative inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
444 aria-label="Add panel surface"
445 >
446 <Plus className="size-4" />
447 </MenuTrigger>
448 <MenuPopup align="start" side="bottom" sideOffset={6} className="min-w-44">
449 <SurfaceMenuItem
450 available={props.browserAvailable}
451 disabledReason={SURFACE_DISABLED_REASONS.browser}
452 onClick={props.onAddBrowser}
453 >
454 <Globe2 />
455 Browser
456 </SurfaceMenuItem>
457 <SurfaceMenuItem available onClick={props.onAddTerminal}>
458 <TerminalSquare />
459 Terminal
460 </SurfaceMenuItem>
461 <SurfaceMenuItem
462 available={props.filesAvailable}
463 disabledReason={SURFACE_DISABLED_REASONS.files}
464 onClick={props.onAddFiles}
465 >
466 <Files />
467 Files
468 </SurfaceMenuItem>
469 <SurfaceMenuItem
470 available={props.diffAvailable}
471 disabledReason={SURFACE_DISABLED_REASONS.diff}
472 onClick={props.onAddDiff}
473 >
474 <FileDiff />
475 Diff
476 </SurfaceMenuItem>
477 </MenuPopup>
478 </Menu>
479 ) : null}
480 </div>
481 </ScrollArea>
482 {props.layoutControls}
483 </div>
484 <div className="flex min-h-0 flex-1 flex-col">
485 {props.activeSurfaceId === null ? (
486 <RightPanelEmptyState
487 onAddBrowser={props.onAddBrowser}
488 onAddTerminal={props.onAddTerminal}
489 onAddDiff={props.onAddDiff}
490 onAddFiles={props.onAddFiles}
491 browserAvailable={props.browserAvailable}
492 diffAvailable={props.diffAvailable}
493 filesAvailable={props.filesAvailable}
494 />
495 ) : (
496 props.children
497 )}
498 </div>
499 </PreviewPanelShell>
500 );
501}