Open History to see the last commit
1import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";
4import {
5 threadPullRequestKeysEqual,
6 visibleThreadPullRequests,
7} from "@t3tools/shared/threadPullRequests";
8import type {
9 ContextMenuItem,
10 EnvironmentId,
11 PreviewSessionSnapshot,
12 ProjectId,
13 PullRequestState,
14 ResolvedKeybindingsConfig,
15} from "@t3tools/contracts";
16import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
17import {
18 closestCenter,
19 DndContext,
20 type DragEndEvent,
21 PointerSensor,
22 useSensor,
23 useSensors,
24} from "@dnd-kit/core";
25import { restrictToFirstScrollableAncestor, restrictToHorizontalAxis } from "@dnd-kit/modifiers";
26import { horizontalListSortingStrategy, SortableContext, useSortable } from "@dnd-kit/sortable";
27import { CSS } from "@dnd-kit/utilities";
28import {
29 Smartphone,
30 ChevronDown,
31 ChevronLeft,
32 ChevronRight,
33 FileDiff,
34 Files,
35 Globe2,
36 Plus,
37 TerminalSquare,
38} from "lucide-react";
39import { Volume2, VolumeOff } from "lucide";
40import {
41 type KeyboardEvent as ReactKeyboardEvent,
42 type MouseEvent as ReactMouseEvent,
43 type ReactElement,
44 type ReactNode,
45 useEffect,
46 useEffectEvent,
47 useRef,
48 useState,
49} from "react";
50
51import { isElectron } from "~/env";
52import type { DesktopPreviewOverlay } from "~/previewStateStore";
53import type { RightPanelSurface } from "~/rightPanelStore";
54import { cn } from "~/lib/utils";
55import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings";
56import { readLocalApi } from "~/localApi";
57import { useStableCallback } from "~/hooks/useStableCallback";
58import { Button } from "~/components/ui/button";
59import { MorphIcon } from "~/components/MorphIcon";
60import { AndroidIcon, AppleIcon } from "~/components/Icons";
61import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
62import { Kbd } from "~/components/ui/kbd";
63import {
64 Menu,
65 MenuItem,
66 MenuPopup,
67 MenuShortcut,
68 MenuSub,
69 MenuSubPopup,
70 MenuSubTrigger,
71 MenuTrigger,
72} from "~/components/ui/menu";
73import { useBrowserDefaults } from "~/browser/browserDefaults";
74import { ScrollArea } from "~/components/ui/scroll-area";
75import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";
76import { faviconUrlForOrigin } from "~/lib/favicon";
77import { useTheme } from "~/hooks/useTheme";
78import { useDeviceState } from "~/state/device";
79import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize";
80import {
81 newestPullRequestSummary,
82 pullRequestEnvironment,
83 useSharedPullRequestSummary,
84} from "~/state/pullRequests";
85import { useEnvironmentQuery } from "~/state/query";
86import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
87
88import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
89import { FaviconImage } from "./preview/PreviewFaviconIcon";
90import { previewBridge } from "./preview/previewBridge";
91import { PierreEntryIcon } from "./chat/PierreEntryIcon";
92import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
93import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
94import { observeResize } from "~/lib/observeResize";
95
96interface RightPanelTabsProps {
97 mode: PreviewPanelMode;
98 maximized?: boolean;
99 open?: boolean;
100 keybindings: ResolvedKeybindingsConfig;
101 getShortcutContext: () => ShortcutMatchContext;
102 widthStorageKey?: string;
103 defaultWidth?: number;
104 inlineSize?: PreviewPanelInlineSize;
105 layoutControls?: ReactNode;
106 surfaces: readonly RightPanelSurface[];
107 environmentId: EnvironmentId | null;
108 activeSurfaceId: string | null;
109 pendingSurfaceIds: ReadonlySet<string>;
110 previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
111 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
112 /**
113 * Maps a server session tab id to the desktop runtime tab id the Electron
114 * preview manager is keyed by. Session ids are only unique within one server
115 * process, so desktop operations must not be addressed with them.
116 */
117 previewRuntimeTabId?: ((tabId: string) => string) | undefined;
118 terminalLabelsById: ReadonlyMap<string, string>;
119 onActivate: (surface: RightPanelSurface) => void;
120 onRenameDevice?: (surfaceId: string, title: string) => void;
121 onCloseSurface: (surface: RightPanelSurface) => void;
122 onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
123 onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
124 onCloseAllSurfaces: () => void;
125 onMoveSurface?: (surfaceId: string, toIndex: number) => void;
126 onCopyFilePath: (relativePath: string) => void;
127 onAddBrowser: () => void;
128 /**
129 * Separate from `onAddBrowser` on purpose: that one is passed directly as a
130 * DOM click handler, and a `(profileId?: string)` signature would silently
131 * accept the MouseEvent as a profile id.
132 */
133 onAddBrowserInProfile: (profileId: string) => void;
134 onAddTerminal: () => void;
135 onAddDiff: () => void;
136 onAddFiles: () => void;
137 onAddPullRequest: () => void;
138 onAddPullRequests: () => void;
139 onAddDevice: () => void;
140 browserAvailable: boolean;
141 terminalAvailable: boolean;
142 diffAvailable: boolean;
143 filesAvailable: boolean;
144 pullRequestAvailable: boolean;
145 pullRequestsAvailable: boolean;
146 deviceAvailable: boolean;
147 pullRequestStatusSeeds?: Readonly<Record<string, PullRequestTabStatusSeed>>;
148 children: ReactNode;
149}
150
151export interface PullRequestTabStatus {
152 projectId: string;
153 repository: string;
154 number: number;
155 state: PullRequestState;
156 isDraft: boolean;
157}
158
159export type PullRequestTabStatusSeed = Pick<PullRequestTabStatus, "state" | "isDraft">;
160
161export function shouldOpenDefaultBrowserProfileFromMenuClick(
162 pointerType: string | undefined,
163): boolean {
164 return pointerType !== "touch";
165}
166
167const SURFACE_DISABLED_REASONS = {
168 browser: "Browser previews are only available in the T3 Code desktop app.",
169 terminal: "Terminal surfaces are only available from a project thread.",
170 files: "Files are only available when a project is open.",
171 diff: "Diff is only available for server threads in Git repositories.",
172 pullRequest: "This thread's branch has no pull request yet.",
173 pullRequests: "No linked pull requests are available for this thread.",
174 device: "Devices are only available from a thread.",
175} as const;
176
177// Closed keepMounted popups must stop blocking shortcuts once their exit transition ends.
178const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
179 "dialog-popup",
180 "alert-dialog-popup",
181 "command-dialog-popup",
182 "menu-popup",
183 "select-popup",
184 "popover-popup",
185 "combobox-popup",
186 "autocomplete-popup",
187]
188 .map((slot) => `[data-slot="${slot}"]:is([data-open],[data-ending-style])`)
189 .join(",");
190
191const SURFACE_UNAVAILABLE_HINTS = {
192 browser: "Only available in the desktop app.",
193 terminal: "Available when a project is open.",
194 files: "Available when a project is open.",
195 diff: "Available for Git repositories.",
196 pullRequest: "No pull request on this branch yet.",
197 pullRequests: "No linked pull requests available.",
198 device: "Available from a thread.",
199} as const;
200
201type TabContextMenuAction =
202 | "rename"
203 | "copy-path"
204 | "toggle-mute"
205 | "close"
206 | "close-others"
207 | "close-to-right"
208 | "close-all";
209
210const TAB_SCROLL_EDGE_TOLERANCE = 1;
211const TAB_DRAG_MODIFIERS = [restrictToHorizontalAxis, restrictToFirstScrollableAncestor];
212
213function tabScrollViewport(root: HTMLDivElement | null): HTMLDivElement | null {
214 return root?.querySelector<HTMLDivElement>('[data-slot="scroll-area-viewport"]') ?? null;
215}
216
217function previewTabIdOf(
218 surface: RightPanelSurface,
219 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
220): string | null {
221 if (surface.kind !== "preview" || !surface.resourceId) return null;
222 return sessions[surface.resourceId]?.tabId ?? null;
223}
224
225/**
226 * Stays disabled until desktop overlay state arrives: a server session id can
227 * resolve while the preview manager's createTab is still in flight, and muting
228 * then fails with a PreviewTabNotFoundError nothing surfaces to the user.
229 */
230export function tabMuteMenuItem(input: {
231 overlay: DesktopPreviewOverlay | null;
232 canResolveRuntimeTabId: boolean;
233}): { label: string; disabled: boolean } {
234 const muted = input.overlay?.audioMuted ?? false;
235 return {
236 label: muted ? "Unmute tab" : "Mute tab",
237 disabled: input.overlay === null || !input.canResolveRuntimeTabId,
238 };
239}
240
241type TabAudioState = "none" | "audible" | "muted";
242
243function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState {
244 if (!overlay?.audible) return "none";
245 return overlay.audioMuted ? "muted" : "audible";
246}
247
248type SurfaceShortcutEvent = Pick<
249 KeyboardEvent,
250 "altKey" | "ctrlKey" | "defaultPrevented" | "isComposing" | "key" | "metaKey"
251>;
252
253export function surfaceShortcutActionForKey<
254 const Action extends { available: boolean; shortcut: string },
255>(actions: readonly Action[], event: SurfaceShortcutEvent): Action | null {
256 if (event.defaultPrevented || event.isComposing) return null;
257 if (event.metaKey || event.ctrlKey || event.altKey) return null;
258 return (
259 actions.find(
260 (action) => action.available && action.shortcut.toLowerCase() === event.key.toLowerCase(),
261 ) ?? null
262 );
263}
264
265/**
266 * The `:not` clause lets `closest` see past non-editable islands
267 * (`contenteditable="false"`) to an editable host around them, matching
268 * ComposerPendingUserInputPanel's typing guard.
269 */
270export function surfaceShortcutTargetsTypingContext(
271 target: { closest(selectors: string): unknown } | null,
272): boolean {
273 return (
274 target?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])') !=
275 null
276 );
277}
278
279function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
280 return (
281 <Tooltip>
282 <TooltipTrigger render={props.trigger} />
283 <TooltipPopup side="top">{props.reason}</TooltipPopup>
284 </Tooltip>
285 );
286}
287
288function SurfaceMenuItem(props: {
289 available: boolean;
290 disabledReason?: string;
291 shortcut: string;
292 onClick: () => void;
293 children: ReactNode;
294}) {
295 const item = (
296 <MenuItem
297 className={!props.available ? "data-disabled:pointer-events-auto" : undefined}
298 onClick={props.onClick}
299 disabled={!props.available}
300 aria-keyshortcuts={props.shortcut}
301 >
302 {props.children}
303 <MenuShortcut>{props.shortcut}</MenuShortcut>
304 </MenuItem>
305 );
306 if (props.available || !props.disabledReason) return item;
307 return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
308}
309
310function RightPanelEmptyState(props: {
311 onAddBrowser: () => void;
312 onAddBrowserInProfile: (profileId: string) => void;
313 browserProfiles: ReadonlyArray<{ readonly id: string; readonly name: string }>;
314 onAddTerminal: () => void;
315 onAddDiff: () => void;
316 onAddFiles: () => void;
317 onAddPullRequest: () => void;
318 onAddPullRequests: () => void;
319 onAddDevice: () => void;
320 browserAvailable: boolean;
321 terminalAvailable: boolean;
322 diffAvailable: boolean;
323 filesAvailable: boolean;
324 pullRequestAvailable: boolean;
325 pullRequestsAvailable: boolean;
326 deviceAvailable: boolean;
327}) {
328 const [highlight, setHighlight] = useState(-1);
329
330 const actions = [
331 {
332 label: "Browser",
333 icon: Globe2,
334 shortcut: "B",
335 available: props.browserAvailable,
336 disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
337 onClick: props.onAddBrowser,
338 },
339 {
340 label: "Terminal",
341 icon: TerminalSquare,
342 shortcut: "T",
343 available: props.terminalAvailable,
344 disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
345 onClick: props.onAddTerminal,
346 },
347 {
348 label: "Files",
349 icon: Files,
350 shortcut: "F",
351 available: props.filesAvailable,
352 disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
353 onClick: props.onAddFiles,
354 },
355 {
356 label: "Diff",
357 icon: FileDiff,
358 shortcut: "D",
359 available: props.diffAvailable,
360 disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
361 onClick: props.onAddDiff,
362 },
363 {
364 label: "Pull request",
365 icon: PullRequestGlyph.pullRequest,
366 shortcut: "P",
367 available: props.pullRequestAvailable,
368 disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
369 onClick: props.onAddPullRequest,
370 },
371 {
372 label: "Linked pull requests",
373 icon: PullRequestGlyph.link,
374 shortcut: "L",
375 available: props.pullRequestsAvailable,
376 disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequests,
377 onClick: props.onAddPullRequests,
378 },
379 {
380 label: "Device",
381 description: "Watch an iOS Simulator or Android Emulator.",
382 icon: Smartphone,
383 shortcut: "M",
384 available: props.deviceAvailable,
385 disabledReason: SURFACE_UNAVAILABLE_HINTS.device,
386 onClick: props.onAddDevice,
387 },
388 ] as const;
389
390 type SurfaceAction = (typeof actions)[number];
391
392 const availableActions = actions.filter((action) => action.available);
393 const highlightIndex =
394 availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
395
396 const handleShortcut = useEffectEvent((event: KeyboardEvent) => {
397 const action = surfaceShortcutActionForKey(availableActions, event);
398 if (!action) return;
399 if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
400 const target = event.composedPath()[0] ?? event.target;
401 if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return;
402 event.preventDefault();
403 event.stopPropagation();
404 action.onClick();
405 });
406 useEffect(() => {
407 const handler = (event: KeyboardEvent) => handleShortcut(event);
408 window.addEventListener("keydown", handler, true);
409 return () => window.removeEventListener("keydown", handler, true);
410 }, []);
411
412 const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
413 if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
414 if (availableActions.length === 0) return;
415 if (event.key === "ArrowDown" || event.key === "ArrowRight") {
416 event.preventDefault();
417 setHighlight((highlightIndex + 1) % availableActions.length);
418 return;
419 }
420 if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
421 event.preventDefault();
422 setHighlight(
423 highlightIndex === -1
424 ? availableActions.length - 1
425 : (highlightIndex - 1 + availableActions.length) % availableActions.length,
426 );
427 return;
428 }
429 if (event.key === "Enter") {
430 if (event.target !== event.currentTarget) return;
431 const action = availableActions[highlightIndex];
432 if (!action) return;
433 event.preventDefault();
434 action.onClick();
435 }
436 };
437
438 const isHighlighted = (action: SurfaceAction) =>
439 highlightIndex !== -1 && availableActions[highlightIndex] === action;
440
441 const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
442 const Icon = action.icon;
443 return (
444 <span className="relative inline-flex shrink-0">
445 <Icon className={iconClassName} />
446 </span>
447 );
448 };
449
450 return (
451 <div
452 ref={focusOnMount}
453 tabIndex={0}
454 onKeyDown={handleKeyDown}
455 aria-label="Open a surface"
456 data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
457 className={cn(
458 "scrollbar-gutter-both flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 outline-none",
459 "pb-(--workspace-topbar-height)",
460 )}
461 >
462 <div className="w-full max-w-xs py-6">
463 <h3 className="mb-3 text-center font-medium text-foreground text-sm">Open a surface</h3>
464 <div className="flex flex-col gap-0.5">
465 {actions.map((action) =>
466 action.available ? (
467 <div
468 key={action.label}
469 className="group relative"
470 onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
471 onMouseLeave={() =>
472 setHighlight((current) =>
473 current === availableActions.indexOf(action) ? -1 : current,
474 )
475 }
476 >
477 <button
478 type="button"
479 onClick={action.onClick}
480 className={cn(
481 "flex h-8 w-full cursor-pointer items-center gap-2.5 rounded-(--control-radius) px-2.5 text-left text-sm transition-colors group-hover:bg-accent/60",
482 isHighlighted(action) && "bg-accent/60",
483 )}
484 >
485 {actionIcon(action, "size-4")}
486 <span
487 className={cn(
488 "min-w-0 flex-1 truncate",
489 action.label === "Browser" && props.browserProfiles.length > 1 && "pr-7",
490 )}
491 >
492 {action.label}
493 </span>
494 <Kbd>{action.shortcut}</Kbd>
495 </button>
496 {action.label === "Browser" && props.browserProfiles.length > 1 ? (
497 <Menu>
498 <MenuTrigger
499 render={
500 <Button
501 aria-label="Open browser in a profile"
502 className="absolute top-1/2 right-8 -translate-y-1/2"
503 size="icon-xs"
504 variant="ghost-muted"
505 />
506 }
507 >
508 <ChevronDown className="size-3.5" />
509 </MenuTrigger>
510 <MenuPopup align="end" side="bottom" sideOffset={6} className="max-w-56">
511 {props.browserProfiles.map((profile) => (
512 <MenuItem
513 key={profile.id}
514 onClick={() => props.onAddBrowserInProfile(profile.id)}
515 >
516 <span className="min-w-0 truncate">{profile.name}</span>
517 </MenuItem>
518 ))}
519 </MenuPopup>
520 </Menu>
521 ) : null}
522 </div>
523 ) : (
524 <DisabledReasonTooltip
525 key={action.label}
526 reason={action.disabledReason}
527 trigger={
528 <div
529 tabIndex={0}
530 aria-disabled="true"
531 className="flex h-8 w-full cursor-default items-center gap-2.5 rounded-(--control-radius) px-2.5 text-left text-sm opacity-50"
532 >
533 {actionIcon(action, "size-4")}
534 <span className="min-w-0 flex-1 truncate">{action.label}</span>
535 <Kbd>{action.shortcut}</Kbd>
536 </div>
537 }
538 />
539 ),
540 )}
541 </div>
542 </div>
543 </div>
544 );
545}
546
547function surfaceTitle(
548 surface: RightPanelSurface,
549 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
550 terminalLabelsById: ReadonlyMap<string, string>,
551): string {
552 switch (surface.kind) {
553 case "diff":
554 return "Diff";
555 case "files":
556 return "Files";
557 case "file":
558 return surface.relativePath.slice(
559 Math.max(surface.relativePath.lastIndexOf("/"), surface.relativePath.lastIndexOf("\\")) + 1,
560 );
561 case "terminal":
562 return (
563 terminalLabelsById.get(surface.activeTerminalId) ??
564 getTerminalLabel(surface.activeTerminalId)
565 );
566 case "pull-request":
567 return `#${surface.number}`;
568 case "pull-requests":
569 return "Pull requests";
570 case "device":
571 return surface.title ?? surface.target?.name ?? "Device";
572 case "preview": {
573 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
574 if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
575 if (snapshot.navStatus.title.trim().length > 0) return snapshot.navStatus.title;
576 try {
577 return new URL(snapshot.navStatus.url).host || "Browser";
578 } catch {
579 return "Browser";
580 }
581 }
582 }
583}
584
585function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) {
586 const publicProviderUrl = faviconUrlForOrigin(url, 32);
587 return (
588 <FaviconImage
589 sources={[capturedUrl, publicProviderUrl]}
590 fallback={<Globe2 className="size-3 shrink-0" />}
591 className="size-3 shrink-0 rounded-sm object-contain"
592 />
593 );
594}
595
596function sameOrigin(left: string, right: string): boolean {
597 try {
598 return new URL(left).origin === new URL(right).origin;
599 } catch {
600 return false;
601 }
602}
603
604function previewFaviconOf(
605 surface: RightPanelSurface,
606 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
607 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>,
608): { url: string | null; capturedUrl: string | null } {
609 const snapshot =
610 surface.kind === "preview" && surface.resourceId ? sessions[surface.resourceId] : null;
611 const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
612 const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null;
613 const capturedUrl = favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null;
614 return { url, capturedUrl };
615}
616
617function SurfaceIcon({
618 surface,
619 previewUrl,
620 previewCapturedUrl,
621 theme,
622 environmentId,
623 pullRequestStatusSeed,
624}: {
625 surface: RightPanelSurface;
626 previewUrl: string | null;
627 previewCapturedUrl: string | null;
628 theme: "light" | "dark";
629 environmentId: EnvironmentId | null;
630 pullRequestStatusSeed: PullRequestTabStatusSeed | undefined;
631}) {
632 switch (surface.kind) {
633 case "preview":
634 return <PreviewFavicon capturedUrl={previewCapturedUrl} url={previewUrl} />;
635 case "diff":
636 return <FileDiff className="size-3 shrink-0" />;
637 case "files":
638 return <Files className="size-3 shrink-0" />;
639 case "file":
640 return (
641 <PierreEntryIcon
642 pathValue={surface.relativePath}
643 kind="file"
644 theme={theme}
645 className="size-3"
646 />
647 );
648 case "terminal":
649 return <TerminalSquare className="size-3 shrink-0" />;
650 case "pull-request":
651 return (
652 <PullRequestSurfaceIcon
653 surface={surface}
654 environmentId={environmentId}
655 seed={pullRequestStatusSeed}
656 />
657 );
658 case "pull-requests":
659 return <PullRequestGlyph.link className="size-3 shrink-0" />;
660 case "device":
661 return surface.target?.platform === "ios" ? (
662 <AppleIcon className="size-3 shrink-0" />
663 ) : surface.target?.platform === "android" ? (
664 <AndroidIcon className="size-3 shrink-0" />
665 ) : (
666 <Smartphone className="size-3 shrink-0" />
667 );
668 }
669}
670
671export function resolvePullRequestTabLink(
672 threads: readonly Pick<EnvironmentThreadShell, "environmentId" | "pullRequests">[],
673 environmentId: EnvironmentId | null,
674 host: string | null,
675 reference: { repository: string; number: number },
676) {
677 if (environmentId === null || host === null) return undefined;
678 let newest: EnvironmentThreadShell["pullRequests"][number] | undefined;
679 for (const thread of threads) {
680 if (thread.environmentId !== environmentId) continue;
681 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
682 if (
683 !threadPullRequestKeysEqual(link, {
684 host,
685 repository: reference.repository,
686 number: reference.number,
687 })
688 )
689 continue;
690 if (
691 newest === undefined ||
692 (link.snapshot?.syncedAt ?? "") > (newest.snapshot?.syncedAt ?? "")
693 )
694 newest = link;
695 }
696 }
697 return newest;
698}
699
700function PullRequestSurfaceIcon({
701 surface,
702 environmentId,
703 seed,
704}: {
705 surface: Extract<RightPanelSurface, { kind: "pull-request" }>;
706 environmentId: EnvironmentId | null;
707 seed: PullRequestTabStatusSeed | undefined;
708}) {
709 const resolvedEnvironmentId =
710 (surface.environmentId as EnvironmentId | undefined) ?? environmentId;
711 const projects = useProjects();
712 const threads = useThreadShells();
713 const project = projects.find(
714 (entry) => entry.environmentId === resolvedEnvironmentId && entry.id === surface.projectId,
715 );
716 const identity = project?.repositoryIdentity;
717 const host =
718 surface.host ??
719 (identity?.provider
720 ? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)
721 : null);
722 const configs = useServerConfigs();
723 const capabilities =
724 resolvedEnvironmentId === null
725 ? undefined
726 : configs.get(resolvedEnvironmentId)?.environment.capabilities;
727 const linkedSnapshot =
728 capabilities?.threadPullRequests === true
729 ? (resolvePullRequestTabLink(threads, resolvedEnvironmentId, host, surface)?.snapshot ?? null)
730 : null;
731 const detail = useEnvironmentQuery(
732 resolvedEnvironmentId === null || capabilities?.pullRequests !== true || linkedSnapshot !== null
733 ? null
734 : pullRequestEnvironment.detail({
735 environmentId: resolvedEnvironmentId,
736 input: {
737 projectId: surface.projectId as ProjectId,
738 ...(capabilities?.threadPullRequests === true && surface.host !== undefined
739 ? { host: surface.host }
740 : {}),
741 repository: surface.repository,
742 number: surface.number,
743 },
744 }),
745 ).data;
746 const reference = {
747 projectId: surface.projectId as ProjectId,
748 repository: surface.repository,
749 number: surface.number,
750 };
751 const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference, null);
752 const status = linkedSnapshot ?? newestPullRequestSummary(detail, sharedSummary) ?? seed ?? null;
753 if (status === null) {
754 return <PullRequestGlyph.pullRequest className="size-3 shrink-0 text-muted-foreground" />;
755 }
756 const presentation = resolvePullRequestState({
757 state: status.state,
758 isDraft: status.isDraft ?? detail?.isDraft ?? seed?.isDraft ?? false,
759 });
760 return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;
761}
762
763// Module-level so React only runs this callback ref on mount and unmount;
764// a fresh function would re-attach and re-focus on every render.
765function focusOnMount(node: HTMLDivElement | null) {
766 node?.focus();
767}
768
769function SortableTabList(props: {
770 surfaces: readonly RightPanelSurface[];
771 onMove: ((surfaceId: string, toIndex: number) => void) | undefined;
772 children: ReactNode;
773}) {
774 const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
775 const surfaceIds = props.surfaces.map((surface) => surface.id);
776 const { onMove, surfaces } = props;
777 const handleDragEnd = ({ active, over }: DragEndEvent) => {
778 if (!over || active.id === over.id) return;
779 const toIndex = surfaces.findIndex((surface) => surface.id === over.id);
780 if (toIndex >= 0) onMove?.(String(active.id), toIndex);
781 };
782 return (
783 <DndContext
784 sensors={sensors}
785 collisionDetection={closestCenter}
786 modifiers={TAB_DRAG_MODIFIERS}
787 onDragEnd={handleDragEnd}
788 >
789 <SortableContext items={surfaceIds} strategy={horizontalListSortingStrategy}>
790 {props.children}
791 </SortableContext>
792 </DndContext>
793 );
794}
795
796interface RightPanelTabHandlers {
797 onActivate: (surface: RightPanelSurface) => void;
798 onClose: (surface: RightPanelSurface) => void;
799 onAuxClick: (event: ReactMouseEvent, surface: RightPanelSurface) => void;
800 onContextMenu: (event: ReactMouseEvent, surface: RightPanelSurface) => void;
801 onStartRename: (surfaceId: string) => void;
802 onFinishRename: (surfaceId: string, title: string) => void;
803}
804
805function handleTabMouseDown(event: ReactMouseEvent) {
806 if (event.button !== 1) return;
807 event.preventDefault();
808}
809
810// One tab owns its sortable state and receives only its own values, so the
811// compiled subtree is reused unless this tab's surface, title or state changed.
812// The handlers must be stable: the tab list re-renders on every parent render.
813function RightPanelTab(
814 props: RightPanelTabHandlers & {
815 surface: RightPanelSurface;
816 dragDisabled: boolean;
817 active: boolean;
818 pending: boolean;
819 title: string;
820 audio: TabAudioState;
821 audioRuntimeTabId: string | null;
822 previewUrl: string | null;
823 previewCapturedUrl: string | null;
824 theme: "light" | "dark";
825 environmentId: EnvironmentId | null;
826 pullRequestStatusSeed: PullRequestTabStatusSeed | undefined;
827 renaming: boolean;
828 canRename: boolean;
829 ownsDesktopTitleBar: boolean;
830 },
831) {
832 const {
833 surface,
834 title,
835 audio,
836 audioRuntimeTabId,
837 onActivate,
838 onClose,
839 onAuxClick,
840 onContextMenu,
841 onStartRename,
842 onFinishRename,
843 } = props;
844 const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
845 id: surface.id,
846 disabled: props.dragDisabled,
847 });
848 const content = (
849 <>
850 <PanelTabCloseButton label={`Close ${title}`} onClick={() => onClose(surface)}>
851 <SurfaceIcon
852 surface={surface}
853 previewUrl={props.previewUrl}
854 previewCapturedUrl={props.previewCapturedUrl}
855 theme={props.theme}
856 environmentId={props.environmentId}
857 pullRequestStatusSeed={props.pullRequestStatusSeed}
858 />
859 {props.pending ? (
860 <span
861 className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
862 aria-hidden
863 />
864 ) : null}
865 </PanelTabCloseButton>
866 {audio === "none" || !audioRuntimeTabId ? null : (
867 <Tooltip>
868 <TooltipTrigger
869 render={
870 <button
871 type="button"
872 className="cursor-pointer flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
873 aria-label={audio === "muted" ? `Unmute ${title}` : `Mute ${title}`}
874 onClick={(event) => {
875 event.stopPropagation();
876 void previewBridge
877 ?.setAudioMuted(audioRuntimeTabId, audio !== "muted")
878 .catch(() => undefined);
879 }}
880 >
881 <MorphIcon className="size-3" icon={audio === "muted" ? VolumeOff : Volume2} />
882 </button>
883 }
884 />
885 <TooltipPopup>{audio === "muted" ? "Unmute tab" : "Mute tab"}</TooltipPopup>
886 </Tooltip>
887 )}
888 {props.renaming ? (
889 <input
890 aria-label="Device tab name"
891 className="w-24 min-w-0 rounded-sm bg-background px-1 outline-none ring-1 ring-inset ring-ring"
892 defaultValue={title}
893 ref={(element) => {
894 element?.focus();
895 element?.select();
896 }}
897 onBlur={(event) => onFinishRename(surface.id, event.currentTarget.value)}
898 onKeyDown={(event) => {
899 event.stopPropagation();
900 if (event.key === "Enter") event.currentTarget.blur();
901 if (event.key === "Escape") {
902 event.currentTarget.value = title;
903 event.currentTarget.blur();
904 }
905 }}
906 />
907 ) : (
908 <Tooltip>
909 <TooltipTrigger
910 render={
911 <button
912 type="button"
913 onDoubleClick={() => {
914 if (surface.kind === "device" && props.canRename) onStartRename(surface.id);
915 }}
916 className="cursor-pointer flex min-w-0 items-center"
917 onClick={() => onActivate(surface)}
918 >
919 <span className="truncate">{title}</span>
920 </button>
921 }
922 />
923 <TooltipPopup>
924 {surface.kind === "device" ? (
925 <DeviceTabTooltip
926 surface={surface}
927 environmentId={props.environmentId}
928 title={title}
929 />
930 ) : (
931 title
932 )}
933 </TooltipPopup>
934 </Tooltip>
935 )}
936 </>
937 );
938 return (
939 <div
940 data-active-tab={props.active}
941 onMouseDown={handleTabMouseDown}
942 onAuxClick={(event) => onAuxClick(event, surface)}
943 onContextMenu={(event) => onContextMenu(event, surface)}
944 {...listeners}
945 ref={setNodeRef}
946 style={{ transform: CSS.Translate.toString(transform), transition }}
947 className={cn(
948 "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",
949 props.ownsDesktopTitleBar && "[-webkit-app-region:no-drag]",
950 props.active
951 ? "bg-accent text-foreground"
952 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
953 isDragging && "relative z-10",
954 )}
955 >
956 {content}
957 </div>
958 );
959}
960
961export function RightPanelTabs(props: RightPanelTabsProps) {
962 const ownsDesktopTitleBar = isElectron && props.mode === "inline";
963 const browserProfiles = useBrowserDefaults().profiles;
964 const { resolvedTheme } = useTheme();
965 const tabListRef = useRef<HTMLDivElement>(null);
966 const addSurfaceTriggerRef = useRef<HTMLButtonElement>(null);
967 const [renamingDevice, setRenamingDevice] = useState<string | null>(null);
968 const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
969 const [tabScrollState, setTabScrollState] = useState({
970 hasOverflow: false,
971 canScrollLeft: false,
972 canScrollRight: false,
973 });
974
975 if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false);
976
977 const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => {
978 if (event.defaultPrevented || event.isComposing) return;
979 if (
980 resolveShortcutCommand(event, props.keybindings, {
981 context: { ...props.getShortcutContext(), rightPanelOpen: true },
982 }) !== "rightPanel.new"
983 )
984 return;
985 if (!addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
986 event.preventDefault();
987 event.stopPropagation();
988 if (!event.repeat) {
989 addSurfaceTriggerRef.current?.focus();
990 setAddSurfaceMenuOpen(true);
991 }
992 });
993 useEffect(() => {
994 if (props.open === false) return;
995 document.addEventListener("keydown", onNewSurfaceKeyDown, true);
996 return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true);
997 }, [props.open]);
998
999 const updateTabScrollState = () => {
1000 const viewport = tabScrollViewport(tabListRef.current);
1001 if (!viewport) return;
1002
1003 const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
1004 const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
1005 const canScrollRight =
1006 hasOverflow &&
1007 viewport.scrollLeft + viewport.clientWidth < viewport.scrollWidth - TAB_SCROLL_EDGE_TOLERANCE;
1008 setTabScrollState((current) => {
1009 if (
1010 current.hasOverflow === hasOverflow &&
1011 current.canScrollLeft === canScrollLeft &&
1012 current.canScrollRight === canScrollRight
1013 ) {
1014 return current;
1015 }
1016 return { hasOverflow, canScrollLeft, canScrollRight };
1017 });
1018 };
1019
1020 const scrollTabs = (direction: -1 | 1) => {
1021 const viewport = tabScrollViewport(tabListRef.current);
1022 if (!viewport) return;
1023 const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1024 viewport.scrollBy({
1025 left: direction * Math.max(120, viewport.clientWidth * 0.75),
1026 behavior: reduceMotion ? "auto" : "smooth",
1027 });
1028 };
1029
1030 const addSurfaceActions = [
1031 {
1032 label: "Browser",
1033 icon: Globe2,
1034 shortcut: "B",
1035 available: props.browserAvailable,
1036 disabledReason: SURFACE_DISABLED_REASONS.browser,
1037 onClick: props.onAddBrowser,
1038 },
1039 {
1040 label: "Terminal",
1041 icon: TerminalSquare,
1042 shortcut: "T",
1043 available: props.terminalAvailable,
1044 disabledReason: SURFACE_DISABLED_REASONS.terminal,
1045 onClick: props.onAddTerminal,
1046 },
1047 {
1048 label: "Files",
1049 icon: Files,
1050 shortcut: "F",
1051 available: props.filesAvailable,
1052 disabledReason: SURFACE_DISABLED_REASONS.files,
1053 onClick: props.onAddFiles,
1054 },
1055 {
1056 label: "Diff",
1057 icon: FileDiff,
1058 shortcut: "D",
1059 available: props.diffAvailable,
1060 disabledReason: SURFACE_DISABLED_REASONS.diff,
1061 onClick: props.onAddDiff,
1062 },
1063 {
1064 label: "Pull request",
1065 icon: PullRequestGlyph.pullRequest,
1066 shortcut: "P",
1067 available: props.pullRequestAvailable,
1068 disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
1069 onClick: props.onAddPullRequest,
1070 },
1071 {
1072 label: "Linked pull requests",
1073 icon: PullRequestGlyph.link,
1074 shortcut: "L",
1075 available: props.pullRequestsAvailable,
1076 disabledReason: SURFACE_DISABLED_REASONS.pullRequests,
1077 onClick: props.onAddPullRequests,
1078 },
1079 {
1080 label: "Device",
1081 icon: Smartphone,
1082 shortcut: "M",
1083 available: props.deviceAvailable,
1084 disabledReason: SURFACE_DISABLED_REASONS.device,
1085 onClick: props.onAddDevice,
1086 },
1087 ] as const;
1088
1089 const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
1090 const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent);
1091 if (!action) return;
1092 event.preventDefault();
1093 event.stopPropagation();
1094 setAddSurfaceMenuOpen(false);
1095 action.onClick();
1096 };
1097
1098 const handleTabContextMenu = async (event: ReactMouseEvent, surface: RightPanelSurface) => {
1099 event.preventDefault();
1100 event.stopPropagation();
1101
1102 const api = readLocalApi();
1103 if (!api) return;
1104
1105 const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
1106 if (surfaceIndex < 0) return;
1107
1108 const items: ContextMenuItem<TabContextMenuAction>[] = [];
1109 if (surface.kind === "device" && props.onRenameDevice)
1110 items.push({ id: "rename", label: "Rename" });
1111 if (surface.kind === "file" && surface.attachment === undefined) {
1112 items.push({ id: "copy-path", label: "Copy path" });
1113 }
1114 const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
1115 const menuOverlay = menuPreviewTabId ? (props.desktopByTabId[menuPreviewTabId] ?? null) : null;
1116 const menuMuted = menuOverlay?.audioMuted ?? false;
1117 if (surface.kind === "preview") {
1118 items.push({
1119 id: "toggle-mute",
1120 ...tabMuteMenuItem({
1121 overlay: menuOverlay,
1122 canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined,
1123 }),
1124 });
1125 }
1126 items.push(
1127 { id: "close", label: "Close" },
1128 {
1129 id: "close-others",
1130 label: "Close others",
1131 disabled: props.surfaces.length <= 1,
1132 },
1133 {
1134 id: "close-to-right",
1135 label: "Close to the right",
1136 disabled: surfaceIndex >= props.surfaces.length - 1,
1137 },
1138 {
1139 id: "close-all",
1140 label: "Close all",
1141 disabled: props.surfaces.length === 0,
1142 },
1143 );
1144
1145 const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
1146 switch (action) {
1147 case "rename":
1148 setRenamingDevice(surface.id);
1149 break;
1150 case "copy-path":
1151 if (surface.kind === "file" && surface.attachment === undefined) {
1152 props.onCopyFilePath(surface.relativePath);
1153 }
1154 break;
1155 case "toggle-mute": {
1156 const runtimeTabId =
1157 menuPreviewTabId && menuOverlay
1158 ? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null)
1159 : null;
1160 if (runtimeTabId) {
1161 void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined);
1162 }
1163 break;
1164 }
1165 case "close":
1166 props.onCloseSurface(surface);
1167 break;
1168 case "close-others":
1169 props.onCloseOtherSurfaces(surface);
1170 break;
1171 case "close-to-right":
1172 props.onCloseSurfacesToRight(surface);
1173 break;
1174 case "close-all":
1175 props.onCloseAllSurfaces();
1176 break;
1177 case null:
1178 break;
1179 }
1180 };
1181 const handleTabAuxClick = (event: ReactMouseEvent, surface: RightPanelSurface) => {
1182 if (event.button !== 1) return;
1183 event.preventDefault();
1184 event.stopPropagation();
1185 props.onCloseSurface(surface);
1186 };
1187 // Every tab receives these. Parents pass fresh closures on each render, so
1188 // stable forwarders keep a tab's props equal unless its own surface changed.
1189 const onActivateTab = useStableCallback(props.onActivate);
1190 const onCloseTab = useStableCallback(props.onCloseSurface);
1191 const onTabAuxClick = useStableCallback(handleTabAuxClick);
1192 const onTabContextMenu = useStableCallback(
1193 (event: ReactMouseEvent, surface: RightPanelSurface) => {
1194 void handleTabContextMenu(event, surface);
1195 },
1196 );
1197 const onStartRenameTab = useStableCallback((surfaceId: string) => setRenamingDevice(surfaceId));
1198 const onFinishRenameTab = useStableCallback((surfaceId: string, title: string) => {
1199 props.onRenameDevice?.(surfaceId, title);
1200 setRenamingDevice(null);
1201 });
1202
1203 useEffect(() => {
1204 if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
1205 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
1206 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
1207 }, [props.activeSurfaceId, tabScrollState.hasOverflow]);
1208
1209 useEffect(() => {
1210 const viewport = tabScrollViewport(tabListRef.current);
1211 if (!viewport) return;
1212
1213 const content = viewport.firstElementChild;
1214 const stopObserving = observeResize(
1215 content ? [viewport, content] : viewport,
1216 updateTabScrollState,
1217 );
1218 viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
1219 updateTabScrollState();
1220
1221 return () => {
1222 stopObserving();
1223 viewport.removeEventListener("scroll", updateTabScrollState);
1224 };
1225 }, [updateTabScrollState]);
1226
1227 useEffect(() => {
1228 const viewport = tabScrollViewport(tabListRef.current);
1229 if (!viewport) return;
1230
1231 const handleWheel = (event: WheelEvent) => {
1232 if (event.ctrlKey) return;
1233 let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
1234 if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16;
1235 if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth;
1236 if (delta === 0) return;
1237
1238 const previousScrollLeft = viewport.scrollLeft;
1239 viewport.scrollLeft += delta;
1240 if (viewport.scrollLeft === previousScrollLeft) return;
1241 event.preventDefault();
1242 updateTabScrollState();
1243 };
1244
1245 viewport.addEventListener("wheel", handleWheel, { passive: false });
1246 return () => viewport.removeEventListener("wheel", handleWheel);
1247 }, [updateTabScrollState]);
1248
1249 return (
1250 <PreviewPanelShell
1251 mode={props.mode}
1252 {...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
1253 {...(props.open !== undefined ? { open: props.open } : {})}
1254 {...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
1255 {...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
1256 {...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
1257 >
1258 <div
1259 className={cn(
1260 "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1 pl-2",
1261 props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
1262 ownsDesktopTitleBar && "drag-region",
1263 ownsDesktopTitleBar && "wco:pr-(--workspace-native-controls-inset)",
1264 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
1265 )}
1266 data-right-panel-tabbar
1267 >
1268 <ScrollArea
1269 radius="none"
1270 ref={tabListRef}
1271 hideScrollbars
1272 scrollFade
1273 className="min-w-0 flex-1"
1274 data-right-panel-tab-list
1275 >
1276 <div className="flex h-full w-max min-w-full items-center gap-1">
1277 <SortableTabList surfaces={props.surfaces} onMove={props.onMoveSurface}>
1278 {props.surfaces.map((surface) => {
1279 const previewTabId = previewTabIdOf(surface, props.previewSessions);
1280 const favicon = previewFaviconOf(
1281 surface,
1282 props.previewSessions,
1283 props.desktopByTabId,
1284 );
1285 return (
1286 <RightPanelTab
1287 key={surface.id}
1288 surface={surface}
1289 dragDisabled={!props.onMoveSurface || renamingDevice === surface.id}
1290 active={surface.id === props.activeSurfaceId}
1291 pending={props.pendingSurfaceIds.has(surface.id)}
1292 title={surfaceTitle(surface, props.previewSessions, props.terminalLabelsById)}
1293 audio={tabAudioState(
1294 previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null,
1295 )}
1296 audioRuntimeTabId={
1297 previewTabId ? (props.previewRuntimeTabId?.(previewTabId) ?? null) : null
1298 }
1299 previewUrl={favicon.url}
1300 previewCapturedUrl={favicon.capturedUrl}
1301 theme={resolvedTheme}
1302 environmentId={props.environmentId}
1303 pullRequestStatusSeed={props.pullRequestStatusSeeds?.[surface.id]}
1304 renaming={renamingDevice === surface.id}
1305 canRename={props.onRenameDevice !== undefined}
1306 ownsDesktopTitleBar={ownsDesktopTitleBar}
1307 onActivate={onActivateTab}
1308 onClose={onCloseTab}
1309 onAuxClick={onTabAuxClick}
1310 onContextMenu={onTabContextMenu}
1311 onStartRename={onStartRenameTab}
1312 onFinishRename={onFinishRenameTab}
1313 />
1314 );
1315 })}
1316 </SortableTabList>
1317 {props.open !== false ? (
1318 <Menu open={addSurfaceMenuOpen} onOpenChange={setAddSurfaceMenuOpen}>
1319 <MenuTrigger
1320 ref={addSurfaceTriggerRef}
1321 render={
1322 <Button
1323 aria-label="Add panel surface"
1324 className="shrink-0"
1325 size="icon-xs"
1326 variant="ghost-muted"
1327 />
1328 }
1329 >
1330 <Plus className="size-3.5" />
1331 </MenuTrigger>
1332 <MenuPopup
1333 align="start"
1334 side="bottom"
1335 sideOffset={6}
1336 onKeyDownCapture={handleAddSurfaceMenuKeyDown}
1337 >
1338 {addSurfaceActions.map((action) => {
1339 const Icon = action.icon;
1340 if (action.label === "Browser" && action.available) {
1341 return (
1342 <MenuSub key={action.label}>
1343 <MenuSubTrigger
1344 className="[&>svg:last-child]:ms-0"
1345 aria-keyshortcuts={action.shortcut}
1346 onClick={(event) => {
1347 const pointerType =
1348 "pointerType" in event.nativeEvent &&
1349 typeof event.nativeEvent.pointerType === "string"
1350 ? event.nativeEvent.pointerType
1351 : undefined;
1352 if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType))
1353 return;
1354 setAddSurfaceMenuOpen(false);
1355 action.onClick();
1356 }}
1357 >
1358 <Icon />
1359 {action.label}
1360 <MenuShortcut>{action.shortcut}</MenuShortcut>
1361 </MenuSubTrigger>
1362 <MenuSubPopup className="max-w-56">
1363 {browserProfiles.map((profile) => (
1364 <MenuItem
1365 key={profile.id}
1366 onClick={() => props.onAddBrowserInProfile(profile.id)}
1367 >
1368 <span className="min-w-0 truncate">{profile.name}</span>
1369 </MenuItem>
1370 ))}
1371 </MenuSubPopup>
1372 </MenuSub>
1373 );
1374 }
1375 return (
1376 <SurfaceMenuItem
1377 key={action.label}
1378 available={action.available}
1379 disabledReason={action.disabledReason}
1380 shortcut={action.shortcut}
1381 onClick={action.onClick}
1382 >
1383 <Icon />
1384 {action.label}
1385 </SurfaceMenuItem>
1386 );
1387 })}
1388 </MenuPopup>
1389 </Menu>
1390 ) : null}
1391 </div>
1392 </ScrollArea>
1393 {tabScrollState.hasOverflow ? (
1394 <div
1395 className="flex shrink-0 items-center gap-0.5 [-webkit-app-region:no-drag]"
1396 role="group"
1397 aria-label="Scroll panel tabs"
1398 >
1399 <Tooltip>
1400 <TooltipTrigger
1401 render={
1402 <span className="inline-flex">
1403 <Button
1404 aria-label="Scroll tabs left"
1405 disabled={!tabScrollState.canScrollLeft}
1406 onClick={() => scrollTabs(-1)}
1407 size="icon-xs"
1408 variant="ghost"
1409 >
1410 <ChevronLeft />
1411 </Button>
1412 </span>
1413 }
1414 />
1415 <TooltipPopup>Scroll tabs left</TooltipPopup>
1416 </Tooltip>
1417 <Tooltip>
1418 <TooltipTrigger
1419 render={
1420 <span className="inline-flex">
1421 <Button
1422 aria-label="Scroll tabs right"
1423 disabled={!tabScrollState.canScrollRight}
1424 onClick={() => scrollTabs(1)}
1425 size="icon-xs"
1426 variant="ghost"
1427 >
1428 <ChevronRight />
1429 </Button>
1430 </span>
1431 }
1432 />
1433 <TooltipPopup>Scroll tabs right</TooltipPopup>
1434 </Tooltip>
1435 </div>
1436 ) : null}
1437 {props.layoutControls}
1438 {ownsDesktopTitleBar && !props.layoutControls ? (
1439 <span aria-hidden className="hidden w-24 shrink-0 wco:block" />
1440 ) : null}
1441 {ownsDesktopTitleBar ? (
1442 <span
1443 aria-hidden
1444 className="pointer-events-none fixed top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] h-[var(--workspace-topbar-height)] w-28 [-webkit-app-region:no-drag]"
1445 />
1446 ) : null}
1447 </div>
1448 <div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
1449 {props.activeSurfaceId === null ? (
1450 <RightPanelEmptyState
1451 onAddBrowser={props.onAddBrowser}
1452 onAddBrowserInProfile={props.onAddBrowserInProfile}
1453 browserProfiles={browserProfiles}
1454 onAddTerminal={props.onAddTerminal}
1455 onAddDiff={props.onAddDiff}
1456 onAddFiles={props.onAddFiles}
1457 onAddPullRequest={props.onAddPullRequest}
1458 onAddPullRequests={props.onAddPullRequests}
1459 onAddDevice={props.onAddDevice}
1460 browserAvailable={props.browserAvailable}
1461 terminalAvailable={props.terminalAvailable}
1462 diffAvailable={props.diffAvailable}
1463 filesAvailable={props.filesAvailable}
1464 pullRequestAvailable={props.pullRequestAvailable}
1465 pullRequestsAvailable={props.pullRequestsAvailable}
1466 deviceAvailable={props.deviceAvailable}
1467 />
1468 ) : (
1469 props.children
1470 )}
1471 </div>
1472 </PreviewPanelShell>
1473 );
1474}
1475
1476function DeviceTabTooltip(props: {
1477 surface: Extract<RightPanelSurface, { kind: "device" }>;
1478 environmentId: EnvironmentId | null;
1479 title: string;
1480}) {
1481 const target = props.surface.target;
1482 const { state } = useDeviceState(target ? props.environmentId : null);
1483 const device = target
1484 ? state.devices.find((entry) => entry.hostId === target.hostId && entry.id === target.deviceId)
1485 : undefined;
1486 const host = target ? state.hosts.find((entry) => entry.id === target.hostId) : undefined;
1487 return (
1488 <div className="flex flex-col gap-0.5">
1489 <span>{props.title}</span>
1490 {target ? (
1491 <span className="text-muted-foreground">
1492 {host?.label ?? "Device host"} ·{" "}
1493 {device?.version ?? (target.platform === "ios" ? "iOS" : "Android")}
1494 </span>
1495 ) : null}
1496 </div>
1497 );
1498}