The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(titlebar): start window drags on macOS only for a press that is still held (#1074)
ntbang090129c54c243ae1
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 8c6d65f11..e99b4838e 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -78,7 +78,7 @@ block2 = "0.6"# Plugin secrets in the login keychain.security-framework = "3.7"objc2 = "0.6"-objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSButton", "NSResponder", "NSScreen", "NSView", "NSWindow"] }+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSButton", "NSEvent", "NSResponder", "NSScreen", "NSView", "NSWindow"] }objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "CFRunLoop"] }objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex d54186784..7d8de235f 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -45,6 +45,7 @@ pub mod tools;pub mod vcs;pub mod web;pub mod window;+pub mod window_drag;pub mod window_group;pub mod workspace;@@ -404,6 +405,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {window::window_cycle,window::window_toggle_fullscreen,window::window_set_titlebar_height,+ window_drag::window_start_drag,window::window_take_launch,window::window_close_context,window::window_open_projects,diff --git a/src-tauri/src/commands/window_drag.rs b/src-tauri/src/commands/window_drag.rsnew file mode 100644index 000000000..700bf8651--- /dev/null+++ b/src-tauri/src/commands/window_drag.rs@@ -0,0 +1,19 @@+//! Native window drag started from the web title bar.++use ide_core::{IdeError, IdeResult};+use tauri::WebviewWindow;++/// Starts dragging `window` while the primary mouse button is still down; returns whether a drag began.+///+/// macOS WebKit can deliver a tap's `mousedown` after the button is already up. AppKit would then run+/// its drag loop with no release left to end it, and the window follows the pointer until the next click.+#[tauri::command]+#[specta::specta]+pub fn window_start_drag(window: WebviewWindow) -> IdeResult<bool> {+ #[cfg(target_os = "macos")]+ if objc2_app_kit::NSEvent::pressedMouseButtons() & 1 == 0 {+ return Ok(false);+ }+ window.start_dragging().map_err(|e| IdeError::internal(e.to_string()))?;+ Ok(true)+}diff --git a/src/bindings.ts b/src/bindings.tsindex 364c5b4b5..d46c6bb64 100644--- a/src/bindings.ts+++ b/src/bindings.ts@@ -811,6 +811,13 @@ export const commands = {windowToggleFullscreen: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_toggle_fullscreen")),/** Height of the web title bar in native logical pixels (CSS height × IDE zoom). */windowSetTitlebarHeight: (height: number | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_set_titlebar_height", { height })),+ /**+ * Starts dragging `window` while the primary mouse button is still down; returns whether a drag began.+ *+ * macOS WebKit can deliver a tap's `mousedown` after the button is already up. AppKit would then run+ * its drag loop with no release left to end it, and the window follows the pointer until the next click.+ */+ windowStartDrag: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_start_drag")),/** What this window was opened for (taken once). */windowTakeLaunch: () => __TAURI_INVOKE<{/** Project folder to open. */diff --git a/src/main.tsx b/src/main.tsxindex b2109ff6f..10a197d6c 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -20,6 +20,7 @@ import { installPointerFocus } from "./platform/pointerFocus";import { isTauri } from "./platform/ipc";import { hideSplash } from "./platform/splash";import { prefetchLazyComponents } from "./ui";+import { installWindowDrag } from "./workbench/window-drag";if (import.meta.env.DEV && isTauri()) {// The Tauri MCP bridge returns eval results via `window.__TAURI__` on Windows/Linux@@ -29,6 +30,7 @@ if (import.meta.env.DEV && isTauri()) {}installRepeatedDoubleClick();+installWindowDrag();installPointerFocus();installErrorLogging();diff --git a/src/workbench/TitleBar.tsx b/src/workbench/TitleBar.tsxindex cd8b6b3c9..3ac6a89a4 100644--- a/src/workbench/TitleBar.tsx+++ b/src/workbench/TitleBar.tsx@@ -28,6 +28,7 @@ import { useContributedThemes } from "@/platform/themes";import { currentThemeChoice, useThemeOverride } from "./theme";import styles from "./TitleBar.module.css";import { useNativeTitlebar } from "./nativeTitlebar";+import { windowDragRegion } from "./window-drag";export function orderTitleItems(items: Iterable<TitleItemContribution>) {const all = [...items];@@ -287,11 +288,11 @@ export function TitleBar({// main menu (Windows, Linux) it stays, or nothing would lead back out of the mode.if (bare)return (- <header ref={setBar} className={className} data-tauri-drag-region data-titlebar="bare">+ <header ref={setBar} className={className} {...windowDragRegion} data-titlebar="bare">{frameless && (<><MainMenu />- <div className={styles.drag} data-tauri-drag-region />+ <div className={styles.drag} {...windowDragRegion} /><WindowControls /></>)}@@ -303,7 +304,7 @@ export function TitleBar({<headerref={setBar}className={clsx(className, minimal && styles.minimal, dialog && styles.dialogBar)}- data-tauri-drag-region+ {...windowDragRegion}onContextMenu={(e) => {if (!toolbar || e.defaultPrevented) return;e.preventDefault();@@ -312,12 +313,12 @@ export function TitleBar({>{frameless && !minimal && <MainMenu onExpandedChange={setMenuExpanded} />}{title && (- <span className={styles.windowTitle} data-tauri-drag-region>+ <span className={styles.windowTitle} {...windowDragRegion}>{typeof title === "string" ? <T>{title}</T> : title}</span>)}{toolbar && !menuExpanded && shown.left.map(entry)}- <div className={styles.drag} data-tauri-drag-region />+ <div className={styles.drag} {...windowDragRegion} />{!minimal && (<>{toolbar && !menuExpanded && shown.right.map(entry)}diff --git a/src/workbench/distractionFree.test.tsx b/src/workbench/distractionFree.test.tsxindex 295dcfacb..b38bafbd7 100644--- a/src/workbench/distractionFree.test.tsx+++ b/src/workbench/distractionFree.test.tsx@@ -217,7 +217,8 @@ describe("distraction free shell", () => {expect(screen.queryByRole("button", { name: "Project" })).toBeNull();expect(screen.queryByRole("button", { name: "Search Everywhere" })).toBeNull();const bar = document.querySelector("header[data-titlebar='bare']");- expect(bar).toHaveAttribute("data-tauri-drag-region");+ // macOS uses its own drag region attribute (window-drag.ts); jsdom reports the host OS.+ expect(bar?.hasAttribute("data-tauri-drag-region") || bar?.hasAttribute("data-window-drag-region")).toBe(true);act(() => setDistractionFree(false));expect(screen.getByText("df-demo")).toBeInTheDocument();diff --git a/src/workbench/window-drag.test.ts b/src/workbench/window-drag.test.tsnew file mode 100644index 000000000..4c8125ca1--- /dev/null+++ b/src/workbench/window-drag.test.ts@@ -0,0 +1,68 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { installWindowDrag } from "./window-drag";++describe("installWindowDrag", () => {+ let uninstall: () => void;+ let bar: HTMLElement;+ let region: HTMLElement;+ let button: HTMLButtonElement;+ const start = vi.fn();+ const toggleMaximize = vi.fn();++ beforeEach(() => {+ start.mockClear();+ toggleMaximize.mockClear();+ uninstall = installWindowDrag({ enabled: true, start, toggleMaximize });+ bar = document.body.appendChild(document.createElement("header"));+ region = bar.appendChild(document.createElement("div"));+ region.setAttribute("data-window-drag-region", "");+ button = bar.appendChild(document.createElement("button"));+ });+ afterEach(() => {+ uninstall();+ bar.remove();+ });++ const mouse = (el: Element, type: string, init: MouseEventInit = {}) => {+ const e = new MouseEvent(type, { bubbles: true, cancelable: true, composed: true, button: 0, detail: 1, ...init });+ el.dispatchEvent(e);+ return e;+ };++ it("starts a native drag only while the primary button is held", () => {+ const e = mouse(region, "mousedown", { buttons: 1 });+ expect(start).toHaveBeenCalledOnce();+ expect(e.defaultPrevented).toBe(true);+ });++ it("does not drag for a tap whose mousedown arrives after the release", () => {+ mouse(region, "mousedown", { buttons: 0 });+ expect(start).not.toHaveBeenCalled();+ });++ it("ignores presses on controls, other buttons and the region's children", () => {+ mouse(button, "mousedown", { buttons: 1 });+ mouse(region, "mousedown", { buttons: 2, button: 2 });+ const child = region.appendChild(document.createElement("span"));+ mouse(child, "mousedown", { buttons: 1 });+ expect(start).not.toHaveBeenCalled();+ });++ it("zooms on the mouseup of a double click that did not move, not on a drag away", () => {+ mouse(region, "mousedown", { detail: 2, clientX: 5, clientY: 5, buttons: 1 });+ expect(start).not.toHaveBeenCalled();+ mouse(region, "mouseup", { detail: 2, clientX: 5, clientY: 5 });+ expect(toggleMaximize).toHaveBeenCalledOnce();++ mouse(region, "mousedown", { detail: 2, clientX: 5, clientY: 5, buttons: 1 });+ mouse(region, "mouseup", { detail: 2, clientX: 40, clientY: 5 });+ expect(toggleMaximize).toHaveBeenCalledOnce();+ });++ it("does nothing when disabled or after uninstall", () => {+ uninstall();+ uninstall = installWindowDrag({ enabled: false, start, toggleMaximize });+ mouse(region, "mousedown", { buttons: 1 });+ expect(start).not.toHaveBeenCalled();+ });+});diff --git a/src/workbench/window-drag.ts b/src/workbench/window-drag.tsnew file mode 100644index 000000000..a21c948ef--- /dev/null+++ b/src/workbench/window-drag.ts@@ -0,0 +1,86 @@+import { invoke } from "@tauri-apps/api/core";+import { commands } from "@/platform/ipc";+import { guessOs } from "@/platform/platformInfo";++/**+ * Title bar drag on macOS, replacing Tauri's injected `data-tauri-drag-region` script there.+ * That script starts the native drag on any `mousedown`, but WebKit can deliver a tap's `mousedown`+ * after the button is already up; AppKit then drags the window until the next click. Here the drag+ * starts only while the button is down (`buttons` here, and again natively in `window_start_drag`).+ * Windows and Linux keep the Tauri attribute.+ */+const REGION = "data-window-drag-region";++/** Attribute that makes an element a title bar drag region on this OS. */+export const windowDragRegion: Record<string, string> =+ guessOs() === "macos" ? { [REGION]: "" } : { "data-tauri-drag-region": "" };++const CLICKABLE_TAGS = new Set(["A", "BUTTON", "INPUT", "SELECT", "TEXTAREA", "LABEL", "SUMMARY"]);+const INTERACTIVE_ROLES = new Set(["button", "link", "menuitem", "tab", "checkbox", "radio", "switch", "option"]);++function isClickable(el: HTMLElement) {+ const editable = el.getAttribute("contenteditable");+ const tabindex = el.getAttribute("tabindex");+ return (+ CLICKABLE_TAGS.has(el.tagName) ||+ (editable !== null && editable !== "false") ||+ (tabindex !== null && tabindex !== "-1") ||+ INTERACTIVE_ROLES.has(el.getAttribute("role") ?? "")+ );+}++/** Same rules as Tauri's script: a bare attribute counts only for direct clicks, `deep` for the subtree. */+function isDragRegion(path: EventTarget[]) {+ for (const el of path) {+ if (!(el instanceof HTMLElement)) continue;+ const attr = el.getAttribute(REGION);+ if (attr === null) {+ if (isClickable(el)) return false;+ continue;+ }+ if (attr === "false") return false;+ if (attr === "deep") return true;+ return el === path[0];+ }+ return false;+}++interface Deps {+ enabled?: boolean;+ start?: () => unknown;+ toggleMaximize?: () => unknown;+}++/** Installs the handlers on macOS (no-op elsewhere); returns the uninstall function. */+export function installWindowDrag({+ enabled = guessOs() === "macos",+ start = () => commands.windowStartDrag(),+ toggleMaximize = () => invoke("plugin:window|internal_toggle_maximize"),+}: Deps = {}): () => void {+ if (!enabled) return () => {};+ let down = { x: 0, y: 0 };++ const onMouseDown = (e: MouseEvent) => {+ if (e.button !== 0 || (e.detail !== 1 && e.detail !== 2) || !isDragRegion(e.composedPath())) return;+ // Zoom happens on mouseup, as in AppKit, so moving away cancels it.+ if (e.detail === 2) {+ down = { x: e.clientX, y: e.clientY };+ return;+ }+ e.preventDefault(); // no text cursor+ e.stopImmediatePropagation();+ // A tap's mousedown arrives with the button already released: nothing to drag.+ if (e.buttons & 1) void start();+ };+ const onMouseUp = (e: MouseEvent) => {+ if (e.button !== 0 || e.detail !== 2 || e.clientX !== down.x || e.clientY !== down.y) return;+ if (isDragRegion(e.composedPath())) void toggleMaximize();+ };++ document.addEventListener("mousedown", onMouseDown);+ document.addEventListener("mouseup", onMouseUp);+ return () => {+ document.removeEventListener("mousedown", onMouseDown);+ document.removeEventListener("mouseup", onMouseUp);+ };+}