From 0177ee52bce198b4dbcede1fc964f926dc1e9fb5 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:57:00 +0800 Subject: [PATCH] fix(keymap): support mouse wheel shortcuts --- e2e/keymap.spec.ts | 31 ++++++ src/editor/core/fontZoom.test.ts | 40 +++++++- .../settings/__tests__/mouseShortcut.test.tsx | 72 ++++++++++++++ .../settings/keymap/RecordShortcutDialog.tsx | 55 +++++++++-- src/platform/ideaKeymap.test.ts | 4 +- src/platform/ideaKeymap.ts | 11 ++- src/platform/keymap.ts | 97 ++++++++++++++++--- src/platform/keymapMouse.test.ts | 72 ++++++++++++++ src/platform/locales/text/en.json | 4 + src/platform/locales/text/zh.json | 4 + 10 files changed, 363 insertions(+), 27 deletions(-) diff --git a/e2e/keymap.spec.ts b/e2e/keymap.spec.ts index 1d6617759d..18f96010f2 100644 --- a/e2e/keymap.spec.ts +++ b/e2e/keymap.spec.ts @@ -93,6 +93,37 @@ for (const activation of ["double-click", "Enter"] as const) { }); } +test("records a modified wheel gesture and runs the assigned action", async ({ workbench: page }) => { + await page.keyboard.press("Meta+,"); + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click(); + await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action"); + const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: /Find Action/ }); + await row.click({ button: "right" }); + await page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true }).click(); + const recorder = page.getByRole("dialog", { name: "Mouse Shortcut: Find Action…", exact: true }); + const pad = recorder.getByRole("textbox", { name: "Mouse shortcut" }); + await pad.hover(); + const scrollUp = async () => { + await page.keyboard.down("Control"); + await page.mouse.wheel(0, -120); + await page.keyboard.up("Control"); + }; + await scrollUp(); + await expect(pad).toHaveText("⌃Wheel Up"); + const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true }); + await expect(search).toBeHidden(); + await recorder.getByRole("button", { name: "OK", exact: true }).click(); + await expect(row).toContainText("⌃Wheel Up"); + await settings.getByRole("button", { name: "OK", exact: true }).click(); + await expect(settings).toBeHidden(); + await page.mouse.move(700, 450); + await page.mouse.wheel(0, 120); + await expect(search).toBeHidden(); + await scrollUp(); + await expect(search).toBeVisible(); +}); + test("rectangular drag remains configurable after removal and saves a middle mouse binding", async ({ workbench: page, }) => { diff --git a/src/editor/core/fontZoom.test.ts b/src/editor/core/fontZoom.test.ts index 4f4bce06fe..78dfb3a2ad 100644 --- a/src/editor/core/fontZoom.test.ts +++ b/src/editor/core/fontZoom.test.ts @@ -1,8 +1,10 @@ -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { useEditorRegistry, type TextEditorHandle } from "@/editor/api"; import { useProject } from "@/platform/project"; +import { registerAction } from "@/platform/actions"; +import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap"; import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs"; import { resetWheelZoomGesture } from "@/platform/wheelZoom"; @@ -57,6 +59,42 @@ describe("editor font zoom (active editor by default, all editors when configure expect(zoomOf(view)).toBe(0); }); + it("zooms when no enabled keymap action claims the gesture", () => { + const original = useKeymap.getState(); + const view = makeView(); + const run = vi.fn(); + let enabled = true; + const unregister = registerAction({ id: "test.wheel", title: "Test", enabled: () => enabled, run }); + const uninstall = installKeyboardDispatcher(window); + useKeymap.setState({ overrides: { "test.wheel": ["Ctrl+WheelUp"] } }); + const scroll = (deltaY: number) => { + const event = new WheelEvent("wheel", { + bubbles: true, + cancelable: true, + ctrlKey: true, + deltaY, + deltaMode: WheelEvent.DOM_DELTA_LINE, + }); + view.contentDOM.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + }; + try { + scroll(-1); + expect(run).toHaveBeenCalledOnce(); + expect(zoomOf(view)).toBe(0); + scroll(1); + expect(zoomOf(view)).toBe(-1); + enabled = false; + scroll(-1); + expect(run).toHaveBeenCalledOnce(); + expect(zoomOf(view)).toBe(0); + } finally { + uninstall(); + unregister(); + useKeymap.setState(original); + } + }); + it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => { useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never); const first = makeView(); diff --git a/src/features/settings/__tests__/mouseShortcut.test.tsx b/src/features/settings/__tests__/mouseShortcut.test.tsx index b14ef91867..15e50113e2 100644 --- a/src/features/settings/__tests__/mouseShortcut.test.tsx +++ b/src/features/settings/__tests__/mouseShortcut.test.tsx @@ -2,10 +2,15 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { RecordShortcutDialog } from "../keymap/RecordShortcutDialog"; import { usePlatform } from "@/platform/platformInfo"; +import { useProject } from "@/platform/project"; +import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap"; +import { registerAction } from "@/platform/actions"; afterEach(cleanup); const originalPlatform = usePlatform.getState(); afterEach(() => usePlatform.setState(originalPlatform)); +const originalSettings = useProject.getState().settings; +afterEach(() => useProject.setState({ settings: originalSettings })); const action = { id: "my.action", title: "My Action", category: "Test" }; const rectangular = { @@ -15,6 +20,71 @@ const rectangular = { }; describe("Mouse Shortcut dialog", () => { + it.each([ + [{ deltaY: -1, ctrlKey: true }, "Ctrl+Wheel Up", "Ctrl+WheelUp"], + [{ deltaY: 1, shiftKey: true, altKey: true }, "Alt+Shift+Wheel Down", "Alt+Shift+WheelDown"], + [{ deltaY: 1 }, "Wheel Down", "WheelDown"], + ])("records and consumes %j as %s", (init, label, binding) => { + usePlatform.setState({ os: "windows" }); + const onSubmit = vi.fn(); + render( + {}} + onSubmit={onSubmit} + />, + ); + const pad = screen.getByRole("textbox", { name: "Mouse shortcut" }); + const wheel = new WheelEvent("wheel", { ...init, cancelable: true, bubbles: true }); + fireEvent(pad, wheel); + expect(pad).toHaveTextContent(label); + expect(wheel.defaultPrevented).toBe(true); + fireEvent.click(screen.getByRole("button", { name: "OK" })); + expect(onSubmit).toHaveBeenCalledWith(binding, [], false); + }); + + it("shows the assigned action and the enabled font zoom conflict without running either", () => { + usePlatform.setState({ os: "macos" }); + useProject.setState({ + settings: { ...originalSettings, editor: { general: { wheelZoom: true } } } as typeof originalSettings, + }); + const existing = { id: "my.otherAction", title: "Other Action" }; + const run = vi.fn(); + const unregister = registerAction({ ...existing, run }); + const originalKeymap = useKeymap.getState(); + const overrides = { [existing.id]: ["Meta+WheelDown"] }; + useKeymap.setState({ overrides }); + const uninstall = installKeyboardDispatcher(window); + try { + render( + {}} + onSubmit={() => {}} + />, + ); + const pad = screen.getByRole("textbox", { name: "Mouse shortcut" }); + fireEvent.wheel(pad, { deltaY: 1, metaKey: true }); + expect(pad).toHaveTextContent("⌘Wheel Down"); + expect(screen.getByText("Other Action")).toBeVisible(); + expect(screen.getByText(/takes precedence over.*font zoom/)).toBeVisible(); + expect(run).not.toHaveBeenCalled(); + fireEvent.wheel(pad, { deltaY: -1, altKey: true }); + expect(screen.queryByText(/takes precedence over.*font zoom/)).not.toBeInTheDocument(); + expect(screen.getByText("No conflicts")).toBeVisible(); + } finally { + uninstall(); + unregister(); + useKeymap.setState(originalKeymap); + } + }); + it.each(["windows", "macos", "linux"] as const)("records middle drag and explains Linux paste on %s", (os) => { usePlatform.setState({ os }); const onSubmit = vi.fn(); @@ -52,6 +122,7 @@ describe("Mouse Shortcut dialog", () => { ); const pad = screen.getByRole("textbox", { name: "Mouse shortcut" }); fireEvent.mouseDown(pad, { button, altKey: true }); + fireEvent.wheel(pad, { deltaY: -1, ctrlKey: true }); expect(screen.getByRole("button", { name: "OK" })).toBeDisabled(); expect(pad).toHaveTextContent("Click here with Ctrl, Alt or Command held, or use the middle mouse button"); fireEvent.mouseDown(pad, { button: 0, altKey: true }); @@ -97,6 +168,7 @@ describe("Mouse Shortcut dialog", () => { ); const pad = screen.getByRole("textbox", { name: "Mouse shortcut" }); fireEvent.mouseDown(pad, { button: 0 }); + fireEvent.wheel(pad, { deltaX: 16, deltaY: 1 }); expect(screen.getByRole("button", { name: "OK" })).toBeDisabled(); fireEvent.mouseDown(pad, { button: 3, altKey: true }); fireEvent.click(screen.getByRole("button", { name: "OK" })); diff --git a/src/features/settings/keymap/RecordShortcutDialog.tsx b/src/features/settings/keymap/RecordShortcutDialog.tsx index 7f715b5dd6..73ea94cbef 100644 --- a/src/features/settings/keymap/RecordShortcutDialog.tsx +++ b/src/features/settings/keymap/RecordShortcutDialog.tsx @@ -2,17 +2,21 @@ * IDEA's "Keyboard Shortcut" dialog: records a first (and optional second) * stroke and lists conflicts live; OK with conflicts asks whether to remove the * other assignments (Remove / Leave / Cancel). With `mouse` it is the "Mouse - * Shortcut" dialog: a click on its pad records the button and modifiers. + * Shortcut" dialog: the pad records mouse buttons and wheel gestures. */ -import { useEffect, useMemo, useState, type MouseEvent } from "react"; +import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react"; import { Checkbox, Dialog, Icon, Kbd, T } from "@/ui"; import type { Action } from "@/platform/actions"; +import { useEditorPrefs } from "@/platform/editorSettings"; import { formatBinding, + isWheelBinding, mouseStrokeOf, normalizeBinding, parseDoubleModifier, + supportsWheelShortcut, suspendKeyboardDispatch, + wheelStrokeOf, } from "@/platform/keymap"; import { isPageSwipe } from "@/platform/pageSwipe"; import { ask } from "@/workbench/messages"; @@ -30,7 +34,7 @@ export interface RecordShortcutDialogProps { onCancel: () => void; /** `removeConflicts`: also unbind the conflicting assignments. */ onSubmit: (binding: string, conflicts: Conflict[], removeConflicts: boolean) => void; - /** Record a mouse shortcut (modified left clicks, middle or side buttons) instead of keys. */ + /** Record a mouse button or wheel shortcut. */ mouse?: boolean; } @@ -42,9 +46,11 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi const tx = useTx(); const actionName = tx(action.title); const rectangularSelection = action.id === "editor.createRectangularSelectionOnMouseDrag"; + const wheelZoom = useEditorPrefs().general.wheelZoom; const allowsSecond = !isPageSwipe(first) && !parseDoubleModifier(first); const binding = !mouse && allowsSecond && first && useSecond ? (second ? `${first} ${second}` : "") : first; + const zoomConflict = wheelZoom && isWheelBinding(binding) && /(?:^|\+)(Ctrl|Meta)\+/.test(binding); const conflicts = useMemo( () => (binding ? findConflicts(draft, binding, action.id, actions) : []), [binding, draft, action.id, actions], @@ -96,7 +102,12 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi {mouse ? ( - + ) : ( The action already has this shortcut )} - {!already && binding && conflicts.length === 0 && ( + {!already && binding && !zoomConflict && conflicts.length === 0 && ( No conflicts @@ -135,6 +146,16 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi )} + {zoomConflict && ( +
+ + + + This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available. + + +
+ )} @@ -208,17 +229,34 @@ function KeyStrokes({ first, second, useSecond, allowsSecond, setFirst, setSecon ); } -/** Shortcuts stay off while the dialog records mouse buttons and modifiers. */ +/** Shortcuts stay off while the dialog records mouse gestures. */ function MouseRecorder({ value, onChange, sideButtons, + wheel, }: { value: string; onChange: (binding: string) => void; sideButtons: boolean; + wheel: boolean; }) { + const padRef = useRef(null); useEffect(() => suspendKeyboardDispatch(), []); + useEffect(() => { + const pad = padRef.current; + if (!pad || !wheel) return; + const recordWheel = (e: WheelEvent) => { + const stroke = wheelStrokeOf(e); + if (!stroke) return; + e.preventDefault(); + e.stopPropagation(); + onChange(stroke); + }; + // React's wheel handler is passive. + pad.addEventListener("wheel", recordWheel, { passive: false }); + return () => pad.removeEventListener("wheel", recordWheel); + }, [onChange, wheel]); const record = (e: MouseEvent) => { // Rectangular selection only handles left and middle buttons. if (!sideButtons && e.button > 1) return; @@ -230,6 +268,7 @@ function MouseRecorder({ }; return (
{formatBinding(value)} ) : ( - {sideButtons ? ( + {wheel ? ( + Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button + ) : sideButtons ? ( Click here with Ctrl, Alt or Command held, or use a middle or side mouse button ) : ( Click here with Ctrl, Alt or Command held, or use the middle mouse button diff --git a/src/platform/ideaKeymap.test.ts b/src/platform/ideaKeymap.test.ts index 484b1d906d..134c558099 100644 --- a/src/platform/ideaKeymap.test.ts +++ b/src/platform/ideaKeymap.test.ts @@ -23,6 +23,8 @@ describe("IntelliJ IDEA keymap import", () => { + + @@ -31,7 +33,7 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.name).toBe("My Mac"); expect(k.parent).toBe("intellij-macos"); expect(k.overrides["navigate.gotoClass"]).toEqual( - ["Meta+Shift+N", "Meta+K Meta+C", "Alt+Button1"].map(normalizeBinding), + ["Meta+Shift+N", "Meta+K Meta+C", "Alt+Button1", "Ctrl+WheelUp", "Alt+Shift+WheelDown"].map(normalizeBinding), ); expect(k.overrides["navigate.declaration"]).toEqual([]); expect(k.applied).toBe(2); diff --git a/src/platform/ideaKeymap.ts b/src/platform/ideaKeymap.ts index cd29c24744..786036c144 100644 --- a/src/platform/ideaKeymap.ts +++ b/src/platform/ideaKeymap.ts @@ -24,7 +24,7 @@ export interface ImportedIdeaKeymap { applied: number; /** IDEA action ids without an OpenIDEA counterpart. */ unknownActions: string[]; - /** Shortcuts that cannot be expressed here (wheel, double click, unknown keys). */ + /** Shortcuts that cannot be expressed here (double click, unknown keys). */ skippedShortcuts: number; } @@ -90,12 +90,13 @@ export function fromSwingStroke(stroke: string): string | null { return name ? [...words.map((w) => SWING_MODS[w.toLowerCase()]), name].join("+") : null; } -/** `"meta alt button1"` → `"Meta+Alt+Button1"`; wheel and multi-click gestures → null. */ +/** Converts Swing mouse buttons and wheel directions. */ function fromMouseStroke(stroke: string): string | null { const words = stroke.trim().split(/\s+/); - const button = words.pop(); - if (!button || !/^button\d$/i.test(button) || words.some((w) => !SWING_MODS[w.toLowerCase()])) return null; - return [...words.map((w) => SWING_MODS[w.toLowerCase()]), `Button${button.slice(6)}`].join("+"); + const button = words.pop()?.toLowerCase(); + if (!button || !/^button(?:\d|14[23])$/.test(button) || words.some((w) => !SWING_MODS[w.toLowerCase()])) return null; + const key = button === "button143" ? "WheelUp" : button === "button142" ? "WheelDown" : button; + return [...words.map((w) => SWING_MODS[w.toLowerCase()]), key].join("+"); } /** Parses an IDEA keymap XML; throws when the file is not a keymap. */ diff --git a/src/platform/keymap.ts b/src/platform/keymap.ts index a6ad805e22..491ad2a333 100644 --- a/src/platform/keymap.ts +++ b/src/platform/keymap.ts @@ -8,7 +8,7 @@ * Keys are matched by physical position (`KeyboardEvent.code`), so ⌥-letter * combos work on macOS where `event.key` would be a symbol. Mouse shortcuts * name the button 1-based (`Button1` = left, `Button4` = back side button, `Button5` = forward), - * optionally with modifiers (`Alt+Button4`); they are single strokes. + * or the wheel direction (`WheelUp`, `WheelDown`), optionally with modifiers. */ import { create } from "zustand"; import { executeAction, executeActionFrom, getAction, isActionKeyEnabled } from "./actions"; @@ -79,24 +79,45 @@ interface KeymapState { export const useKeymap = create(() => ({ preset: defaultPreset(), overrides: {}, extensions: {} })); const MOUSE_KEY_RE = /^Button(\d+)$/i; +const WHEEL_KEY_RE = /^Wheel(Up|Down)$/i; +type ModifierKeys = Pick; -/** A mouse shortcut (`Button4`, `Shift+Button5`) rather than a keystroke. */ +export function isWheelBinding(binding: string): boolean { + const b = binding.trim(); + return !/\s/.test(b) && WHEEL_KEY_RE.test(b.split("+").pop()!); +} + +/** A mouse button or wheel shortcut. */ export function isMouseBinding(binding: string): boolean { const b = binding.trim(); - return !/\s/.test(b) && MOUSE_KEY_RE.test(b.split("+").pop()!); + const key = b.split("+").pop()!; + return !/\s/.test(b) && (MOUSE_KEY_RE.test(key) || WHEEL_KEY_RE.test(key)); +} + +/** Editor mouse-selection actions require a button and pointer position. */ +export function supportsWheelShortcut(actionId: string): boolean { + return actionId !== "editor.createRectangularSelectionOnMouseDrag" && actionId !== "editor.addOrRemoveCaret"; +} + +function modifiedStroke(e: ModifierKeys, key: string): string { + const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean); + return [...mods, key].join("+"); } /** * Middle/side buttons, or a left click with Ctrl/Alt/Meta. Plain and Shift-only * left clicks keep selection semantics; right clicks keep the context menu. */ -export function mouseStrokeOf( - e: Pick, -): string | null { +export function mouseStrokeOf(e: Pick & ModifierKeys): string | null { if (!Number.isInteger(e.button) || e.button < 0) return null; if (e.button === 2 || (e.button === 0 && !(e.ctrlKey || e.altKey || e.metaKey))) return null; - const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean); - return [...mods, `Button${e.button + 1}`].join("+"); + return modifiedStroke(e, `Button${e.button + 1}`); +} + +/** Recognizes vertical wheel input for both capture and dispatch. */ +export function wheelStrokeOf(e: Pick & ModifierKeys): string | null { + if (!e.deltaY || Math.abs(e.deltaY) < Math.abs(e.deltaX)) return null; + return modifiedStroke(e, e.deltaY < 0 ? "WheelUp" : "WheelDown"); } const STROKE_RE = /^(?:(?:Ctrl|Alt|Shift|Meta)\+)*[^\s+]+$|^(?:(?:Ctrl|Alt|Shift|Meta)\+)*\+$/i; @@ -118,8 +139,9 @@ export function parseDoubleModifier(binding: string): { modifier: Modifier; key: export function isValidBinding(binding: unknown): binding is string { if (typeof binding !== "string") return false; const b = binding.trim(); - if (parseDoubleModifier(b)) return true; const strokes = b.split(/\s+/); + if (strokes.some(isWheelBinding)) return strokes.length === 1 && STROKE_RE.test(b); + if (parseDoubleModifier(b)) return true; if (strokes.some((s) => /swipe(left|right)$/i.test(s))) { return strokes.length === 1 && /^swipe(left|right)$/i.test(b); } @@ -298,8 +320,10 @@ export function normalizeBinding(binding: string): string { const key = parts.pop()!; const mods = MOD_ORDER.filter((m) => parts.some((p) => p.toLowerCase() === m.toLowerCase())); const mouse = MOUSE_KEY_RE.exec(key); + const wheel = WHEEL_KEY_RE.exec(key); const swipe = /^swipe(left|right)$/i.exec(key); if (swipe) return `Swipe${swipe[1]!.toLowerCase() === "left" ? "Left" : "Right"}`; + if (wheel) return [...mods, wheel[1]!.toLowerCase() === "up" ? "WheelUp" : "WheelDown"].join("+"); return [...mods, mouse ? `Button${mouse[1]}` : key.length === 1 ? key.toUpperCase() : key].join("+"); }) .join(" "); @@ -366,8 +390,7 @@ export function strokeOf( if (["Shift", "Meta", "Control", "Alt"].includes(e.key)) return null; key = e.key.length === 1 ? e.key.toUpperCase() : e.key; } - const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean); - return [...mods, key].join("+"); + return modifiedStroke(e, key); } const SYMBOLS: Record = { @@ -404,8 +427,12 @@ export function formatBinding(binding: string, mac = isMacHost()): string { if (isMouseBinding(binding)) { const parts = normalizeBinding(binding).split("+"); const key = parts.pop(); - const button = key === "Button1" ? "Left Click" : key === "Button2" ? tx("Middle Click") : `${key} Click`; - return mac ? parts.map((p) => SYMBOLS[p] ?? p).join("") + button : [...parts, button].join("+"); + let label = `${key} Click`; + if (key === "WheelUp") label = tx("Wheel Up"); + if (key === "WheelDown") label = tx("Wheel Down"); + if (key === "Button1") label = "Left Click"; + if (key === "Button2") label = tx("Middle Click"); + return mac ? parts.map((p) => SYMBOLS[p] ?? p).join("") + label : [...parts, label].join("+"); } if (!mac) return normalizeBinding(binding) @@ -444,6 +471,13 @@ const CHORD_TIMEOUT = 2000; const DOUBLE_TAP_STEP_MS = 300; /** A modifier tap this soon after typing another key is part of typing, not a gesture. */ const DOUBLE_TAP_TYPING_GUARD_MS = 100; +const WHEEL_GESTURE_GAP_MS = 150; + +function isDiscreteWheelEvent(e: WheelEvent): boolean { + // WebViews also send mouse notches in pixel mode, with legacy ticks in units of 120. + const ticks = (e as WheelEvent & { wheelDeltaY?: number }).wheelDeltaY; + return e.deltaMode !== WheelEvent.DOM_DELTA_PIXEL || (!!ticks && ticks % 120 === 0); +} const KEY_MODIFIER: Record = { Shift: "Shift", Control: "Ctrl", Alt: "Alt", Meta: "Meta" }; @@ -669,6 +703,7 @@ export function installKeyboardDispatcher( ): () => void { let pending: string[] = []; let pendingTimer: ReturnType | undefined; + let wheelGesture: { direction: number; at: number; binding: string | null } | null = null; const doubleModifier = createDoubleModifierRecognizer(now); const reset = () => { @@ -819,6 +854,39 @@ export function installKeyboardDispatcher( for (const id of ids.reverse()) if (runIfEnabled(id)) return; }; + const onWheel = (e: WheelEvent) => { + doubleModifier.reset(); + if (suspended > 0 || e.defaultPrevented) { + wheelGesture = null; + return; + } + const stroke = wheelStrokeOf(e); + if (!stroke) return; + const consume = () => { + e.preventDefault(); + e.stopPropagation(); + }; + const direction = Math.sign(e.deltaY); + // Treat a continuous burst as one gesture, including momentum. Modifiers pressed + // during the burst must not turn an ordinary scroll into a shortcut. + if (wheelGesture?.direction === direction && e.timeStamp - wheelGesture.at <= WHEEL_GESTURE_GAP_MS) { + wheelGesture.at = e.timeStamp; + if (wheelGesture.binding === stroke) consume(); + return; + } + wheelGesture = isDiscreteWheelEvent(e) ? null : { direction, at: e.timeStamp, binding: null }; + const match = effectiveBindings().findLast(([binding, id]) => { + if (binding !== stroke || !supportsWheelShortcut(id)) return false; + const action = getAction(id); + return !!action && isActionKeyEnabled(action); + }); + if (!match) return; + if (wheelGesture) wheelGesture.binding = stroke; + consume(); + reset(); + void executeActionFrom("keyboard", match[1]); + }; + /** The release of a side button: swallowed so the webview doesn't navigate its own history. */ const onMouseRelease = (e: MouseEvent) => { if (e.button < 3) return; @@ -832,6 +900,7 @@ export function installKeyboardDispatcher( const onBlur = () => { reset(); doubleModifier.reset(); + wheelGesture = null; }; const onSwipe = (event: Event) => { @@ -848,6 +917,7 @@ export function installKeyboardDispatcher( target.addEventListener("keydown", onKeyDown, true); target.addEventListener("keyup", onKeyUp, true); target.addEventListener("mousedown", onMouseDown, true); + target.addEventListener("wheel", onWheel, { capture: true, passive: false }); target.addEventListener("mouseup", onMouseRelease, true); target.addEventListener("auxclick", onMouseRelease, true); target.addEventListener("webkitmouseforcewillbegin", onForceWillBegin, true); @@ -857,6 +927,7 @@ export function installKeyboardDispatcher( target.removeEventListener("keydown", onKeyDown, true); target.removeEventListener("keyup", onKeyUp, true); target.removeEventListener("mousedown", onMouseDown, true); + target.removeEventListener("wheel", onWheel, true); target.removeEventListener("mouseup", onMouseRelease, true); target.removeEventListener("auxclick", onMouseRelease, true); target.removeEventListener("webkitmouseforcewillbegin", onForceWillBegin, true); diff --git a/src/platform/keymapMouse.test.ts b/src/platform/keymapMouse.test.ts index 2bc072c58b..64b06ce528 100644 --- a/src/platform/keymapMouse.test.ts +++ b/src/platform/keymapMouse.test.ts @@ -1,5 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { + applyKeymapSettings, + bindingsFor, formatBinding, dispatchMouseShortcut, installKeyboardDispatcher, @@ -76,6 +78,37 @@ describe("mouse shortcuts", () => { expect(shortcutLabel("t.mouseFirst")).toBeUndefined(); }); + it.each([ + ["en", "Wheel Up", "Wheel Down"], + ["zh", "滚轮向上", "滚轮向下"], + ])("formats wheel directions in %s", async (locale, up, down) => { + const originalLocale = useI18n.getState().locale; + try { + await setLocale(locale); + expect(formatBinding("ctrl+wheelup", false)).toBe(`Ctrl+${up}`); + expect(formatBinding("meta+shift+wheeldown", true)).toBe(`⇧⌘${down}`); + } finally { + await setLocale(originalLocale); + } + }); + + it("loads canonical single-stroke wheel bindings from preset and custom overrides", () => { + const original = useKeymap.getState(); + const overrides = { + "t.wheel": ["alt+ctrl+wheelup", "Ctrl+Alt+WheelUp", "WheelDown", "Ctrl+K WheelDown", "Alt Alt+WheelUp"], + }; + try { + for (const id of ["intellij-windows", "user:wheel"]) { + applyKeymapSettings(id, overrides, { "user:wheel": { parent: "intellij-windows", overrides } }); + expect(bindingsFor("t.wheel")).toEqual(["Ctrl+Alt+WheelUp", "WheelDown"]); + expect(bindingsFor("t.wheel").every(isMouseBinding)).toBe(true); + expect(primaryKeyBinding("t.wheel")).toBeUndefined(); + } + } finally { + useKeymap.setState(original); + } + }); + describe("dispatch", () => { let uninstall = () => {}; const back = vi.fn(); @@ -105,6 +138,45 @@ describe("mouse shortcuts", () => { return events; }; + const wheel = (init: WheelEventInit, at: number, ticks?: number) => { + const event = new WheelEvent("wheel", { deltaY: -1, bubbles: true, cancelable: true, ...init }); + Object.defineProperty(event, "timeStamp", { value: at }); + if (ticks !== undefined) Object.defineProperty(event, "wheelDeltaY", { value: ticks }); + editor.dispatchEvent(event); + return event; + }; + + it("consumes one shortcut per notch and leaves unmatched and horizontal scroll events alone", () => { + useKeymap.setState({ overrides: { "navigate.back": ["Ctrl+WheelUp"], "navigate.forward": ["WheelDown"] } }); + const scroll = vi.fn(); + editor.addEventListener("wheel", scroll); + expect(wheel({ ctrlKey: true, deltaMode: WheelEvent.DOM_DELTA_LINE }, 1).defaultPrevented).toBe(true); + expect(wheel({ ctrlKey: true }, 2, 120).defaultPrevented).toBe(true); + expect(wheel({ ctrlKey: true }, 3, 120).defaultPrevented).toBe(true); + expect(wheel({ deltaY: 1, deltaMode: WheelEvent.DOM_DELTA_LINE }, 4).defaultPrevented).toBe(true); + expect(wheel({ ctrlKey: true, deltaY: 1 }, 5).defaultPrevented).toBe(false); + expect(wheel({ ctrlKey: true, deltaY: 0, deltaX: -10 }, 6).defaultPrevented).toBe(false); + expect(wheel({ deltaMode: WheelEvent.DOM_DELTA_LINE }, 7).defaultPrevented).toBe(false); + expect(back).toHaveBeenCalledTimes(3); + expect(forward).toHaveBeenCalledOnce(); + expect(scroll).toHaveBeenCalledTimes(3); + }); + + it("swallows a bound trackpad burst without repeating the action or taking over unbound momentum", () => { + useKeymap.setState({ overrides: { "navigate.back": ["Alt+WheelUp"], "navigate.forward": ["Alt+WheelDown"] } }); + expect(wheel({ deltaY: -30 }, 0).defaultPrevented).toBe(false); + expect(wheel({ altKey: true, deltaY: -20 }, 20).defaultPrevented).toBe(false); + expect(back).not.toHaveBeenCalled(); + expect(wheel({ altKey: true, deltaY: -30 }, 200).defaultPrevented).toBe(true); + expect(wheel({ altKey: true, deltaY: -20 }, 220).defaultPrevented).toBe(true); + expect(wheel({ altKey: true, deltaY: -10 }, 240).defaultPrevented).toBe(true); + expect(back).toHaveBeenCalledOnce(); + expect(wheel({ altKey: true, deltaY: 20 }, 260).defaultPrevented).toBe(true); + expect(forward).toHaveBeenCalledOnce(); + expect(wheel({ altKey: true, deltaY: -30 }, 450).defaultPrevented).toBe(true); + expect(back).toHaveBeenCalledTimes(2); + }); + it("does not prepare the editor for a disabled mouse action", () => { const run = vi.fn(); const prepare = vi.fn(() => true); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 2a16be1e74..6d99242af5 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -981,6 +981,10 @@ "Add or Remove Caret": "Add or Remove Caret", "Create Rectangular Selection on Mouse Drag": "Create Rectangular Selection on Mouse Drag", "Middle Click": "Middle Click", + "Wheel Up": "Wheel Up", + "Wheel Down": "Wheel Down", + "This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available.": "This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available.", + "Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button": "Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button", "On Linux, middle-button rectangular selection conflicts with primary selection paste.": "On Linux, middle-button rectangular selection conflicts with primary selection paste.", "Click here with Ctrl, Alt or Command held, or use a middle or side mouse button": "Click here with Ctrl, Alt or Command held, or use a middle or side mouse button", "Click here with Ctrl, Alt or Command held, or use the middle mouse button": "Click here with Ctrl, Alt or Command held, or use the middle mouse button", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 5cf6e3fa33..65f7af1073 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -988,6 +988,10 @@ "Add or Remove Caret": "添加或移除插入点", "Create Rectangular Selection on Mouse Drag": "拖动鼠标创建矩形选区", "Middle Click": "鼠标中键", + "Wheel Up": "滚轮向上", + "Wheel Down": "滚轮向下", + "This shortcut takes precedence over Ctrl/Command+Mouse Wheel font zoom when the action is available.": "此操作可用时,该快捷键优先于 Ctrl/Command+鼠标滚轮字体缩放。", + "Scroll here, click with Ctrl, Alt or Command held, or use a middle or side mouse button": "在此滚动鼠标滚轮,按住 Ctrl、Alt 或 Command 点击,或使用鼠标中键或侧键", "On Linux, middle-button rectangular selection conflicts with primary selection paste.": "在 Linux 上,中键矩形拖选会与主选区粘贴冲突。", "Add Carets to Ends of Selected Lines": "在所选行末尾添加光标", "Unselect Occurrence": "取消选择匹配项",