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

RightPanelTabs.tsx

1,473 lines51.6 KB

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