Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 137c50175e Refresh right panel close controls for PR #4148
Keep native close focus scoped to the active hosted preview and preserve pointer ownership across webview blur transitions.

Co-authored-by: codex <[email protected]>
2026-07-20 16:55:51 +02:00
caezium 73e5aeb1b4 Add right panel close controls 2026-07-20 16:40:08 +02:00
24 changed files with 1349 additions and 50 deletions

No files matched your search

@@ -78,6 +78,7 @@ function makePoolLayer(
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
dispatchMenuActionToMainWindow: () => Effect.die("unexpected menu action"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
+45 -7
View File
@@ -7,17 +7,22 @@ import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { buildFromTemplateMock, createFromNamedImageMock, setApplicationMenuMock } = vi.hoisted(
() => ({
buildFromTemplateMock: vi.fn(),
createFromNamedImageMock: vi.fn(),
setApplicationMenuMock: vi.fn(),
}),
);
const {
buildFromTemplateMock,
createFromNamedImageMock,
sendActionToFirstResponderMock,
setApplicationMenuMock,
} = vi.hoisted(() => ({
buildFromTemplateMock: vi.fn(),
createFromNamedImageMock: vi.fn(),
sendActionToFirstResponderMock: vi.fn(),
setApplicationMenuMock: vi.fn(),
}));
vi.mock("electron", () => ({
Menu: {
buildFromTemplate: buildFromTemplateMock,
sendActionToFirstResponder: sendActionToFirstResponderMock,
setApplicationMenu: setApplicationMenuMock,
},
nativeImage: {
@@ -41,6 +46,7 @@ describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
createFromNamedImageMock.mockReset();
sendActionToFirstResponderMock.mockReset();
setApplicationMenuMock.mockReset();
});
@@ -160,6 +166,38 @@ describe("ElectronMenu", () => {
}).pipe(Effect.provide(TestLayer)),
);
it.effect("sends native actions to the first responder", () =>
Effect.gen(function* () {
const electronMenu = yield* ElectronMenu.ElectronMenu;
yield* electronMenu.sendActionToFirstResponder("performClose:");
assert.deepEqual(sendActionToFirstResponderMock.mock.calls, [["performClose:"]]);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves first-responder failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("native action failed");
sendActionToFirstResponderMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(electronMenu.sendActionToFirstResponder("performClose:"));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "send-action-to-first-responder");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.equal(error.itemCount, 0);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves popup-template failures with window context", () =>
Effect.gen(function* () {
const cause = new Error("popup failed");
+14
View File
@@ -26,6 +26,7 @@ export interface ElectronMenuTemplateInput {
const ElectronMenuOperation = Schema.Literals([
"set-application-menu",
"send-action-to-first-responder",
"popup-template",
"show-context-menu",
]);
@@ -52,6 +53,7 @@ export class ElectronMenu extends Context.Service<
readonly setApplicationMenu: (
template: readonly Electron.MenuItemConstructorOptions[],
) => Effect.Effect<void>;
readonly sendActionToFirstResponder: (action: string) => Effect.Effect<void>;
readonly showContextMenu: (
input: ElectronMenuContextInput,
) => Effect.Effect<Option.Option<string>>;
@@ -185,6 +187,18 @@ export const make = Effect.gen(function* () {
cause,
}),
}).pipe(Effect.orDie),
sendActionToFirstResponder: (action) =>
Effect.try({
try: () => Electron.Menu.sendActionToFirstResponder(action),
catch: (cause) =>
new ElectronMenuOperationError({
operation: "send-action-to-first-responder",
platform,
windowId: null,
itemCount: 0,
cause,
}),
}).pipe(Effect.orDie),
popupTemplate: (input) =>
input.template.length === 0
? Effect.void
@@ -66,7 +66,10 @@ const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
install: Effect.die("unexpected install"),
} satisfies DesktopUpdates.DesktopUpdates["Service"]);
const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
const makeDesktopWindowLayer = (
selectedAction: Deferred.Deferred<string>,
mainWindowActionsHandled: boolean,
) =>
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected createMain"),
ensureMain: Effect.die("unexpected ensureMain"),
@@ -78,19 +81,55 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
dispatchMenuActionToMainWindow: (_window, action) =>
mainWindowActionsHandled
? Deferred.succeed(selectedAction, action).pipe(Effect.as(true))
: Effect.succeed(false),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
const makeElectronMenuLayer = (
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
nativeActions: string[] = [],
) =>
Layer.succeed(ElectronMenu.ElectronMenu, {
setApplicationMenu: (template) =>
Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid),
sendActionToFirstResponder: (action) =>
Effect.sync(() => {
nativeActions.push(action);
}),
popupTemplate: () => Effect.void,
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
const configureMenu = (
platform: "darwin" | "linux",
selectedAction: Deferred.Deferred<string>,
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
nativeActions: string[] = [],
mainWindowActionsHandled = true,
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate, nativeActions)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction, mainWindowActionsHandled)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer({ ...environmentInput, platform }).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
Effect.gen(function* () {
@@ -98,25 +137,7 @@ describe("DesktopApplicationMenu", () => {
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
yield* configureMenu("linux", selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
@@ -135,4 +156,86 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
it.effect("routes the macOS close shortcut through the renderer", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu("darwin", selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
assert.isDefined(fileMenu);
if (!Array.isArray(fileMenu.submenu)) {
throw new Error("Expected File menu submenu to be an array.");
}
const closeItem = fileMenu.submenu.find((item) => item.label === "Close Window");
assert.isDefined(closeItem);
assert.equal(closeItem.accelerator, "Cmd+W");
const closeClick = closeItem.click;
if (typeof closeClick !== "function") {
throw new Error("Expected Close Window menu item to have a click handler.");
}
closeClick({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.equal(yield* Deferred.await(selectedAction), "close-window-or-right-panel");
}),
);
it.effect("preserves native close behavior when system UI owns focus", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
const nativeActions: string[] = [];
yield* configureMenu("darwin", selectedAction, applicationMenuTemplate, nativeActions);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
assert.isDefined(fileMenu);
if (!Array.isArray(fileMenu.submenu)) {
throw new Error("Expected File menu submenu to be an array.");
}
const closeItem = fileMenu.submenu.find((item) => item.label === "Close Window");
assert.isDefined(closeItem);
const closeClick = closeItem.click;
if (typeof closeClick !== "function") {
throw new Error("Expected Close Window menu item to have a click handler.");
}
closeClick({} as Electron.MenuItem, undefined, {} as KeyboardEvent);
assert.deepEqual(nativeActions, ["performClose:"]);
}),
);
it.effect("preserves native close behavior for a non-main browser window", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
const nativeActions: string[] = [];
yield* configureMenu("darwin", selectedAction, applicationMenuTemplate, nativeActions, false);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
assert.isDefined(fileMenu);
if (!Array.isArray(fileMenu.submenu)) {
throw new Error("Expected File menu submenu to be an array.");
}
const closeItem = fileMenu.submenu.find((item) => item.label === "Close Window");
assert.isDefined(closeItem);
const closeClick = closeItem.click;
if (typeof closeClick !== "function") {
throw new Error("Expected Close Window menu item to have a click handler.");
}
closeClick({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
yield* Effect.yieldNow;
assert.deepEqual(nativeActions, ["performClose:"]);
}),
);
});
@@ -127,6 +127,31 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
const closeWindowClick: NonNullable<Electron.MenuItemConstructorOptions["click"]> = (
_menuItem,
browserWindow,
) => {
if (!browserWindow) {
runMenuEffect(
"close-focused-native-window",
electronMenu.sendActionToFirstResponder("performClose:"),
);
return;
}
runMenuEffect(
"close-window-or-right-panel",
Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const handled = yield* desktopWindow.dispatchMenuActionToMainWindow(
browserWindow,
"close-window-or-right-panel",
);
if (!handled) {
yield* electronMenu.sendActionToFirstResponder("performClose:");
}
}),
);
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -170,7 +195,15 @@ export const make = Effect.gen(function* () {
},
{ type: "separator" as const },
]),
{ role: environment.platform === "darwin" ? "close" : "quit" },
...(environment.platform === "darwin"
? [
{
label: "Close Window",
accelerator: "Cmd+W",
click: closeWindowClick,
},
]
: [{ role: "quit" as const }]),
],
},
{ role: "editMenu" },
@@ -148,6 +148,7 @@ const desktopServerExposureLayer = Layer.succeed(DesktopServerExposure.DesktopSe
const electronMenuLayer = Layer.succeed(ElectronMenu.ElectronMenu, {
setApplicationMenu: () => Effect.void,
sendActionToFirstResponder: () => Effect.void,
popupTemplate: () => Effect.void,
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
@@ -1096,4 +1097,27 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("dispatches targeted menu actions only to the registered main window", () =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
const scenario = yield* makeSplashScenario([splash.window]);
yield* Ref.set(scenario.mainWindow, Option.some(main.window));
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
assert.isTrue(
yield* desktopWindow.dispatchMenuActionToMainWindow(main.window, "close-window"),
);
assert.isFalse(
yield* desktopWindow.dispatchMenuActionToMainWindow(splash.window, "close-window"),
);
assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "close-window"]]);
assert.equal(splash.send.mock.calls.length, 0);
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), []);
}).pipe(Effect.provide(scenario.layer));
}),
);
});
+31 -13
View File
@@ -80,6 +80,10 @@ export class DesktopWindow extends Context.Service<
readonly handleBackendNotReady: Effect.Effect<void>;
readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly dispatchMenuActionToMainWindow: (
window: Electron.BaseWindow,
action: string,
) => Effect.Effect<boolean, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
>()("@t3tools/desktop/window/DesktopWindow") {}
@@ -286,6 +290,24 @@ export const make = Effect.gen(function* () {
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const sendMenuAction = Effect.fn("desktop.window.sendMenuAction")(
(targetWindow: Electron.BrowserWindow, action: string, reveal: boolean) =>
Effect.sync(() => {
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
if (reveal) void runPromise(electronWindow.reveal(targetWindow));
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
}),
);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
DesktopWindowError
@@ -772,20 +794,16 @@ export const make = Effect.gen(function* () {
return;
}
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
const send = () => {
if (targetWindow.isDestroyed()) return;
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
void runPromise(electronWindow.reveal(targetWindow));
};
if (targetWindow.webContents.isLoadingMainFrame()) {
targetWindow.webContents.once("did-finish-load", send);
return;
}
send();
yield* sendMenuAction(targetWindow, action, true);
}),
dispatchMenuActionToMainWindow: Effect.fn("desktop.window.dispatchMenuActionToMainWindow")(
function* (window, action) {
const mainWindow = yield* electronWindow.main;
if (Option.isNone(mainWindow) || mainWindow.value !== window) return false;
yield* sendMenuAction(mainWindow.value, action, false);
return true;
},
),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
@@ -6,6 +6,7 @@ import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { requestCloseActiveRightPanelSurface } from "../lib/rightPanelCloseRequest";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import ThreadSidebar from "./Sidebar";
@@ -144,6 +145,13 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
if (!isSettingsRoute) {
void navigate({ to: "/settings" });
}
return;
}
if (action === "close-window-or-right-panel") {
if (!requestCloseActiveRightPanelSurface()) {
window.close();
}
}
});
+152 -1
View File
@@ -48,6 +48,7 @@ import {
Suspense,
useCallback,
useEffect,
useEffectEvent,
useLayoutEffect,
useMemo,
useRef,
@@ -155,6 +156,21 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
import { useEnvironmentSettings } from "../hooks/useSettings";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import {
clearNativeCloseFocusOwner,
finishNativeClosePointer,
getNativeCloseFocusOwner,
recordNativeCloseFocus,
recordNativeCloseFocusOut,
recordNativeClosePointer,
} from "../lib/nativeCloseFocus";
import { isRightPanelFocused } from "../lib/rightPanelFocus";
import {
CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT,
resolveNativeCloseTarget,
resolveRightPanelCloseTarget,
shouldDeferCloseCommandToDesktopMenu,
} from "../lib/rightPanelCloseRequest";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
deriveLogicalProjectKeyFromSettings,
@@ -208,7 +224,11 @@ import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { MessagesTimeline } from "./chat/MessagesTimeline";
import { ChatHeader } from "./chat/ChatHeader";
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
import {
PanelLayoutControls,
RightPanelCloseControl,
RightPanelMaximizeControl,
} from "./chat/PanelLayoutControls";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { NoActiveThreadState } from "./NoActiveThreadState";
import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";
@@ -1459,6 +1479,13 @@ function ChatViewContent(props: ChatViewProps) {
canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey;
const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;
useEffect(() => {
if (rightPanelOpen) return;
setMaximizedRightPanelThreadKey((threadKey) =>
threadKey === routeThreadKey ? null : threadKey,
);
}, [rightPanelOpen, routeThreadKey]);
useEffect(() => {
if (!activeThreadRef) return;
useRightPanelStore
@@ -3146,6 +3173,103 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface],
);
const activeRightPanelPreviewTabId =
activeRightPanelSurface?.kind === "preview"
? (activeRightPanelSurface.resourceId ?? null)
: null;
const closeActiveRightPanelTarget = useCallback(
(terminalFocusOwner = getTerminalFocusOwner()) => {
const target = resolveRightPanelCloseTarget({
isOpen: rightPanelOpen,
hasActiveSurface: activeRightPanelSurface !== null,
hasFocusedTerminal:
activeRightPanelSurface?.kind === "terminal" && terminalFocusOwner === "right-panel",
});
if (target === "terminal" && activeRightPanelSurface?.kind === "terminal") {
closePanelTerminal(activeRightPanelSurface.activeTerminalId);
} else if (target === "surface" && activeRightPanelSurface) {
closeRightPanelSurface(activeRightPanelSurface);
} else if (target === "panel" && activeThreadRef) {
setMaximizedRightPanelThreadKey(null);
useRightPanelStore.getState().close(activeThreadRef);
}
return target !== null;
},
[
activeRightPanelSurface,
activeThreadRef,
closePanelTerminal,
closeRightPanelSurface,
rightPanelOpen,
],
);
const handleCloseRequest = useEffectEvent((event: Event) => {
const target = resolveNativeCloseTarget({
focusOwner: getNativeCloseFocusOwner(activeRightPanelPreviewTabId),
drawerTerminalOpen: terminalUiState.terminalOpen,
rightPanelOpen,
hasActiveRightPanelSurface: activeRightPanelSurface !== null,
activeRightPanelSurfaceIsTerminal: activeRightPanelSurface?.kind === "terminal",
});
if (target === "drawer-terminal") {
closeTerminal(terminalUiState.activeTerminalId);
} else if (target === "right-panel-terminal" && activeRightPanelSurface?.kind === "terminal") {
closePanelTerminal(activeRightPanelSurface.activeTerminalId);
} else if (target === "right-panel-surface" && activeRightPanelSurface) {
closeRightPanelSurface(activeRightPanelSurface);
} else if (target === "right-panel" && activeThreadRef) {
setMaximizedRightPanelThreadKey(null);
useRightPanelStore.getState().close(activeThreadRef);
} else {
return;
}
event.preventDefault();
});
useEffect(() => {
const listener = (event: Event) => handleCloseRequest(event);
window.addEventListener(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, listener);
return () => {
window.removeEventListener(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, listener);
};
}, []);
useEffect(() => {
const recordFocus = (event: FocusEvent | PointerEvent) => {
recordNativeCloseFocus(event.target, activeRightPanelPreviewTabId);
};
const recordFocusOut = (event: FocusEvent) => {
recordNativeCloseFocusOut(
event.relatedTarget,
document.hasFocus(),
activeRightPanelPreviewTabId,
);
};
const recordPointer = (event: PointerEvent) => {
recordNativeClosePointer(event.target, activeRightPanelPreviewTabId);
};
recordNativeCloseFocus(document.activeElement, activeRightPanelPreviewTabId);
window.addEventListener("focusin", recordFocus, true);
window.addEventListener("focusout", recordFocusOut, true);
window.addEventListener("pointerdown", recordPointer, true);
window.addEventListener("pointerup", finishNativeClosePointer, true);
window.addEventListener("pointercancel", finishNativeClosePointer, true);
return () => {
window.removeEventListener("focusin", recordFocus, true);
window.removeEventListener("focusout", recordFocusOut, true);
window.removeEventListener("pointerdown", recordPointer, true);
window.removeEventListener("pointerup", finishNativeClosePointer, true);
window.removeEventListener("pointercancel", finishNativeClosePointer, true);
clearNativeCloseFocusOwner();
};
}, [activeRightPanelPreviewTabId, routeThreadKey]);
useEffect(() => {
if (!terminalUiState.terminalOpen) clearNativeCloseFocusOwner("drawer-terminal");
if (!rightPanelOpen) {
clearNativeCloseFocusOwner("right-panel-terminal");
clearNativeCloseFocusOwner("right-panel");
}
}, [rightPanelOpen, terminalUiState.terminalOpen]);
const closeOtherRightPanelSurfaces = useCallback(
(surface: RightPanelSurface) => {
if (!activeThreadRef) return;
@@ -3832,6 +3956,10 @@ function ChatViewContent(props: ChatViewProps) {
terminalFocus: terminalFocusOwner !== null,
terminalOpen: Boolean(terminalUiState.terminalOpen),
modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
rightPanelFocus: isRightPanelFocused({
rightPanelOpen,
activePreviewTabId: activeRightPanelPreviewTabId,
}),
};
if (
@@ -3851,6 +3979,18 @@ function ChatViewContent(props: ChatViewProps) {
});
if (!command) return;
if (
shouldDeferCloseCommandToDesktopMenu({
command,
desktop: isElectron,
platform: navigator.platform,
event,
terminalFocused: terminalFocusOwner !== null,
})
) {
return;
}
if (command === "terminal.toggle") {
event.preventDefault();
event.stopPropagation();
@@ -3865,6 +4005,13 @@ function ChatViewContent(props: ChatViewProps) {
return;
}
if (command === "rightPanel.closeActiveSurface") {
if (!closeActiveRightPanelTarget()) return;
event.preventDefault();
event.stopPropagation();
return;
}
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
@@ -3952,6 +4099,7 @@ function ChatViewContent(props: ChatViewProps) {
activeThreadId,
closeTerminal,
closePanelTerminal,
closeActiveRightPanelTarget,
createNewTerminal,
setTerminalOpen,
runProjectScript,
@@ -5110,6 +5258,9 @@ function ChatViewContent(props: ChatViewProps) {
/>
) : null}
{panelToggleControls}
{rightPanelOpen && !shouldUsePlanSidebarSheet ? (
<RightPanelCloseControl onClose={toggleRightPanel} />
) : null}
</div>
);
const rightPanelContent = activeThreadRef ? (
@@ -0,0 +1,104 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { handleSurfaceTabAuxClick } from "~/lib/rightPanelTabPointer";
import { RightPanelTabs } from "./RightPanelTabs";
import {
PanelLayoutControls,
RightPanelCloseControl,
RightPanelMaximizeControl,
} from "./chat/PanelLayoutControls";
vi.mock("~/env", () => ({ isElectron: false }));
function renderTabs(mode: "inline" | "sheet"): string {
return renderToStaticMarkup(
<RightPanelTabs
mode={mode}
surfaces={[]}
activeSurfaceId={null}
pendingSurfaceIds={new Set()}
previewSessions={{}}
terminalLabelsById={new Map()}
onActivate={vi.fn()}
onCloseSurface={vi.fn()}
onCloseOtherSurfaces={vi.fn()}
onCloseSurfacesToRight={vi.fn()}
onCloseAllSurfaces={vi.fn()}
onCopyFilePath={vi.fn()}
onAddBrowser={vi.fn()}
onAddTerminal={vi.fn()}
onAddDiff={vi.fn()}
onAddFiles={vi.fn()}
browserAvailable
diffAvailable
filesAvailable
>
<div>Active surface</div>
</RightPanelTabs>,
);
}
describe("RightPanelTabs", () => {
it("closes the clicked surface on middle mouse button", () => {
const surface = { id: "files", kind: "files" } as const;
const event = {
button: 1,
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
};
const onCloseSurface = vi.fn();
handleSurfaceTabAuxClick(event, surface, onCloseSurface);
expect(event.preventDefault).toHaveBeenCalledOnce();
expect(event.stopPropagation).toHaveBeenCalledOnce();
expect(onCloseSurface).toHaveBeenCalledOnce();
expect(onCloseSurface).toHaveBeenCalledWith(surface);
});
it.each([0, 2])("ignores auxiliary click button %s", (button) => {
const event = {
button,
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
};
const onCloseSurface = vi.fn();
handleSurfaceTabAuxClick(event, { id: "files", kind: "files" }, onCloseSurface);
expect(event.preventDefault).not.toHaveBeenCalled();
expect(event.stopPropagation).not.toHaveBeenCalled();
expect(onCloseSurface).not.toHaveBeenCalled();
});
it("marks the panel content region", () => {
const markup = renderTabs("inline");
expect(markup).toContain("data-right-panel-content");
});
it("places the whole-panel close control after the other title-bar controls", () => {
const markup = renderToStaticMarkup(
<div>
<RightPanelMaximizeControl maximized={false} onToggle={vi.fn()} />
<PanelLayoutControls
terminalAvailable
terminalOpen={false}
terminalShortcutLabel={null}
rightPanelAvailable
rightPanelOpen
rightPanelShortcutLabel={null}
onToggleTerminal={vi.fn()}
onToggleRightPanel={vi.fn()}
/>
<RightPanelCloseControl onClose={vi.fn()} />
</div>,
);
expect(markup.indexOf('aria-label="Close right panel"')).toBeGreaterThan(
markup.indexOf('aria-label="Toggle right panel"'),
);
});
});
+5 -7
View File
@@ -19,6 +19,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
import { handleSurfaceTabAuxClick } from "~/lib/rightPanelTabPointer";
import { useTheme } from "~/hooks/useTheme";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
@@ -337,10 +338,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
}, []);
const handleTabAuxClick = useCallback(
(event: ReactMouseEvent, surface: RightPanelSurface) => {
if (event.button !== 1) return;
event.preventDefault();
event.stopPropagation();
props.onCloseSurface(surface);
handleSurfaceTabAuxClick(event, surface, props.onCloseSurface);
},
[props],
);
@@ -358,8 +356,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<div
className={cn(
"workspace-topbar gap-1 pl-2",
props.mode === "inline" ? "pr-28" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
props.mode === "inline" ? "pr-36" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+8rem)]",
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
data-right-panel-tabbar
@@ -477,7 +475,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
</ScrollArea>
{props.layoutControls}
</div>
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex min-h-0 flex-1 flex-col" data-right-panel-content>
{props.activeSurfaceId === null ? (
<RightPanelEmptyState
onAddBrowser={props.onAddBrowser}
@@ -1,6 +1,7 @@
import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon } from "lucide-react";
import { Maximize2Icon, Minimize2Icon, PanelBottomIcon, PanelRightIcon, XIcon } from "lucide-react";
import { memo } from "react";
import { Button } from "../ui/button";
import { Toggle } from "../ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -57,6 +58,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
data-right-panel-control
pressed={rightPanelOpen}
onPressedChange={onToggleRightPanel}
aria-label="Toggle right panel"
@@ -92,6 +94,7 @@ export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
data-right-panel-control
pressed={maximized}
onPressedChange={onToggle}
aria-label={label}
@@ -110,3 +113,29 @@ export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl
</Tooltip>
);
});
export const RightPanelCloseControl = memo(function RightPanelCloseControl({
onClose,
}: {
onClose: () => void;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Button
className="[-webkit-app-region:no-drag]"
data-right-panel-control
variant="ghost"
size="icon-sm"
aria-label="Close right panel"
onClick={onClose}
>
<XIcon className="size-4" />
</Button>
}
/>
<TooltipPopup side="bottom">Close right panel</TooltipPopup>
</Tooltip>
);
});
+33
View File
@@ -108,6 +108,11 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("w"),
command: "rightPanel.closeActiveSurface",
whenAst: whenAnd(whenIdentifier("rightPanelFocus"), whenNot(whenIdentifier("terminalFocus"))),
},
{
shortcut: modShortcut("d"),
command: "diff.toggle",
@@ -289,6 +294,34 @@ describe("split/new/close terminal shortcuts", () => {
});
});
describe("right panel close shortcut", () => {
it("matches Cmd+W only while the right panel owns focus", () => {
assert.strictEqual(
resolveShortcutCommand(event({ key: "w", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { rightPanelFocus: true },
}),
"rightPanel.closeActiveSurface",
);
assert.isNull(
resolveShortcutCommand(event({ key: "w", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { rightPanelFocus: false },
}),
);
});
it("keeps terminal close active for a focused right-panel terminal", () => {
assert.strictEqual(
resolveShortcutCommand(event({ key: "w", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel",
context: { rightPanelFocus: true, terminalFocus: true },
}),
"terminal.close",
);
});
});
describe("shortcutLabelForCommand", () => {
it("returns the effective binding label", () => {
const bindings = compile([
+2
View File
@@ -32,6 +32,7 @@ export interface ShortcutMatchContext {
terminalOpen: boolean;
previewFocus: boolean;
previewOpen: boolean;
rightPanelFocus: boolean;
[key: string]: boolean;
}
@@ -120,6 +121,7 @@ function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatc
terminalOpen: false,
previewFocus: false,
previewOpen: false,
rightPanelFocus: false,
...options?.context,
};
}
+166
View File
@@ -0,0 +1,166 @@
import { afterEach, describe, expect, it } from "vite-plus/test";
import {
clearNativeCloseFocusOwner,
finishNativeClosePointer,
getNativeCloseFocusOwner,
recordNativeCloseFocus,
recordNativeCloseFocusOut,
recordNativeClosePointer,
} from "./nativeCloseFocus";
class MockElement extends EventTarget {
isConnected = true;
owner: "drawer" | "right-panel" | null = null;
inRightPanel = false;
inPreviewViewport = false;
previewTabId: string | null = null;
tagName = "div";
closest(selector: string): MockElement | null {
if (!this.isConnected) return null;
if (selector === "[data-terminal-owner]" && this.owner !== null) return this;
if (selector.includes("[data-right-panel-tabbar]") && this.inRightPanel) return this;
if (selector === "[data-preview-viewport]" && this.inPreviewViewport) return this;
return null;
}
get dataset(): DOMStringMap {
return { terminalOwner: this.owner ?? undefined } as DOMStringMap;
}
getAttribute(name: string): string | null {
if (name === "data-preview-tab" || name === "data-preview-viewport") {
return this.previewTabId;
}
return null;
}
}
const originalDocument = globalThis.document;
const originalElement = globalThis.Element;
afterEach(() => {
clearNativeCloseFocusOwner();
if (originalDocument === undefined) {
delete (globalThis as { document?: Document }).document;
} else {
globalThis.document = originalDocument;
}
if (originalElement === undefined) {
delete (globalThis as { Element?: typeof Element }).Element;
} else {
globalThis.Element = originalElement;
}
});
function installDom(activeElement: MockElement, body = new MockElement()): void {
globalThis.Element = MockElement as unknown as typeof Element;
globalThis.document = { activeElement, body } as unknown as Document;
}
describe("native close focus", () => {
it("distinguishes drawer terminals, right-panel terminals, and other panel focus", () => {
const drawer = new MockElement();
drawer.owner = "drawer";
installDom(drawer);
expect(getNativeCloseFocusOwner(null)).toBe("drawer-terminal");
const panelTerminal = new MockElement();
panelTerminal.owner = "right-panel";
installDom(panelTerminal);
expect(getNativeCloseFocusOwner(null)).toBe("right-panel-terminal");
const panelControl = new MockElement();
panelControl.inRightPanel = true;
installDom(panelControl);
expect(getNativeCloseFocusOwner(null)).toBe("right-panel");
});
it("retains ownership only while focus is obscured by native UI", () => {
const terminal = new MockElement();
terminal.owner = "drawer";
const body = new MockElement();
installDom(body, body);
recordNativeCloseFocus(terminal, null);
recordNativeCloseFocusOut(null, false, null);
expect(getNativeCloseFocusOwner(null)).toBe("drawer-terminal");
recordNativeCloseFocusOut(null, true, null);
expect(getNativeCloseFocusOwner(null)).toBeNull();
});
it("preserves pointer ownership until the pointer gesture finishes", async () => {
const panelChrome = new MockElement();
panelChrome.inRightPanel = true;
const body = new MockElement();
installDom(body, body);
recordNativeClosePointer(panelChrome, null);
await Promise.resolve();
recordNativeCloseFocusOut(null, true, null);
finishNativeClosePointer();
expect(getNativeCloseFocusOwner(null)).toBe("right-panel");
});
it("clears retained ownership on focus or pointer movement outside the panel", () => {
const panel = new MockElement();
panel.inRightPanel = true;
const outside = new MockElement();
installDom(outside);
recordNativeCloseFocus(panel, null);
recordNativeCloseFocus(outside, null);
expect(getNativeCloseFocusOwner(null)).toBeNull();
});
it("updates ownership directly from a focusout related target", () => {
const drawer = new MockElement();
drawer.owner = "drawer";
const panel = new MockElement();
panel.inRightPanel = true;
installDom(panel);
recordNativeCloseFocus(drawer, null);
recordNativeCloseFocusOut(panel, true, null);
expect(getNativeCloseFocusOwner(null)).toBe("right-panel");
});
it("treats hosted preview webviews and viewport chrome as right-panel focus", () => {
const webview = new MockElement();
webview.tagName = "webview";
webview.previewTabId = "active-preview";
installDom(webview);
expect(getNativeCloseFocusOwner("active-preview")).toBe("right-panel");
const viewport = new MockElement();
viewport.inPreviewViewport = true;
viewport.previewTabId = "active-preview";
installDom(viewport);
expect(getNativeCloseFocusOwner("active-preview")).toBe("right-panel");
});
it("ignores previews that are not the active right-panel preview", () => {
const webview = new MockElement();
webview.tagName = "webview";
webview.previewTabId = "standalone-preview";
installDom(webview);
recordNativeClosePointer(webview, "right-panel-preview");
expect(getNativeCloseFocusOwner("right-panel-preview")).toBeNull();
});
it("ignores detached retained targets", () => {
const terminal = new MockElement();
terminal.owner = "drawer";
terminal.isConnected = false;
const body = new MockElement();
installDom(body, body);
recordNativeCloseFocus(terminal, null);
expect(getNativeCloseFocusOwner(null)).toBeNull();
});
});
+92
View File
@@ -0,0 +1,92 @@
export type NativeCloseFocusOwner = "drawer-terminal" | "right-panel-terminal" | "right-panel";
const RIGHT_PANEL_SELECTOR =
"[data-right-panel-tabbar], [data-right-panel-content], [data-right-panel-control]";
let retainedOwner: NativeCloseFocusOwner | null = null;
let pointerTransitionActive = false;
function ownerForElement(
element: Element,
activePreviewTabId: string | null,
): NativeCloseFocusOwner | null {
if (!element.isConnected) return null;
const terminalOwner =
element.closest<HTMLElement>("[data-terminal-owner]")?.dataset.terminalOwner;
if (terminalOwner === "drawer") return "drawer-terminal";
if (terminalOwner === "right-panel") return "right-panel-terminal";
const previewViewport = element.closest<HTMLElement>("[data-preview-viewport]");
const focusedPreviewTabId =
element.tagName.toLowerCase() === "webview"
? element.getAttribute("data-preview-tab")
: (previewViewport?.getAttribute("data-preview-viewport") ?? null);
if (focusedPreviewTabId !== null) {
return focusedPreviewTabId === activePreviewTabId ? "right-panel" : null;
}
if (element.closest(RIGHT_PANEL_SELECTOR)) return "right-panel";
return null;
}
/** Records an in-document focus or pointer transition before native UI can obscure DOM focus. */
export function recordNativeCloseFocus(
target: EventTarget | null,
activePreviewTabId: string | null,
): void {
retainedOwner = target instanceof Element ? ownerForElement(target, activePreviewTabId) : null;
}
/** Records pointer intent before a non-focusable target can blur the previous owner to body. */
export function recordNativeClosePointer(
target: EventTarget | null,
activePreviewTabId: string | null,
): void {
pointerTransitionActive = true;
recordNativeCloseFocus(target, activePreviewTabId);
}
export function finishNativeClosePointer(): void {
pointerTransitionActive = false;
}
/**
* Clears real in-document focus exits while preserving ownership when focus
* temporarily moves into native application UI such as the macOS menu bar.
*/
export function recordNativeCloseFocusOut(
relatedTarget: EventTarget | null,
documentHasFocus: boolean,
activePreviewTabId: string | null,
): void {
if (relatedTarget instanceof Element) {
retainedOwner = ownerForElement(relatedTarget, activePreviewTabId);
return;
}
if (documentHasFocus && !pointerTransitionActive) retainedOwner = null;
}
export function getNativeCloseFocusOwner(
activePreviewTabId: string | null,
): NativeCloseFocusOwner | null {
const activeElement = document.activeElement;
if (activeElement instanceof Element && activeElement.isConnected) {
const liveOwner = ownerForElement(activeElement, activePreviewTabId);
if (liveOwner !== null) {
retainedOwner = liveOwner;
return liveOwner;
}
if (activeElement !== document.body) {
retainedOwner = null;
return null;
}
}
return retainedOwner;
}
export function clearNativeCloseFocusOwner(owner?: NativeCloseFocusOwner): void {
if (owner !== undefined && retainedOwner !== owner) return;
retainedOwner = null;
pointerTransitionActive = false;
}
@@ -0,0 +1,216 @@
import { describe, expect, it } from "vite-plus/test";
import {
CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT,
requestCloseActiveRightPanelSurface,
resolveNativeCloseTarget,
resolveRightPanelCloseTarget,
shouldDeferCloseCommandToDesktopMenu,
shouldDeferCloseShortcutToDesktopMenu,
} from "./rightPanelCloseRequest";
const keyboardEvent = (overrides: Partial<KeyboardEvent> = {}) =>
({
code: "KeyW",
key: "w",
metaKey: true,
ctrlKey: false,
shiftKey: false,
altKey: false,
...overrides,
}) as KeyboardEvent;
describe("requestCloseActiveRightPanelSurface", () => {
it("reports when the active right-panel surface handles the request", () => {
const target = new EventTarget();
target.addEventListener(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, (event) => {
event.preventDefault();
});
expect(requestCloseActiveRightPanelSurface(target)).toBe(true);
});
it("leaves an unhandled request available for window closing", () => {
expect(requestCloseActiveRightPanelSurface(new EventTarget())).toBe(false);
});
it("defers the native Cmd+W accelerator only in the macOS desktop app", () => {
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent(),
}),
).toBe(true);
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: false,
platform: "MacIntel",
event: keyboardEvent(),
}),
).toBe(false);
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "Win32",
event: keyboardEvent(),
}),
).toBe(false);
});
it("keeps rebound macOS shortcuts in the renderer", () => {
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent({ code: "KeyK", key: "k" }),
}),
).toBe(false);
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent({ shiftKey: true }),
}),
).toBe(false);
});
it("defers Cmd+W when the physical key and layout character differ", () => {
expect(
shouldDeferCloseShortcutToDesktopMenu({
desktop: true,
platform: "MacIntel",
event: keyboardEvent({ key: "z" }),
}),
).toBe(true);
});
it("defers native Cmd+W for focused terminal close commands", () => {
expect(
shouldDeferCloseCommandToDesktopMenu({
command: "terminal.close",
desktop: true,
event: keyboardEvent(),
platform: "MacIntel",
terminalFocused: true,
}),
).toBe(true);
expect(
shouldDeferCloseCommandToDesktopMenu({
command: "terminal.close",
desktop: true,
event: keyboardEvent(),
platform: "MacIntel",
terminalFocused: false,
}),
).toBe(false);
});
});
describe("resolveRightPanelCloseTarget", () => {
it("closes the active surface when the open panel has one", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: true,
hasActiveSurface: true,
hasFocusedTerminal: false,
}),
).toBe("surface");
});
it("closes the focused terminal pane before its containing surface", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: true,
hasActiveSurface: true,
hasFocusedTerminal: true,
}),
).toBe("terminal");
});
it("closes the panel itself when it is open without a surface", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: true,
hasActiveSurface: false,
hasFocusedTerminal: false,
}),
).toBe("panel");
});
it("does not intercept window close when the panel is hidden", () => {
expect(
resolveRightPanelCloseTarget({
isOpen: false,
hasActiveSurface: true,
hasFocusedTerminal: false,
}),
).toBeNull();
});
});
describe("resolveNativeCloseTarget", () => {
const defaults = {
focusOwner: null,
drawerTerminalOpen: true,
rightPanelOpen: true,
hasActiveRightPanelSurface: true,
activeRightPanelSurfaceIsTerminal: false,
} as const;
it("does not intercept window close when focus is outside an open panel", () => {
expect(resolveNativeCloseTarget(defaults)).toBeNull();
});
it("closes a focused drawer terminal before an open right panel", () => {
expect(resolveNativeCloseTarget({ ...defaults, focusOwner: "drawer-terminal" })).toBe(
"drawer-terminal",
);
});
it("ignores stale drawer ownership after the drawer closes", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "drawer-terminal",
drawerTerminalOpen: false,
}),
).toBeNull();
});
it("closes only the focused pane in a right-panel terminal group", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "right-panel-terminal",
activeRightPanelSurfaceIsTerminal: true,
}),
).toBe("right-panel-terminal");
});
it("closes the active surface for other right-panel focus", () => {
expect(resolveNativeCloseTarget({ ...defaults, focusOwner: "right-panel" })).toBe(
"right-panel-surface",
);
});
it("closes an empty focused panel without closing the window", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "right-panel",
hasActiveRightPanelSurface: false,
}),
).toBe("right-panel");
});
it("does not intercept after the right panel closes", () => {
expect(
resolveNativeCloseTarget({
...defaults,
focusOwner: "right-panel",
rightPanelOpen: false,
}),
).toBeNull();
});
});
@@ -0,0 +1,96 @@
import { isMacPlatform } from "./utils";
import type { NativeCloseFocusOwner } from "./nativeCloseFocus";
export const CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT = "t3:close-active-right-panel-surface";
interface NativeCloseShortcutInput {
readonly desktop: boolean;
readonly platform: string;
readonly event: {
readonly code?: string;
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
};
}
export function shouldDeferCloseShortcutToDesktopMenu({
desktop,
platform,
event,
}: NativeCloseShortcutInput): boolean {
return (
desktop &&
isMacPlatform(platform) &&
(event.key.toLowerCase() === "w" || event.code === "KeyW") &&
event.metaKey &&
!event.ctrlKey &&
!event.shiftKey &&
!event.altKey
);
}
export function shouldDeferCloseCommandToDesktopMenu({
command,
terminalFocused,
...shortcut
}: NativeCloseShortcutInput & {
readonly command: string;
readonly terminalFocused: boolean;
}): boolean {
const isNativeCloseCommand =
command === "rightPanel.closeActiveSurface" ||
(command === "terminal.close" && terminalFocused);
return isNativeCloseCommand && shouldDeferCloseShortcutToDesktopMenu(shortcut);
}
export function resolveRightPanelCloseTarget({
isOpen,
hasActiveSurface,
hasFocusedTerminal,
}: {
readonly isOpen: boolean;
readonly hasActiveSurface: boolean;
readonly hasFocusedTerminal: boolean;
}): "terminal" | "surface" | "panel" | null {
if (!isOpen) return null;
if (hasFocusedTerminal) return "terminal";
return hasActiveSurface ? "surface" : "panel";
}
export function resolveNativeCloseTarget({
focusOwner,
drawerTerminalOpen,
rightPanelOpen,
hasActiveRightPanelSurface,
activeRightPanelSurfaceIsTerminal,
}: {
readonly focusOwner: NativeCloseFocusOwner | null;
readonly drawerTerminalOpen: boolean;
readonly rightPanelOpen: boolean;
readonly hasActiveRightPanelSurface: boolean;
readonly activeRightPanelSurfaceIsTerminal: boolean;
}): "drawer-terminal" | "right-panel-terminal" | "right-panel-surface" | "right-panel" | null {
if (focusOwner === "drawer-terminal") {
return drawerTerminalOpen ? "drawer-terminal" : null;
}
if (focusOwner !== "right-panel" && focusOwner !== "right-panel-terminal") return null;
if (!rightPanelOpen) return null;
if (!hasActiveRightPanelSurface) return "right-panel";
if (focusOwner === "right-panel-terminal" && activeRightPanelSurfaceIsTerminal) {
return "right-panel-terminal";
}
return "right-panel-surface";
}
export function requestCloseActiveRightPanelSurface(
target: Pick<Window, "dispatchEvent"> = window,
): boolean {
const event = new Event(CLOSE_ACTIVE_RIGHT_PANEL_SURFACE_EVENT, {
cancelable: true,
});
target.dispatchEvent(event);
return event.defaultPrevented;
}
+113
View File
@@ -0,0 +1,113 @@
import { afterEach, describe, expect, it } from "vite-plus/test";
import { isRightPanelFocused } from "./rightPanelFocus";
class MockHTMLElement {
isConnected = false;
rightPanelRegion = false;
inPreviewViewport = false;
previewTabId: string | null = null;
tagName = "div";
closest(selector: string): MockHTMLElement | null {
if (!this.isConnected) return null;
if (selector === "[data-preview-viewport]" && this.inPreviewViewport) return this;
if (
selector ===
"[data-right-panel-tabbar], [data-right-panel-content], [data-right-panel-control]" &&
this.rightPanelRegion
) {
return this;
}
return null;
}
getAttribute(name: string): string | null {
if (name === "data-preview-tab" || name === "data-preview-viewport") {
return this.previewTabId;
}
return null;
}
}
const originalDocument = globalThis.document;
const originalHTMLElement = globalThis.HTMLElement;
afterEach(() => {
if (originalDocument === undefined) {
delete (globalThis as { document?: Document }).document;
} else {
globalThis.document = originalDocument;
}
if (originalHTMLElement === undefined) {
delete (globalThis as { HTMLElement?: typeof HTMLElement }).HTMLElement;
} else {
globalThis.HTMLElement = originalHTMLElement;
}
});
describe("isRightPanelFocused", () => {
it("recognizes focus in the right-panel tab bar or active surface", () => {
const activeElement = new MockHTMLElement();
activeElement.isConnected = true;
activeElement.rightPanelRegion = true;
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: null })).toBe(true);
});
it("recognizes hosted preview focus while the right panel is open", () => {
const webview = new MockHTMLElement();
webview.isConnected = true;
webview.tagName = "webview";
webview.previewTabId = "preview-a";
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement: webview } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: "preview-a" })).toBe(
true,
);
const viewport = new MockHTMLElement();
viewport.isConnected = true;
viewport.inPreviewViewport = true;
viewport.previewTabId = "preview-a";
globalThis.document = { activeElement: viewport } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: "preview-a" })).toBe(
true,
);
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: "preview-b" })).toBe(
false,
);
});
it("ignores right-panel controls when the panel is closed", () => {
const activeElement = new MockHTMLElement();
activeElement.isConnected = true;
activeElement.rightPanelRegion = true;
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: false, activePreviewTabId: null })).toBe(false);
});
it("ignores detached elements and focus outside the right panel", () => {
const activeElement = new MockHTMLElement();
activeElement.rightPanelRegion = true;
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement } as unknown as Document;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: null })).toBe(false);
activeElement.isConnected = true;
activeElement.rightPanelRegion = false;
expect(isRightPanelFocused({ rightPanelOpen: true, activePreviewTabId: null })).toBe(false);
});
});
+30
View File
@@ -0,0 +1,30 @@
/**
* Returns true when keyboard focus belongs to the tabbed right-panel chrome
* or its active surface. This deliberately excludes other preview-panel
* shells so right-panel shortcuts do not affect standalone preview layouts.
*/
export function isRightPanelFocused({
rightPanelOpen,
activePreviewTabId,
}: {
readonly rightPanelOpen: boolean;
readonly activePreviewTabId: string | null;
}): boolean {
if (!rightPanelOpen) return false;
const activeElement = document.activeElement;
if (!(activeElement instanceof HTMLElement)) return false;
if (!activeElement.isConnected) return false;
const previewViewport = activeElement.closest<HTMLElement>("[data-preview-viewport]");
const focusedPreviewTabId =
activeElement.tagName.toLowerCase() === "webview"
? activeElement.getAttribute("data-preview-tab")
: (previewViewport?.getAttribute("data-preview-viewport") ?? null);
if (focusedPreviewTabId !== null) {
return focusedPreviewTabId === activePreviewTabId;
}
return (
activeElement.closest(
"[data-right-panel-tabbar], [data-right-panel-content], [data-right-panel-control]",
) !== null
);
}
+18
View File
@@ -0,0 +1,18 @@
import type { RightPanelSurface } from "~/rightPanelStore";
interface SurfaceTabAuxClickEvent {
readonly button: number;
preventDefault(): void;
stopPropagation(): void;
}
export function handleSurfaceTabAuxClick(
event: SurfaceTabAuxClickEvent,
surface: RightPanelSurface,
onCloseSurface: (surface: RightPanelSurface) => void,
): void {
if (event.button !== 1) return;
event.preventDefault();
event.stopPropagation();
onCloseSurface(surface);
}
@@ -41,6 +41,12 @@ it.effect("parses keybinding rules", () =>
});
assert.strictEqual(parsedRightPanelToggle.command, "rightPanel.toggle");
const parsedRightPanelClose = yield* decode(KeybindingRule, {
key: "mod+w",
command: "rightPanel.closeActiveSurface",
});
assert.strictEqual(parsedRightPanelClose.command, "rightPanel.closeActiveSurface");
const parsedClose = yield* decode(KeybindingRule, {
key: "mod+w",
command: "terminal.close",
+1
View File
@@ -55,6 +55,7 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.new",
"terminal.close",
"rightPanel.toggle",
"rightPanel.closeActiveSurface",
"diff.toggle",
"preview.toggle",
"preview.refresh",
+5
View File
@@ -26,6 +26,11 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+shift+d", command: "terminal.splitVertical", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{
key: "mod+w",
command: "rightPanel.closeActiveSurface",
when: "rightPanelFocus && !terminalFocus",
},
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+shift+j", command: "preview.toggle" },
{ key: "mod+r", command: "preview.refresh", when: "previewFocus" },