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

RightPanelTabs.tsx

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