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

RightPanelTabs.tsx

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