Skip to content
TypeScript

feat(web): reorder right panel tabs by dragging (#17730)

eimexdev4107930420cf
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 06a6bacaf48..2aeca85e6aa 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -6233,6 +6233,13 @@ export default function ChatView(props: ChatViewProps) {
finishRightPanelSurfaceClose,
rightPanelState.surfaces,
]);
+ const moveRightPanelSurface = useCallback(
+ (surfaceId: string, toIndex: number) => {
+ if (activeThreadRef)
+ useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex);
+ },
+ [activeThreadRef],
+ );
const copyRightPanelFilePath = useCallback((relativePath: string) => {
if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
toastManager.add(
@@ -11991,6 +11998,7 @@ export default function ChatView(props: ChatViewProps) {
onCloseOtherSurfaces={closeOtherRightPanelSurfaces}
onCloseSurfacesToRight={closeRightPanelSurfacesToRight}
onCloseAllSurfaces={closeAllRightPanelSurfaces}
+ onMoveSurface={moveRightPanelSurface}
onCopyFilePath={copyRightPanelFilePath}
onAddBrowser={() => createBrowserSurface()}
onAddBrowserInProfile={createBrowserSurface}
@@ -12049,6 +12057,7 @@ export default function ChatView(props: ChatViewProps) {
onCloseOtherSurfaces={closeOtherRightPanelSurfaces}
onCloseSurfacesToRight={closeRightPanelSurfacesToRight}
onCloseAllSurfaces={closeAllRightPanelSurfaces}
+ onMoveSurface={moveRightPanelSurface}
onCopyFilePath={copyRightPanelFilePath}
onAddBrowser={() => createBrowserSurface()}
onAddBrowserInProfile={createBrowserSurface}
diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx
index 6c1206929b4..5c8323a7ae3 100644
--- a/apps/web/src/components/RightPanelTabs.tsx
+++ b/apps/web/src/components/RightPanelTabs.tsx
@@ -14,6 +14,17 @@ import type {
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,
@@ -27,6 +38,7 @@ import {
} from "lucide-react";
import { Volume2, VolumeOff } from "lucide";
import {
+ type ComponentProps,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type ReactElement,
@@ -115,6 +127,8 @@ interface RightPanelTabsProps {
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;
/**
@@ -199,6 +213,7 @@ type TabContextMenuAction =
| "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;
@@ -795,6 +810,61 @@ function PullRequestSurfaceIcon({
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;
@@ -1118,135 +1188,143 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
data-right-panel-tab-list
>
<div className="flex h-full w-max min-w-full items-center gap-1">
- {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 (
- <div
- key={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)}
+ <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",
+ )}
>
- <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>
- }
+ <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}
/>
- <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>
- }
+ {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();
+ }
+ }}
/>
- <TooltipPopup>
- {surface.kind === "device" ? (
- <DeviceTabTooltip
- surface={surface}
- environmentId={props.environmentId}
- title={title}
- />
- ) : (
- title
- )}
- </TooltipPopup>
- </Tooltip>
- )}
- </div>
- );
- })}
+ ) : (
+ <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
diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts
index 3babb2ed749..ed27a64edd6 100644
--- a/apps/web/src/rightPanelStore.test.ts
+++ b/apps/web/src/rightPanelStore.test.ts
@@ -1187,4 +1187,27 @@ describe("rightPanelStore", () => {
),
).toEqual(["terminal:term-1", "browser:tab-b", "browser:tab-c"]);
});
+
+ it("moves a surface to a new index and keeps it there through browser reconciliation", () => {
+ const store = useRightPanelStore.getState();
+ store.openTerminal(refA, "term-1");
+ store.openBrowser(refA, "tab-a");
+ store.open(refA, "diff");
+ const revision = store.getUserActionRevision(refA);
+ const surfaceIds = () =>
+ selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.map(
+ (surface) => surface.id,
+ );
+
+ store.moveSurface(refA, "browser:tab-a", 0);
+ expect(surfaceIds()).toEqual(["browser:tab-a", "terminal:term-1", "diff"]);
+ store.moveSurface(refA, "browser:tab-a", 2);
+ expect(surfaceIds()).toEqual(["terminal:term-1", "diff", "browser:tab-a"]);
+ store.moveSurface(refA, "browser:tab-a", 0);
+
+ store.reconcileBrowserSurfaces(refA, ["tab-a", "tab-b"]);
+ expect(surfaceIds()).toEqual(["browser:tab-a", "terminal:term-1", "diff", "browser:tab-b"]);
+ // Reordering is not a choice about what the panel shows.
+ expect(store.getUserActionRevision(refA)).toBe(revision);
+ });
});
diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts
index 812de880404..8afdbedfcc8 100644
--- a/apps/web/src/rightPanelStore.ts
+++ b/apps/web/src/rightPanelStore.ts
@@ -176,6 +176,7 @@ interface RightPanelStoreState {
closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
closeAllSurfaces: (ref: ScopedThreadRef) => void;
+ moveSurface: (ref: ScopedThreadRef, surfaceId: string, toIndex: number) => void;
reconcileBrowserSurfaces: (
ref: ScopedThreadRef,
tabIds: readonly string[],
@@ -893,22 +894,33 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
: { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
),
),
+ // Reordering is not a choice about what the panel shows, so it leaves the
+ // user-action revision alone and proactive opens still apply.
+ moveSurface: (ref, surfaceId, toIndex) =>
+ set((state) =>
+ updateThread(state, scopedThreadKey(ref), (current) => {
+ const fromIndex = current.surfaces.findIndex((surface) => surface.id === surfaceId);
+ if (fromIndex < 0 || fromIndex === toIndex) return current;
+ const surfaces = [...current.surfaces];
+ surfaces.splice(toIndex, 0, ...surfaces.splice(fromIndex, 1));
+ return { ...current, surfaces };
+ }),
+ ),
reconcileBrowserSurfaces: (ref, tabIds, hiddenTabIds) =>
set((state) =>
automaticUpdate(state, scopedThreadKey(ref), (current) => {
const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
- const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
- const existingBrowser = current.surfaces.filter(
- (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
- surface.kind === "preview" &&
- surface.id !== "browser:new" &&
- validIds.has(surface.id),
+ // Filtered in place so browser tabs keep the order the user dragged them into.
+ const kept = current.surfaces.filter(
+ (surface) =>
+ surface.kind !== "preview" ||
+ (surface.id !== "browser:new" && validIds.has(surface.id)),
);
- const knownIds = new Set(existingBrowser.map((surface) => surface.id));
+ const knownIds = new Set(kept.map((surface) => surface.id));
const added = tabIds
.filter((tabId) => !knownIds.has(`browser:${tabId}`) && !hiddenTabIds?.has(tabId))
.map((tabId) => browserSurface(tabId));
- const surfaces = [...nonBrowser, ...existingBrowser, ...added];
+ const surfaces = [...kept, ...added];
const activeStillExists = surfaces.some(
(surface) => surface.id === current.activeSurfaceId,
);
diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsx
index c6b0591ee25..02e0e9e26d4 100644
--- a/apps/web/src/routes/_chat.pull-requests.tsx
+++ b/apps/web/src/routes/_chat.pull-requests.tsx
@@ -2241,6 +2241,10 @@ function PullRequestsRouteView() {
if (surface.kind === "pull-request") closeSurfacesToRight(surface);
}}
onCloseAllSurfaces={closeAllSurfaces}
+ onMoveSurface={(surfaceId, toIndex) => {
+ if (rightPanelRef !== null)
+ useRightPanelStore.getState().moveSurface(rightPanelRef, surfaceId, toIndex);
+ }}
onCopyFilePath={() => undefined}
onAddBrowser={() => undefined}
onAddBrowserInProfile={() => undefined}