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

RightPanelTabs.tsx

1,443 lines53.5 KB

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