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

RightPanelTabs.tsx

1,426 lines50.8 KB

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