diff --git a/src/features/terminal/keys.ts b/src/features/terminal/keys.ts index 44c18ffe3d..c6eddd2793 100644 --- a/src/features/terminal/keys.ts +++ b/src/features/terminal/keys.ts @@ -17,7 +17,7 @@ */ import { executeAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; -import { effectiveBindings, isMacHost, letterOf, registerKeyClaim, strokeOf } from "@/platform/keymap"; +import { effectiveBindings, isMacHost, letterOf, limitKeyActions, registerKeyClaim, strokeOf } from "@/platform/keymap"; import { workflowSettings } from "@/platform/workflowSettings"; import { terminalRuntime } from "./loader"; import { isImeKey } from "@/platform/ime"; @@ -131,19 +131,24 @@ const ALLOWED_ACTION_IDS = new Set([ "terminal.splitDown", ]); +/** Whether action `id` may take `stroke` from the terminal. */ +export function isAllowedIdeAction(id: string, stroke: string, inEditorTab = false): boolean { + if (id === "terminal.newInEditor" && !inEditorTab) return false; + if (id === "terminal.new" && inEditorTab) return false; + // Ctrl+E stays with the shell (end of line), as in IDEA. + return ALLOWED_ACTION_IDS.has(id) && !(id === "navigate.recentFiles" && stroke === "Ctrl+E"); +} + /** Whether `stroke` starts a binding of an allowed action. */ export function isAllowedIdeShortcut( stroke: string, bindings: ReadonlyArray, inEditorTab = false, ): boolean { - return bindings.some(([binding, id]) => { - if (id === "terminal.newInEditor" && !inEditorTab) return false; - if (id === "terminal.new" && inEditorTab) return false; - if (!ALLOWED_ACTION_IDS.has(id) || (binding !== stroke && !binding.startsWith(`${stroke} `))) return false; - // Ctrl+E stays with the shell (end of line), as in IDEA. - return !(id === "navigate.recentFiles" && stroke === "Ctrl+E"); - }); + return bindings.some( + ([binding, id]) => + (binding === stroke || binding.startsWith(`${stroke} `)) && isAllowedIdeAction(id, stroke, inEditorTab), + ); } export function installTerminalKeys(target: Window = window): () => void { @@ -182,7 +187,12 @@ export function installTerminalKeys(target: Window = window): () => void { const t = workflowSettings().terminal; if (action.kind === "send" && (e.ctrlKey || e.key === "Escape") && !t.overrideIdeShortcuts) return; if (action.kind === "send" && (e.ctrlKey || e.key === "Escape")) { - if (stroke && isAllowedIdeShortcut(stroke, effectiveBindings(), inEditorTab)) return; + if (stroke && isAllowedIdeShortcut(stroke, effectiveBindings(), inEditorTab)) { + // Only the allowed action runs: another one sharing the key (a user's binding of + // Reopen Closed Tab on New Tab's Ctrl+Shift+T) stays out of the terminal, as in IDEA. + limitKeyActions(e, (id) => isAllowedIdeAction(id, stroke, inEditorTab)); + return; + } } // "Move focus to the Editor with Escape": the IDE keymap's Escape (Focus Editor) runs instead. if (action.kind === "send" && e.key === "Escape" && t.escapeToEditor) return; diff --git a/src/features/terminal/terminal.test.ts b/src/features/terminal/terminal.test.ts index dccbcaf105..79cdb7f3cf 100644 --- a/src/features/terminal/terminal.test.ts +++ b/src/features/terminal/terminal.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { FIT_SETTLE_MS, PROCESS_RESIZE_DELAY_MS, fitScheduler, settledResize } from "./fit"; -import { isAllowedIdeShortcut, terminalKeyAction } from "./keys"; +import { isAllowedIdeAction, isAllowedIdeShortcut, terminalKeyAction } from "./keys"; import { matchCounter } from "./FindBar"; import { buildSearchDecorations } from "./theme"; import { findTerminalLinks, resolvePath, trimUrl } from "./links"; @@ -285,6 +285,9 @@ describe("terminal keys", () => { expect(isAllowedIdeShortcut("Ctrl+E", bindings)).toBe(false); expect(isAllowedIdeShortcut("Ctrl+K", bindings)).toBe(false); expect(isAllowedIdeShortcut("Ctrl+R", bindings)).toBe(false); + // The key reaches only the allowed action, not another one bound to it (#7889). + expect(isAllowedIdeAction("terminal.new", "Ctrl+Shift+T")).toBe(true); + expect(isAllowedIdeAction("editor.reopenClosedTab", "Ctrl+Shift+T")).toBe(false); }); }); diff --git a/src/platform/keymap.test.ts b/src/platform/keymap.test.ts index c8b84b1680..6eeda1a545 100644 --- a/src/platform/keymap.test.ts +++ b/src/platform/keymap.test.ts @@ -10,6 +10,7 @@ import { isAltGrTyping, isValidBinding, letterOf, + limitKeyActions, normalizeBinding, parseDoubleModifier, PRESETS, @@ -393,20 +394,29 @@ describe("keymap", () => { } }); - it("prefers a preset's matching keyWhen over a context-free user binding sharing the stroke", async () => { - const specific = vi.fn(); - const general = vi.fn(); - registerAction({ id: "t.presetKeyWhenMatch", title: "preset specific", keyWhen: "terminalFocus", run: specific }); - registerAction({ id: "t.userKeyWhenless", title: "general", run: general }); - PRESETS["__test-keymap-7889"] = { "t.presetKeyWhenMatch": ["Ctrl+Shift+T"] }; - useKeymap.setState({ preset: "__test-keymap-7889", overrides: { "t.userKeyWhenless": ["Ctrl+Shift+T"] } }); + it("runs only the actions a component limits a keystroke to (#7889)", async () => { + const terminalNew = vi.fn(); + const reopen = vi.fn(); + registerAction({ id: "t.terminalNewTab", title: "new tab", keyWhen: "terminalFocus", run: terminalNew }); + registerAction({ id: "t.reopenClosedTab", title: "reopen", run: reopen }); + PRESETS["__test-keymap-7889"] = { "t.terminalNewTab": ["Ctrl+Shift+T"] }; + useKeymap.setState({ preset: "__test-keymap-7889", overrides: { "t.reopenClosedTab": ["Ctrl+Shift+T"] } }); setContext("terminalFocus", true); uninstall = installKeyboardDispatcher(window); + const press = (limited: boolean) => { + const e = new KeyboardEvent("keydown", { code: "KeyT", key: "T", ctrlKey: true, shiftKey: true }); + if (limited) limitKeyActions(e, (id) => id === "t.terminalNewTab"); + window.dispatchEvent(e); + }; try { - window.dispatchEvent(new KeyboardEvent("keydown", { code: "KeyT", key: "T", ctrlKey: true, shiftKey: true })); + press(true); await Promise.resolve(); - expect(specific).toHaveBeenCalledOnce(); - expect(general).not.toHaveBeenCalled(); + expect(terminalNew).toHaveBeenCalledOnce(); + expect(reopen).not.toHaveBeenCalled(); + // Without a limit the user's binding wins, as everywhere else. + press(false); + await Promise.resolve(); + expect(reopen).toHaveBeenCalledOnce(); } finally { clearContext("terminalFocus"); delete PRESETS["__test-keymap-7889"]; diff --git a/src/platform/keymap.ts b/src/platform/keymap.ts index b043c5f1fc..4eda54c43a 100644 --- a/src/platform/keymap.ts +++ b/src/platform/keymap.ts @@ -764,6 +764,17 @@ export const FORWARDABLE_ACTIONS: ReadonlySet = new Set([ ]); const restrictedKeys = new WeakSet(); +/** Keydowns whose target hands the keymap only some actions (a terminal: IDEA's allowed actions). */ +const keyActionLimits = new WeakMap boolean>(); + +/** + * Lets only the actions `allowed` accepts run for keydown `e`. A component that passes a + * keystroke on for one of its allowed actions (the terminal's New Tab) uses it so that + * another action sharing the key, such as a user's binding without a context, doesn't run there. + */ +export function limitKeyActions(e: Event, allowed: (id: string) => boolean): void { + keyActionLimits.set(e, allowed); +} function isForwardableAction(id: string, target: EventTarget | null): boolean { if (FORWARDABLE_ACTIONS.has(id)) return true; @@ -876,6 +887,7 @@ export function installKeyboardDispatcher( return; } const restricted = restrictedKeys.has(e); + const limit = keyActionLimits.get(e); if (restricted) { reset(); if (KEY_MODIFIER[e.key]) return; @@ -917,11 +929,8 @@ export function installKeyboardDispatcher( // context runs before one without it: the context-specific claim beats the // context-free one at equal specificity, so Eclipse's Alt+Shift+R renames // in the project view instead of reaching the Git log's Edit Commit - // Message. A preset binding scoped to the focused component (its `keyWhen` - // needs some focus to hold, like `terminalFocus`) also runs before a user - // binding without a context, so the terminal keeps its New Tab key; a broad - // guard such as `!popupOpen` does not outrank the user. An unmatching - // `keyWhen` fails the enablement check below. + // Message. An unmatching `keyWhen` fails the enablement check below, and + // when no `keyWhen` matches, the preset/override order decides as before. const { overrides } = useKeymap.getState(); const isOverridden = (id: string) => Object.hasOwn(overrides, id); const keyWhenMatches = (id: string) => { @@ -931,24 +940,21 @@ export function installKeyboardDispatcher( const ordered = exact.reverse(); const overridePreferred: string[] = []; const overrideFallback: string[] = []; - const presetFocused: string[] = []; const presetPreferred: string[] = []; const presetFallback: string[] = []; for (const id of ordered) { const specific = keyWhenMatches(id); if (isOverridden(id)) (specific ? overridePreferred : overrideFallback).push(id); - else if (!specific) presetFallback.push(id); - else (evaluateWhen(getAction(id)!.keyWhen, {}) ? presetPreferred : presetFocused).push(id); + else (specific ? presetPreferred : presetFallback).push(id); } - for (const id of [ - ...overridePreferred, - ...presetFocused, - ...overrideFallback, - ...presetPreferred, - ...presetFallback, - ]) { + for (const id of [...overridePreferred, ...overrideFallback, ...presetPreferred, ...presetFallback]) { const action = getAction(id); - if (action && actionEnabledForKey(action, e) && (!restricted || isForwardableAction(id, e.target))) { + if ( + action && + (!limit || limit(id)) && + actionEnabledForKey(action, e) && + (!restricted || isForwardableAction(id, e.target)) + ) { e.preventDefault(); e.stopPropagation(); reset();