GeezerVison is showing github.com — fix(terminal): protect held Ctrl/Cmd+W close shortcut by StiensWout · Pull Request #5322 · pingdotgg/t3code
fix(terminal): protect held Ctrl/Cmd+W close shortcut
#5322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(4)
.tsx
(2)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(terminal): protect held close shortcut
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit 3334961830b1c969545f75ba174ec56013b128b7
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
}),
);
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
if (!beforeInput) {
return yield* Effect.die("before-input-event listener was not registered");
}
let prevented = false;
const event = { preventDefault: () => (prevented = true) };
const input = {
type: "keyDown",
isAutoRepeat: true,
key: "W",
meta: true,
control: false,
alt: false,
shift: false,
};
beforeInput(event, input);
assert.isTrue(prevented);
prevented = false;
beforeInput(event, { ...input, isAutoRepeat: false });
assert.isFalse(prevented);
prevented = false;
beforeInput(event, { ...input, meta: false });
assert.isFalse(prevented);
}).pipe(Effect.provide(layer));
}),
);
it.effect("uses the persisted main window bounds when opening the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -514,6 +514,18 @@ export const make = Effect.gen(function* () {
}
});
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
// close-terminal shortcut can outlive the terminal that handled its first
// press, so reject repeats before they reach the native window accelerator.
// Deliberate presses still flow through the renderer or native menu.
window.webContents.on("before-input-event", (event, input) => {
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
const modifier = environment.platform === "darwin" ? input.meta : input.control;
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
event.preventDefault();
}
});
window.on("page-title-updated", (event) => {
event.preventDefault();
window.setTitle(environment.displayName);
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -171,6 +171,7 @@ import { useNowMinute } from "../hooks/useNowMinute";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import { preventRepeatedTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import {
deriveLogicalProjectKeyFromSettings,
Expand Down
Expand Up
@@ -4354,6 +4355,10 @@ function ChatViewContent(props: ChatViewProps) {
useEffect(() => {
const handler = (event: globalThis.KeyboardEvent) => {
if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {
event.stopPropagation();
return;
}
if (!activeThreadId || isCommandPaletteOpen()) {
return;
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -43,7 +43,6 @@ import { isTerminalLinkActivation, resolvePathLinkTarget } from "../terminal-lin
import {
isDiffToggleShortcut,
isTerminalClearShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalSplitVerticalShortcut,
Expand All
@@ -63,6 +62,7 @@ import { previewEnvironment } from "../state/preview";
import { terminalEnvironment } from "../state/terminal";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
Expand Down
Expand Up
@@ -527,12 +527,14 @@ export function TerminalViewport({
function handleBeforeKey(event: KeyboardEvent): boolean {
const currentKeybindings = keybindingsRef.current;
const options = { context: { terminalFocus: true, terminalOpen: true } };
if (preventTerminalCloseShortcut(event, currentKeybindings)) {
return false;
}
if (
isTerminalToggleShortcut(event, currentKeybindings, options) ||
isTerminalSplitShortcut(event, currentKeybindings, options) ||
isTerminalSplitVerticalShortcut(event, currentKeybindings, options) ||
isTerminalNewShortcut(event, currentKeybindings, options) ||
isTerminalCloseShortcut(event, currentKeybindings, options) ||
isDiffToggleShortcut(event, currentKeybindings, options)
) {
return false;
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vite-plus/test";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import {
preventRepeatedTerminalCloseShortcut,
preventTerminalCloseShortcut,
type TerminalCloseShortcutEvent,
} from "./terminalCloseShortcut";
const keybindings = [
{
command: "terminal.close",
shortcut: {
key: "w",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: { type: "identifier", name: "terminalFocus" },
},
] satisfies ResolvedKeybindingsConfig;
type KeyboardEventOverrides = Partial<
Pick<
TerminalCloseShortcutEvent,
"key" | "code" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey" | "repeat"
>
>;
function keyboardEvent(
overrides: KeyboardEventOverrides = {},
): TerminalCloseShortcutEvent & { readonly defaultPrevented: boolean } {
let defaultPrevented = false;
return {
key: "w",
code: "KeyW",
metaKey: false,
ctrlKey: true,
shiftKey: false,
altKey: false,
repeat: false,
...overrides,
preventDefault: () => {
defaultPrevented = true;
},
get defaultPrevented() {
return defaultPrevented;
},
};
}
describe("terminal close shortcut guards", () => {
it("prevents the browser default for a deliberate terminal close", () => {
const event = keyboardEvent();
expect(preventTerminalCloseShortcut(event, keybindings, "Linux x86_64")).toBe(true);
expect(event.defaultPrevented).toBe(true);
});
it("keeps held close repeats from closing the browser after the last terminal unmounts", () => {
const firstPress = keyboardEvent();
expect(preventTerminalCloseShortcut(firstPress, keybindings, "Linux x86_64")).toBe(true);
let browserCloseCount = 0;
for (const repeat of [true, true, true]) {
const event = keyboardEvent({ repeat });
preventRepeatedTerminalCloseShortcut(event, keybindings, "Linux x86_64");
if (!event.defaultPrevented) browserCloseCount += 1;
}
expect(browserCloseCount).toBe(0);
expect(preventRepeatedTerminalCloseShortcut(keyboardEvent(), keybindings, "Linux x86_64")).toBe(
false,
);
});
it("leaves a non-repeated window close and unrelated repeats alone", () => {
const deliberateWindowClose = keyboardEvent({ repeat: false });
const unrelatedRepeat = keyboardEvent({ key: "q", code: "KeyQ", repeat: true });
expect(
preventRepeatedTerminalCloseShortcut(deliberateWindowClose, keybindings, "Linux x86_64"),
).toBe(false);
expect(deliberateWindowClose.defaultPrevented).toBe(false);
expect(preventRepeatedTerminalCloseShortcut(unrelatedRepeat, keybindings, "Linux x86_64")).toBe(
false,
);
expect(unrelatedRepeat.defaultPrevented).toBe(false);
});
});
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,36 @@
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { isTerminalCloseShortcut, type ShortcutEventLike } from "../keybindings";
export interface TerminalCloseShortcutEvent extends ShortcutEventLike {
readonly repeat?: boolean;
readonly preventDefault: () => void;
}
function terminalCloseShortcutOptions(platform?: string) {
return {
...(platform === undefined ? {} : { platform }),
context: { terminalFocus: true, terminalOpen: true },
};
}
export function preventTerminalCloseShortcut(
event: TerminalCloseShortcutEvent,
keybindings: ResolvedKeybindingsConfig,
platform?: string,
): boolean {
if (!isTerminalCloseShortcut(event, keybindings, terminalCloseShortcutOptions(platform))) {
return false;
}
event.preventDefault();
return true;
}
export function preventRepeatedTerminalCloseShortcut(
event: TerminalCloseShortcutEvent,
keybindings: ResolvedKeybindingsConfig,
platform?: string,
): boolean {
if (!event.repeat) return false;
return preventTerminalCloseShortcut(event, keybindings, platform);
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.