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

RightPanelTabs.tsx

1,498 lines52.4 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​
96export interface 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​
161function shouldOpenDefaultBrowserProfileFromMenuClick(pointerType: string | undefined): boolean {
162 return pointerType !== "touch";
164​
165const SURFACE_DISABLED_REASONS = {
166 browser: "Browser previews are only available in the T3 Code desktop app.",
167 terminal: "Terminal surfaces are only available from a project thread.",
168 files: "Files are only available when a project is open.",
169 diff: "Diff is only available for server threads in Git repositories.",
170 pullRequest: "This thread's branch has no pull request yet.",
171 pullRequests: "No linked pull requests are available for this thread.",
172 device: "Devices are only available from a thread.",
173} as const;
174​
175// Closed keepMounted popups must stop blocking shortcuts once their exit transition ends.
176const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
177 "dialog-popup",
178 "alert-dialog-popup",
179 "command-dialog-popup",
180 "menu-popup",
181 "select-popup",
182 "popover-popup",
183 "combobox-popup",
184 "autocomplete-popup",
186 .map((slot) => `[data-slot="${slot}"]:is([data-open],[data-ending-style])`)
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 */
228function 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​
803// Chromium on Linux only suppresses primary-selection paste when mouseup is cancelled.
804function preventTabMiddleButtonDefault(event: ReactMouseEvent) {
805 if (event.button !== 1) return;
806 event.preventDefault();
808​
809// One tab owns its sortable state and receives only its own values, so the
810// compiled subtree is reused unless this tab's surface, title or state changed.
811// The handlers must be stable: the tab list re-renders on every parent render.
812function RightPanelTab(
813 props: RightPanelTabHandlers & {
814 surface: RightPanelSurface;
815 dragDisabled: boolean;
816 active: boolean;
817 pending: boolean;
818 title: string;
819 audio: TabAudioState;
820 audioRuntimeTabId: string | null;
821 previewUrl: string | null;
822 previewCapturedUrl: string | null;
823 theme: "light" | "dark";
824 environmentId: EnvironmentId | null;
825 pullRequestStatusSeed: PullRequestTabStatusSeed | undefined;
826 renaming: boolean;
827 canRename: boolean;
828 ownsDesktopTitleBar: boolean;
829 },
830) {
831 const {
832 surface,
833 title,
834 audio,
835 audioRuntimeTabId,
836 onActivate,
837 onClose,
838 onAuxClick,
839 onContextMenu,
840 onStartRename,
841 onFinishRename,
842 } = props;
843 const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
844 id: surface.id,
845 disabled: props.dragDisabled,
846 });
847 const content = (
848 <>
849 <PanelTabCloseButton label={`Close ${title}`} onClick={() => onClose(surface)}>
850 <SurfaceIcon
851 surface={surface}
852 previewUrl={props.previewUrl}
853 previewCapturedUrl={props.previewCapturedUrl}
854 theme={props.theme}
855 environmentId={props.environmentId}
856 pullRequestStatusSeed={props.pullRequestStatusSeed}
857 />
858 {props.pending ? (
859 <span
860 className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
861 aria-hidden
862 />
863 ) : null}
864 </PanelTabCloseButton>
865 {audio === "none" || !audioRuntimeTabId ? null : (
866 <Tooltip>
867 <TooltipTrigger
868 render={
869 <button
870 type="button"
871 className="cursor-pointer flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
872 aria-label={audio === "muted" ? `Unmute ${title}` : `Mute ${title}`}
873 onClick={(event) => {
874 event.stopPropagation();
875 void previewBridge
876 ?.setAudioMuted(audioRuntimeTabId, audio !== "muted")
877 .catch(() => undefined);
878 }}
879 >
880 <MorphIcon className="size-3" icon={audio === "muted" ? VolumeOff : Volume2} />
881 </button>
882 }
883 />
884 <TooltipPopup>{audio === "muted" ? "Unmute tab" : "Mute tab"}</TooltipPopup>
885 </Tooltip>
886 )}
887 {props.renaming ? (
888 <input
889 aria-label="Device tab name"
890 className="w-24 min-w-0 rounded-sm bg-background px-1 outline-none ring-1 ring-inset ring-ring"
891 defaultValue={title}
892 ref={(element) => {
893 element?.focus();
894 element?.select();
895 }}
896 onBlur={(event) => onFinishRename(surface.id, event.currentTarget.value)}
897 onKeyDown={(event) => {
898 event.stopPropagation();
899 if (event.key === "Enter") event.currentTarget.blur();
900 if (event.key === "Escape") {
901 event.currentTarget.value = title;
902 event.currentTarget.blur();
903 }
904 }}
905 />
906 ) : (
907 <Tooltip>
908 <TooltipTrigger
909 render={
910 <button
911 type="button"
912 onDoubleClick={() => {
913 if (surface.kind === "device" && props.canRename) onStartRename(surface.id);
914 }}
915 className="cursor-pointer flex min-w-0 items-center"
916 onClick={() => onActivate(surface)}
917 >
918 <span className="truncate">{title}</span>
919 </button>
920 }
921 />
922 <TooltipPopup>
923 {surface.kind === "device" ? (
924 <DeviceTabTooltip
925 surface={surface}
926 environmentId={props.environmentId}
927 title={title}
928 />
929 ) : (
930 title
931 )}
932 </TooltipPopup>
933 </Tooltip>
934 )}
935 </>
936 );
937 return (
938 <div
939 data-active-tab={props.active}
940 onMouseDown={preventTabMiddleButtonDefault}
941 onMouseUp={preventTabMiddleButtonDefault}
942 onAuxClick={(event) => onAuxClick(event, surface)}
943 onContextMenu={(event) => onContextMenu(event, surface)}
944 {...listeners}
945 ref={setNodeRef}
946 style={{ transform: CSS.Translate.toString(transform), transition }}
947 className={cn(
948 "cursor-pointer group/tab flex h-6 max-w-36 shrink-0 items-center gap-0.5 rounded-md pr-2 pl-1.5 text-xs",
949 props.ownsDesktopTitleBar && "[-webkit-app-region:no-drag]",
950 props.active
951 ? "bg-accent text-foreground"
952 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
953 isDragging && "relative z-10",
954 )}
955 >
956 {content}
957 </div>
958 );
960​
961export function RightPanelTabs(props: RightPanelTabsProps) {
962 const ownsDesktopTitleBar = isElectron && props.mode === "inline";
963 const browserProfiles = useBrowserDefaults().profiles;
964 const { resolvedTheme } = useTheme();
965 const tabListRef = useRef<HTMLDivElement>(null);
966 const addSurfaceTriggerRef = useRef<HTMLButtonElement>(null);
967 const [renamingDevice, setRenamingDevice] = useState<string | null>(null);
968 const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
969 const [tabScrollState, setTabScrollState] = useState({
970 hasOverflow: false,
971 canScrollLeft: false,
972 canScrollRight: false,
973 });
974​
975 if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false);
976​
977 const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => {
978 if (event.defaultPrevented || event.isComposing) return;
979 if (
980 resolveShortcutCommand(event, props.keybindings, {
981 context: { ...props.getShortcutContext(), rightPanelOpen: true },
982 }) !== "rightPanel.new"
983 )
984 return;
985 if (!addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
986 event.preventDefault();
987 event.stopPropagation();
988 if (!event.repeat) {
989 addSurfaceTriggerRef.current?.focus();
990 setAddSurfaceMenuOpen(true);
991 }
992 });
993 useEffect(() => {
994 if (props.open === false) return;
995 document.addEventListener("keydown", onNewSurfaceKeyDown, true);
996 return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true);
997 }, [props.open]);
998​
999 const updateTabScrollState = () => {
1000 const viewport = tabScrollViewport(tabListRef.current);
1001 if (!viewport) return;
1002​
1003 const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
1004 const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
1005 const canScrollRight =
1006 hasOverflow &&
1007 viewport.scrollLeft + viewport.clientWidth < viewport.scrollWidth - TAB_SCROLL_EDGE_TOLERANCE;
1008 setTabScrollState((current) => {
1009 if (
1010 current.hasOverflow === hasOverflow &&
1011 current.canScrollLeft === canScrollLeft &&
1012 current.canScrollRight === canScrollRight
1013 ) {
1014 return current;
1016 return { hasOverflow, canScrollLeft, canScrollRight };
1017 });
1018 };
1019​
1020 const scrollTabs = (direction: -1 | 1) => {
1021 const viewport = tabScrollViewport(tabListRef.current);
1022 if (!viewport) return;
1023 const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1024 viewport.scrollBy({
1025 left: direction * Math.max(120, viewport.clientWidth * 0.75),
1026 behavior: reduceMotion ? "auto" : "smooth",
1027 });
1028 };
1029​
1030 const addSurfaceActions = [
1032 label: "Browser",
1033 icon: Globe2,
1034 shortcut: "B",
1035 available: props.browserAvailable,
1036 disabledReason: SURFACE_DISABLED_REASONS.browser,
1037 onClick: props.onAddBrowser,
1038 },
1040 label: "Terminal",
1041 icon: TerminalSquare,
1042 shortcut: "T",
1043 available: props.terminalAvailable,
1044 disabledReason: SURFACE_DISABLED_REASONS.terminal,
1045 onClick: props.onAddTerminal,
1046 },
1048 label: "Files",
1049 icon: Files,
1050 shortcut: "F",
1051 available: props.filesAvailable,
1052 disabledReason: SURFACE_DISABLED_REASONS.files,
1053 onClick: props.onAddFiles,
1054 },
1056 label: "Diff",
1057 icon: FileDiff,
1058 shortcut: "D",
1059 available: props.diffAvailable,
1060 disabledReason: SURFACE_DISABLED_REASONS.diff,
1061 onClick: props.onAddDiff,
1062 },
1064 label: "Pull request",
1065 icon: PullRequestGlyph.pullRequest,
1066 shortcut: "P",
1067 available: props.pullRequestAvailable,
1068 disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
1069 onClick: props.onAddPullRequest,
1070 },
1072 label: "Linked pull requests",
1073 icon: PullRequestGlyph.link,
1074 shortcut: "L",
1075 available: props.pullRequestsAvailable,
1076 disabledReason: SURFACE_DISABLED_REASONS.pullRequests,
1077 onClick: props.onAddPullRequests,
1078 },
1080 label: "Device",
1081 icon: Smartphone,
1082 shortcut: "M",
1083 available: props.deviceAvailable,
1084 disabledReason: SURFACE_DISABLED_REASONS.device,
1085 onClick: props.onAddDevice,
1086 },
1087 ] as const;
1088​
1089 const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
1090 const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent);
1091 if (!action) return;
1092 event.preventDefault();
1093 event.stopPropagation();
1094 setAddSurfaceMenuOpen(false);
1095 action.onClick();
1096 };
1097​
1098 const handleTabContextMenu = async (event: ReactMouseEvent, surface: RightPanelSurface) => {
1099 event.preventDefault();
1100 event.stopPropagation();
1101​
1102 const api = readLocalApi();
1103 if (!api) return;
1104​
1105 const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
1106 if (surfaceIndex < 0) return;
1107​
1108 const items: ContextMenuItem<TabContextMenuAction>[] = [];
1109 if (surface.kind === "device" && props.onRenameDevice)
1110 items.push({ id: "rename", label: "Rename" });
1111 if (surface.kind === "file" && surface.attachment === undefined) {
1112 items.push({ id: "copy-path", label: "Copy path" });
1114 const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
1115 const menuOverlay = menuPreviewTabId ? (props.desktopByTabId[menuPreviewTabId] ?? null) : null;
1116 const menuMuted = menuOverlay?.audioMuted ?? false;
1117 if (surface.kind === "preview") {
1118 items.push({
1119 id: "toggle-mute",
1120 ...tabMuteMenuItem({
1121 overlay: menuOverlay,
1122 canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined,
1123 }),
1124 });
1126 items.push(
1127 { id: "close", label: "Close" },
1129 id: "close-others",
1130 label: "Close others",
1131 disabled: props.surfaces.length <= 1,
1132 },
1134 id: "close-to-right",
1135 label: "Close to the right",
1136 disabled: surfaceIndex >= props.surfaces.length - 1,
1137 },
1139 id: "close-all",
1140 label: "Close all",
1141 disabled: props.surfaces.length === 0,
1142 },
1143 );
1144​
1145 const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
1146 switch (action) {
1147 case "rename":
1148 setRenamingDevice(surface.id);
1149 break;
1150 case "copy-path":
1151 if (surface.kind === "file" && surface.attachment === undefined) {
1152 props.onCopyFilePath(surface.relativePath);
1154 break;
1155 case "toggle-mute": {
1156 const runtimeTabId =
1157 menuPreviewTabId && menuOverlay
1158 ? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null)
1159 : null;
1160 if (runtimeTabId) {
1161 void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined);
1163 break;
1165 case "close":
1166 props.onCloseSurface(surface);
1167 break;
1168 case "close-others":
1169 props.onCloseOtherSurfaces(surface);
1170 break;
1171 case "close-to-right":
1172 props.onCloseSurfacesToRight(surface);
1173 break;
1174 case "close-all":
1175 props.onCloseAllSurfaces();
1176 break;
1177 case null:
1178 break;
1180 };
1181 const handleTabAuxClick = (event: ReactMouseEvent, surface: RightPanelSurface) => {
1182 if (event.button !== 1) return;
1183 event.preventDefault();
1184 event.stopPropagation();
1185 props.onCloseSurface(surface);
1186 };
1187 // Every tab receives these. Parents pass fresh closures on each render, so
1188 // stable forwarders keep a tab's props equal unless its own surface changed.
1189 const onActivateTab = useStableCallback(props.onActivate);
1190 const onCloseTab = useStableCallback(props.onCloseSurface);
1191 const onTabAuxClick = useStableCallback(handleTabAuxClick);
1192 const onTabContextMenu = useStableCallback(
1193 (event: ReactMouseEvent, surface: RightPanelSurface) => {
1194 void handleTabContextMenu(event, surface);
1195 },
1196 );
1197 const onStartRenameTab = useStableCallback((surfaceId: string) => setRenamingDevice(surfaceId));
1198 const onFinishRenameTab = useStableCallback((surfaceId: string, title: string) => {
1199 props.onRenameDevice?.(surfaceId, title);
1200 setRenamingDevice(null);
1201 });
1202​
1203 useEffect(() => {
1204 if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
1205 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
1206 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
1207 }, [props.activeSurfaceId, tabScrollState.hasOverflow]);
1208​
1209 useEffect(() => {
1210 const viewport = tabScrollViewport(tabListRef.current);
1211 if (!viewport) return;
1212​
1213 const content = viewport.firstElementChild;
1214 const stopObserving = observeResize(
1215 content ? [viewport, content] : viewport,
1216 updateTabScrollState,
1217 );
1218 viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
1219 updateTabScrollState();
1220​
1221 return () => {
1222 stopObserving();
1223 viewport.removeEventListener("scroll", updateTabScrollState);
1224 };
1225 }, [updateTabScrollState]);
1226​
1227 useEffect(() => {
1228 const viewport = tabScrollViewport(tabListRef.current);
1229 if (!viewport) return;
1230​
1231 const handleWheel = (event: WheelEvent) => {
1232 if (event.ctrlKey) return;
1233 let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
1234 if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16;
1235 if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth;
1236 if (delta === 0) return;
1237​
1238 const previousScrollLeft = viewport.scrollLeft;
1239 viewport.scrollLeft += delta;
1240 if (viewport.scrollLeft === previousScrollLeft) return;
1241 event.preventDefault();
1242 updateTabScrollState();
1243 };
1244​
1245 viewport.addEventListener("wheel", handleWheel, { passive: false });
1246 return () => viewport.removeEventListener("wheel", handleWheel);
1247 }, [updateTabScrollState]);
1248​
1249 return (
1250 <PreviewPanelShell
1251 mode={props.mode}
1252 {...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
1253 {...(props.open !== undefined ? { open: props.open } : {})}
1254 {...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
1255 {...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
1256 {...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
1258 <div
1259 className={cn(
1260 "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1 pl-2",
1261 props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
1262 ownsDesktopTitleBar && "drag-region",
1263 ownsDesktopTitleBar && "wco:pr-(--workspace-native-controls-inset)",
1264 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
1265 )}
1266 data-right-panel-tabbar
1268 <ScrollArea
1269 radius="none"
1270 ref={tabListRef}
1271 hideScrollbars
1272 scrollFade
1273 className="min-w-0 flex-1"
1274 data-right-panel-tab-list
1276 <div className="flex h-full w-max min-w-full items-center gap-1">
1277 <SortableTabList surfaces={props.surfaces} onMove={props.onMoveSurface}>
1278 {props.surfaces.map((surface) => {
1279 const previewTabId = previewTabIdOf(surface, props.previewSessions);
1280 const favicon = previewFaviconOf(
1281 surface,
1282 props.previewSessions,
1283 props.desktopByTabId,
1284 );
1285 return (
1286 <RightPanelTab
1287 key={surface.id}
1288 surface={surface}
1289 dragDisabled={!props.onMoveSurface || renamingDevice === surface.id}
1290 active={surface.id === props.activeSurfaceId}
1291 pending={props.pendingSurfaceIds.has(surface.id)}
1292 title={surfaceTitle(surface, props.previewSessions, props.terminalLabelsById)}
1293 audio={tabAudioState(
1294 previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null,
1295 )}
1296 audioRuntimeTabId={
1297 previewTabId ? (props.previewRuntimeTabId?.(previewTabId) ?? null) : null
1299 previewUrl={favicon.url}
1300 previewCapturedUrl={favicon.capturedUrl}
1301 theme={resolvedTheme}
1302 environmentId={props.environmentId}
1303 pullRequestStatusSeed={props.pullRequestStatusSeeds?.[surface.id]}
1304 renaming={renamingDevice === surface.id}
1305 canRename={props.onRenameDevice !== undefined}
1306 ownsDesktopTitleBar={ownsDesktopTitleBar}
1307 onActivate={onActivateTab}
1308 onClose={onCloseTab}
1309 onAuxClick={onTabAuxClick}
1310 onContextMenu={onTabContextMenu}
1311 onStartRename={onStartRenameTab}
1312 onFinishRename={onFinishRenameTab}
1313 />
1314 );
1315 })}
1316 </SortableTabList>
1317 {props.open !== false ? (
1318 <Menu open={addSurfaceMenuOpen} onOpenChange={setAddSurfaceMenuOpen}>
1319 <MenuTrigger
1320 ref={addSurfaceTriggerRef}
1321 render={
1322 <Button
1323 aria-label="Add panel surface"
1324 className="shrink-0"
1325 size="icon-xs"
1326 variant="ghost-muted"
1327 />
1330 <Plus className="size-3.5" />
1331 </MenuTrigger>
1332 <MenuPopup
1333 align="start"
1334 side="bottom"
1335 sideOffset={6}
1336 onKeyDownCapture={handleAddSurfaceMenuKeyDown}
1338 {addSurfaceActions.map((action) => {
1339 const Icon = action.icon;
1340 if (action.label === "Browser" && action.available) {
1341 return (
1342 <MenuSub key={action.label}>
1343 <MenuSubTrigger
1344 className="[&>svg:last-child]:ms-0"
1345 aria-keyshortcuts={action.shortcut}
1346 onClick={(event) => {
1347 const pointerType =
1348 "pointerType" in event.nativeEvent &&
1349 typeof event.nativeEvent.pointerType === "string"
1350 ? event.nativeEvent.pointerType
1351 : undefined;
1352 if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType))
1353 return;
1354 setAddSurfaceMenuOpen(false);
1355 action.onClick();
1356 }}
1358 <Icon />
1359 {action.label}
1360 <MenuShortcut>{action.shortcut}</MenuShortcut>
1361 </MenuSubTrigger>
1362 <MenuSubPopup className="max-w-56">
1363 {browserProfiles.map((profile) => (
1364 <MenuItem
1365 key={profile.id}
1366 onClick={() => props.onAddBrowserInProfile(profile.id)}
1368 <span className="min-w-0 truncate">{profile.name}</span>
1369 </MenuItem>
1370 ))}
1371 </MenuSubPopup>
1372 </MenuSub>
1373 );
1375 return (
1376 <SurfaceMenuItem
1377 key={action.label}
1378 available={action.available}
1379 disabledReason={action.disabledReason}
1380 shortcut={action.shortcut}
1381 onClick={action.onClick}
1383 <Icon />
1384 {action.label}
1385 </SurfaceMenuItem>
1386 );
1387 })}
1388 </MenuPopup>
1389 </Menu>
1390 ) : null}
1391 </div>
1392 </ScrollArea>
1393 {tabScrollState.hasOverflow ? (
1394 <div
1395 className="flex shrink-0 items-center gap-0.5 [-webkit-app-region:no-drag]"
1396 role="group"
1397 aria-label="Scroll panel tabs"
1399 <Tooltip>
1400 <TooltipTrigger
1401 render={
1402 <span className="inline-flex">
1403 <Button
1404 aria-label="Scroll tabs left"
1405 disabled={!tabScrollState.canScrollLeft}
1406 onClick={() => scrollTabs(-1)}
1407 size="icon-xs"
1408 variant="ghost"
1410 <ChevronLeft />
1411 </Button>
1412 </span>
1414 />
1415 <TooltipPopup>Scroll tabs left</TooltipPopup>
1416 </Tooltip>
1417 <Tooltip>
1418 <TooltipTrigger
1419 render={
1420 <span className="inline-flex">
1421 <Button
1422 aria-label="Scroll tabs right"
1423 disabled={!tabScrollState.canScrollRight}
1424 onClick={() => scrollTabs(1)}
1425 size="icon-xs"
1426 variant="ghost"
1428 <ChevronRight />
1429 </Button>
1430 </span>
1432 />
1433 <TooltipPopup>Scroll tabs right</TooltipPopup>
1434 </Tooltip>
1435 </div>
1436 ) : null}
1437 {props.layoutControls}
1438 {ownsDesktopTitleBar && !props.layoutControls ? (
1439 <span aria-hidden className="hidden w-24 shrink-0 wco:block" />
1440 ) : null}
1441 {ownsDesktopTitleBar ? (
1442 <span
1443 aria-hidden
1444 className="pointer-events-none fixed top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] h-[var(--workspace-topbar-height)] w-28 [-webkit-app-region:no-drag]"
1445 />
1446 ) : null}
1447 </div>
1448 <div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
1449 {props.activeSurfaceId === null ? (
1450 <RightPanelEmptyState
1451 onAddBrowser={props.onAddBrowser}
1452 onAddBrowserInProfile={props.onAddBrowserInProfile}
1453 browserProfiles={browserProfiles}
1454 onAddTerminal={props.onAddTerminal}
1455 onAddDiff={props.onAddDiff}
1456 onAddFiles={props.onAddFiles}
1457 onAddPullRequest={props.onAddPullRequest}
1458 onAddPullRequests={props.onAddPullRequests}
1459 onAddDevice={props.onAddDevice}
1460 browserAvailable={props.browserAvailable}
1461 terminalAvailable={props.terminalAvailable}
1462 diffAvailable={props.diffAvailable}
1463 filesAvailable={props.filesAvailable}
1464 pullRequestAvailable={props.pullRequestAvailable}
1465 pullRequestsAvailable={props.pullRequestsAvailable}
1466 deviceAvailable={props.deviceAvailable}
1467 />
1468 ) : (
1469 props.children
1470 )}
1471 </div>
1472 </PreviewPanelShell>
1473 );
1475​
1476function DeviceTabTooltip(props: {
1477 surface: Extract<RightPanelSurface, { kind: "device" }>;
1478 environmentId: EnvironmentId | null;
1479 title: string;
1480}) {
1481 const target = props.surface.target;
1482 const { state } = useDeviceState(target ? props.environmentId : null);
1483 const device = target
1484 ? state.devices.find((entry) => entry.hostId === target.hostId && entry.id === target.deviceId)
1485 : undefined;
1486 const host = target ? state.hosts.find((entry) => entry.id === target.hostId) : undefined;
1487 return (
1488 <div className="flex flex-col gap-0.5">
1489 <span>{props.title}</span>
1490 {target ? (
1491 <span className="text-muted-foreground">
1492 {host?.label ?? "Device host"} ·{" "}
1493 {device?.version ?? (target.platform === "ios" ? "iOS" : "Android")}
1494 </span>
1495 ) : null}
1496 </div>
1497 );