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