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

RightPanelTabs.tsx

1,481 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 = () => {
985 const viewport = tabScrollViewport(tabListRef.current);
986 if (!viewport) return;
987​
988 const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
989 const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
990 const canScrollRight =
991 hasOverflow &&
992 viewport.scrollLeft + viewport.clientWidth < viewport.scrollWidth - TAB_SCROLL_EDGE_TOLERANCE;
993 setTabScrollState((current) => {
994 if (
995 current.hasOverflow === hasOverflow &&
996 current.canScrollLeft === canScrollLeft &&
997 current.canScrollRight === canScrollRight
998 ) {
999 return current;
1001 return { hasOverflow, canScrollLeft, canScrollRight };
1002 });
1003 };
1004​
1005 const scrollTabs = (direction: -1 | 1) => {
1006 const viewport = tabScrollViewport(tabListRef.current);
1007 if (!viewport) return;
1008 const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1009 viewport.scrollBy({
1010 left: direction * Math.max(120, viewport.clientWidth * 0.75),
1011 behavior: reduceMotion ? "auto" : "smooth",
1012 });
1013 };
1014​
1015 const addSurfaceActions = [
1017 label: "Browser",
1018 icon: Globe2,
1019 shortcut: "B",
1020 available: props.browserAvailable,
1021 disabledReason: SURFACE_DISABLED_REASONS.browser,
1022 onClick: props.onAddBrowser,
1023 },
1025 label: "Terminal",
1026 icon: TerminalSquare,
1027 shortcut: "T",
1028 available: props.terminalAvailable,
1029 disabledReason: SURFACE_DISABLED_REASONS.terminal,
1030 onClick: props.onAddTerminal,
1031 },
1033 label: "Files",
1034 icon: Files,
1035 shortcut: "F",
1036 available: props.filesAvailable,
1037 disabledReason: SURFACE_DISABLED_REASONS.files,
1038 onClick: props.onAddFiles,
1039 },
1041 label: "Diff",
1042 icon: FileDiff,
1043 shortcut: "D",
1044 available: props.diffAvailable,
1045 disabledReason: SURFACE_DISABLED_REASONS.diff,
1046 onClick: props.onAddDiff,
1047 },
1049 label: "Pull request",
1050 icon: PullRequestGlyph.pullRequest,
1051 shortcut: "P",
1052 available: props.pullRequestAvailable,
1053 disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
1054 onClick: props.onAddPullRequest,
1055 },
1057 label: "Linked pull requests",
1058 icon: PullRequestGlyph.link,
1059 shortcut: "L",
1060 available: props.pullRequestsAvailable,
1061 disabledReason: SURFACE_DISABLED_REASONS.pullRequests,
1062 onClick: props.onAddPullRequests,
1063 },
1065 label: "Device",
1066 icon: Smartphone,
1067 shortcut: "M",
1068 available: props.deviceAvailable,
1069 disabledReason: SURFACE_DISABLED_REASONS.device,
1070 onClick: props.onAddDevice,
1071 },
1072 ] as const;
1073​
1074 const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
1075 const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent);
1076 if (!action) return;
1077 event.preventDefault();
1078 event.stopPropagation();
1079 setAddSurfaceMenuOpen(false);
1080 action.onClick();
1081 };
1082​
1083 const handleTabContextMenu = async (event: ReactMouseEvent, surface: RightPanelSurface) => {
1084 event.preventDefault();
1085 event.stopPropagation();
1086​
1087 const api = readLocalApi();
1088 if (!api) return;
1089​
1090 const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
1091 if (surfaceIndex < 0) return;
1092​
1093 const items: ContextMenuItem<TabContextMenuAction>[] = [];
1094 if (surface.kind === "device" && props.onRenameDevice)
1095 items.push({ id: "rename", label: "Rename" });
1096 if (surface.kind === "file" && surface.attachment === undefined) {
1097 items.push({ id: "copy-path", label: "Copy path" });
1099 const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
1100 const menuOverlay = menuPreviewTabId ? (props.desktopByTabId[menuPreviewTabId] ?? null) : null;
1101 const menuMuted = menuOverlay?.audioMuted ?? false;
1102 if (surface.kind === "preview") {
1103 items.push({
1104 id: "toggle-mute",
1105 ...tabMuteMenuItem({
1106 overlay: menuOverlay,
1107 canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined,
1108 }),
1109 });
1111 items.push(
1112 { id: "close", label: "Close" },
1114 id: "close-others",
1115 label: "Close others",
1116 disabled: props.surfaces.length <= 1,
1117 },
1119 id: "close-to-right",
1120 label: "Close to the right",
1121 disabled: surfaceIndex >= props.surfaces.length - 1,
1122 },
1124 id: "close-all",
1125 label: "Close all",
1126 disabled: props.surfaces.length === 0,
1127 },
1128 );
1129​
1130 const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
1131 switch (action) {
1132 case "rename":
1133 setRenamingDevice(surface.id);
1134 break;
1135 case "copy-path":
1136 if (surface.kind === "file" && surface.attachment === undefined) {
1137 props.onCopyFilePath(surface.relativePath);
1139 break;
1140 case "toggle-mute": {
1141 const runtimeTabId =
1142 menuPreviewTabId && menuOverlay
1143 ? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null)
1144 : null;
1145 if (runtimeTabId) {
1146 void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined);
1148 break;
1150 case "close":
1151 props.onCloseSurface(surface);
1152 break;
1153 case "close-others":
1154 props.onCloseOtherSurfaces(surface);
1155 break;
1156 case "close-to-right":
1157 props.onCloseSurfacesToRight(surface);
1158 break;
1159 case "close-all":
1160 props.onCloseAllSurfaces();
1161 break;
1162 case null:
1163 break;
1165 };
1166 const handleTabAuxClick = (event: ReactMouseEvent, surface: RightPanelSurface) => {
1167 if (event.button !== 1) return;
1168 event.preventDefault();
1169 event.stopPropagation();
1170 props.onCloseSurface(surface);
1171 };
1172 const onActivateTab = useStableCallback(props.onActivate);
1173 const onCloseTab = useStableCallback(props.onCloseSurface);
1174 const onTabAuxClick = useStableCallback(handleTabAuxClick);
1175 const onTabContextMenu = useStableCallback(
1176 (event: ReactMouseEvent, surface: RightPanelSurface) => {
1177 void handleTabContextMenu(event, surface);
1178 },
1179 );
1180 const onStartRenameTab = useStableCallback((surfaceId: string) => setRenamingDevice(surfaceId));
1181 const onFinishRenameTab = useStableCallback((surfaceId: string, title: string) => {
1182 props.onRenameDevice?.(surfaceId, title);
1183 setRenamingDevice(null);
1184 });
1185​
1186 useEffect(() => {
1187 if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
1188 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
1189 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
1190 }, [props.activeSurfaceId, tabScrollState.hasOverflow]);
1191​
1192 useEffect(() => {
1193 const viewport = tabScrollViewport(tabListRef.current);
1194 if (!viewport) return;
1195​
1196 const content = viewport.firstElementChild;
1197 const stopObserving = observeResize(
1198 content ? [viewport, content] : viewport,
1199 updateTabScrollState,
1200 );
1201 viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
1202 updateTabScrollState();
1203​
1204 return () => {
1205 stopObserving();
1206 viewport.removeEventListener("scroll", updateTabScrollState);
1207 };
1208 }, [updateTabScrollState]);
1209​
1210 useEffect(() => {
1211 const viewport = tabScrollViewport(tabListRef.current);
1212 if (!viewport) return;
1213​
1214 const handleWheel = (event: WheelEvent) => {
1215 if (event.ctrlKey) return;
1216 let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
1217 if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16;
1218 if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth;
1219 if (delta === 0) return;
1220​
1221 const previousScrollLeft = viewport.scrollLeft;
1222 viewport.scrollLeft += delta;
1223 if (viewport.scrollLeft === previousScrollLeft) return;
1224 event.preventDefault();
1225 updateTabScrollState();
1226 };
1227​
1228 viewport.addEventListener("wheel", handleWheel, { passive: false });
1229 return () => viewport.removeEventListener("wheel", handleWheel);
1230 }, [updateTabScrollState]);
1231​
1232 return (
1233 <PreviewPanelShell
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 } : {})}
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
1251 <ScrollArea
1252 radius="none"
1253 ref={tabListRef}
1254 hideScrollbars
1255 scrollFade
1256 className="min-w-0 flex-1"
1257 data-right-panel-tab-list
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
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 />
1313 <Plus className="size-3.5" />
1314 </MenuTrigger>
1315 <MenuPopup
1316 align="start"
1317 side="bottom"
1318 sideOffset={6}
1319 onKeyDownCapture={handleAddSurfaceMenuKeyDown}
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 }}
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)}
1351 <span className="min-w-0 truncate">{profile.name}</span>
1352 </MenuItem>
1353 ))}
1354 </MenuSubPopup>
1355 </MenuSub>
1356 );
1358 return (
1359 <SurfaceMenuItem
1360 key={action.label}
1361 available={action.available}
1362 disabledReason={action.disabledReason}
1363 shortcut={action.shortcut}
1364 onClick={action.onClick}
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"
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"
1393 <ChevronLeft />
1394 </Button>
1395 </span>
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"
1411 <ChevronRight />
1412 </Button>
1413 </span>
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 );
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 );