Files
Netcatty/electron/bridges/windowManagerReadiness.test.cjs
T
atoz03 e948a7a869 fix: route Cmd+W through existing tab close flow (#1234)
* fix: route Cmd+W through existing tab close flow

Keep the original tab-close behavior intact, and close the main or settings window only when there is no active closable tab to handle.

* fix: fall back to closing non-listener windows on Cmd+W

Treat BrowserWindow instances that do not participate in Netcatty's command-close bridge as regular closable windows. Keep the existing command-close path for the main and settings windows, and add tests that cover both the fallback close behavior and the renderer-capable send path.
2026-06-04 17:20:44 +08:00

416 lines
9.8 KiB
JavaScript

const test = require("node:test");
const assert = require("node:assert/strict");
const {
buildAppMenu,
isWindowUsable,
registerWindowHandlers,
resolveSettingsWindowBounds,
restoreWindowInputFocus,
requestWindowCommandClose,
shouldCloseWindowFromInput,
} = require("./windowManager.cjs");
const { createMainWindowApi } = require("./windowManager/mainWindow.cjs");
function createWindowStub({ destroyed = false, webContents } = {}) {
return {
isDestroyed() {
return destroyed;
},
isVisible() {
return true;
},
webContents,
};
}
test("isWindowUsable returns false when webContents is crashed", () => {
const win = createWindowStub({
webContents: {
isDestroyed() {
return false;
},
isCrashed() {
return true;
},
},
});
assert.equal(isWindowUsable(win), false);
});
test("isWindowUsable returns true for a healthy live window", () => {
const win = createWindowStub({
webContents: {
isDestroyed() {
return false;
},
isCrashed() {
return false;
},
},
});
assert.equal(isWindowUsable(win), true);
});
test("isWindowUsable can require a visible window", () => {
const hiddenWin = {
...createWindowStub({
webContents: {
isDestroyed() {
return false;
},
isCrashed() {
return false;
},
},
}),
isVisible() {
return false;
},
};
assert.equal(isWindowUsable(hiddenWin, { requireVisible: true }), false);
assert.equal(isWindowUsable(hiddenWin, { requireVisible: false }), true);
});
test("restoreWindowInputFocus focuses the window and renderer on Windows without showing hidden windows", () => {
const calls = [];
const win = {
isDestroyed() {
return false;
},
show() {
calls.push("show");
},
focus() {
calls.push("focus");
},
setAlwaysOnTop(value) {
calls.push(`alwaysOnTop:${value}`);
},
webContents: {
isDestroyed() {
return false;
},
focus() {
calls.push("webContents.focus");
},
},
};
const restored = restoreWindowInputFocus(win, { platform: "win32" });
assert.equal(restored, true);
assert.deepEqual(calls, [
"alwaysOnTop:true",
"focus",
"alwaysOnTop:false",
"webContents.focus",
]);
});
test("restoreWindowInputFocus clears Windows always-on-top even if window focus throws", () => {
const calls = [];
const win = {
isDestroyed() {
return false;
},
focus() {
calls.push("focus");
throw new Error("focus failed");
},
setAlwaysOnTop(value) {
calls.push(`alwaysOnTop:${value}`);
},
webContents: {
isDestroyed() {
return false;
},
focus() {
calls.push("webContents.focus");
},
},
};
const restored = restoreWindowInputFocus(win, { platform: "win32" });
assert.equal(restored, true);
assert.deepEqual(calls, [
"alwaysOnTop:true",
"focus",
"alwaysOnTop:false",
"webContents.focus",
]);
});
test("restoreWindowInputFocus can show the window when requested", () => {
const calls = [];
const win = {
isDestroyed() {
return false;
},
show() {
calls.push("show");
},
focus() {
calls.push("focus");
},
webContents: {
isDestroyed() {
return false;
},
focus() {
calls.push("webContents.focus");
},
},
};
const restored = restoreWindowInputFocus(win, { platform: "darwin", show: true });
assert.equal(restored, true);
assert.deepEqual(calls, ["show", "focus", "webContents.focus"]);
});
test("buildAppMenu closes a non-app window directly when Cmd+W is invoked", () => {
let capturedTemplate = null;
const Menu = {
buildFromTemplate(template) {
capturedTemplate = template;
return { template };
},
};
buildAppMenu(Menu, { name: "Netcatty" }, true);
const windowMenu = capturedTemplate.find((item) => item.label === "Window");
assert.ok(windowMenu);
const closeItem = windowMenu.submenu.find((item) => item.accelerator === "CommandOrControl+W");
assert.ok(closeItem);
assert.equal(closeItem.label, "Close Window");
const calls = [];
closeItem.click(null, {
isDestroyed() { return false; },
close() {
calls.push("close");
},
webContents: {
isDestroyed() { return false; },
send(channel) {
calls.push(`send:${channel}`);
},
},
});
assert.deepEqual(calls, ["close"]);
});
test("requestWindowCommandClose sends command-close to renderer-capable windows", () => {
const sentChannels = [];
const win = {
isDestroyed() { return false; },
webContents: {
isDestroyed() { return false; },
send(channel) {
sentChannels.push(channel);
},
},
};
assert.equal(requestWindowCommandClose(win), true);
assert.deepEqual(sentChannels, ["netcatty:window:command-close"]);
});
test("shouldCloseWindowFromInput only matches macOS Command+W keydown", () => {
assert.equal(shouldCloseWindowFromInput({ type: "keyDown", meta: true, key: "w" }), true);
assert.equal(shouldCloseWindowFromInput({ type: "keyDown", meta: true, key: "W" }), true);
assert.equal(shouldCloseWindowFromInput({ type: "keyUp", meta: true, key: "w" }), false);
assert.equal(shouldCloseWindowFromInput({ type: "keyDown", control: true, key: "w" }), false);
assert.equal(shouldCloseWindowFromInput({ type: "keyDown", meta: true, shift: true, key: "w" }), false);
});
test("main window asks renderer to close tabs from macOS Command+W before-input-event", async () => {
let beforeInputHandler = null;
const commandCloseRequests = [];
class BrowserWindowStub {
constructor() {
this.webContents = {
id: 1,
on(channel, handler) {
if (channel === "before-input-event") beforeInputHandler = handler;
},
once() {},
isDestroyed() {
return false;
},
isCrashed() {
return false;
},
setIgnoreMenuShortcuts() {},
setWindowOpenHandler() {},
openDevTools() {},
};
}
on() {}
once() {}
isDestroyed() { return false; }
isMaximized() { return false; }
isFullScreen() { return false; }
getBounds() { return { x: 0, y: 0, width: 1400, height: 900 }; }
setBackgroundColor() {}
async loadURL() {}
close() {}
}
const api = createMainWindowApi({
mainWindow: null,
electronApp: null,
currentTheme: "light",
isQuitting: false,
pendingWindowStateWrite: null,
queuedWindowState: null,
windowStateCloseRequested: false,
DEFAULT_WINDOW_WIDTH: 1400,
DEFAULT_WINDOW_HEIGHT: 900,
MIN_WINDOW_WIDTH: 1100,
MIN_WINDOW_HEIGHT: 640,
V8_CACHE_OPTIONS: "bypassHeatCheck",
THEME_COLORS: { light: { background: "#fff" } },
unhealthyWebContentsIds: new Set(),
rendererReadySeenByWebContentsId: new Set(),
__dirname,
URL,
require,
console,
setTimeout,
clearTimeout,
getGlobalShortcutBridge() {
return { handleWindowClose: () => false };
},
debugLog() {},
resolveFrontendBackgroundColor() { return null; },
loadWindowState() { return null; },
getDevRendererBaseUrl(url) { return url; },
getWindowBoundsState() { return null; },
queueWindowStateSave() {},
saveWindowStateSync() {},
setupDeferredShow() {},
createExternalOnlyWindowOpenHandler() { return {}; },
createAppWindowOpenHandler() { return {}; },
attachOAuthLoadingOverlay() {},
registerWindowHandlers() {},
requestWindowCommandClose(win) {
commandCloseRequests.push(win);
return true;
},
shouldCloseWindowFromInput,
closeSettingsWindow() {},
hideSettingsWindow() {},
});
await api.createWindow(
{
BrowserWindow: BrowserWindowStub,
nativeTheme: {},
app: {},
screen: {},
shell: {},
ipcMain: {},
},
{
preload: "/tmp/preload.cjs",
devServerUrl: "http://localhost:5173",
isDev: true,
appIcon: null,
isMac: true,
electronDir: __dirname,
},
);
let prevented = false;
beforeInputHandler({ preventDefault: () => { prevented = true; } }, {
type: "keyDown",
meta: true,
key: "w",
});
assert.equal(prevented, true);
assert.equal(commandCloseRequests.length, 1);
});
test("window focus IPC handler focuses the sender owner window", async () => {
const handlers = new Map();
const ipcMain = {
handle(channel, handler) {
handlers.set(channel, handler);
},
on(channel, handler) {
handlers.set(channel, handler);
},
};
const calls = [];
const win = {
isDestroyed() {
return false;
},
focus() {
calls.push("focus");
},
webContents: {
id: 101,
isDestroyed() {
return false;
},
focus() {
calls.push("webContents.focus");
},
},
};
registerWindowHandlers(ipcMain, { themeSource: "light" });
const result = await handlers.get("netcatty:window:focus")({
sender: {
id: 202,
getOwnerBrowserWindow() {
return win;
},
},
});
assert.equal(result, true);
assert.deepEqual(calls, ["focus", "webContents.focus"]);
});
test("resolveSettingsWindowBounds centers settings on the requesting window display", () => {
const sourceWindow = {
getBounds() {
return { x: 2100, y: 80, width: 900, height: 700 };
},
isDestroyed() {
return false;
},
};
const electronModule = {
screen: {
getDisplayMatching(bounds) {
assert.deepEqual(bounds, { x: 2100, y: 80, width: 900, height: 700 });
return { workArea: { x: 1920, y: 0, width: 1440, height: 900 } };
},
},
};
assert.deepEqual(
resolveSettingsWindowBounds(electronModule, {
sourceWindow,
settingsWidth: 980,
settingsHeight: 720,
}),
{ x: 2150, y: 90 },
);
});