Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): rightclick to pan canvas (#12110)

David Luzarc0ad61c6743a
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index d453d86dde..ac26f21d79 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -16,7 +16,7 @@ Please add the latest change on the top under the correct section.
### Wheel navigation (2026-09-13) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)
- Scrolling while holding the wheel (middle) mouse button zooms the canvas around the pointer, the same as ctrl/cmd+wheel — a wheel-button pan can be zoomed one-handed, without reaching for a modifier.
-- New `appState.inputDevice` preference (`"auto" | "mouse" | "trackpad"`, default `"auto"`, persisted in browser storage) selecting the wheel mappings. With `"trackpad"` a plain wheel pans and ctrl/cmd+wheel (how a pinch is delivered) zooms, as before; with `"mouse"` a plain wheel zooms and ctrl/cmd+wheel pans vertically instead, while shift+wheel keeps panning horizontally and the wheel-button zoom above is unaffected. `"auto"` is reserved for detecting the device from the wheel events and resolves to `"trackpad"` until that is implemented (`resolveInputDevice()`). Set it from the new "Input device" radio in the main menu's preferences submenu, also exposed as `MainMenu.DefaultItems.Preferences.InputDevice`.
+- New `appState.inputDevice` preference (`"auto" | "mouse" | "trackpad"`, default `"auto"`, persisted in browser storage) selecting the wheel mappings. With `"trackpad"` a plain wheel pans; with `"mouse"` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is delivered) zooms with either device. Shift+wheel pans horizontally, and ctrl/cmd+shift+wheel pans vertically. The wheel-button zoom above is unaffected. `"auto"` is reserved for detecting the device from the wheel events and resolves to `"trackpad"` until that is implemented (`resolveInputDevice()`). Set it from the new "Input device" radio in the main menu's preferences submenu, also exposed as `MainMenu.DefaultItems.Preferences.InputDevice`.
### Sticky notes (2026-09-06) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)
diff --git a/packages/excalidraw/components/App.pan.ts b/packages/excalidraw/components/App.pan.ts
new file mode 100644
index 0000000000..66f6a60cae
--- /dev/null
+++ b/packages/excalidraw/components/App.pan.ts
@@ -0,0 +1,275 @@
+import { CURSOR_TYPE, EVENT, POINTER_BUTTON } from "@excalidraw/common";
+
+import { isHandToolActive } from "../appState";
+import { withBatchedUpdates, withBatchedUpdatesThrottled } from "../reactUtils";
+
+import type React from "react";
+
+import type App from "./App";
+
+const SECONDARY_BUTTON_PAN_THRESHOLD = 5; // px
+
+/**
+ * The drag-pan: a pointer drag that moves the canvas — the wheel or the
+ * secondary button, the main button while space is held or the hand tool
+ * is active, or any button in view mode. One session at a time, owning its
+ * window listeners and teardown; wheel input is gated on it (see
+ * `AppWheel`).
+ *
+ * A secondary-button session is a pan only once the pointer travels past
+ * the drag threshold; released before that, it is a right-click. The
+ * platform's `contextmenu` event opens the menu for a right-click where it
+ * follows the release (Windows), as it always has; where it comes with the
+ * press (macOS, Linux) it is swallowed — a drag cannot be told from a
+ * click yet — and the session opens the menu on release instead.
+ */
+export class AppPan {
+ /** space held down turns a main-button drag into a pan */
+ private spaceHeld = false;
+ private active = false;
+ /** the secondary-button session, while one is active */
+ private secondary: { engaged: boolean; nativeMenuSeen: boolean } | null =
+ null;
+ /** the platform fires `contextmenu` on mouseup (Windows) or on mousedown
+ * (macOS, Linux); the one belonging to a secondary-button session is not a
+ * new click, whichever side of the session it lands on */
+ private suppressNextContextMenu = false;
+ /** applies the pointer move the session is holding back for its next
+ * frame, if any */
+ private pendingMoveFlush: (() => void) | null = null;
+ private teardown: (() => void) | null = null;
+
+ constructor(
+ private app: App,
+ private dependencies: {
+ /** pointers currently down (a two-finger gesture is not a pan) */
+ getPointerCount: () => number;
+ },
+ ) {}
+
+ isActive = () => this.active;
+
+ isSpaceHeld = () => this.spaceHeld;
+
+ setSpaceHeld = (held: boolean) => {
+ this.spaceHeld = held;
+ };
+
+ /** applies the pointer move still waiting for its frame, if any */
+ flushMove = () => {
+ this.pendingMoveFlush?.();
+ };
+
+ /** ends the active session, if any — pointerup may never arrive (the user
+ * tabs away, a new pointerdown lands first) */
+ end = () => {
+ this.teardown?.();
+ };
+
+ /**
+ * Whether a `contextmenu` event belongs to a secondary-button session and
+ * must not open the menu: it came with the press (the session decides on
+ * release), or it follows a release that turned out to be a drag.
+ */
+ consumesContextMenuEvent = () => {
+ if (this.secondary) {
+ this.secondary.nativeMenuSeen = true;
+ return true;
+ }
+ if (this.suppressNextContextMenu) {
+ this.suppressNextContextMenu = false;
+ return true;
+ }
+ return false;
+ };
+
+ /** starts a session for the pointerdown if it qualifies; returns whether
+ * it did */
+ start = (event: React.PointerEvent<HTMLElement> | MouseEvent): boolean => {
+ const { app } = this;
+ // a new press supersedes whatever the previous session left pending
+ this.suppressNextContextMenu = false;
+ const isSecondary = event.button === POINTER_BUTTON.SECONDARY;
+ if (
+ !(
+ this.dependencies.getPointerCount() <= 1 &&
+ (((event.button === POINTER_BUTTON.WHEEL ||
+ isSecondary ||
+ (event.button === POINTER_BUTTON.MAIN && this.spaceHeld) ||
+ isHandToolActive(app.state)) &&
+ // reachable while non-interactive when the active tool is allowed
+ // via `interaction.enabled.tools` — panning must remain gated on
+ // `navigation` then
+ (app.isInteractionEnabled() || app.isNavigationEnabled())) ||
+ (app.state.viewModeEnabled && !app.isActiveToolPointerCapturing()))
+ )
+ ) {
+ return false;
+ }
+ this.active = true;
+ this.secondary = isSecondary
+ ? { engaged: false, nativeMenuSeen: false }
+ : null;
+
+ // due to event.preventDefault below, container wouldn't get focus
+ // automatically
+ app.focusContainer();
+
+ // preventing defualt while text editing messes with cursor/focus
+ if (!app.state.editingTextElement) {
+ // necessary to prevent browser from scrolling the page if excalidraw
+ // not full-page #4489
+ //
+ // as such, the above is broken when panning canvas while in wysiwyg
+ event.preventDefault();
+ }
+
+ let nextPastePrevented = false;
+ const isLinux = /Linux/.test(app.ownerWindow.navigator.platform);
+
+ if (!this.secondary) {
+ app.cursor.set(CURSOR_TYPE.GRABBING);
+ }
+ const { clientX: startX, clientY: startY } = event;
+ let { clientX: lastX, clientY: lastY } = event;
+ const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
+ if (this.secondary && !this.secondary.engaged) {
+ // a right-click until the pointer travels far enough for a drag
+ if (
+ Math.hypot(event.clientX - startX, event.clientY - startY) <=
+ SECONDARY_BUTTON_PAN_THRESHOLD
+ ) {
+ return;
+ }
+ this.secondary.engaged = true;
+ app.cursor.set(CURSOR_TYPE.GRABBING);
+ // pans from here on; the threshold distance is not caught up
+ lastX = event.clientX;
+ lastY = event.clientY;
+ return;
+ }
+
+ const deltaX = lastX - event.clientX;
+ const deltaY = lastY - event.clientY;
+ lastX = event.clientX;
+ lastY = event.clientY;
+
+ /*
+ * Prevent paste event if we move while middle clicking on Linux.
+ * See issue #1383.
+ */
+ if (
+ isLinux &&
+ !nextPastePrevented &&
+ (Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1)
+ ) {
+ nextPastePrevented = true;
+
+ /* Prevent the next paste event */
+ const preventNextPaste = (event: ClipboardEvent) => {
+ app.ownerDocument.body.removeEventListener(
+ EVENT.PASTE,
+ preventNextPaste,
+ );
+ event.stopPropagation();
+ };
+
+ /*
+ * Reenable next paste in case of disabled middle click paste for
+ * any reason:
+ * - right click paste
+ * - empty clipboard
+ */
+ const enableNextPaste = () => {
+ setTimeout(() => {
+ app.ownerDocument.body.removeEventListener(
+ EVENT.PASTE,
+ preventNextPaste,
+ );
+ app.ownerWindow.removeEventListener(
+ EVENT.POINTER_UP,
+ enableNextPaste,
+ );
+ }, 100);
+ };
+
+ app.ownerDocument.body.addEventListener(EVENT.PASTE, preventNextPaste);
+ app.ownerWindow.addEventListener(EVENT.POINTER_UP, enableNextPaste);
+ }
+
+ // an updater, not a snapshot of `app.state`: a wheel zoom queued in
+ // the same React flush would otherwise be overwritten by a pan
+ // computed from the pre-zoom state
+ app.viewport.translate((state) => ({
+ scrollX: state.scrollX - deltaX / state.zoom.value,
+ scrollY: state.scrollY - deltaY / state.zoom.value,
+ }));
+ });
+ this.pendingMoveFlush = onPointerMove.flush;
+ const teardown = withBatchedUpdates(
+ (upEvent?: PointerEvent | FocusEvent) => {
+ const { secondary } = this;
+ this.teardown = null;
+ this.pendingMoveFlush = null;
+ this.active = false;
+ this.secondary = null;
+ if (secondary?.engaged && !secondary.nativeMenuSeen) {
+ // a drag: the platform's `contextmenu` still to come is no click
+ this.suppressNextContextMenu = true;
+ }
+ if (!this.spaceHeld) {
+ app.cursor.reset();
+ }
+ app.setState(
+ {
+ cursorButton: "up",
+ },
+ // Wait for the trailing pan move to commit before converting the
+ // pointer to scene coordinates or starting the snap-back.
+ () => {
+ // Missing-pointerup cleanup can run during a new press. Don't
+ // overwrite the newer button state with this pan's release.
+ if (app.state.cursorButton === "up") {
+ const pointer =
+ upEvent && "clientX" in upEvent
+ ? upEvent
+ : { clientX: lastX, clientY: lastY };
+ app.savePointer(pointer.clientX, pointer.clientY, "up");
+ }
+ app.viewport.releaseOverscroll();
+ },
+ );
+ app.ownerWindow.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
+ app.ownerWindow.removeEventListener(EVENT.POINTER_UP, teardown);
+ app.ownerWindow.removeEventListener(EVENT.BLUR, teardown);
+ onPointerMove.flush();
+
+ // released without a drag: a right-click. Where the platform's
+ // `contextmenu` came with the press it was swallowed, so the menu
+ // opens here, at the release point; where it is still to come it
+ // opens the menu itself, as it always has
+ if (
+ secondary &&
+ !secondary.engaged &&
+ secondary.nativeMenuSeen &&
+ upEvent &&
+ "clientX" in upEvent
+ ) {
+ app.openContextMenu({
+ clientX: upEvent.clientX,
+ clientY: upEvent.clientY,
+ button: upEvent.button,
+ pointerType: upEvent.pointerType,
+ });
+ }
+ },
+ );
+ this.teardown = teardown;
+ app.ownerWindow.addEventListener(EVENT.BLUR, teardown);
+ app.ownerWindow.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {
+ passive: true,
+ });
+ app.ownerWindow.addEventListener(EVENT.POINTER_UP, teardown);
+ return true;
+ };
+}
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index a1055d2050..c730c7023e 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -454,6 +454,7 @@ import { AppToolDrag, TOOL_DRAG_PREVIEW_OPACITY } from "./App.toolDrag";
import { AppCursor } from "./App.cursor";
import { AppDrawShape } from "./App.drawshape";
import { AppFlowchart } from "./App.flowchart";
+import { AppPan } from "./App.pan";
import { AppViewport, RIGHT_SIDEBAR_WIDTH } from "./App.viewport";
import { AppWheel } from "./App.wheel";
import BraveMeasureTextError from "./BraveMeasureTextError";
@@ -609,8 +610,6 @@ export const useExcalidrawAPI = () => useContext(ExcalidrawAPIContext);
let didTapTwice: boolean = false;
let tappedTwiceTimer = 0;
let firstTapPosition: { x: number; y: number } | null = null;
-let isHoldingSpace: boolean = false;
-let isPanning: boolean = false;
let isDraggingScrollBar: boolean = false;
let currentScrollBars: ScrollBars = { horizontal: null, vertical: null };
let touchTimeout = 0;
@@ -631,9 +630,6 @@ let IS_PLAIN_PASTE_TIMER = 0;
let PLAIN_PASTE_TOAST_SHOWN = false;
let lastPointerUp: (() => void) | null = null;
-/** applies the pointer movement the active drag-pan is holding back for its
- * next frame, if any */
-let flushPanMove: (() => void) | null = null;
const gesture: Gesture = {
pointers: new Map(),
lastCenter: null,
@@ -725,15 +721,15 @@ class App extends React.Component<AppProps, AppState> {
public flowchart: AppFlowchart = new AppFlowchart(this);
public cursor: AppCursor = new AppCursor(this);
public arrowText: AppArrowText = new AppArrowText(this);
+ public pan: AppPan = new AppPan(this, {
+ getPointerCount: () => gesture.pointers.size,
+ });
public viewport: AppViewport = new AppViewport(this, {
getContainer: () => this.excalidrawContainerRef.current,
getStylesPanelMode: () => this.stylesPanelMode,
- isGestureActive: () => gesture.pointers.size >= 2 || isPanning,
- });
- public wheel: AppWheel = new AppWheel(this, {
- isPanning: () => isPanning,
- flushPanMove: () => flushPanMove?.(),
+ isGestureActive: () => gesture.pointers.size >= 2 || this.pan.isActive(),
});
+ public wheel: AppWheel = new AppWheel(this);
bindModeHandler: ReturnType<typeof setTimeout> | null = null;
private textWysiwygSubmitHandler: ReturnType<typeof textWysiwyg> | null =
@@ -1606,7 +1602,7 @@ class App extends React.Component<AppProps, AppState> {
// middle-click or something other than primary
this.lastPointerDownEvent.button !== POINTER_BUTTON.MAIN ||
// panning
- isHoldingSpace ||
+ this.pan.isSpaceHeld() ||
// wrong tool
!oneOf(this.state.activeTool.type, ["laser", "selection", "lasso"])
) {
@@ -3245,7 +3241,7 @@ class App extends React.Component<AppProps, AppState> {
// Lifecycle
private onBlur = withBatchedUpdates(() => {
- isHoldingSpace = false;
+ this.pan.setSpaceHeld(false);
this.setState({
isBindingEnabled: this.state.bindingPreference === "enabled",
});
@@ -3322,8 +3318,7 @@ class App extends React.Component<AppProps, AppState> {
// relies on. Among other things this tears down window-level listeners.
this.maybeCleanupAfterMissingPointerUp(null);
- isHoldingSpace = false;
- isPanning = false;
+ this.pan.setSpaceHeld(false);
isDraggingScrollBar = false;
lastPointerUp = null;
@@ -5933,7 +5928,7 @@ class App extends React.Component<AppProps, AppState> {
}
if (event.key === KEYS.SPACE && gesture.pointers.size === 0) {
- isHoldingSpace = true;
+ this.pan.setSpaceHeld(true);
this.cursor.set(CURSOR_TYPE.GRAB);
event.preventDefault();
}
@@ -6041,7 +6036,7 @@ class App extends React.Component<AppProps, AppState> {
activeEmbeddable: null,
});
}
- isHoldingSpace = false;
+ this.pan.setSpaceHeld(false);
}
if (event.key === KEYS.ALT) {
@@ -6219,7 +6214,7 @@ class App extends React.Component<AppProps, AppState> {
: updateActiveTool(this.state, tool);
if (nextActiveTool.type === "hand") {
this.cursor.set(CURSOR_TYPE.GRAB);
- } else if (!isHoldingSpace) {
+ } else if (!this.pan.isSpaceHeld()) {
this.cursor.applyForTool(nextActiveTool);
}
if (isToolIcon(this.ownerDocument.activeElement)) {
@@ -7853,7 +7848,10 @@ class App extends React.Component<AppProps, AppState> {
// the pan session set up on pointerdown)
this.updateMultiTouchGesture(event);
}
- if ((this.isLinksEnabled() || this.isEmbedsEnabled()) && !isPanning) {
+ if (
+ (this.isLinksEnabled() || this.isEmbedsEnabled()) &&
+ !this.pan.isActive()
+ ) {
this.handleInteractiveContentPointerMove(event);
}
return;
@@ -7870,8 +7868,8 @@ class App extends React.Component<AppProps, AppState> {
this.updateMultiTouchGesture(event);
if (
- isHoldingSpace ||
- isPanning ||
+ this.pan.isSpaceHeld() ||
+ this.pan.isActive() ||
isDraggingScrollBar ||
isHandToolActive(this.state)
) {
@@ -8570,10 +8568,10 @@ class App extends React.Component<AppProps, AppState> {
}
if (this.isNavigationEnabled()) {
this.updateGestureOnPointerDown(event);
- if (!isPanning) {
+ if (!this.pan.isActive()) {
// pans on drag same as view mode (the pan session manages its own
// window listeners & teardown)
- this.handleCanvasPanUsingWheelOrSpaceDrag(event);
+ this.pan.start(event);
}
}
return;
@@ -8722,7 +8720,7 @@ class App extends React.Component<AppProps, AppState> {
});
}
- if (isPanning) {
+ if (this.pan.isActive()) {
return;
}
@@ -8731,7 +8729,7 @@ class App extends React.Component<AppProps, AppState> {
// we must exit before we set `cursorButton` state and `savePointer`
// else it will send pointer state & laser pointer events in collab when
// panning
- if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) {
+ if (this.pan.start(event)) {
return;
}
@@ -9011,7 +9009,7 @@ class App extends React.Component<AppProps, AppState> {
// onPointerDown/onPointerUp callbacks, pointer-up teardown,
// missing-pointer-up cleanup — runs for bucket clicks too. In view
// mode this branch is unreachable:
- // `handleCanvasPanUsingWheelOrSpaceDrag` swallows the pointer-down.
+ // `pan.start` swallows the pointer-down.
this.bucketFill.handlePointerDown(scenePointer);
} else if (
this.state.activeTool.type !== "eraser" &&
@@ -9152,138 +9150,11 @@ class App extends React.Component<AppProps, AppState> {
* pointerup handlers manually
*/
private maybeCleanupAfterMissingPointerUp = (event: PointerEvent | null) => {
+ this.pan.end();
lastPointerUp?.();
this.missingPointerEventCleanupEmitter.trigger(event).clear();
};
- // Returns whether the event is a panning
- public handleCanvasPanUsingWheelOrSpaceDrag = (
- event: React.PointerEvent<HTMLElement> | MouseEvent,
- ): boolean => {
- if (
- !(
- gesture.pointers.size <= 1 &&
- (((event.button === POINTER_BUTTON.WHEEL ||
- (event.button === POINTER_BUTTON.MAIN && isHoldingSpace) ||
- isHandToolActive(this.state)) &&
- // reachable while non-interactive when the active tool is allowed
- // via `interaction.enabled.tools` — panning must remain gated on
- // `navigation` then
- (this.isInteractionEnabled() || this.isNavigationEnabled())) ||
- (this.state.viewModeEnabled && !this.isActiveToolPointerCapturing()))
- )
- ) {
- return false;
- }
- isPanning = true;
-
- // due to event.preventDefault below, container wouldn't get focus
- // automatically
- this.focusContainer();
-
- // preventing defualt while text editing messes with cursor/focus
- if (!this.state.editingTextElement) {
- // necessary to prevent browser from scrolling the page if excalidraw
- // not full-page #4489
- //
- // as such, the above is broken when panning canvas while in wysiwyg
- event.preventDefault();
- }
-
- let nextPastePrevented = false;
- const isLinux = /Linux/.test(this.ownerWindow.navigator.platform);
-
- this.cursor.set(CURSOR_TYPE.GRABBING);
- let { clientX: lastX, clientY: lastY } = event;
- const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
- const deltaX = lastX - event.clientX;
- const deltaY = lastY - event.clientY;
- lastX = event.clientX;
- lastY = event.clientY;
-
- /*
- * Prevent paste event if we move while middle clicking on Linux.
- * See issue #1383.
- */
- if (
- isLinux &&
- !nextPastePrevented &&
- (Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1)
- ) {
- nextPastePrevented = true;
-
- /* Prevent the next paste event */
- const preventNextPaste = (event: ClipboardEvent) => {
- this.ownerDocument.body.removeEventListener(
- EVENT.PASTE,
- preventNextPaste,
- );
- event.stopPropagation();
- };
-
- /*
- * Reenable next paste in case of disabled middle click paste for
- * any reason:
- * - right click paste
- * - empty clipboard
- */
- const enableNextPaste = () => {
- setTimeout(() => {
- this.ownerDocument.body.removeEventListener(
- EVENT.PASTE,
- preventNextPaste,
- );
- this.ownerWindow.removeEventListener(
- EVENT.POINTER_UP,
- enableNextPaste,
- );
- }, 100);
- };
-
- this.ownerDocument.body.addEventListener(EVENT.PASTE, preventNextPaste);
- this.ownerWindow.addEventListener(EVENT.POINTER_UP, enableNextPaste);
- }
-
- // an updater, not a snapshot of `this.state`: a wheel zoom queued in
- // the same React flush would otherwise be overwritten by a pan
- // computed from the pre-zoom state
- this.viewport.translate((state) => ({
- scrollX: state.scrollX - deltaX / state.zoom.value,
- scrollY: state.scrollY - deltaY / state.zoom.value,
- }));
- });
- flushPanMove = onPointerMove.flush;
- const teardown = withBatchedUpdates(
- (lastPointerUp = () => {
- lastPointerUp = null;
- flushPanMove = null;
- isPanning = false;
- if (!isHoldingSpace) {
- this.cursor.reset();
- }
- this.setState(
- {
- cursorButton: "up",
- },
- // Runs after the trailing throttled pointer move has committed, so
- // the snap-back starts from the pan's actual final viewport.
- this.viewport.releaseOverscroll,
- );
- this.savePointer(event.clientX, event.clientY, "up");
- this.ownerWindow.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
- this.ownerWindow.removeEventListener(EVENT.POINTER_UP, teardown);
- this.ownerWindow.removeEventListener(EVENT.BLUR, teardown);
- onPointerMove.flush();
- }),
- );
- this.ownerWindow.addEventListener(EVENT.BLUR, teardown);
- this.ownerWindow.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {
- passive: true,
- });
- this.ownerWindow.addEventListener(EVENT.POINTER_UP, teardown);
- return true;
- };
-
private updateGestureOnPointerDown(
event: React.PointerEvent<HTMLElement>,
): void {
@@ -13530,9 +13401,35 @@ class App extends React.Component<AppProps, AppState> {
private handleCanvasContextMenu = (
event: React.MouseEvent<HTMLElement | HTMLCanvasElement>,
) => {
- // Always suppress the native menu over the canvas. In non-interactive
- // mode we stop here so it cannot be mistaken for Excalidraw's own menu.
+ // Always suppress the native menu over the canvas.
event.preventDefault();
+ // a secondary-button press is a pan session: this event is not a click
+ // when it comes with the press (macOS and Linux fire it on mousedown,
+ // and the session opens the menu on release if no drag follows), nor
+ // when it follows a release that was a drag
+ if (this.pan.consumesContextMenuEvent()) {
+ return;
+ }
+ this.openContextMenu({
+ clientX: event.clientX,
+ clientY: event.clientY,
+ button: event.button,
+ pointerType:
+ "pointerType" in event.nativeEvent
+ ? (event.nativeEvent as PointerEvent).pointerType
+ : undefined,
+ });
+ };
+
+ /** opens the context menu for the element under the pointer, or the canvas */
+ public openContextMenu = (pointer: {
+ clientX: number;
+ clientY: number;
+ button?: number;
+ pointerType?: string;
+ }) => {
+ // In non-interactive mode there is no menu, so the native one cannot be
+ // mistaken for Excalidraw's own.
if (!this.isInteractionEnabled()) {
return;
}
@@ -13542,18 +13439,16 @@ class App extends React.Component<AppProps, AppState> {
this.bucketFill.cancel();
if (
- (("pointerType" in event.nativeEvent &&
- event.nativeEvent.pointerType === "touch") ||
- ("pointerType" in event.nativeEvent &&
- event.nativeEvent.pointerType === "pen" &&
+ (pointer.pointerType === "touch" ||
+ (pointer.pointerType === "pen" &&
// always allow if user uses a pen secondary button
- event.button !== POINTER_BUTTON.SECONDARY)) &&
+ pointer.button !== POINTER_BUTTON.SECONDARY)) &&
this.state.activeTool.type !== this.state.preferredSelectionTool.type
) {
return;
}
- const { x, y } = viewportCoordsToSceneCoords(event, this.state);
+ const { x, y } = viewportCoordsToSceneCoords(pointer, this.state);
const element = this.getElementAtPosition(x, y, {
preferSelected: true,
includeLockedElements: true,
@@ -13571,8 +13466,8 @@ class App extends React.Component<AppProps, AppState> {
const container = this.excalidrawContainerRef.current!;
const { top: offsetTop, left: offsetLeft } =
container.getBoundingClientRect();
- const left = event.clientX - offsetLeft;
- const top = event.clientY - offsetTop;
+ const left = pointer.clientX - offsetLeft;
+ const top = pointer.clientY - offsetTop;
trackEvent("contextMenu", "openContextMenu", type);
@@ -14112,7 +14007,12 @@ class App extends React.Component<AppProps, AppState> {
}
}
- private savePointer = (x: number, y: number, button: "up" | "down") => {
+ public savePointer = (x: number, y: number, button: "up" | "down") => {
+ // Pan teardown broadcasts once the viewport has settled. Updates during
+ // the drag use a viewport that can lag behind the pointer and flicker.
+ if (this.pan.isActive()) {
+ return;
+ }
// don't broadcast pointer updates (props.onPointerUpdate) when
// non-interactive, unless the active tool stays user-driven via
// `interaction.enabled.tools` — collaborators render e.g. a presenter's
diff --git a/packages/excalidraw/components/App.wheel.ts b/packages/excalidraw/components/App.wheel.ts
index 6d3a689848..15e5e2d8aa 100644
--- a/packages/excalidraw/components/App.wheel.ts
+++ b/packages/excalidraw/components/App.wheel.ts
@@ -15,20 +15,11 @@ const WHEEL_BUTTON_MASK = 4;
* pointer (`viewport.lastPosition`) — on ctrl/cmd+wheel (which is also how
* a trackpad pinch is delivered), while the wheel button itself is held
* down, or on a plain wheel when the input device is a mouse
- * (`appState.inputDevice`; ctrl/cmd+wheel pans instead then).
+ * (`appState.inputDevice`). Shift+wheel pans horizontally;
+ * ctrl/cmd+shift+wheel pans vertically.
*/
export class AppWheel {
- constructor(
- private app: App,
- private dependencies: {
- /** whether a drag-pan (wheel button, space+drag, hand tool) is in
- * progress — wheel input is ignored meanwhile */
- isPanning: () => boolean;
- /** applies the pointer movement the drag-pan is holding back for its
- * next frame, if any */
- flushPanMove: () => void;
- },
- ) {}
+ constructor(private app: App) {}
/** the editor surfaces whose wheel input the editor consumes; everywhere
* else (menus, sidebars, …) the DOM keeps scrolling. The frame-name labels
@@ -66,7 +57,10 @@ export class AppWheel {
// drag-pan the button itself started
const isWheelButtonHeld = !!(event.buttons & WHEEL_BUTTON_MASK);
- if (this.dependencies.isPanning()) {
+ // a drag-pan (wheel button, space+drag, hand tool) in progress owns the
+ // viewport; wheel input is ignored meanwhile — except for the wheel
+ // button's own zoom
+ if (this.app.pan.isActive()) {
if (!isWheelButtonHeld) {
return;
}
@@ -75,7 +69,7 @@ export class AppWheel {
// it — at the new zoom, on a viewport the zoom anchored without it —
// and the point grabbed by the pan drifts from under the cursor a
// little on every tick
- this.dependencies.flushPanMove();
+ this.app.pan.flushMove();
}
const { deltaX, deltaY } = event;
@@ -86,24 +80,24 @@ export class AppWheel {
const hasZoomModifier = event.metaKey || event.ctrlKey;
const shouldZoom =
// a horizontal-only wheel (tilt wheel, sideways two-finger scroll)
- // has nothing to zoom by; it pans sideways below instead
+ // has nothing to zoom by; it follows the pan mappings below instead
deltaY !== 0 &&
(isWheelButtonHeld ||
- (resolveInputDevice(this.app.state.inputDevice) === "mouse"
- ? // a mouse has no pinch: a plain wheel zooms, and any modifier
- // pans instead (ctrl/cmd vertically, shift horizontally)
- !hasZoomModifier && !event.shiftKey
- : hasZoomModifier));
+ (!event.shiftKey &&
+ (hasZoomModifier ||
+ resolveInputDevice(this.app.state.inputDevice) === "mouse")));
if (shouldZoom) {
this.zoomBy(deltaY);
return;
}
- // scroll horizontally when shift pressed
+ // Shift pans horizontally; ctrl/cmd+shift pans vertically.
if (event.shiftKey) {
- this.app.viewport.translate(({ zoom, scrollX }) => ({
- // on Mac, shift+wheel tends to result in deltaX
- scrollX: scrollX - (deltaY || deltaX) / zoom.value,
+ // on Mac, shift+wheel tends to result in deltaX
+ const delta = deltaY || deltaX;
+ this.app.viewport.translate(({ zoom, scrollX, scrollY }) => ({
+ scrollX: hasZoomModifier ? scrollX : scrollX - delta / zoom.value,
+ scrollY: hasZoomModifier ? scrollY - delta / zoom.value : scrollY,
}));
return;
}
diff --git a/packages/excalidraw/tests/pan.test.tsx b/packages/excalidraw/tests/pan.test.tsx
new file mode 100644
index 0000000000..0f98d2a4b1
--- /dev/null
+++ b/packages/excalidraw/tests/pan.test.tsx
@@ -0,0 +1,216 @@
+import React from "react";
+import { fireEvent } from "@testing-library/react";
+import { vi } from "vitest";
+
+import {
+ CURSOR_TYPE,
+ POINTER_BUTTON,
+ viewportCoordsToSceneCoords,
+} from "@excalidraw/common";
+
+import { Excalidraw } from "../index";
+
+import { API } from "./helpers/api";
+import { GlobalTestState, render } from "./test-utils";
+
+const { h } = window;
+
+const secondaryButton = {
+ pointerId: 1,
+ pointerType: "mouse",
+ // `button` identifies the pressed button, `buttons` the held-down set
+ button: POINTER_BUTTON.SECONDARY,
+ buttons: 2,
+};
+
+const at = (clientX: number, clientY: number) => ({
+ ...secondaryButton,
+ clientX,
+ clientY,
+});
+
+const getViewport = () => ({
+ scrollX: h.state.scrollX,
+ scrollY: h.state.scrollY,
+ zoom: h.state.zoom.value,
+});
+
+const canvas = () => GlobalTestState.interactiveCanvas;
+
+describe("secondary-button pan", () => {
+ beforeEach(async () => {
+ await render(<Excalidraw />);
+ });
+
+ it.each([false, true])(
+ "pans past five pixels with no context menu (viewModeEnabled=%s)",
+ (viewModeEnabled) => {
+ API.setAppState({ viewModeEnabled });
+ fireEvent.pointerDown(canvas(), at(100, 100));
+ const start = getViewport();
+
+ // at the five-pixel threshold it is still a click
+ fireEvent.pointerMove(canvas(), at(103, 104));
+ expect(getViewport()).toEqual(start);
+ expect(canvas().style.cursor).not.toBe(CURSOR_TYPE.GRABBING);
+
+ // past it the pan engages, and moves from here on
+ fireEvent.pointerMove(canvas(), at(106, 100));
+ expect(getViewport()).toEqual(start);
+ expect(canvas().style.cursor).toBe(CURSOR_TYPE.GRABBING);
+ fireEvent.pointerMove(canvas(), at(108, 103));
+ expect(getViewport()).toEqual({
+ ...start,
+ scrollX: start.scrollX + 2 / start.zoom,
+ scrollY: start.scrollY + 3 / start.zoom,
+ });
+
+ fireEvent.pointerUp(window, { ...at(108, 103), buttons: 0 });
+ expect(h.state.contextMenu).toBe(null);
+
+ // the platform's own contextmenu for this press (Windows fires it on
+ // mouseup) is not a new click...
+ fireEvent.contextMenu(canvas(), at(108, 103));
+ expect(h.state.contextMenu).toBe(null);
+ // ...but only that one
+ fireEvent.contextMenu(canvas(), at(108, 103));
+ expect(h.state.contextMenu).not.toBe(null);
+ },
+ );
+
+ it("lets the platform's contextmenu after mouseup open the menu, as always", () => {
+ fireEvent.pointerDown(canvas(), at(100, 100));
+ fireEvent.pointerMove(canvas(), at(104, 102));
+ expect(h.state.contextMenu).toBe(null);
+
+ // Windows fires contextmenu after mouseup: nothing is open at release,
+ // so the event lands on the canvas and opens the menu, as before
+ fireEvent.pointerUp(window, { ...at(104, 102), buttons: 0 });
+ expect(h.state.contextMenu).toBe(null);
+ fireEvent.contextMenu(canvas(), at(104, 102));
+ const menu = h.state.contextMenu;
+ expect(menu).not.toBe(null);
+ expect(menu!.left).toBe(104 - h.state.offsetLeft);
+ expect(menu!.top).toBe(102 - h.state.offsetTop);
+ });
+
+ it.each([false, true])(
+ "pauses pointer broadcasts until pan release (viewModeEnabled=%s)",
+ (viewModeEnabled) => {
+ const onPointerUpdate = vi.fn();
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw onPointerUpdate={onPointerUpdate} />,
+ );
+ API.setAppState({ viewModeEnabled });
+ fireEvent.pointerDown(canvas(), at(100, 100));
+ fireEvent.pointerMove(canvas(), at(103, 104));
+ fireEvent.pointerMove(canvas(), at(106, 100));
+ fireEvent.pointerMove(canvas(), at(140, 135));
+ expect(onPointerUpdate).not.toHaveBeenCalled();
+
+ // The release can be beyond the last delivered pointer move.
+ const released = { ...at(150, 145), buttons: 0 };
+ fireEvent.pointerUp(canvas(), released);
+
+ expect(onPointerUpdate).toHaveBeenCalledTimes(1);
+ expect(onPointerUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ pointer: {
+ ...viewportCoordsToSceneCoords(released, h.state),
+ tool: "pointer",
+ },
+ button: "up",
+ }),
+ );
+
+ const hovered = { ...released, clientX: 160, clientY: 155 };
+ fireEvent.pointerMove(canvas(), hovered);
+ expect(onPointerUpdate).toHaveBeenCalledTimes(2);
+ expect(onPointerUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ pointer: {
+ ...viewportCoordsToSceneCoords(hovered, h.state),
+ tool: "pointer",
+ },
+ button: "up",
+ }),
+ );
+ },
+ );
+
+ it("does not broadcast an old pan release after a new press", () => {
+ const onPointerUpdate = vi.fn();
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw onPointerUpdate={onPointerUpdate} />,
+ );
+ fireEvent.pointerDown(canvas(), at(100, 100));
+ fireEvent.pointerMove(canvas(), at(106, 100));
+ fireEvent.pointerMove(canvas(), at(140, 135));
+
+ const nextPress = { ...at(150, 145), button: 0, buttons: 1 };
+ try {
+ // A new press cleans up the pan if its pointerup was missed.
+ fireEvent.pointerDown(canvas(), nextPress);
+ expect(onPointerUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({ button: "down" }),
+ );
+ } finally {
+ fireEvent.pointerUp(canvas(), { ...nextPress, buttons: 0 });
+ }
+ });
+
+ it("opens the context menu on release when not dragged (contextmenu on mousedown)", () => {
+ fireEvent.pointerDown(canvas(), at(100, 100));
+ // macOS and Linux fire contextmenu with the press, before any drag
+ // could be told apart from a click
+ fireEvent.contextMenu(canvas(), at(100, 100));
+ expect(h.state.contextMenu).toBe(null);
+
+ fireEvent.pointerUp(window, { ...at(100, 100), buttons: 0 });
+ expect(h.state.contextMenu).not.toBe(null);
+ });
+
+ it("does not open a menu for a drag on platforms that fire contextmenu on mousedown", () => {
+ fireEvent.pointerDown(canvas(), at(100, 100));
+ fireEvent.contextMenu(canvas(), at(100, 100));
+ fireEvent.pointerMove(canvas(), at(130, 120));
+ fireEvent.pointerMove(canvas(), at(150, 140));
+ fireEvent.pointerUp(window, { ...at(150, 140), buttons: 0 });
+ expect(h.state.contextMenu).toBe(null);
+
+ // the menu is available again to a later, unrelated request
+ fireEvent.contextMenu(canvas(), at(150, 140));
+ expect(h.state.contextMenu).not.toBe(null);
+ });
+
+ it("selects the element under the pointer like a right-click does", () => {
+ const rectangle = API.createElement({
+ type: "rectangle",
+ x: 10,
+ y: 10,
+ width: 50,
+ height: 50,
+ // filled, so its interior hit-tests (a transparent shape only hits
+ // on its stroke)
+ backgroundColor: "#ffc9c9",
+ fillStyle: "solid",
+ });
+ API.setElements([rectangle]);
+
+ fireEvent.pointerDown(canvas(), at(30, 30));
+ // contextmenu with the press: the session opens the menu on release
+ fireEvent.contextMenu(canvas(), at(30, 30));
+ fireEvent.pointerUp(window, { ...at(30, 30), buttons: 0 });
+
+ expect(h.state.contextMenu).not.toBe(null);
+ expect(h.state.selectedElementIds[rectangle.id]).toBe(true);
+ });
+
+ it("leaves a menu-less editor menu-less while still panning", async () => {
+ await render(<Excalidraw interaction={false} />);
+ fireEvent.pointerDown(canvas(), at(100, 100));
+ fireEvent.contextMenu(canvas(), at(100, 100));
+ fireEvent.pointerUp(window, { ...at(100, 100), buttons: 0 });
+ expect(h.state.contextMenu).toBe(null);
+ });
+});
diff --git a/packages/excalidraw/tests/wheel.test.tsx b/packages/excalidraw/tests/wheel.test.tsx
index fbb0361afd..336b243054 100644
--- a/packages/excalidraw/tests/wheel.test.tsx
+++ b/packages/excalidraw/tests/wheel.test.tsx
@@ -238,6 +238,57 @@ describe("wheel navigation", () => {
expectGrabbedUnderCursor(grabbed);
});
+ it.each(["pointerup", "blur", "cleanup"] as const)(
+ "broadcasts the final pointer using the committed pan viewport on %s",
+ (ending) => {
+ const onPointerUpdate = vi.fn();
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw onPointerUpdate={onPointerUpdate} />,
+ );
+ grab();
+ fireEvent.pointerMove(GlobalTestState.interactiveCanvas, {
+ ...wheelButtonPointer,
+ clientX: 110,
+ clientY: 105,
+ });
+
+ const released = {
+ ...moved,
+ clientX: 150,
+ clientY: 140,
+ buttons: 0,
+ };
+ throttle.holding = true;
+ try {
+ fireEvent.pointerMove(GlobalTestState.interactiveCanvas, moved);
+ expect(onPointerUpdate).not.toHaveBeenCalled();
+ if (ending === "pointerup") {
+ fireEvent.pointerUp(GlobalTestState.interactiveCanvas, released);
+ } else if (ending === "blur") {
+ fireEvent.blur(window);
+ } else {
+ React.act(() => h.app.pan.end());
+ }
+ } finally {
+ throttle.holding = false;
+ }
+
+ expect(onPointerUpdate).toHaveBeenCalledTimes(1);
+ expect(onPointerUpdate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ pointer: {
+ ...viewportCoordsToSceneCoords(
+ ending === "pointerup" ? released : moved,
+ h.state,
+ ),
+ tool: "pointer",
+ },
+ button: "up",
+ }),
+ );
+ },
+ );
+
it("keeps drawing from zoom-scaled bitmaps until the gesture is over", async () => {
grab();
@@ -267,43 +318,83 @@ describe("wheel navigation", () => {
expect(resolveInputDevice(h.state.inputDevice)).toBe("trackpad");
});
+ describe.each(["auto", "mouse", "trackpad"] as const)(
+ "shift+wheel with %s input",
+ (inputDevice) => {
+ beforeEach(() => {
+ API.setAppState({
+ inputDevice,
+ zoom: { value: getNormalizedZoom(2) },
+ scrollX: 12,
+ scrollY: 34,
+ });
+ });
+
+ it.each([
+ { label: "shift+wheel", modifiers: {}, axis: "scrollX" },
+ {
+ label: "ctrl+shift+wheel",
+ modifiers: { ctrlKey: true },
+ axis: "scrollY",
+ },
+ {
+ label: "cmd+shift+wheel",
+ modifiers: { metaKey: true },
+ axis: "scrollY",
+ },
+ ] as const)("pans only $axis on $label", ({ modifiers, axis }) => {
+ const start = getViewport();
+ wheel({ deltaX: 10, deltaY: 40, shiftKey: true, ...modifiers });
+ expect(getViewport()).toEqual({
+ ...start,
+ [axis]: start[axis] - 20,
+ });
+
+ // A horizontal-only wheel delta must follow the requested axis too.
+ wheel({ deltaX: -40, shiftKey: true, ...modifiers });
+ expect(getViewport()).toEqual(start);
+ });
+ },
+ );
+
describe("mouse", () => {
beforeEach(() => {
API.setAppState({ inputDevice: "mouse" });
});
- it("zooms on plain wheel and pans vertically on ctrl/cmd+wheel", () => {
+ it.each([
+ { label: "plain wheel", modifiers: {} },
+ { label: "ctrl+wheel", modifiers: { ctrlKey: true } },
+ { label: "cmd+wheel", modifiers: { metaKey: true } },
+ ])("zooms around the pointer on $label", ({ modifiers }) => {
+ const pointer = { clientX: 100, clientY: 100 };
+ fireEvent.pointerMove(GlobalTestState.interactiveCanvas, pointer);
+ const scenePoint = viewportCoordsToSceneCoords(pointer, h.state);
const start = getViewport();
- wheel({ deltaY: -100 });
+ wheel({ deltaY: -100, ...modifiers });
expect(h.state.zoom.value).toBeGreaterThan(start.zoom);
- const zoomed = getViewport();
- wheel({ deltaY: 40, ctrlKey: true });
- expect(getViewport()).toEqual({
- ...zoomed,
- scrollY: zoomed.scrollY - 40 / zoomed.zoom,
- });
+ const zoomedInPoint = viewportCoordsToSceneCoords(pointer, h.state);
+ expect(zoomedInPoint.x).toBeCloseTo(scenePoint.x);
+ expect(zoomedInPoint.y).toBeCloseTo(scenePoint.y);
- const panned = getViewport();
- wheel({ deltaY: 40, metaKey: true });
- expect(getViewport()).toEqual({
- ...panned,
- scrollY: panned.scrollY - 40 / panned.zoom,
- });
- });
+ const zoomedIn = h.state.zoom.value;
+ wheel({ deltaY: 100, ...modifiers });
+ expect(h.state.zoom.value).toBeLessThan(zoomedIn);
- it("keeps shift+wheel panning horizontally", () => {
- const start = getViewport();
- wheel({ deltaY: 40, shiftKey: true });
- expect(getViewport()).toEqual({
- ...start,
- scrollX: start.scrollX - 40 / start.zoom,
- });
+ const zoomedOutPoint = viewportCoordsToSceneCoords(pointer, h.state);
+ expect(zoomedOutPoint.x).toBeCloseTo(scenePoint.x);
+ expect(zoomedOutPoint.y).toBeCloseTo(scenePoint.y);
});
it("keeps zooming with the wheel button held", () => {
const start = getViewport();
- wheel({ deltaY: -100, buttons: WHEEL_BUTTON, ctrlKey: true });
+ wheel({
+ deltaY: -100,
+ buttons: WHEEL_BUTTON,
+ ctrlKey: true,
+ shiftKey: true,
+ });
expect(h.state.zoom.value).toBeGreaterThan(start.zoom);
});
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index c9c13ca9e6..e719119dd5 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -368,9 +368,10 @@ export interface AppState {
isMidpointSnappingEnabled: boolean;
/**
* user preference for what the wheel does: with a `trackpad` a plain wheel
- * pans and ctrl/cmd+wheel (how a pinch is delivered) zooms; with a `mouse`
- * a plain wheel zooms and ctrl/cmd+wheel pans vertically. `auto` resolves
- * to `trackpad` until device detection exists — see `resolveInputDevice`
+ * pans; with a `mouse` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is
+ * delivered) zooms with either device. Shift+wheel pans horizontally;
+ * ctrl/cmd+shift+wheel pans vertically. `auto` resolves to `trackpad` until
+ * device detection exists — see `resolveInputDevice`
*/
inputDevice: InputDevice;
/**
diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.tsx
index ec356d1b63..569318c153 100644
--- a/packages/excalidraw/wysiwyg/textWysiwyg.tsx
+++ b/packages/excalidraw/wysiwyg/textWysiwyg.tsx
@@ -952,7 +952,7 @@ export const textWysiwyg = ({
// trying to pan by clicking inside text area itself -> handle here
if (target instanceof ownerWindow.HTMLTextAreaElement) {
event.preventDefault();
- app.handleCanvasPanUsingWheelOrSpaceDrag(event);
+ app.pan.start(event);
}
temporarilyDisableSubmit();