1525 lines
56 KiB
TypeScript
1525 lines
56 KiB
TypeScript
import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
|
|
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
|
import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";
|
|
import {
|
|
threadPullRequestKeysEqual,
|
|
visibleThreadPullRequests,
|
|
} from "@t3tools/shared/threadPullRequests";
|
|
import type {
|
|
ContextMenuItem,
|
|
EnvironmentId,
|
|
PreviewSessionSnapshot,
|
|
ProjectId,
|
|
PullRequestState,
|
|
ResolvedKeybindingsConfig,
|
|
} from "@t3tools/contracts";
|
|
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
|
|
import {
|
|
closestCenter,
|
|
DndContext,
|
|
type DragEndEvent,
|
|
PointerSensor,
|
|
useSensor,
|
|
useSensors,
|
|
} from "@dnd-kit/core";
|
|
import { restrictToFirstScrollableAncestor, restrictToHorizontalAxis } from "@dnd-kit/modifiers";
|
|
import { horizontalListSortingStrategy, SortableContext, useSortable } from "@dnd-kit/sortable";
|
|
import { CSS } from "@dnd-kit/utilities";
|
|
import {
|
|
Smartphone,
|
|
ChevronDown,
|
|
ChevronLeft,
|
|
ChevronRight,
|
|
FileDiff,
|
|
Files,
|
|
Globe2,
|
|
Plus,
|
|
TerminalSquare,
|
|
} from "lucide-react";
|
|
import { Volume2, VolumeOff } from "lucide";
|
|
import {
|
|
type ComponentProps,
|
|
type KeyboardEvent as ReactKeyboardEvent,
|
|
type MouseEvent as ReactMouseEvent,
|
|
type ReactElement,
|
|
type ReactNode,
|
|
useCallback,
|
|
useEffect,
|
|
useEffectEvent,
|
|
useMemo,
|
|
useRef,
|
|
useState,
|
|
} from "react";
|
|
|
|
import { isElectron } from "~/env";
|
|
import type { DesktopPreviewOverlay } from "~/previewStateStore";
|
|
import type { RightPanelSurface } from "~/rightPanelStore";
|
|
import { cn } from "~/lib/utils";
|
|
import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings";
|
|
import { readLocalApi } from "~/localApi";
|
|
import { Button } from "~/components/ui/button";
|
|
import { MorphIcon } from "~/components/MorphIcon";
|
|
import { AndroidIcon, AppleIcon } from "~/components/Icons";
|
|
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
|
import { Kbd } from "~/components/ui/kbd";
|
|
import {
|
|
Menu,
|
|
MenuItem,
|
|
MenuPopup,
|
|
MenuShortcut,
|
|
MenuSub,
|
|
MenuSubPopup,
|
|
MenuSubTrigger,
|
|
MenuTrigger,
|
|
} from "~/components/ui/menu";
|
|
import { useBrowserDefaults } from "~/browser/browserDefaults";
|
|
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";
|
|
import { faviconUrlForOrigin } from "~/lib/favicon";
|
|
import { useTheme } from "~/hooks/useTheme";
|
|
import { useDeviceState } from "~/state/device";
|
|
import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize";
|
|
import {
|
|
newestPullRequestSummary,
|
|
pullRequestEnvironment,
|
|
useSharedPullRequestSummary,
|
|
} from "~/state/pullRequests";
|
|
import { useEnvironmentQuery } from "~/state/query";
|
|
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
|
|
|
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
|
|
import { FaviconImage } from "./preview/PreviewFaviconIcon";
|
|
import { previewBridge } from "./preview/previewBridge";
|
|
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
|
|
import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
|
|
import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
|
|
import { observeResize } from "~/lib/observeResize";
|
|
|
|
interface RightPanelTabsProps {
|
|
mode: PreviewPanelMode;
|
|
maximized?: boolean;
|
|
open?: boolean;
|
|
keybindings: ResolvedKeybindingsConfig;
|
|
getShortcutContext: () => ShortcutMatchContext;
|
|
/** Forwarded to PreviewPanelShell so this surface persists its own width. */
|
|
widthStorageKey?: string;
|
|
/** Forwarded to PreviewPanelShell as the initial width before a user resize. */
|
|
defaultWidth?: number;
|
|
inlineSize?: PreviewPanelInlineSize;
|
|
layoutControls?: ReactNode;
|
|
surfaces: readonly RightPanelSurface[];
|
|
/** Fallback environment for surfaces that do not carry their own. */
|
|
environmentId: EnvironmentId | null;
|
|
activeSurfaceId: string | null;
|
|
pendingSurfaceIds: ReadonlySet<string>;
|
|
previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
|
|
desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
|
|
/**
|
|
* Maps a server session tab id to the desktop runtime tab id the Electron
|
|
* preview manager is keyed by. Session ids are only unique within one server
|
|
* process, so desktop operations must not be addressed with them.
|
|
*/
|
|
previewRuntimeTabId?: ((tabId: string) => string) | undefined;
|
|
terminalLabelsById: ReadonlyMap<string, string>;
|
|
onActivate: (surface: RightPanelSurface) => void;
|
|
onRenameDevice?: (surfaceId: string, title: string) => void;
|
|
onCloseSurface: (surface: RightPanelSurface) => void;
|
|
onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
|
|
onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
|
|
onCloseAllSurfaces: () => void;
|
|
/** Tabs are draggable only when the owner can persist the new order. */
|
|
onMoveSurface?: (surfaceId: string, toIndex: number) => void;
|
|
onCopyFilePath: (relativePath: string) => void;
|
|
onAddBrowser: () => void;
|
|
/**
|
|
* Separate from `onAddBrowser` on purpose: that one is passed directly as a
|
|
* DOM click handler, and a `(profileId?: string)` signature would silently
|
|
* accept the MouseEvent as a profile id.
|
|
*/
|
|
onAddBrowserInProfile: (profileId: string) => void;
|
|
onAddTerminal: () => void;
|
|
onAddDiff: () => void;
|
|
onAddFiles: () => void;
|
|
onAddPullRequest: () => void;
|
|
onAddPullRequests: () => void;
|
|
onAddDevice: () => void;
|
|
browserAvailable: boolean;
|
|
terminalAvailable: boolean;
|
|
diffAvailable: boolean;
|
|
filesAvailable: boolean;
|
|
pullRequestAvailable: boolean;
|
|
pullRequestsAvailable: boolean;
|
|
deviceAvailable: boolean;
|
|
pullRequestStatusSeeds?: Readonly<Record<string, PullRequestTabStatusSeed>>;
|
|
children: ReactNode;
|
|
}
|
|
|
|
export interface PullRequestTabStatus {
|
|
projectId: string;
|
|
repository: string;
|
|
number: number;
|
|
state: PullRequestState;
|
|
isDraft: boolean;
|
|
}
|
|
|
|
export type PullRequestTabStatusSeed = Pick<PullRequestTabStatus, "state" | "isDraft">;
|
|
|
|
export function shouldOpenDefaultBrowserProfileFromMenuClick(
|
|
pointerType: string | undefined,
|
|
): boolean {
|
|
return pointerType !== "touch";
|
|
}
|
|
|
|
const SURFACE_DISABLED_REASONS = {
|
|
browser: "Browser previews are only available in the T3 Code desktop app.",
|
|
terminal: "Terminal surfaces are only available from a project thread.",
|
|
files: "Files are only available when a project is open.",
|
|
diff: "Diff is only available for server threads in Git repositories.",
|
|
pullRequest: "This thread's branch has no pull request yet.",
|
|
pullRequests: "No linked pull requests are available for this thread.",
|
|
device: "Devices are only available from a thread.",
|
|
} as const;
|
|
|
|
/** Overlays that must win over the launcher's letter shortcuts. */
|
|
const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
|
|
'[data-slot="dialog-popup"]',
|
|
'[data-slot="alert-dialog-popup"]',
|
|
'[data-slot="command-dialog-popup"]',
|
|
'[data-slot="menu-popup"]',
|
|
'[data-slot="select-popup"]',
|
|
'[data-slot="popover-popup"]',
|
|
'[data-slot="combobox-popup"]',
|
|
'[data-slot="autocomplete-popup"]',
|
|
].join(",");
|
|
|
|
/** One-line unavailability hints for the empty-state rows. */
|
|
const SURFACE_UNAVAILABLE_HINTS = {
|
|
browser: "Only available in the desktop app.",
|
|
terminal: "Available when a project is open.",
|
|
files: "Available when a project is open.",
|
|
diff: "Available for Git repositories.",
|
|
pullRequest: "No pull request on this branch yet.",
|
|
pullRequests: "No linked pull requests available.",
|
|
device: "Available from a thread.",
|
|
} as const;
|
|
|
|
type TabContextMenuAction =
|
|
| "rename"
|
|
| "copy-path"
|
|
| "toggle-mute"
|
|
| "close"
|
|
| "close-others"
|
|
| "close-to-right"
|
|
| "close-all";
|
|
|
|
const TAB_SCROLL_EDGE_TOLERANCE = 1;
|
|
const TAB_DRAG_MODIFIERS = [restrictToHorizontalAxis, restrictToFirstScrollableAncestor];
|
|
|
|
function tabScrollViewport(root: HTMLDivElement | null): HTMLDivElement | null {
|
|
return root?.querySelector<HTMLDivElement>('[data-slot="scroll-area-viewport"]') ?? null;
|
|
}
|
|
|
|
/**
|
|
* Desktop preview tab backing a surface, or null for non-preview surfaces, the
|
|
* "new browser tab" placeholder, and the web build where no desktop tab exists.
|
|
*/
|
|
function previewTabIdOf(
|
|
surface: RightPanelSurface,
|
|
sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
|
|
): string | null {
|
|
if (surface.kind !== "preview" || !surface.resourceId) return null;
|
|
return sessions[surface.resourceId]?.tabId ?? null;
|
|
}
|
|
|
|
/**
|
|
* Label and enabled state for a preview tab's mute menu entry.
|
|
* Stays disabled until desktop overlay state arrives: a server session id can
|
|
* resolve while the preview manager's createTab is still in flight, and muting
|
|
* then fails with a PreviewTabNotFoundError nothing surfaces to the user.
|
|
*/
|
|
export function tabMuteMenuItem(input: {
|
|
overlay: DesktopPreviewOverlay | null;
|
|
canResolveRuntimeTabId: boolean;
|
|
}): { label: string; disabled: boolean } {
|
|
const muted = input.overlay?.audioMuted ?? false;
|
|
return {
|
|
label: muted ? "Unmute tab" : "Mute tab",
|
|
disabled: input.overlay === null || !input.canResolveRuntimeTabId,
|
|
};
|
|
}
|
|
|
|
type TabAudioState = "none" | "audible" | "muted";
|
|
|
|
/**
|
|
* A muted tab that is not making sound shows nothing: mute is armed silently,
|
|
* and the indicator only appears once there is audio to speak of.
|
|
*/
|
|
function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState {
|
|
if (!overlay?.audible) return "none";
|
|
return overlay.audioMuted ? "muted" : "audible";
|
|
}
|
|
|
|
type SurfaceShortcutEvent = Pick<
|
|
KeyboardEvent,
|
|
"altKey" | "ctrlKey" | "defaultPrevented" | "isComposing" | "key" | "metaKey"
|
|
>;
|
|
|
|
export function surfaceShortcutActionForKey<
|
|
const Action extends { available: boolean; shortcut: string },
|
|
>(actions: readonly Action[], event: SurfaceShortcutEvent): Action | null {
|
|
if (event.defaultPrevented || event.isComposing) return null;
|
|
if (event.metaKey || event.ctrlKey || event.altKey) return null;
|
|
return (
|
|
actions.find(
|
|
(action) => action.available && action.shortcut.toLowerCase() === event.key.toLowerCase(),
|
|
) ?? null
|
|
);
|
|
}
|
|
|
|
/**
|
|
* A focused editable is a typing context whether or not it has text yet: an
|
|
* empty chat composer at rest is still where the user's next keystrokes are
|
|
* meant to land, and claiming launcher letters from it would redirect prompts
|
|
* into whatever surface opens. The `:not` clause lets `closest` see past
|
|
* non-editable islands (`contenteditable="false"`) to an editable host around
|
|
* them, matching ComposerPendingUserInputPanel's typing guard.
|
|
*/
|
|
export function surfaceShortcutTargetsTypingContext(
|
|
target: { closest(selectors: string): unknown } | null,
|
|
): boolean {
|
|
return (
|
|
target?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])') !=
|
|
null
|
|
);
|
|
}
|
|
|
|
function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger render={props.trigger} />
|
|
<TooltipPopup side="top">{props.reason}</TooltipPopup>
|
|
</Tooltip>
|
|
);
|
|
}
|
|
|
|
function SurfaceMenuItem(props: {
|
|
available: boolean;
|
|
disabledReason?: string;
|
|
shortcut: string;
|
|
onClick: () => void;
|
|
children: ReactNode;
|
|
}) {
|
|
const item = (
|
|
<MenuItem
|
|
className={!props.available ? "data-disabled:pointer-events-auto" : undefined}
|
|
onClick={props.onClick}
|
|
disabled={!props.available}
|
|
aria-keyshortcuts={props.shortcut}
|
|
>
|
|
{props.children}
|
|
<MenuShortcut>{props.shortcut}</MenuShortcut>
|
|
</MenuItem>
|
|
);
|
|
if (props.available || !props.disabledReason) return item;
|
|
return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
|
|
}
|
|
|
|
/**
|
|
* List launcher shown when the right panel has no surfaces. Keyboard-first
|
|
* without palette chrome: a surface's letter opens it directly from anywhere
|
|
* outside a typing context, and arrows plus Enter work while the launcher is
|
|
* focused. The highlight only appears on hover or arrow use. Unavailable
|
|
* surfaces stay visible with a one-line reason.
|
|
*/
|
|
function RightPanelEmptyState(props: {
|
|
onAddBrowser: () => void;
|
|
onAddBrowserInProfile: (profileId: string) => void;
|
|
browserProfiles: ReadonlyArray<{ readonly id: string; readonly name: string }>;
|
|
onAddTerminal: () => void;
|
|
onAddDiff: () => void;
|
|
onAddFiles: () => void;
|
|
onAddPullRequest: () => void;
|
|
onAddPullRequests: () => void;
|
|
onAddDevice: () => void;
|
|
browserAvailable: boolean;
|
|
terminalAvailable: boolean;
|
|
diffAvailable: boolean;
|
|
filesAvailable: boolean;
|
|
pullRequestAvailable: boolean;
|
|
pullRequestsAvailable: boolean;
|
|
deviceAvailable: boolean;
|
|
}) {
|
|
// -1 means no highlight: it only appears on hover or arrow use.
|
|
const [highlight, setHighlight] = useState(-1);
|
|
|
|
const actions = [
|
|
{
|
|
label: "Browser",
|
|
icon: Globe2,
|
|
shortcut: "B",
|
|
available: props.browserAvailable,
|
|
disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
|
|
onClick: props.onAddBrowser,
|
|
},
|
|
{
|
|
label: "Terminal",
|
|
icon: TerminalSquare,
|
|
shortcut: "T",
|
|
available: props.terminalAvailable,
|
|
disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
|
|
onClick: props.onAddTerminal,
|
|
},
|
|
{
|
|
label: "Files",
|
|
icon: Files,
|
|
shortcut: "F",
|
|
available: props.filesAvailable,
|
|
disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
|
|
onClick: props.onAddFiles,
|
|
},
|
|
{
|
|
label: "Diff",
|
|
icon: FileDiff,
|
|
shortcut: "D",
|
|
available: props.diffAvailable,
|
|
disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
|
|
onClick: props.onAddDiff,
|
|
},
|
|
{
|
|
label: "Pull request",
|
|
icon: PullRequestGlyph.pullRequest,
|
|
shortcut: "P",
|
|
available: props.pullRequestAvailable,
|
|
disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
|
|
onClick: props.onAddPullRequest,
|
|
},
|
|
{
|
|
label: "Linked pull requests",
|
|
icon: PullRequestGlyph.link,
|
|
shortcut: "L",
|
|
available: props.pullRequestsAvailable,
|
|
disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequests,
|
|
onClick: props.onAddPullRequests,
|
|
},
|
|
{
|
|
label: "Device",
|
|
description: "Watch an iOS Simulator or Android Emulator.",
|
|
icon: Smartphone,
|
|
shortcut: "M",
|
|
available: props.deviceAvailable,
|
|
disabledReason: SURFACE_UNAVAILABLE_HINTS.device,
|
|
onClick: props.onAddDevice,
|
|
},
|
|
] as const;
|
|
|
|
type SurfaceAction = (typeof actions)[number];
|
|
|
|
const availableActions = actions.filter((action) => action.available);
|
|
const highlightIndex =
|
|
availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
|
|
|
|
// Letter shortcuts work while the launcher is visible, not only while it
|
|
// is focused; focus moves around too easily (stray clicks) to carry them.
|
|
// Capture phase so app-level key handlers cannot swallow the event first;
|
|
// typing contexts and already-handled events are left alone.
|
|
const shortcutActionsRef = useRef(availableActions);
|
|
useEffect(() => {
|
|
shortcutActionsRef.current = availableActions;
|
|
});
|
|
useEffect(() => {
|
|
const handler = (event: KeyboardEvent) => {
|
|
const action = surfaceShortcutActionForKey(shortcutActionsRef.current, event);
|
|
if (!action) return;
|
|
if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
|
|
// The composed path starts at the real target, which may sit inside a shadow root.
|
|
const target = event.composedPath()[0] ?? event.target;
|
|
if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return;
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
action.onClick();
|
|
};
|
|
window.addEventListener("keydown", handler, true);
|
|
return () => window.removeEventListener("keydown", handler, true);
|
|
}, []);
|
|
|
|
const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
|
|
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
|
|
if (availableActions.length === 0) return;
|
|
if (event.key === "ArrowDown" || event.key === "ArrowRight") {
|
|
event.preventDefault();
|
|
setHighlight((highlightIndex + 1) % availableActions.length);
|
|
return;
|
|
}
|
|
if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
|
|
event.preventDefault();
|
|
setHighlight(
|
|
highlightIndex === -1
|
|
? availableActions.length - 1
|
|
: (highlightIndex - 1 + availableActions.length) % availableActions.length,
|
|
);
|
|
return;
|
|
}
|
|
if (event.key === "Enter") {
|
|
// Only activate the highlight when the launcher itself has focus.
|
|
if (event.target !== event.currentTarget) return;
|
|
const action = availableActions[highlightIndex];
|
|
if (!action) return;
|
|
event.preventDefault();
|
|
action.onClick();
|
|
}
|
|
};
|
|
|
|
// Stable identity so React only runs this callback ref on mount/unmount;
|
|
// an inline arrow would re-attach and re-focus on every render.
|
|
const focusOnMount = useCallback((node: HTMLDivElement | null) => {
|
|
node?.focus();
|
|
}, []);
|
|
|
|
const isHighlighted = (action: SurfaceAction) =>
|
|
highlightIndex !== -1 && availableActions[highlightIndex] === action;
|
|
|
|
const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
|
|
const Icon = action.icon;
|
|
return (
|
|
<span className="relative inline-flex shrink-0">
|
|
<Icon className={iconClassName} />
|
|
</span>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div
|
|
ref={focusOnMount}
|
|
tabIndex={0}
|
|
onKeyDown={handleKeyDown}
|
|
aria-label="Open a surface"
|
|
data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
|
|
className={cn(
|
|
"scrollbar-gutter-both flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 outline-none",
|
|
// The panel topbar sits above this container; matching bottom padding
|
|
// keeps the list centered against the full panel, not the leftover.
|
|
"pb-(--workspace-topbar-height)",
|
|
)}
|
|
>
|
|
<div className="w-full max-w-xs py-6">
|
|
<h3 className="mb-3 text-center font-medium text-foreground text-sm">Open a surface</h3>
|
|
<div className="flex flex-col gap-0.5">
|
|
{actions.map((action) =>
|
|
action.available ? (
|
|
// The row is itself a button, so the profile chooser sits beside
|
|
// it in a wrapper rather than inside it. Hover lives on the
|
|
// wrapper: the chooser overlays the row, and a pointer moving
|
|
// onto it must not read as leaving the row.
|
|
<div
|
|
key={action.label}
|
|
className="group relative"
|
|
onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
|
|
onMouseLeave={() =>
|
|
setHighlight((current) =>
|
|
current === availableActions.indexOf(action) ? -1 : current,
|
|
)
|
|
}
|
|
>
|
|
<button
|
|
type="button"
|
|
onClick={action.onClick}
|
|
className={cn(
|
|
"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",
|
|
isHighlighted(action) && "bg-accent/60",
|
|
)}
|
|
>
|
|
{actionIcon(action, "size-4")}
|
|
<span
|
|
className={cn(
|
|
"min-w-0 flex-1 truncate",
|
|
action.label === "Browser" && props.browserProfiles.length > 1 && "pr-7",
|
|
)}
|
|
>
|
|
{action.label}
|
|
</span>
|
|
<Kbd>{action.shortcut}</Kbd>
|
|
</button>
|
|
{/*
|
|
Same choice the tab bar's "+" menu offers: the row opens the
|
|
default profile, the chevron picks another. Only worth showing
|
|
once there is something to choose between.
|
|
*/}
|
|
{action.label === "Browser" && props.browserProfiles.length > 1 ? (
|
|
<Menu>
|
|
<MenuTrigger
|
|
render={
|
|
<Button
|
|
aria-label="Open browser in a profile"
|
|
className="absolute top-1/2 right-8 -translate-y-1/2"
|
|
size="icon-xs"
|
|
variant="ghost-muted"
|
|
/>
|
|
}
|
|
>
|
|
<ChevronDown className="size-3.5" />
|
|
</MenuTrigger>
|
|
<MenuPopup align="end" side="bottom" sideOffset={6} className="max-w-56">
|
|
{props.browserProfiles.map((profile) => (
|
|
<MenuItem
|
|
key={profile.id}
|
|
onClick={() => props.onAddBrowserInProfile(profile.id)}
|
|
>
|
|
<span className="min-w-0 truncate">{profile.name}</span>
|
|
</MenuItem>
|
|
))}
|
|
</MenuPopup>
|
|
</Menu>
|
|
) : null}
|
|
</div>
|
|
) : (
|
|
<DisabledReasonTooltip
|
|
key={action.label}
|
|
reason={action.disabledReason}
|
|
trigger={
|
|
<div
|
|
tabIndex={0}
|
|
aria-disabled="true"
|
|
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"
|
|
>
|
|
{actionIcon(action, "size-4")}
|
|
<span className="min-w-0 flex-1 truncate">{action.label}</span>
|
|
<Kbd>{action.shortcut}</Kbd>
|
|
</div>
|
|
}
|
|
/>
|
|
),
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function surfaceTitle(
|
|
surface: RightPanelSurface,
|
|
sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
|
|
terminalLabelsById: ReadonlyMap<string, string>,
|
|
): string {
|
|
switch (surface.kind) {
|
|
case "diff":
|
|
return "Diff";
|
|
case "files":
|
|
return "Files";
|
|
case "file":
|
|
return surface.relativePath.slice(
|
|
Math.max(surface.relativePath.lastIndexOf("/"), surface.relativePath.lastIndexOf("\\")) + 1,
|
|
);
|
|
case "terminal":
|
|
return (
|
|
terminalLabelsById.get(surface.activeTerminalId) ??
|
|
getTerminalLabel(surface.activeTerminalId)
|
|
);
|
|
case "pull-request":
|
|
return `#${surface.number}`;
|
|
case "pull-requests":
|
|
return "Pull requests";
|
|
case "device":
|
|
return surface.title ?? surface.target?.name ?? "Device";
|
|
case "preview": {
|
|
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
|
|
if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
|
|
if (snapshot.navStatus.title.trim().length > 0) return snapshot.navStatus.title;
|
|
try {
|
|
return new URL(snapshot.navStatus.url).host || "Browser";
|
|
} catch {
|
|
return "Browser";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) {
|
|
const publicProviderUrl = faviconUrlForOrigin(url, 32);
|
|
return (
|
|
<FaviconImage
|
|
sources={[capturedUrl, publicProviderUrl]}
|
|
fallback={<Globe2 className="size-3 shrink-0" />}
|
|
className="size-3 shrink-0 rounded-sm object-contain"
|
|
/>
|
|
);
|
|
}
|
|
|
|
function sameOrigin(left: string, right: string): boolean {
|
|
try {
|
|
return new URL(left).origin === new URL(right).origin;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function SurfaceIcon({
|
|
surface,
|
|
sessions,
|
|
desktopByTabId,
|
|
theme,
|
|
environmentId,
|
|
pullRequestStatusSeeds,
|
|
}: {
|
|
surface: RightPanelSurface;
|
|
sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
|
|
desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
|
|
theme: "light" | "dark";
|
|
environmentId: EnvironmentId | null;
|
|
pullRequestStatusSeeds: Readonly<Record<string, PullRequestTabStatusSeed>> | undefined;
|
|
}) {
|
|
switch (surface.kind) {
|
|
case "preview": {
|
|
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
|
|
const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
|
|
const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null;
|
|
const capturedUrl =
|
|
favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null;
|
|
return <PreviewFavicon capturedUrl={capturedUrl} url={url} />;
|
|
}
|
|
case "diff":
|
|
return <FileDiff className="size-3 shrink-0" />;
|
|
case "files":
|
|
return <Files className="size-3 shrink-0" />;
|
|
case "file":
|
|
return (
|
|
<PierreEntryIcon
|
|
pathValue={surface.relativePath}
|
|
kind="file"
|
|
theme={theme}
|
|
className="size-3"
|
|
/>
|
|
);
|
|
case "terminal":
|
|
return <TerminalSquare className="size-3 shrink-0" />;
|
|
case "pull-request":
|
|
return (
|
|
<PullRequestSurfaceIcon
|
|
surface={surface}
|
|
environmentId={environmentId}
|
|
seed={pullRequestStatusSeeds?.[surface.id]}
|
|
/>
|
|
);
|
|
case "pull-requests":
|
|
return <PullRequestGlyph.link className="size-3 shrink-0" />;
|
|
case "device":
|
|
return surface.target?.platform === "ios" ? (
|
|
<AppleIcon className="size-3 shrink-0" />
|
|
) : surface.target?.platform === "android" ? (
|
|
<AndroidIcon className="size-3 shrink-0" />
|
|
) : (
|
|
<Smartphone className="size-3 shrink-0" />
|
|
);
|
|
}
|
|
}
|
|
|
|
export function resolvePullRequestTabLink(
|
|
threads: readonly Pick<EnvironmentThreadShell, "environmentId" | "pullRequests">[],
|
|
environmentId: EnvironmentId | null,
|
|
host: string | null,
|
|
reference: { repository: string; number: number },
|
|
) {
|
|
if (environmentId === null || host === null) return undefined;
|
|
let newest: EnvironmentThreadShell["pullRequests"][number] | undefined;
|
|
for (const thread of threads) {
|
|
if (thread.environmentId !== environmentId) continue;
|
|
for (const link of visibleThreadPullRequests(thread.pullRequests)) {
|
|
if (
|
|
!threadPullRequestKeysEqual(link, {
|
|
host,
|
|
repository: reference.repository,
|
|
number: reference.number,
|
|
})
|
|
)
|
|
continue;
|
|
if (
|
|
newest === undefined ||
|
|
(link.snapshot?.syncedAt ?? "") > (newest.snapshot?.syncedAt ?? "")
|
|
)
|
|
newest = link;
|
|
}
|
|
}
|
|
return newest;
|
|
}
|
|
|
|
function PullRequestSurfaceIcon({
|
|
surface,
|
|
environmentId,
|
|
seed,
|
|
}: {
|
|
surface: Extract<RightPanelSurface, { kind: "pull-request" }>;
|
|
environmentId: EnvironmentId | null;
|
|
seed: PullRequestTabStatusSeed | undefined;
|
|
}) {
|
|
const resolvedEnvironmentId =
|
|
(surface.environmentId as EnvironmentId | undefined) ?? environmentId;
|
|
const projects = useProjects();
|
|
const threads = useThreadShells();
|
|
const project = projects.find(
|
|
(entry) => entry.environmentId === resolvedEnvironmentId && entry.id === surface.projectId,
|
|
);
|
|
const identity = project?.repositoryIdentity;
|
|
const host =
|
|
surface.host ??
|
|
(identity?.provider
|
|
? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)
|
|
: null);
|
|
const configs = useServerConfigs();
|
|
const capabilities =
|
|
resolvedEnvironmentId === null
|
|
? undefined
|
|
: configs.get(resolvedEnvironmentId)?.environment.capabilities;
|
|
const linkedSnapshot =
|
|
capabilities?.threadPullRequests === true
|
|
? (resolvePullRequestTabLink(threads, resolvedEnvironmentId, host, surface)?.snapshot ?? null)
|
|
: null;
|
|
const detail = useEnvironmentQuery(
|
|
resolvedEnvironmentId === null || capabilities?.pullRequests !== true || linkedSnapshot !== null
|
|
? null
|
|
: pullRequestEnvironment.detail({
|
|
environmentId: resolvedEnvironmentId,
|
|
input: {
|
|
projectId: surface.projectId as ProjectId,
|
|
...(capabilities?.threadPullRequests === true && surface.host !== undefined
|
|
? { host: surface.host }
|
|
: {}),
|
|
repository: surface.repository,
|
|
number: surface.number,
|
|
},
|
|
}),
|
|
).data;
|
|
const reference = useMemo(
|
|
() => ({
|
|
projectId: surface.projectId as ProjectId,
|
|
repository: surface.repository,
|
|
number: surface.number,
|
|
}),
|
|
[surface.projectId, surface.repository, surface.number],
|
|
);
|
|
const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference, null);
|
|
// The compact tab intentionally shows lifecycle and draft state only. Conflict warnings have
|
|
// their own presentation on surfaces that have mergeability, while this tab stays stable as
|
|
// detail data arrives.
|
|
const status = linkedSnapshot ?? newestPullRequestSummary(detail, sharedSummary) ?? seed ?? null;
|
|
if (status === null) {
|
|
return <PullRequestGlyph.pullRequest className="size-3 shrink-0 text-muted-foreground" />;
|
|
}
|
|
const presentation = resolvePullRequestState({
|
|
state: status.state,
|
|
isDraft: status.isDraft ?? detail?.isDraft ?? seed?.isDraft ?? false,
|
|
});
|
|
return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;
|
|
}
|
|
|
|
/**
|
|
* Lets its tabs be dragged into a new order. Neighbours slide aside while dragging,
|
|
* and the order commits on drop.
|
|
*/
|
|
function SortableTabList(props: {
|
|
surfaces: readonly RightPanelSurface[];
|
|
onMove: ((surfaceId: string, toIndex: number) => void) | undefined;
|
|
children: ReactNode;
|
|
}) {
|
|
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
|
|
const surfaceIds = useMemo(() => props.surfaces.map((surface) => surface.id), [props.surfaces]);
|
|
const { onMove, surfaces } = props;
|
|
const handleDragEnd = useCallback(
|
|
({ active, over }: DragEndEvent) => {
|
|
if (!over || active.id === over.id) return;
|
|
const toIndex = surfaces.findIndex((surface) => surface.id === over.id);
|
|
if (toIndex >= 0) onMove?.(String(active.id), toIndex);
|
|
},
|
|
[onMove, surfaces],
|
|
);
|
|
return (
|
|
<DndContext
|
|
sensors={sensors}
|
|
collisionDetection={closestCenter}
|
|
modifiers={TAB_DRAG_MODIFIERS}
|
|
onDragEnd={handleDragEnd}
|
|
>
|
|
<SortableContext items={surfaceIds} strategy={horizontalListSortingStrategy}>
|
|
{props.children}
|
|
</SortableContext>
|
|
</DndContext>
|
|
);
|
|
}
|
|
|
|
function SortableTab({
|
|
surfaceId,
|
|
disabled,
|
|
className,
|
|
...props
|
|
}: ComponentProps<"div"> & { surfaceId: string; disabled: boolean }) {
|
|
const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
|
id: surfaceId,
|
|
disabled,
|
|
});
|
|
return (
|
|
<div
|
|
{...props}
|
|
{...listeners}
|
|
ref={setNodeRef}
|
|
style={{ transform: CSS.Translate.toString(transform), transition }}
|
|
className={cn(className, isDragging && "relative z-10")}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function RightPanelTabs(props: RightPanelTabsProps) {
|
|
const ownsDesktopTitleBar = isElectron && props.mode === "inline";
|
|
const browserProfiles = useBrowserDefaults().profiles;
|
|
const { resolvedTheme } = useTheme();
|
|
const tabListRef = useRef<HTMLDivElement>(null);
|
|
const addSurfaceTriggerRef = useRef<HTMLButtonElement>(null);
|
|
const [renamingDevice, setRenamingDevice] = useState<string | null>(null);
|
|
const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
|
|
const [tabScrollState, setTabScrollState] = useState({
|
|
hasOverflow: false,
|
|
canScrollLeft: false,
|
|
canScrollRight: false,
|
|
});
|
|
|
|
if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false);
|
|
|
|
const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => {
|
|
if (event.defaultPrevented || event.isComposing) return;
|
|
if (
|
|
resolveShortcutCommand(event, props.keybindings, {
|
|
context: { ...props.getShortcutContext(), rightPanelOpen: true },
|
|
}) !== "rightPanel.new"
|
|
)
|
|
return;
|
|
if (!addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
if (!event.repeat) {
|
|
addSurfaceTriggerRef.current?.focus();
|
|
setAddSurfaceMenuOpen(true);
|
|
}
|
|
});
|
|
useEffect(() => {
|
|
if (props.open === false) return;
|
|
document.addEventListener("keydown", onNewSurfaceKeyDown, true);
|
|
return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true);
|
|
}, [props.open]);
|
|
|
|
const updateTabScrollState = useCallback(() => {
|
|
const viewport = tabScrollViewport(tabListRef.current);
|
|
if (!viewport) return;
|
|
|
|
const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
|
|
const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
|
|
const canScrollRight =
|
|
hasOverflow &&
|
|
viewport.scrollLeft + viewport.clientWidth < viewport.scrollWidth - TAB_SCROLL_EDGE_TOLERANCE;
|
|
setTabScrollState((current) => {
|
|
if (
|
|
current.hasOverflow === hasOverflow &&
|
|
current.canScrollLeft === canScrollLeft &&
|
|
current.canScrollRight === canScrollRight
|
|
) {
|
|
return current;
|
|
}
|
|
return { hasOverflow, canScrollLeft, canScrollRight };
|
|
});
|
|
}, []);
|
|
|
|
const scrollTabs = useCallback((direction: -1 | 1) => {
|
|
const viewport = tabScrollViewport(tabListRef.current);
|
|
if (!viewport) return;
|
|
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
viewport.scrollBy({
|
|
left: direction * Math.max(120, viewport.clientWidth * 0.75),
|
|
behavior: reduceMotion ? "auto" : "smooth",
|
|
});
|
|
}, []);
|
|
|
|
const addSurfaceActions = [
|
|
{
|
|
label: "Browser",
|
|
icon: Globe2,
|
|
shortcut: "B",
|
|
available: props.browserAvailable,
|
|
disabledReason: SURFACE_DISABLED_REASONS.browser,
|
|
onClick: props.onAddBrowser,
|
|
},
|
|
{
|
|
label: "Terminal",
|
|
icon: TerminalSquare,
|
|
shortcut: "T",
|
|
available: props.terminalAvailable,
|
|
disabledReason: SURFACE_DISABLED_REASONS.terminal,
|
|
onClick: props.onAddTerminal,
|
|
},
|
|
{
|
|
label: "Files",
|
|
icon: Files,
|
|
shortcut: "F",
|
|
available: props.filesAvailable,
|
|
disabledReason: SURFACE_DISABLED_REASONS.files,
|
|
onClick: props.onAddFiles,
|
|
},
|
|
{
|
|
label: "Diff",
|
|
icon: FileDiff,
|
|
shortcut: "D",
|
|
available: props.diffAvailable,
|
|
disabledReason: SURFACE_DISABLED_REASONS.diff,
|
|
onClick: props.onAddDiff,
|
|
},
|
|
{
|
|
label: "Pull request",
|
|
icon: PullRequestGlyph.pullRequest,
|
|
shortcut: "P",
|
|
available: props.pullRequestAvailable,
|
|
disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
|
|
onClick: props.onAddPullRequest,
|
|
},
|
|
{
|
|
label: "Linked pull requests",
|
|
icon: PullRequestGlyph.link,
|
|
shortcut: "L",
|
|
available: props.pullRequestsAvailable,
|
|
disabledReason: SURFACE_DISABLED_REASONS.pullRequests,
|
|
onClick: props.onAddPullRequests,
|
|
},
|
|
{
|
|
label: "Device",
|
|
icon: Smartphone,
|
|
shortcut: "M",
|
|
available: props.deviceAvailable,
|
|
disabledReason: SURFACE_DISABLED_REASONS.device,
|
|
onClick: props.onAddDevice,
|
|
},
|
|
] as const;
|
|
|
|
const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
|
|
const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent);
|
|
if (!action) return;
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
setAddSurfaceMenuOpen(false);
|
|
action.onClick();
|
|
};
|
|
|
|
const handleTabContextMenu = useCallback(
|
|
async (event: ReactMouseEvent, surface: RightPanelSurface) => {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
|
|
const api = readLocalApi();
|
|
if (!api) return;
|
|
|
|
const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
|
|
if (surfaceIndex < 0) return;
|
|
|
|
const items: ContextMenuItem<TabContextMenuAction>[] = [];
|
|
if (surface.kind === "device" && props.onRenameDevice)
|
|
items.push({ id: "rename", label: "Rename" });
|
|
if (surface.kind === "file" && surface.attachment === undefined) {
|
|
items.push({ id: "copy-path", label: "Copy path" });
|
|
}
|
|
const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
|
|
// Desktop overlay state only arrives once the preview manager has created
|
|
// the tab. A server session id alone can still be ahead of that, and
|
|
// muting then fails with PreviewTabNotFoundError that nobody surfaces.
|
|
const menuOverlay = menuPreviewTabId
|
|
? (props.desktopByTabId[menuPreviewTabId] ?? null)
|
|
: null;
|
|
const menuMuted = menuOverlay?.audioMuted ?? false;
|
|
if (surface.kind === "preview") {
|
|
// Not gated on audibility: silencing a quiet tab ahead of time is the
|
|
// point, so the item is offered whenever the tab is mutable at all.
|
|
items.push({
|
|
id: "toggle-mute",
|
|
...tabMuteMenuItem({
|
|
overlay: menuOverlay,
|
|
canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined,
|
|
}),
|
|
});
|
|
}
|
|
items.push(
|
|
{ id: "close", label: "Close" },
|
|
{
|
|
id: "close-others",
|
|
label: "Close others",
|
|
disabled: props.surfaces.length <= 1,
|
|
},
|
|
{
|
|
id: "close-to-right",
|
|
label: "Close to the right",
|
|
disabled: surfaceIndex >= props.surfaces.length - 1,
|
|
},
|
|
{
|
|
id: "close-all",
|
|
label: "Close all",
|
|
disabled: props.surfaces.length === 0,
|
|
},
|
|
);
|
|
|
|
const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
|
|
switch (action) {
|
|
case "rename":
|
|
setRenamingDevice(surface.id);
|
|
break;
|
|
case "copy-path":
|
|
if (surface.kind === "file" && surface.attachment === undefined) {
|
|
props.onCopyFilePath(surface.relativePath);
|
|
}
|
|
break;
|
|
case "toggle-mute": {
|
|
// menuOverlay repeats the disabled gate above: the desktop tab must
|
|
// exist before it can be addressed, however the menu was dismissed.
|
|
const runtimeTabId =
|
|
menuPreviewTabId && menuOverlay
|
|
? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null)
|
|
: null;
|
|
if (runtimeTabId) {
|
|
void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined);
|
|
}
|
|
break;
|
|
}
|
|
case "close":
|
|
props.onCloseSurface(surface);
|
|
break;
|
|
case "close-others":
|
|
props.onCloseOtherSurfaces(surface);
|
|
break;
|
|
case "close-to-right":
|
|
props.onCloseSurfacesToRight(surface);
|
|
break;
|
|
case "close-all":
|
|
props.onCloseAllSurfaces();
|
|
break;
|
|
case null:
|
|
break;
|
|
}
|
|
},
|
|
[props],
|
|
);
|
|
const handleTabMouseDown = useCallback((event: ReactMouseEvent) => {
|
|
if (event.button !== 1) return;
|
|
event.preventDefault();
|
|
}, []);
|
|
const handleTabAuxClick = useCallback(
|
|
(event: ReactMouseEvent, surface: RightPanelSurface) => {
|
|
if (event.button !== 1) return;
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
props.onCloseSurface(surface);
|
|
},
|
|
[props],
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
|
|
const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
|
|
activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
|
}, [props.activeSurfaceId, tabScrollState.hasOverflow]);
|
|
|
|
useEffect(() => {
|
|
const viewport = tabScrollViewport(tabListRef.current);
|
|
if (!viewport) return;
|
|
|
|
const content = viewport.firstElementChild;
|
|
const stopObserving = observeResize(
|
|
content ? [viewport, content] : viewport,
|
|
updateTabScrollState,
|
|
);
|
|
viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
|
|
updateTabScrollState();
|
|
|
|
return () => {
|
|
stopObserving();
|
|
viewport.removeEventListener("scroll", updateTabScrollState);
|
|
};
|
|
}, [updateTabScrollState]);
|
|
|
|
useEffect(() => {
|
|
const viewport = tabScrollViewport(tabListRef.current);
|
|
if (!viewport) return;
|
|
|
|
const handleWheel = (event: WheelEvent) => {
|
|
if (event.ctrlKey) return;
|
|
let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
|
|
if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16;
|
|
if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth;
|
|
if (delta === 0) return;
|
|
|
|
const previousScrollLeft = viewport.scrollLeft;
|
|
viewport.scrollLeft += delta;
|
|
if (viewport.scrollLeft === previousScrollLeft) return;
|
|
event.preventDefault();
|
|
updateTabScrollState();
|
|
};
|
|
|
|
viewport.addEventListener("wheel", handleWheel, { passive: false });
|
|
return () => viewport.removeEventListener("wheel", handleWheel);
|
|
}, [updateTabScrollState]);
|
|
|
|
return (
|
|
<PreviewPanelShell
|
|
mode={props.mode}
|
|
{...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
|
|
{...(props.open !== undefined ? { open: props.open } : {})}
|
|
{...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
|
|
{...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
|
|
{...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
|
|
>
|
|
<div
|
|
className={cn(
|
|
"flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1 pl-2",
|
|
// The sheet overlays from the viewport top, so its tab bar keeps
|
|
// the titlebar's height: a compact row re-centers the layout
|
|
// controls a few pixels higher and the cluster jumps on open.
|
|
props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
|
|
ownsDesktopTitleBar && "drag-region",
|
|
ownsDesktopTitleBar && "wco:pr-(--workspace-native-controls-inset)",
|
|
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
|
)}
|
|
data-right-panel-tabbar
|
|
>
|
|
<ScrollArea
|
|
radius="none"
|
|
ref={tabListRef}
|
|
hideScrollbars
|
|
scrollFade
|
|
className="min-w-0 flex-1"
|
|
data-right-panel-tab-list
|
|
>
|
|
<div className="flex h-full w-max min-w-full items-center gap-1">
|
|
<SortableTabList surfaces={props.surfaces} onMove={props.onMoveSurface}>
|
|
{props.surfaces.map((surface) => {
|
|
const active = surface.id === props.activeSurfaceId;
|
|
const pending = props.pendingSurfaceIds.has(surface.id);
|
|
const title = surfaceTitle(
|
|
surface,
|
|
props.previewSessions,
|
|
props.terminalLabelsById,
|
|
);
|
|
const previewTabId = previewTabIdOf(surface, props.previewSessions);
|
|
// Desktop state is keyed by the session id, but desktop actions
|
|
// must be addressed with the runtime id.
|
|
const audio = tabAudioState(
|
|
previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null,
|
|
);
|
|
const audioRuntimeTabId = previewTabId
|
|
? (props.previewRuntimeTabId?.(previewTabId) ?? null)
|
|
: null;
|
|
return (
|
|
<SortableTab
|
|
key={surface.id}
|
|
surfaceId={surface.id}
|
|
disabled={!props.onMoveSurface || renamingDevice === surface.id}
|
|
data-active-tab={active}
|
|
onMouseDown={handleTabMouseDown}
|
|
onAuxClick={(event) => handleTabAuxClick(event, surface)}
|
|
onContextMenu={(event) => void handleTabContextMenu(event, surface)}
|
|
className={cn(
|
|
"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",
|
|
ownsDesktopTitleBar && "[-webkit-app-region:no-drag]",
|
|
active
|
|
? "bg-accent text-foreground"
|
|
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
|
|
)}
|
|
>
|
|
<PanelTabCloseButton
|
|
label={`Close ${title}`}
|
|
onClick={() => props.onCloseSurface(surface)}
|
|
>
|
|
<SurfaceIcon
|
|
surface={surface}
|
|
sessions={props.previewSessions}
|
|
desktopByTabId={props.desktopByTabId}
|
|
theme={resolvedTheme}
|
|
environmentId={props.environmentId}
|
|
pullRequestStatusSeeds={props.pullRequestStatusSeeds}
|
|
/>
|
|
{pending ? (
|
|
<span
|
|
className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
|
|
aria-hidden
|
|
/>
|
|
) : null}
|
|
</PanelTabCloseButton>
|
|
{audio === "none" || !audioRuntimeTabId ? null : (
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<button
|
|
type="button"
|
|
className="cursor-pointer flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
|
|
aria-label={audio === "muted" ? `Unmute ${title}` : `Mute ${title}`}
|
|
onClick={(event) => {
|
|
// Sibling of the close button, inside a tab that
|
|
// activates on click: keep this to the toggle.
|
|
event.stopPropagation();
|
|
void previewBridge
|
|
?.setAudioMuted(audioRuntimeTabId, audio !== "muted")
|
|
.catch(() => undefined);
|
|
}}
|
|
>
|
|
<MorphIcon
|
|
className="size-3"
|
|
icon={audio === "muted" ? VolumeOff : Volume2}
|
|
/>
|
|
</button>
|
|
}
|
|
/>
|
|
<TooltipPopup>{audio === "muted" ? "Unmute tab" : "Mute tab"}</TooltipPopup>
|
|
</Tooltip>
|
|
)}
|
|
{renamingDevice === surface.id ? (
|
|
<input
|
|
aria-label="Device tab name"
|
|
className="w-24 min-w-0 rounded-sm bg-background px-1 outline-none ring-1 ring-inset ring-ring"
|
|
defaultValue={title}
|
|
ref={(element) => {
|
|
element?.focus();
|
|
element?.select();
|
|
}}
|
|
onBlur={(event) => {
|
|
props.onRenameDevice?.(surface.id, event.currentTarget.value);
|
|
setRenamingDevice(null);
|
|
}}
|
|
onKeyDown={(event) => {
|
|
event.stopPropagation();
|
|
if (event.key === "Enter") event.currentTarget.blur();
|
|
if (event.key === "Escape") {
|
|
event.currentTarget.value = title;
|
|
event.currentTarget.blur();
|
|
}
|
|
}}
|
|
/>
|
|
) : (
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<button
|
|
type="button"
|
|
onDoubleClick={() => {
|
|
if (surface.kind === "device" && props.onRenameDevice)
|
|
setRenamingDevice(surface.id);
|
|
}}
|
|
className="cursor-pointer flex min-w-0 items-center"
|
|
onClick={() => props.onActivate(surface)}
|
|
>
|
|
<span className="truncate">{title}</span>
|
|
</button>
|
|
}
|
|
/>
|
|
<TooltipPopup>
|
|
{surface.kind === "device" ? (
|
|
<DeviceTabTooltip
|
|
surface={surface}
|
|
environmentId={props.environmentId}
|
|
title={title}
|
|
/>
|
|
) : (
|
|
title
|
|
)}
|
|
</TooltipPopup>
|
|
</Tooltip>
|
|
)}
|
|
</SortableTab>
|
|
);
|
|
})}
|
|
</SortableTabList>
|
|
{props.open !== false ? (
|
|
<Menu open={addSurfaceMenuOpen} onOpenChange={setAddSurfaceMenuOpen}>
|
|
<MenuTrigger
|
|
ref={addSurfaceTriggerRef}
|
|
render={
|
|
<Button
|
|
aria-label="Add panel surface"
|
|
className="shrink-0"
|
|
size="icon-xs"
|
|
variant="ghost-muted"
|
|
/>
|
|
}
|
|
>
|
|
<Plus className="size-3.5" />
|
|
</MenuTrigger>
|
|
<MenuPopup
|
|
align="start"
|
|
side="bottom"
|
|
sideOffset={6}
|
|
onKeyDownCapture={handleAddSurfaceMenuKeyDown}
|
|
>
|
|
{addSurfaceActions.map((action) => {
|
|
const Icon = action.icon;
|
|
// Browser collapses into one row: clicking the trigger opens
|
|
// the default profile (the common case stays one click),
|
|
// while hover or arrow reveals the profiles. The choice
|
|
// lives at open time because a tab's profile is fixed then —
|
|
// Electron only honours a partition before attach.
|
|
if (action.label === "Browser" && action.available) {
|
|
return (
|
|
<MenuSub key={action.label}>
|
|
<MenuSubTrigger
|
|
className="[&>svg:last-child]:ms-0"
|
|
aria-keyshortcuts={action.shortcut}
|
|
onClick={(event) => {
|
|
const pointerType =
|
|
"pointerType" in event.nativeEvent &&
|
|
typeof event.nativeEvent.pointerType === "string"
|
|
? event.nativeEvent.pointerType
|
|
: undefined;
|
|
// Touch has no hover path to the profile choices:
|
|
// its first tap opens the submenu, then a profile
|
|
// is selected there. Mouse click keeps the common
|
|
// default-profile action at one click.
|
|
if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType))
|
|
return;
|
|
setAddSurfaceMenuOpen(false);
|
|
action.onClick();
|
|
}}
|
|
>
|
|
<Icon />
|
|
{action.label}
|
|
<MenuShortcut>{action.shortcut}</MenuShortcut>
|
|
</MenuSubTrigger>
|
|
{/*
|
|
Capped and truncated: profile names are user-supplied
|
|
and run to 48 characters, which would otherwise widen
|
|
the popup to fit-content and wrap.
|
|
*/}
|
|
<MenuSubPopup className="max-w-56">
|
|
{browserProfiles.map((profile) => (
|
|
<MenuItem
|
|
key={profile.id}
|
|
onClick={() => props.onAddBrowserInProfile(profile.id)}
|
|
>
|
|
<span className="min-w-0 truncate">{profile.name}</span>
|
|
</MenuItem>
|
|
))}
|
|
</MenuSubPopup>
|
|
</MenuSub>
|
|
);
|
|
}
|
|
return (
|
|
<SurfaceMenuItem
|
|
key={action.label}
|
|
available={action.available}
|
|
disabledReason={action.disabledReason}
|
|
shortcut={action.shortcut}
|
|
onClick={action.onClick}
|
|
>
|
|
<Icon />
|
|
{action.label}
|
|
</SurfaceMenuItem>
|
|
);
|
|
})}
|
|
</MenuPopup>
|
|
</Menu>
|
|
) : null}
|
|
</div>
|
|
</ScrollArea>
|
|
{tabScrollState.hasOverflow ? (
|
|
<div
|
|
className="flex shrink-0 items-center gap-0.5 [-webkit-app-region:no-drag]"
|
|
role="group"
|
|
aria-label="Scroll panel tabs"
|
|
>
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<span className="inline-flex">
|
|
<Button
|
|
aria-label="Scroll tabs left"
|
|
disabled={!tabScrollState.canScrollLeft}
|
|
onClick={() => scrollTabs(-1)}
|
|
size="icon-xs"
|
|
variant="ghost"
|
|
>
|
|
<ChevronLeft />
|
|
</Button>
|
|
</span>
|
|
}
|
|
/>
|
|
<TooltipPopup>Scroll tabs left</TooltipPopup>
|
|
</Tooltip>
|
|
<Tooltip>
|
|
<TooltipTrigger
|
|
render={
|
|
<span className="inline-flex">
|
|
<Button
|
|
aria-label="Scroll tabs right"
|
|
disabled={!tabScrollState.canScrollRight}
|
|
onClick={() => scrollTabs(1)}
|
|
size="icon-xs"
|
|
variant="ghost"
|
|
>
|
|
<ChevronRight />
|
|
</Button>
|
|
</span>
|
|
}
|
|
/>
|
|
<TooltipPopup>Scroll tabs right</TooltipPopup>
|
|
</Tooltip>
|
|
</div>
|
|
) : null}
|
|
{props.layoutControls}
|
|
{ownsDesktopTitleBar && !props.layoutControls ? (
|
|
// Keeps the tabs clear of the window controls when the layout toggles live elsewhere.
|
|
<span aria-hidden className="hidden w-24 shrink-0 wco:block" />
|
|
) : null}
|
|
{ownsDesktopTitleBar ? (
|
|
<span
|
|
aria-hidden
|
|
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]"
|
|
/>
|
|
) : null}
|
|
</div>
|
|
<div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
|
|
{props.activeSurfaceId === null ? (
|
|
<RightPanelEmptyState
|
|
onAddBrowser={props.onAddBrowser}
|
|
onAddBrowserInProfile={props.onAddBrowserInProfile}
|
|
browserProfiles={browserProfiles}
|
|
onAddTerminal={props.onAddTerminal}
|
|
onAddDiff={props.onAddDiff}
|
|
onAddFiles={props.onAddFiles}
|
|
onAddPullRequest={props.onAddPullRequest}
|
|
onAddPullRequests={props.onAddPullRequests}
|
|
onAddDevice={props.onAddDevice}
|
|
browserAvailable={props.browserAvailable}
|
|
terminalAvailable={props.terminalAvailable}
|
|
diffAvailable={props.diffAvailable}
|
|
filesAvailable={props.filesAvailable}
|
|
pullRequestAvailable={props.pullRequestAvailable}
|
|
pullRequestsAvailable={props.pullRequestsAvailable}
|
|
deviceAvailable={props.deviceAvailable}
|
|
/>
|
|
) : (
|
|
props.children
|
|
)}
|
|
</div>
|
|
</PreviewPanelShell>
|
|
);
|
|
}
|
|
|
|
function DeviceTabTooltip(props: {
|
|
surface: Extract<RightPanelSurface, { kind: "device" }>;
|
|
environmentId: EnvironmentId | null;
|
|
title: string;
|
|
}) {
|
|
const target = props.surface.target;
|
|
const { state } = useDeviceState(target ? props.environmentId : null);
|
|
const device = target
|
|
? state.devices.find((entry) => entry.hostId === target.hostId && entry.id === target.deviceId)
|
|
: undefined;
|
|
const host = target ? state.hosts.find((entry) => entry.id === target.hostId) : undefined;
|
|
return (
|
|
<div className="flex flex-col gap-0.5">
|
|
<span>{props.title}</span>
|
|
{target ? (
|
|
<span className="text-muted-foreground">
|
|
{host?.label ?? "Device host"} ·{" "}
|
|
{device?.version ?? (target.platform === "ios" ? "iOS" : "Android")}
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|