Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(packages/excalidraw): interaction and UI control (#11605)

David Luzar2423819ee0d5
diff --git a/examples/with-script-in-browser/components/ExampleApp.tsx b/examples/with-script-in-browser/components/ExampleApp.tsx
index fd380cbac4..8ee104f6d0 100644
--- a/examples/with-script-in-browser/components/ExampleApp.tsx
+++ b/examples/with-script-in-browser/components/ExampleApp.tsx
@@ -102,6 +102,12 @@ export default function ExampleApp({
} = excalidrawLib;
const appRef = useRef<any>(null);
const [viewModeEnabled, setViewModeEnabled] = useState(false);
+ const [interactive, setInteractive] = useState(true);
+ const [interactiveLinks, setInteractiveLinks] = useState(false);
+ const [interactiveEmbeds, setInteractiveEmbeds] = useState(false);
+ const [interactiveNavigation, setInteractiveNavigation] = useState(false);
+ const [interactiveBrowserZoom, setInteractiveBrowserZoom] = useState(false);
+ const [ui, setUi] = useState(true);
const [zenModeEnabled, setZenModeEnabled] = useState(false);
const [gridModeEnabled, setGridModeEnabled] = useState(false);
const [renderScrollbars, setRenderScrollbars] = useState(false);
@@ -192,6 +198,17 @@ export default function ExampleApp({
pointersMap: Gesture["pointers"];
}) => setPointerData(payload),
viewModeEnabled,
+ interaction: interactive
+ ? true
+ : {
+ enabled: {
+ links: interactiveLinks,
+ embeds: interactiveEmbeds,
+ navigation: interactiveNavigation,
+ browserZoom: interactiveBrowserZoom,
+ },
+ },
+ ui,
zenModeEnabled,
renderScrollbars,
gridModeEnabled,
@@ -696,6 +713,52 @@ export default function ExampleApp({
/>
View mode
</label>
+ <label>
+ <input
+ type="checkbox"
+ checked={!interactive}
+ onChange={() => setInteractive(!interactive)}
+ />
+ Non-interactive
+ </label>
+ <label>
+ <input
+ type="checkbox"
+ checked={interactiveLinks}
+ onChange={() => setInteractiveLinks(!interactiveLinks)}
+ />
+ Links when non-interactive
+ </label>
+ <label>
+ <input
+ type="checkbox"
+ checked={interactiveEmbeds}
+ onChange={() => setInteractiveEmbeds(!interactiveEmbeds)}
+ />
+ Embeds when non-interactive
+ </label>
+ <label>
+ <input
+ type="checkbox"
+ checked={interactiveNavigation}
+ onChange={() => setInteractiveNavigation(!interactiveNavigation)}
+ />
+ Navigation when non-interactive
+ </label>
+ <label>
+ <input
+ type="checkbox"
+ checked={interactiveBrowserZoom}
+ onChange={() =>
+ setInteractiveBrowserZoom(!interactiveBrowserZoom)
+ }
+ />
+ Browser zoom when non-interactive
+ </label>
+ <label>
+ <input type="checkbox" checked={!ui} onChange={() => setUi(!ui)} />
+ Hide UI
+ </label>
<label>
<input
type="checkbox"
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index 09d1f55d29..cfe8df7fd2 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -15,6 +15,12 @@ Please add the latest change on the top under the correct section.
## Excalidraw API
+### Interaction and UI control (2026-07-05) [#11605](https://github.com/excalidraw/excalidraw/pull/11605)
+
+- Added `interaction` prop (`boolean | { enabled?: { navigation?: boolean; links?: boolean; embeds?: boolean; interactiveContent?: boolean; browserZoom?: boolean } }`). When set to `false`, the editor becomes fully inert for the user — no panning, zooming, selecting, editing, keyboard shortcuts, clipboard, or drag&drop. It implies view mode (`appState.viewModeEnabled` reports `true` and cannot be unset while non-interactive), and the page scrolls naturally over the component since wheel/touch input is no longer captured (the browser's own zoom is still prevented over the editor by default). Interactions under `enabled` are opt-in exceptions: with `navigation` allowed, the user can pan (pointer drag, wheel) and zoom (ctrl/cmd + wheel, pinch, and the canvas zoom & zoom-to-fit shortcuts — ctrl/cmd +/-/0, shift+1/2/3) the canvas view-mode style — respecting `appState.scrollConstraints`, so it composes with viewport locking for constrained viewers, while the rest of the keyboard stays disabled and the editor consumes wheel & touch input again (the page no longer scrolls over the editor); with `links` allowed, link icons render and linked elements stay clickable (view-mode behavior: clicking anywhere on a linked element opens its link) while the editor stays otherwise non-interactive — when links are not allowed, link icons are not rendered at all; with `embeds` allowed, embeddable & iframe elements stay interactive (hover & click activates them, view-mode style); `interactiveContent` is an additive shorthand enabling `links` & `embeds` (and future interactive content kinds) together; with `browserZoom` allowed, the browser's own zoom gestures (ctrl/cmd + wheel, pinch, keyboard) stay available over the editor (moot when `navigation` is allowed, since the editor consumes the zoom input instead). The scene still renders and remains fully controllable through the imperative API (`updateScene`, `setViewport`, ...), making it suitable for live previews, thumbnails, and annotation overlays.
+
+- Added `ui` prop. When set to `false`, Excalidraw's default UI is not rendered — toolbar, default menu and footer controls, sidebars, canvas popups, and context menu. Canvas content (elements, text editing, frame names, embeds) still renders, and the editor remains interactive unless `interaction={false}` is set as well. Host children continue to mount (they may be functional, e.g. a collaboration component), and host-supplied UI — including Excalidraw-exported components such as `<MainMenu>` and `<Footer>` — continues to render together with any supporting dialogs it opens. You're responsible for hiding your own presentational components.
+
### Tool system & toolbar rework
The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>` elements composed from a central tool registry, and all tool activation now goes through a single `setActiveTool` code path.
@@ -44,9 +50,9 @@ The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>
- Mobile toolbar popovers: the active option stays highlighted after tapping it (the highlight was being suppressed by sticky touch-hover).
- The active-tool highlight can no longer desync from the actually active tool (controlled-radio DOM desync).
-### Viewport control & scroll/zoom locking
+### Viewport control & scroll/zoom locking (2026-07-03) [#11554](https://github.com/excalidraw/excalidraw/pull/11554)
-`ExcalidrawAPI.scrollToContent` was rebuilt into `ExcalidrawAPI.setViewport()` — a single API for navigating the viewport (`fit: "scale-down" | "contain" | "none"`), locking scroll/zoom to a target (with rubberband overscroll), fitting around the rendered editor UI, and initializing the viewport on scene load [#11554](https://github.com/excalidraw/excalidraw/pull/11554).
+`ExcalidrawAPI.scrollToContent` was rebuilt into `ExcalidrawAPI.setViewport()` — a single API for navigating the viewport (`fit: "scale-down" | "contain" | "none"`), locking scroll/zoom to a target (with rubberband overscroll), fitting around the rendered editor UI, and initializing the viewport on scene load.
#### Breaking changes
@@ -76,11 +82,13 @@ The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>
- `lock.overscroll` adds a rubberband to the lock: panning can overshoot the constraint by the given amount (viewport px, zoom-independent) and snaps back once the interaction settles — on touch, once the multi-finger gesture ends. Defaults to `true` = `DEFAULT_OVERSCROLL` (150px, exported from the package root); pass a number to customize, or `false` / `0` for a rigid lock. Zooming is always hard-clamped against the lock, gliding along its edge instead of overscrolling.
+- While a lock is active, the zoom-to-fit shortcuts (shift+1/2/3) target the locked box instead of the scene elements (with no selection), so they return the viewport to the lock's resting state; reset-zoom (ctrl/cmd+0) resets to the lock's minimum zoom instead of 100%. Fit results are always re-clamped against the lock. [#11605](https://github.com/excalidraw/excalidraw/pull/11605)
+
- Added `<Excalidraw initialState={{ viewport }} />` for initializing the viewport (and optionally installing a lock) once on scene load. Accepts the same options as `setViewport` except `animation`, and takes precedence over `initialData.scrollToContent`.
- The `offsets` option (on `setViewport` and `initialState.viewport`) insets the usable viewport per side so targets aren't fitted underneath overlaid UI. It combines static pixel sides with `ui: true | ViewportOffsetsOptions`, which measures the currently rendered editor UI (toolbar, styles panel, sidebar…) — with configurable padding, per-side overrides, and reserving space for currently-hidden surfaces (`reserve: { stylesPanel?: boolean; sidebar?: boolean }`). The same measurement is exposed through the new `ExcalidrawAPI.getViewportOffsets(opts?)`, and custom UI rendered inside the editor container can opt into being measured via the `data-viewport-ui="top" | "bottom" | "side"` attribute.
-### Breaking changes
+### Other Breaking changes
- `UIAppState` no longer includes `zoom`, `shouldCacheIgnoreZoom`, and the canvas-interaction transients `snapLines`, `originSnapOffset`, `suggestedBinding`, `frameToHighlight`, and `elementsToHighlight`. These update per pointermove or per animation frame and no longer re-render the editor UI, so UI render props receiving `UIAppState` (`renderCustomStats`, custom `<Footer/>` content, etc.) don't receive them anymore and would render stale values if they read them off the full `AppState`. Subscribe through `useExcalidrawStateValue` instead — the component re-renders only when the selected value changes:
@@ -113,7 +121,7 @@ The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>
- Renamed the `excalidrawAPI` prop to `onExcalidrawAPI`.
- `onExcalidrawAPI` is now called on mount (instead of during constructor), and later on unmount (with `null` value). The API may be removed altogether in the future (you can use `onMount` & `onUnmount` to manage the `ExcalidrawAPI` object (e.g. to cache it to a global state), already).
-### Features
+### Other Features
- Added `ExcalidrawAPI.isDestroyed` flag. Set to `true` once the editor unmounts. Calling any `get*` method, `onStateChange`, or `onEvent` on a destroyed API instance will throw in development and `console.error` in production. The `ExcalidrawAPI` will be reset to `null` on unmount, but to be extra safe, you should check `ExcalidrawAPI.isDestroyed` before calling these methods to guard against subtle race conditions in your code.
diff --git a/packages/excalidraw/actions/actionCanvas.tsx b/packages/excalidraw/actions/actionCanvas.tsx
index fa378df291..c97b110239 100644
--- a/packages/excalidraw/actions/actionCanvas.tsx
+++ b/packages/excalidraw/actions/actionCanvas.tsx
@@ -14,7 +14,7 @@ import { getCommonBounds } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
-import type { ExcalidrawElement } from "@excalidraw/element/types";
+import type { Bounds } from "@excalidraw/common";
import { getDefaultAppState } from "../appState";
import { ColorPicker } from "../components/ColorPicker/ColorPicker";
@@ -125,8 +125,10 @@ export const actionZoomIn = register({
name: "zoomIn",
label: "buttons.zoomIn",
viewMode: true,
+ navigation: true,
icon: ZoomInIcon,
trackEvent: { category: "canvas" },
+ predicate: (elements, appState, appProps, app) => app.isNavigationEnabled(),
perform: (_elements, appState, _, app) => {
const nextState = {
...appState,
@@ -171,7 +173,9 @@ export const actionZoomOut = register({
label: "buttons.zoomOut",
icon: ZoomOutIcon,
viewMode: true,
+ navigation: true,
trackEvent: { category: "canvas" },
+ predicate: (elements, appState, appProps, app) => app.isNavigationEnabled(),
perform: (_elements, appState, _, app) => {
const nextState = {
...appState,
@@ -216,7 +220,9 @@ export const actionResetZoom = register({
label: "buttons.resetZoom",
icon: ZoomResetIcon,
viewMode: true,
+ navigation: true,
trackEvent: { category: "canvas" },
+ predicate: (elements, appState, appProps, app) => app.isNavigationEnabled(),
perform: (_elements, appState, _, app) => {
// reset to 100%, unless a zoom lock floors the zoom higher — then reset to
// the locked minimum zoom (the lock's resting zoom level)
@@ -264,6 +270,19 @@ export const actionResetZoom = register({
(event[KEYS.CTRL_OR_CMD] || event.shiftKey),
});
+// under a viewport lock, zoom-to-fit targets the locked box rather than the
+// scene elements
+const getScrollConstraintsBounds = (
+ scrollConstraints: NonNullable<AppState["scrollConstraints"]>,
+) => {
+ return [
+ scrollConstraints.x,
+ scrollConstraints.y,
+ scrollConstraints.x + scrollConstraints.width,
+ scrollConstraints.y + scrollConstraints.height,
+ ] as Bounds;
+};
+
// Note, this action differs from actionZoomToFitSelection in that it doesn't
// zoom beyond 100%. In other words, if the content is smaller than viewport
// size, it won't be zoomed in.
@@ -271,17 +290,22 @@ export const actionZoomToFitSelectionInViewport = register({
name: "zoomToFitSelectionInViewport",
label: "labels.zoomToFitViewport",
icon: zoomAreaIcon,
+ // with no selection (as is always the case in view mode & when
+ // non-interactive), fits all elements, or the locked viewport box when
+ // a viewport lock is active
+ viewMode: true,
+ navigation: true,
trackEvent: { category: "canvas" },
- predicate: (elements, appState) => !appState.scrollConstraints,
+ predicate: (elements, appState, appProps, app) => app.isNavigationEnabled(),
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
- const nonDeletedSelectedElements = getNonDeletedElements(
- (selectedElements.length
- ? selectedElements
- : elements) as ExcalidrawElement[],
- );
- return zoomToFitBounds({
- bounds: getCommonBounds(nonDeletedSelectedElements),
+ const bounds = selectedElements.length
+ ? getCommonBounds(getNonDeletedElements(selectedElements))
+ : appState.scrollConstraints
+ ? getScrollConstraintsBounds(appState.scrollConstraints)
+ : getCommonBounds(getNonDeletedElements(elements));
+ const result = zoomToFitBounds({
+ bounds,
appState: {
...appState,
userToFollow: null,
@@ -289,11 +313,18 @@ export const actionZoomToFitSelectionInViewport = register({
fit: "scale-down",
canvasOffsets: app.getViewportOffsets(),
});
+ return {
+ ...result,
+ // re-clamp so the fit can't escape an active scroll/zoom lock
+ appState: {
+ ...result.appState,
+ ...constrainScrollState(result.appState),
+ },
+ };
},
// NOTE shift-2 should have been assigned actionZoomToFitSelection.
// TBD on how proceed
- keyTest: (event, appState) =>
- !appState.scrollConstraints &&
+ keyTest: (event) =>
event.code === CODES.TWO &&
event.shiftKey &&
!event.altKey &&
@@ -304,17 +335,22 @@ export const actionZoomToFitSelection = register({
name: "zoomToFitSelection",
label: "helpDialog.zoomToSelection",
icon: zoomAreaIcon,
+ // with no selection (as is always the case in view mode & when
+ // non-interactive), fits all elements, or the locked viewport box when
+ // a viewport lock is active
+ viewMode: true,
+ navigation: true,
trackEvent: { category: "canvas" },
- predicate: (elements, appState) => !appState.scrollConstraints,
+ predicate: (elements, appState, appProps, app) => app.isNavigationEnabled(),
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
- const nonDeletedSelectedElements = getNonDeletedElements(
- (selectedElements.length
- ? selectedElements
- : elements) as ExcalidrawElement[],
- );
- return zoomToFitBounds({
- bounds: getCommonBounds(nonDeletedSelectedElements),
+ const bounds = selectedElements.length
+ ? getCommonBounds(getNonDeletedElements(selectedElements))
+ : appState.scrollConstraints
+ ? getScrollConstraintsBounds(appState.scrollConstraints)
+ : getCommonBounds(getNonDeletedElements(elements));
+ const result = zoomToFitBounds({
+ bounds,
appState: {
...appState,
userToFollow: null,
@@ -322,10 +358,17 @@ export const actionZoomToFitSelection = register({
fit: "contain",
canvasOffsets: app.getViewportOffsets(),
});
+ return {
+ ...result,
+ // re-clamp so the fit can't escape an active scroll/zoom lock
+ appState: {
+ ...result.appState,
+ ...constrainScrollState(result.appState),
+ },
+ };
},
// NOTE this action should use shift-2 per figma, alas
- keyTest: (event, appState) =>
- !appState.scrollConstraints &&
+ keyTest: (event) =>
event.code === CODES.THREE &&
event.shiftKey &&
!event.altKey &&
@@ -337,20 +380,33 @@ export const actionZoomToFit = register({
label: "helpDialog.zoomToFit",
icon: zoomAreaIcon,
viewMode: true,
+ navigation: true,
trackEvent: { category: "canvas" },
- predicate: (elements, appState) => !appState.scrollConstraints,
- perform: (elements, appState, _, app) =>
- zoomToFitBounds({
- bounds: getCommonBounds(getNonDeletedElements(elements)),
+ predicate: (elements, appState, appProps, app) => app.isNavigationEnabled(),
+ perform: (elements, appState, _, app) => {
+ // under a viewport lock, fits the locked box rather than the elements
+ const bounds = appState.scrollConstraints
+ ? getScrollConstraintsBounds(appState.scrollConstraints)
+ : getCommonBounds(getNonDeletedElements(elements));
+ const result = zoomToFitBounds({
+ bounds,
appState: {
...appState,
userToFollow: null,
},
fit: "scale-down",
canvasOffsets: app.getViewportOffsets(),
- }),
- keyTest: (event, appState) =>
- !appState.scrollConstraints &&
+ });
+ return {
+ ...result,
+ // re-clamp so the fit can't escape an active scroll/zoom lock
+ appState: {
+ ...result.appState,
+ ...constrainScrollState(result.appState),
+ },
+ };
+ },
+ keyTest: (event) =>
event.code === CODES.ONE &&
event.shiftKey &&
!event.altKey &&
diff --git a/packages/excalidraw/actions/actionToggleViewMode.tsx b/packages/excalidraw/actions/actionToggleViewMode.tsx
index c635f2869e..1cfbdc5562 100644
--- a/packages/excalidraw/actions/actionToggleViewMode.tsx
+++ b/packages/excalidraw/actions/actionToggleViewMode.tsx
@@ -25,8 +25,11 @@ export const actionToggleViewMode = register({
};
},
checked: (appState) => appState.viewModeEnabled,
- predicate: (elements, appState, appProps) => {
- return typeof appProps.viewModeEnabled === "undefined";
+ predicate: (elements, appState, appProps, app) => {
+ return (
+ typeof appProps.viewModeEnabled === "undefined" &&
+ app.isInteractionEnabled()
+ );
},
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.R,
diff --git a/packages/excalidraw/actions/manager.tsx b/packages/excalidraw/actions/manager.tsx
index adac253e22..e4e037c6b6 100644
--- a/packages/excalidraw/actions/manager.tsx
+++ b/packages/excalidraw/actions/manager.tsx
@@ -87,6 +87,10 @@ export class ActionManager {
}
handleKeyDown(event: React.KeyboardEvent | KeyboardEvent) {
+ if (!this.app.isInteractionEnabled() && !this.app.isNavigationEnabled()) {
+ return false;
+ }
+
const canvasActions = this.app.props.UIOptions.canvasActions;
const data = Object.values(this.actions)
.sort((a, b) => (b.keyPriority || 0) - (a.keyPriority || 0))
@@ -113,6 +117,12 @@ export class ActionManager {
const action = data[0];
+ // in the non-interactive editor, only navigation actions are allowed
+ // (when navigation itself is)
+ if (!this.app.isInteractionEnabled() && action.navigation !== true) {
+ return false;
+ }
+
if (this.getAppState().viewModeEnabled && action.viewMode !== true) {
return false;
}
@@ -134,6 +144,17 @@ export class ActionManager {
source: ActionSource = "api",
value: Parameters<T["perform"]>[2] = null,
) {
+ // the user must not be able to affect a non-interactive editor
+ // (programmatic execution by the host remains allowed, as are
+ // navigation actions when navigation is)
+ if (
+ source !== "api" &&
+ !this.app.isInteractionEnabled() &&
+ !(this.app.isNavigationEnabled() && action.navigation === true)
+ ) {
+ return;
+ }
+
const elements = this.getElementsIncludingDeleted();
const appState = this.getAppState();
diff --git a/packages/excalidraw/actions/types.ts b/packages/excalidraw/actions/types.ts
index 0aed4559a9..6cbe6da10a 100644
--- a/packages/excalidraw/actions/types.ts
+++ b/packages/excalidraw/actions/types.ts
@@ -215,4 +215,8 @@ export interface Action<TData = any> {
/** if set to `true`, allow action to be performed in viewMode.
* Defaults to `false` */
viewMode?: boolean;
+ /** if set to `true`, the action counts as canvas navigation and remains
+ * available in the non-interactive editor when
+ * `interaction: { enabled: { navigation: true } }`. Defaults to `false` */
+ navigation?: boolean;
}
diff --git a/packages/excalidraw/components/App.flowchart.ts b/packages/excalidraw/components/App.flowchart.ts
index 1c9b33dedf..50b92c6f5a 100644
--- a/packages/excalidraw/components/App.flowchart.ts
+++ b/packages/excalidraw/components/App.flowchart.ts
@@ -44,6 +44,12 @@ export class AppFlowchart {
return this.creator.isCreatingChart;
}
+ /** ends any in-progress flowchart creation/navigation session */
+ clear = () => {
+ this.creator.clear();
+ this.navigator.clear();
+ };
+
handleKeyEvent = (event: React.KeyboardEvent | KeyboardEvent): boolean => {
const operation = this.resolveKeyboardEventToOperation(event);
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index 223063e992..3e6034c7d3 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -723,6 +723,8 @@ class App extends React.Component<AppProps, AppState> {
public flowchart: AppFlowchart = new AppFlowchart(this);
bindModeHandler: ReturnType<typeof setTimeout> | null = null;
+ private textWysiwygSubmitHandler: ReturnType<typeof textWysiwyg> | null =
+ null;
hitLinkElement?: NonDeletedExcalidrawElement;
lastPointerDownEvent: React.PointerEvent<HTMLElement> | null = null;
@@ -847,7 +849,11 @@ class App extends React.Component<AppProps, AppState> {
exportWithDarkMode: theme === THEME.DARK,
isLoading: true,
...this.getCanvasOffsets(),
- viewModeEnabled,
+ // non-interactive editor implies view mode so that all edit-mode
+ // gates apply
+ viewModeEnabled: this.isInteractionEnabled(props)
+ ? viewModeEnabled
+ : true,
zenModeEnabled,
objectsSnapModeEnabled,
gridModeEnabled: gridModeEnabled ?? defaultAppState.gridModeEnabled,
@@ -896,6 +902,89 @@ class App extends React.Component<AppProps, AppState> {
this.api = this.createExcalidrawAPI();
}
+ /**
+ * Whether the editor accepts user input (pointer, keyboard, wheel, touch,
+ * clipboard, drag&drop). When `false`, the editor is fully inert for the
+ * user, but remains controllable through the imperative API.
+ *
+ * All user-input entry points must consult this getter (directly or by
+ * not being attached/rendered at all).
+ */
+ public isInteractionEnabled(
+ props: Pick<AppProps, "interaction"> = this.props,
+ ): boolean {
+ return props.interaction !== false && typeof props.interaction !== "object";
+ }
+
+ /**
+ * Whether element links render their link icon and are clickable.
+ * True when fully interactive, or when `interaction: { enabled: { links:
+ * true } }`
+ * (in which case clicking anywhere on a linked element opens the link,
+ * same as in view mode).
+ */
+ public isLinksEnabled(
+ props: Pick<AppProps, "interaction"> = this.props,
+ ): boolean {
+ if (typeof props.interaction === "object" && props.interaction !== null) {
+ return (
+ props.interaction.enabled?.links === true ||
+ props.interaction.enabled?.interactiveContent === true
+ );
+ }
+ return props.interaction !== false;
+ }
+
+ /**
+ * Whether canvas navigation — panning & zooming, view-mode style — is
+ * enabled. True when fully interactive, or when `interaction: { enabled:
+ * { navigation: true } }`. Respects `appState.scrollConstraints`.
+ */
+ public isNavigationEnabled(
+ props: Pick<AppProps, "interaction"> = this.props,
+ ): boolean {
+ if (typeof props.interaction === "object" && props.interaction !== null) {
+ return props.interaction.enabled?.navigation === true;
+ }
+ return props.interaction !== false;
+ }
+
+ /**
+ * Whether embeddable & iframe elements are interactive (hover & click to
+ * activate, view-mode style). True when fully interactive, or when
+ * allowed via `interaction.enabled.embeds` / `.interactiveContent`.
+ */
+ public isEmbedsEnabled(
+ props: Pick<AppProps, "interaction"> = this.props,
+ ): boolean {
+ if (typeof props.interaction === "object" && props.interaction !== null) {
+ return (
+ props.interaction.enabled?.embeds === true ||
+ props.interaction.enabled?.interactiveContent === true
+ );
+ }
+ return props.interaction !== false;
+ }
+
+ /**
+ * Whether the browser's own zoom (ctrl/cmd + wheel, pinch, keyboard
+ * shortcuts) stays available over the non-interactive editor.
+ * Prevented by default.
+ */
+ public isBrowserZoomEnabled(
+ props: Pick<AppProps, "interaction"> = this.props,
+ ): boolean {
+ if (typeof props.interaction === "object" && props.interaction !== null) {
+ return props.interaction.enabled?.browserZoom === true;
+ }
+ return false;
+ }
+
+ /** Whether Excalidraw's default UI is rendered. */
+ public isDefaultUIEnabled(props: Pick<AppProps, "ui"> = this.props): boolean {
+ return props.ui !== false;
+ }
+
updateEditorAtom = <Value, Args extends unknown[], Result>(
atom: WritableAtom<Value, Args, Result>,
...args: Args
@@ -2189,6 +2278,14 @@ class App extends React.Component<AppProps, AppState> {
this.state.viewModeEnabled ||
this.state.openDialog?.name === "elementLinkSelector",
"excalidraw--mobile": this.editorInterface.formFactor === "phone",
+ "excalidraw--non-interactive": !this.isInteractionEnabled(),
+ "excalidraw--navigation":
+ !this.isInteractionEnabled() && this.isNavigationEnabled(),
+ "excalidraw--embeds":
+ !this.isInteractionEnabled() && this.isEmbedsEnabled(),
+ "excalidraw--allow-browser-zoom":
+ !this.isInteractionEnabled() && this.isBrowserZoomEnabled(),
+ "excalidraw--ui-hidden": !this.isDefaultUIEnabled(),
})}
style={{
["--ui-pointerEvents" as any]: shouldBlockPointerEvents
@@ -2197,13 +2294,23 @@ class App extends React.Component<AppProps, AppState> {
["--right-sidebar-width" as any]: `${RIGHT_SIDEBAR_WIDTH}px`,
}}
ref={this.excalidrawContainerRef}
- onDrop={this.handleAppOnDrop}
+ onDrop={this.isInteractionEnabled() ? this.handleAppOnDrop : undefined}
tabIndex={0}
onKeyDown={
- this.props.handleKeyboardGlobally ? undefined : this.onKeyDown
+ this.props.handleKeyboardGlobally || !this.isInteractionEnabled()
+ ? undefined
+ : this.onKeyDown
+ }
+ onPointerEnter={
+ this.isInteractionEnabled()
+ ? this.toggleOverscrollBehavior
+ : undefined
+ }
+ onPointerLeave={
+ this.isInteractionEnabled()
+ ? this.toggleOverscrollBehavior
+ : undefined
}
- onPointerEnter={this.toggleOverscrollBehavior}
- onPointerLeave={this.toggleOverscrollBehavior}
>
<ExcalidrawAPIContext.Provider value={this.api}>
<AppContext.Provider value={this}>
@@ -2225,6 +2332,7 @@ class App extends React.Component<AppProps, AppState> {
<LayerUI
canvas={this.canvas}
appState={this.state}
+ defaultUIEnabled={this.isDefaultUIEnabled()}
files={this.files}
setAppState={this.setAppState}
actionManager={this.actionManager}
@@ -2268,8 +2376,9 @@ class App extends React.Component<AppProps, AppState> {
this.eraserTrail,
]}
/>
- <CursorHint />
- {selectedElements.length === 1 &&
+ {this.isDefaultUIEnabled() && <CursorHint />}
+ {this.isDefaultUIEnabled() &&
+ selectedElements.length === 1 &&
this.state.openDialog?.name !==
"elementLinkSelector" &&
this.state.showHyperlinkPopup && (
@@ -2285,7 +2394,8 @@ class App extends React.Component<AppProps, AppState> {
}
/>
)}
- {this.props.aiEnabled !== false &&
+ {this.isDefaultUIEnabled() &&
+ this.props.aiEnabled !== false &&
selectedElements.length === 1 &&
isMagicFrameElement(firstSelectedElement) && (
<ElementCanvasButtons
@@ -2305,7 +2415,8 @@ class App extends React.Component<AppProps, AppState> {
/>
</ElementCanvasButtons>
)}
- {selectedElements.length === 1 &&
+ {this.isDefaultUIEnabled() &&
+ selectedElements.length === 1 &&
isIframeElement(firstSelectedElement) &&
firstSelectedElement.customData?.generationData
?.status === "done" && (
@@ -2357,7 +2468,7 @@ class App extends React.Component<AppProps, AppState> {
</ElementCanvasButtons>
)}
- {this.state.contextMenu && (
+ {this.isDefaultUIEnabled() && this.state.contextMenu && (
<ContextMenu
items={this.state.contextMenu.items}
top={this.state.contextMenu.top}
@@ -2387,6 +2498,7 @@ class App extends React.Component<AppProps, AppState> {
imageCache: this.imageCache,
isExporting: false,
renderGrid: isGridModeEnabled(this),
+ renderLinks: this.isLinksEnabled(),
canvasBackgroundColor:
this.state.viewBackgroundColor,
embedsValidationStatus:
@@ -2439,6 +2551,8 @@ class App extends React.Component<AppProps, AppState> {
this.props.renderScrollbars === true
}
editorInterface={this.editorInterface}
+ interactionEnabled={this.isInteractionEnabled()}
+ navigationEnabled={this.isNavigationEnabled()}
renderInteractiveSceneCallback={
this.renderInteractiveSceneCallback
}
@@ -2452,24 +2566,27 @@ class App extends React.Component<AppProps, AppState> {
onPointerDown={this.handleCanvasPointerDown}
onDoubleClick={this.handleCanvasDoubleClick}
/>
- {this.state.userToFollow && (
- <FollowMode
- width={this.state.width}
- height={this.state.height}
- userToFollow={this.state.userToFollow}
- onDisconnect={this.maybeUnfollowRemoteUser}
- />
- )}
+ {this.isDefaultUIEnabled() &&
+ this.state.userToFollow && (
+ <FollowMode
+ width={this.state.width}
+ height={this.state.height}
+ userToFollow={this.state.userToFollow}
+ onDisconnect={this.maybeUnfollowRemoteUser}
+ />
+ )}
{this.renderFrameNames()}
- {this.state.activeLockedId && (
- <UnlockPopup
- app={this}
- activeLockedId={this.state.activeLockedId}
- />
- )}
- {showShapeSwitchPanel && (
- <ConvertElementTypePopup app={this} />
- )}
+ {this.isDefaultUIEnabled() &&
+ this.state.activeLockedId && (
+ <UnlockPopup
+ app={this}
+ activeLockedId={this.state.activeLockedId}
+ />
+ )}
+ {this.isDefaultUIEnabled() &&
+ showShapeSwitchPanel && (
+ <ConvertElementTypePopup app={this} />
+ )}
</ExcalidrawActionManagerContext.Provider>
{this.renderEmbeddables()}
</ExcalidrawElementsContext.Provider>
@@ -2847,6 +2964,12 @@ class App extends React.Component<AppProps, AppState> {
viewModeEnabled = this.props.viewModeEnabled;
}
+ // non-interactive editor implies view mode (overrides both the action
+ // result and the host-supplied `viewModeEnabled` prop)
+ if (!this.isInteractionEnabled()) {
+ viewModeEnabled = true;
+ }
+
if (typeof this.props.zenModeEnabled !== "undefined") {
zenModeEnabled = this.props.zenModeEnabled;
}
@@ -2915,6 +3038,189 @@ class App extends React.Component<AppProps, AppState> {
event.preventDefault();
};
+ // prevent the browser's own zoom over the non-interactive editor while
+ // letting regular scroll through (trackpad pinch is delivered as
+ // ctrl+wheel)
+ private preventBrowserZoomWheel = (event: WheelEvent) => {
+ if (event[KEYS.CTRL_OR_CMD]) {
+ event.preventDefault();
+ }
+ };
+
+ // dispatches only `navigation`-flagged action shortcuts (canvas zoom &
+ // zoom-to-fit — see `ActionManager.handleKeyDown` gates); the rest of the
+ // keyboard handling stays disabled while non-interactive
+ private handleNavigationModeKeyDown = (event: KeyboardEvent) => {
+ this.actionManager.handleKeyDown(event);
+ };
+
+ private preventBrowserZoomKeyDown = (event: KeyboardEvent) => {
+ if (
+ event[KEYS.CTRL_OR_CMD] &&
+ (event.code === CODES.EQUAL ||
+ event.code === CODES.MINUS ||
+ event.code === CODES.ZERO ||
+ event.code === CODES.NUM_ADD ||
+ event.code === CODES.NUM_SUBTRACT ||
+ event.code === CODES.NUM_ZERO)
+ ) {
+ event.preventDefault();
+ }
+ };
+
+ /** Ends active input sessions before switching to a view-mode/non-interactive
+ * mode. */
+ private terminateActiveInteraction = () => {
+ // Complete any active pointer interaction before clearing the state it
+ // relies on. Among other things this tears down window-level listeners.
+ this.maybeCleanupAfterMissingPointerUp(null);
+
+ isHoldingSpace = false;
+ isPanning = false;
+ isDraggingScrollBar = false;
+ lastPointerUp = null;
+
+ gesture.pointers.clear();
+ gesture.lastCenter = null;
+ gesture.initialDistance = null;
+ gesture.initialScale = null;
+
+ clearTimeout(tappedTwiceTimer);
+ tappedTwiceTimer = 0;
+ App.resetTapTwice();
+ this.resetContextMenuTimer();
+
+ clearTimeout(IS_PLAIN_PASTE_TIMER);
+ IS_PLAIN_PASTE_TIMER = 0;
+ IS_PLAIN_PASTE = false;
+
+ if (this.bindModeHandler) {
+ clearTimeout(this.bindModeHandler);
+ this.bindModeHandler = null;
+ }
+
+ this.flowchart.clear();
+
+ // These components install their own DOM listeners rather than going
+ // through App's input handlers, so they must be explicitly unmounted.
+ editorJotaiStore.set(activeEyeDropperAtom, null);
+ editorJotaiStore.set(convertElementTypePopupAtom, null);
+
+ if (this.state.editingFrame) {
+ const frame = this.scene.getNonDeletedElement(this.state.editingFrame);
+ this.resetEditingFrame(frame && isFrameLikeElement(frame) ? frame : null);
+ }
+
+ // textWysiwyg's submit path uses flushSync. Defer until after the current
+ // componentDidUpdate lifecycle, then submit whichever text-editing session
+ // is active if editing is still disabled.
+ queueMicrotask(() => {
+ if (!this.isInteractionEnabled() || this.state.viewModeEnabled) {
+ this.textWysiwygSubmitHandler?.();
+ }
+ });
+
+ this.setState({
+ contextMenu: null,
+ openMenu: null,
+ openPopup: null,
+ cursorButton: "up",
+ bindMode: "orbit",
+ activeEmbeddable: null,
+ activeLockedId: null,
+ selectedElementsAreBeingDragged: false,
+ selectionElement: null,
+ resizingElement: null,
+ isResizing: false,
+ isRotating: false,
+ isCropping: false,
+ croppingElementId: null,
+ suggestedBinding: null,
+ frameToHighlight: null,
+ elementsToHighlight: null,
+ snapLines: [],
+ showHyperlinkPopup: false,
+ });
+ this.deselectElements();
+ if (!this.isInteractionEnabled()) {
+ this.setState({ originSnapOffset: null });
+ resetCursor(this.interactiveCanvas);
+ }
+ };
+
+ private handleInteractionStateChange = (
+ prevProps: AppProps,
+ prevState: AppState,
+ ) => {
+ const wasInteractionEnabled = this.isInteractionEnabled(prevProps);
+ const interactionEnabledChanged =
+ wasInteractionEnabled !== this.isInteractionEnabled();
+ const viewModePropChanged =
+ prevProps.viewModeEnabled !== this.props.viewModeEnabled;
+
+ // Preserve internally toggled view mode while interactive and
+ // uncontrolled. Synchronize it when its prop changes, when interaction is
+ // re-enabled, or when non-interactive mode needs to force it on.
+ let nextViewModeEnabled = this.state.viewModeEnabled;
+ if (!this.isInteractionEnabled()) {
+ nextViewModeEnabled = true;
+ } else if (viewModePropChanged || interactionEnabledChanged) {
+ nextViewModeEnabled = !!this.props.viewModeEnabled;
+ }
+ if (nextViewModeEnabled !== this.state.viewModeEnabled) {
+ this.setState({ viewModeEnabled: nextViewModeEnabled });
+ }
+
+ const editingWasEnabled =
+ wasInteractionEnabled && !prevState.viewModeEnabled;
+ const editingEnabled =
+ this.isInteractionEnabled() && !this.state.viewModeEnabled;
+ const becameNonInteractive =
+ interactionEnabledChanged && !this.isInteractionEnabled();
+
+ if (becameNonInteractive || (editingWasEnabled && !editingEnabled)) {
+ this.terminateActiveInteraction();
+ }
+
+ if (interactionEnabledChanged) {
+ // listener tiers depend on `props.interaction` even when
+ // `state.viewModeEnabled` ends up unchanged
+ this.addEventListeners();
+ }
+
+ // NOTE link icons appearing/disappearing is handled by the re-render
+ // itself (`renderConfig.renderLinks`)
+ if (this.isLinksEnabled(prevProps) !== this.isLinksEnabled()) {
+ if (!this.isLinksEnabled()) {
+ this.hitLinkElement = undefined;
+ hideHyperlinkToolip();
+ resetCursor(this.interactiveCanvas);
+ }
+ }
+
+ if (this.isEmbedsEnabled(prevProps) !== this.isEmbedsEnabled()) {
+ if (!this.isEmbedsEnabled()) {
+ this.setState({ activeEmbeddable: null });
+ }
+ }
+
+ if (
+ this.isBrowserZoomEnabled(prevProps) !== this.isBrowserZoomEnabled() ||
+ this.isNavigationEnabled(prevProps) !== this.isNavigationEnabled()
+ ) {
+ this.addEventListeners();
+ }
+
+ if (prevState.viewModeEnabled !== this.state.viewModeEnabled) {
+ if (this.isInteractionEnabled()) {
+ this.addEventListeners();
+ }
+ if (!this.state.viewModeEnabled) {
+ this.deselectElements();
+ }
+ }
+ };
+
private resetHistory = () => {
this.history.clear();
};
@@ -3349,6 +3655,138 @@ class App extends React.Component<AppProps, AppState> {
// remove first as we can add event listeners multiple times
this.removeEventListeners();
+ // -------------------------------------------------------------------------
+ // listeners active even when the editor is non-interactive
+ // -------------------------------------------------------------------------
+
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(window, EVENT.MESSAGE, this.onWindowMessage, false),
+ addEventListener(document, EVENT.POINTER_UP, this.removePointer, {
+ passive: false,
+ }), // #3553
+ // rerender text elements on font load to fix #637 && #1553
+ addEventListener(
+ document.fonts,
+ "loadingdone",
+ (event) => {
+ const fontFaces = (event as FontFaceSetLoadEvent).fontfaces;
+ this.fonts.onLoaded(fontFaces);
+ },
+ { passive: false },
+ ),
+ addEventListener(
+ window,
+ EVENT.FOCUS,
+ () => {
+ this.maybeCleanupAfterMissingPointerUp(null);
+ // browsers (chrome?) tend to free up memory a lot, which results
+ // in canvas context being cleared. Thus re-render on focus.
+ this.triggerRender(true);
+ },
+ { passive: false },
+ ),
+ );
+
+ if (!this.isInteractionEnabled()) {
+ // NOTE by not attaching the wheel/touch/gesture listeners below (which
+ // preventDefault), the browser default behavior — such as scrolling the
+ // page over the editor — is retained while non-interactive
+ if (this.isNavigationEnabled()) {
+ // wheel pan/zoom & pinch — the editor consumes these again, so the
+ // page no longer scrolls over the editor
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.WHEEL,
+ this.handleWheel,
+ { passive: false },
+ ),
+ // navigation action shortcuts (canvas zoom & zoom-to-fit)
+ addEventListener(
+ this.props.handleKeyboardGlobally
+ ? document
+ : this.excalidrawContainerRef.current,
+ EVENT.KEYDOWN,
+ this.handleNavigationModeKeyDown as EventListener,
+ false,
+ ),
+ // wheel zoom is anchored on `lastViewportPosition`
+ addEventListener(
+ document,
+ EVENT.POINTER_MOVE,
+ this.updateCurrentCursorPosition,
+ { passive: false },
+ ),
+ // Safari-only desktop pinch
+ addEventListener(
+ document,
+ EVENT.GESTURE_START,
+ this.onGestureStart as any,
+ false,
+ ),
+ addEventListener(
+ document,
+ EVENT.GESTURE_CHANGE,
+ this.onGestureChange as any,
+ false,
+ ),
+ addEventListener(
+ document,
+ EVENT.GESTURE_END,
+ this.onGestureEnd as any,
+ false,
+ ),
+ );
+ }
+ if (!this.isBrowserZoomEnabled()) {
+ // the browser's own zoom is prevented over the editor by default,
+ // mirroring the interactive editor (opt out via
+ // `interaction: { enabled: { browserZoom: true } }`)
+ if (!this.isNavigationEnabled()) {
+ // with navigation enabled, wheel & pinch are consumed by the
+ // editor's own handlers above instead
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.WHEEL,
+ this.preventBrowserZoomWheel,
+ { passive: false },
+ ),
+ // Safari-only desktop pinch
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.GESTURE_START as any,
+ this.disableEvent,
+ false,
+ ),
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.GESTURE_CHANGE as any,
+ this.disableEvent,
+ false,
+ ),
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.GESTURE_END as any,
+ this.disableEvent,
+ false,
+ ),
+ );
+ }
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(
+ this.props.handleKeyboardGlobally
+ ? document
+ : this.excalidrawContainerRef.current,
+ EVENT.KEYDOWN,
+ this.preventBrowserZoomKeyDown as EventListener,
+ false,
+ ),
+ );
+ }
+ return;
+ }
+
// -------------------------------------------------------------------------
// view+edit mode listeners
// -------------------------------------------------------------------------
@@ -3366,10 +3804,6 @@ class App extends React.Component<AppProps, AppState> {
this.handleWheel,
{ passive: false },
),
- addEventListener(window, EVENT.MESSAGE, this.onWindowMessage, false),
- addEventListener(document, EVENT.POINTER_UP, this.removePointer, {
- passive: false,
- }), // #3553
addEventListener(document, EVENT.COPY, this.onCopy, { passive: false }),
addEventListener(document, EVENT.KEYUP, this.onKeyUp, { passive: true }),
addEventListener(
@@ -3378,16 +3812,6 @@ class App extends React.Component<AppProps, AppState> {
this.updateCurrentCursorPosition,
{ passive: false },
),
- // rerender text elements on font load to fix #637 && #1553
- addEventListener(
- document.fonts,
- "loadingdone",
- (event) => {
- const fontFaces = (event as FontFaceSetLoadEvent).fontfaces;
- this.fonts.onLoaded(fontFaces);
- },
- { passive: false },
- ),
// Safari-only desktop pinch zoom
addEventListener(
document,
@@ -3407,17 +3831,6 @@ class App extends React.Component<AppProps, AppState> {
this.onGestureEnd as any,
false,
),
- addEventListener(
- window,
- EVENT.FOCUS,
- () => {
- this.maybeCleanupAfterMissingPointerUp(null);
- // browsers (chrome?) tend to free up memory a lot, which results
- // in canvas context being cleared. Thus re-render on focus.
- this.triggerRender(true);
- },
- { passive: false },
- ),
);
if (this.state.viewModeEnabled) {
@@ -3482,6 +3895,8 @@ class App extends React.Component<AppProps, AppState> {
this.props.onInitialize?.(this.api);
}
+ this.handleInteractionStateChange(prevProps, prevState);
+
this.appStateObserver.flush(prevState);
this.updateEmbeddables();
@@ -3571,15 +3986,6 @@ class App extends React.Component<AppProps, AppState> {
this.eraserTrail.endPath();
}
- if (prevProps.viewModeEnabled !== this.props.viewModeEnabled) {
- this.setState({ viewModeEnabled: !!this.props.viewModeEnabled });
- }
-
- if (prevState.viewModeEnabled !== this.state.viewModeEnabled) {
- this.addEventListeners();
- this.deselectElements();
- }
-
// cleanup
if (
(prevState.openDialog?.name === "elementLinkSelector" ||
@@ -3675,6 +4081,9 @@ class App extends React.Component<AppProps, AppState> {
// Copy/paste
private onCut = withBatchedUpdates((event: ClipboardEvent) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
document.activeElement,
);
@@ -3687,6 +4096,9 @@ class App extends React.Component<AppProps, AppState> {
});
private onCopy = withBatchedUpdates((event: ClipboardEvent) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
document.activeElement,
);
@@ -3704,6 +4116,10 @@ class App extends React.Component<AppProps, AppState> {
}
private onTouchStart = (event: TouchEvent) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
+
// fix for Apple Pencil Scribble (do not prevent for other devices)
if (isIOS) {
event.preventDefault();
@@ -3765,6 +4181,9 @@ class App extends React.Component<AppProps, AppState> {
};
private onTouchEnd = (event: TouchEvent) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
this.resetContextMenuTimer();
if (event.touches.length > 0) {
this.setState({
@@ -3949,6 +4368,10 @@ class App extends React.Component<AppProps, AppState> {
public pasteFromClipboard = withBatchedUpdates(
async (event: ClipboardEvent) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
+
const isPlainPaste = !!IS_PLAIN_PASTE;
// #686
@@ -5010,6 +5433,10 @@ class App extends React.Component<AppProps, AppState> {
// Input handling
private onKeyDown = withBatchedUpdates(
(event: React.KeyboardEvent | KeyboardEvent) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
+
// normalize `event.key` when CapsLock is pressed #2372
if (
@@ -5494,6 +5921,9 @@ class App extends React.Component<AppProps, AppState> {
);
private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
if (event.key === KEYS.SPACE) {
if (
(this.state.viewModeEnabled &&
@@ -5776,6 +6206,9 @@ class App extends React.Component<AppProps, AppState> {
// fires only on Safari
private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
+ if (!this.isNavigationEnabled()) {
+ return;
+ }
event.preventDefault();
// we only want to deselect on touch screens because user may have selected
@@ -5791,6 +6224,9 @@ class App extends React.Component<AppProps, AppState> {
// fires only on Safari
private onGestureChange = withBatchedUpdates((event: GestureEvent) => {
+ if (!this.isNavigationEnabled()) {
+ return;
+ }
event.preventDefault();
// onGestureChange only has zoom factor but not the center.
@@ -5829,6 +6265,9 @@ class App extends React.Component<AppProps, AppState> {
// fires only on Safari
private onGestureEnd = withBatchedUpdates((event: GestureEvent) => {
+ if (!this.isNavigationEnabled()) {
+ return;
+ }
event.preventDefault();
// reselect elements only on touch screens (see onGestureStart)
if (this.isTouchScreenMultiTouchGesture()) {
@@ -5881,7 +6320,7 @@ class App extends React.Component<AppProps, AppState> {
]);
};
- textWysiwyg({
+ this.textWysiwygSubmitHandler = textWysiwyg({
canvas: this.canvas,
getViewportCoords: (x, y) => {
const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
@@ -5903,6 +6342,8 @@ class App extends React.Component<AppProps, AppState> {
}
}),
onSubmit: withBatchedUpdates(({ viaKeyboard, nextOriginalText }) => {
+ this.textWysiwygSubmitHandler = null;
+
const isDeleted = !nextOriginalText.trim();
updateElement(nextOriginalText, isDeleted);
@@ -6607,6 +7048,7 @@ class App extends React.Component<AppProps, AppState> {
>,
) => {
if (
+ !this.isInteractionEnabled() ||
this.state.editingTextElement ||
!this.shouldHandleBrowserCanvasDoubleClick(event.type)
) {
@@ -6825,6 +7267,9 @@ class App extends React.Component<AppProps, AppState> {
};
private handleCanvasClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
if (event.button !== POINTER_BUTTON.MAIN) {
this.lastCompletedCanvasClicks = [];
return;
@@ -6943,34 +7388,159 @@ class App extends React.Component<AppProps, AppState> {
};
/**
- * finds candidate frame under cursor (when dragging frame children/elements
- * inside frames)
+ * Applies (or clears) the element-link hover affordances — pointer cursor
+ * and tooltip — based on the current `hitLinkElement`. Returns whether a
+ * link is being hovered.
*/
- private getTopLayerFrameAtSceneCoords = (
- /**
- * should be already grid aligned (basically should be what the call site
- * sets the element's coords to, if applicable)
- */
- sceneCoords: {
- x: number;
- y: number;
- },
- opts?: {
- /** to exclude selected elements when dragging, etc. */
- excludeElementIds?: AppState["selectedElementIds"];
- currentFrameId?: ExcalidrawElement["frameId"];
- },
- ) => {
- const elementsMap = this.scene.getNonDeletedElementsMap();
- const framesUnderCursor = this.scene
- .getNonDeletedFramesLikes()
- .filter(
- (frame) =>
- !frame.locked && isCursorInFrame(sceneCoords, frame, elementsMap),
- );
-
- if (!framesUnderCursor.length) {
- return null;
+ private applyElementLinkHoverAffordance = (): boolean => {
+ if (
+ this.hitLinkElement &&
+ !this.state.selectedElementIds[this.hitLinkElement.id]
+ ) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+
+ showHyperlinkTooltip(
+ this.hitLinkElement,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ return true;
+ }
+ hideHyperlinkToolip();
+ return false;
+ };
+
+ /**
+ * On touchscreens (where no hover precedes the tap) re-derives
+ * `hitLinkElement`, then opens the hit element link, if any.
+ * Returns whether a link click was handled.
+ */
+ private maybeHandleElementLinkClick = (
+ event: React.PointerEvent<HTMLCanvasElement>,
+ scenePointer: { x: number; y: number },
+ ): boolean => {
+ if (this.editorInterface.isTouchScreen) {
+ const hitElement = this.getElementAtPosition(
+ scenePointer.x,
+ scenePointer.y,
+ {
+ includeLockedElements: true,
+ },
+ );
+ this.hitLinkElement = this.getElementLinkAtPosition(
+ scenePointer,
+ hitElement,
+ );
+ }
+
+ if (
+ this.hitLinkElement &&
+ this.lastPointerDownEvent &&
+ !this.state.selectedElementIds[this.hitLinkElement.id]
+ ) {
+ this.handleElementLinkClick(event);
+ return true;
+ }
+ return false;
+ };
+
+ /**
+ * Restricted pointer handling for the non-interactive editor with links
+ * and/or embeds allowed (`interaction.enabled.links` / `.embeds` /
+ * `.interactiveContent`) — runs only the element-link & embed concerns
+ * (shared with the full pointer handlers above) so they behave like in
+ * view mode without the rest of the canvas pointer machinery.
+ */
+ private handleInteractiveContentPointerMove = (
+ event: React.PointerEvent<HTMLCanvasElement>,
+ ) => {
+ const scenePointer = viewportCoordsToSceneCoords(event, this.state);
+ const hitElementMightBeLocked = this.getElementAtPosition(
+ scenePointer.x,
+ scenePointer.y,
+ { includeLockedElements: true },
+ );
+
+ if (this.isEmbedsEnabled()) {
+ const hitElement = hitElementMightBeLocked?.locked
+ ? null
+ : hitElementMightBeLocked;
+ if (
+ this.handleIframeLikeElementHover({
+ hitElement,
+ scenePointer,
+ moveEvent: event,
+ })
+ ) {
+ return;
+ }
+ }
+
+ this.hitLinkElement = this.isLinksEnabled()
+ ? this.getElementLinkAtPosition(scenePointer, hitElementMightBeLocked)
+ : undefined;
+ if (!this.applyElementLinkHoverAffordance()) {
+ if (this.isNavigationEnabled()) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
+ } else {
+ resetCursor(this.interactiveCanvas);
+ }
+ }
+ };
+
+ private handleInteractiveContentPointerUp = (
+ event: React.PointerEvent<HTMLCanvasElement>,
+ ) => {
+ this.lastPointerUpEvent = event;
+
+ if (this.isEmbedsEnabled() && this.handleIframeLikeCenterClick()) {
+ return;
+ }
+
+ const scenePointer = viewportCoordsToSceneCoords(event, this.state);
+ if (
+ this.isLinksEnabled() &&
+ this.maybeHandleElementLinkClick(event, scenePointer)
+ ) {
+ return;
+ }
+
+ // clicking outside an active embed deactivates it (view-mode style;
+ // clicks inside it are consumed by the embed itself)
+ if (this.state.activeEmbeddable?.state === "active") {
+ this.setState({ activeEmbeddable: null });
+ }
+ };
+
+ /**
+ * finds candidate frame under cursor (when dragging frame children/elements
+ * inside frames)
+ */
+ private getTopLayerFrameAtSceneCoords = (
+ /**
+ * should be already grid aligned (basically should be what the call site
+ * sets the element's coords to, if applicable)
+ */
+ sceneCoords: {
+ x: number;
+ y: number;
+ },
+ opts?: {
+ /** to exclude selected elements when dragging, etc. */
+ excludeElementIds?: AppState["selectedElementIds"];
+ currentFrameId?: ExcalidrawElement["frameId"];
+ },
+ ) => {
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+ const framesUnderCursor = this.scene
+ .getNonDeletedFramesLikes()
+ .filter(
+ (frame) =>
+ !frame.locked && isCursorInFrame(sceneCoords, frame, elementsMap),
+ );
+
+ if (!framesUnderCursor.length) {
+ return null;
}
const topLayerFrame = framesUnderCursor.at(-1)!;
@@ -7102,6 +7672,17 @@ class App extends React.Component<AppProps, AppState> {
private handleCanvasPointerMove = (
event: React.PointerEvent<HTMLCanvasElement>,
) => {
+ if (!this.isInteractionEnabled()) {
+ if (this.isNavigationEnabled()) {
+ // two-finger pinch zoom/pan (single-pointer panning is handled by
+ // the pan session set up on pointerdown)
+ this.updateMultiTouchGesture(event);
+ }
+ if ((this.isLinksEnabled() || this.isEmbedsEnabled()) && !isPanning) {
+ this.handleInteractiveContentPointerMove(event);
+ }
+ return;
+ }
this.savePointer(event.clientX, event.clientY, this.state.cursorButton);
this.lastPointerMoveEvent = event.nativeEvent;
const scenePointer = viewportCoordsToSceneCoords(event, this.state);
@@ -7111,82 +7692,7 @@ class App extends React.Component<AppProps, AppState> {
y: scenePointerY,
};
- if (gesture.pointers.has(event.pointerId)) {
- gesture.pointers.set(event.pointerId, {
- x: event.clientX,
- y: event.clientY,
- });
- }
-
- const initialScale = gesture.initialScale;
- if (
- gesture.pointers.size === 2 &&
- gesture.lastCenter &&
- initialScale &&
- gesture.initialDistance
- ) {
- const center = getCenter(gesture.pointers);
- const deltaX = center.x - gesture.lastCenter.x;
- const deltaY = center.y - gesture.lastCenter.y;
- gesture.lastCenter = center;
-
- const distance = getDistance(Array.from(gesture.pointers.values()));
- const scaleFactor =
- this.state.activeTool.type === "freedraw" && this.state.penMode
- ? 1
- : distance / gesture.initialDistance;
-
- const nextZoom = scaleFactor
- ? getNormalizedZoom(initialScale * scaleFactor)
- : this.state.zoom.value;
-
- this.setState((state) => {
- // constrain the zoom and pan components separately: the zoom step is
- // hard-clamped against the scroll lock (sliding the focal point along
- // the lock edge), while any pre-existing overscroll plus this frame's
- // pan delta are re-applied on top and rubberband-clamped by
- // `translateCanvas` — so pinch-zooming and overscroll-panning compose
- // instead of the zoom yanking the viewport back inside the box.
- const rest = constrainScrollState(state); // hard clamp (no give)
- // pre-existing overscroll, in screen px (zoom-independent)
- const overscrollX = (state.scrollX - rest.scrollX) * state.zoom.value;
- const overscrollY = (state.scrollY - rest.scrollY) * state.zoom.value;
-
- const zoomState = getStateForZoom(
- {
- viewportX: center.x,
- viewportY: center.y,
- nextZoom,
- },
- state,
- );
- const zoomedViewport = constrainScrollState({ ...state, ...zoomState });
- const zoomValue = zoomedViewport.zoom.value;
-
- this.translateCanvas(
- {
- zoom: zoomedViewport.zoom,
- // 2x multiplier is just a magic number that makes this work correctly
- // on touchscreen devices (note: if we get report that panning is slower/faster
- // than actual movement, consider swapping with devicePixelRatio)
- scrollX:
- zoomedViewport.scrollX + (overscrollX + 2 * deltaX) / zoomValue,
- scrollY:
- zoomedViewport.scrollY + (overscrollY + 2 * deltaY) / zoomValue,
- shouldCacheIgnoreZoom: true,
- },
- { zoomPreConstrained: true },
- );
-
- return null;
- });
- this.resetShouldCacheIgnoreZoomDebounced();
- } else {
- gesture.lastCenter =
- gesture.initialDistance =
- gesture.initialScale =
- null;
- }
+ this.updateMultiTouchGesture(event);
if (
isHoldingSpace ||
@@ -7619,19 +8125,7 @@ class App extends React.Component<AppProps, AppState> {
);
}
- if (
- this.hitLinkElement &&
- !this.state.selectedElementIds[this.hitLinkElement.id]
- ) {
- setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
-
- showHyperlinkTooltip(
- this.hitLinkElement,
- this.state,
- this.scene.getNonDeletedElementsMap(),
- );
- } else {
- hideHyperlinkToolip();
+ if (!this.applyElementLinkHoverAffordance()) {
if (isLaserTool) {
return;
}
@@ -7746,6 +8240,9 @@ class App extends React.Component<AppProps, AppState> {
// set touch moving for mobile context menu
private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
invalidateContextMenu = true;
};
@@ -7887,6 +8384,23 @@ class App extends React.Component<AppProps, AppState> {
private handleCanvasPointerDown = (
event: React.PointerEvent<HTMLElement>,
) => {
+ if (!this.isInteractionEnabled()) {
+ if (this.isLinksEnabled() || this.isEmbedsEnabled()) {
+ // needed by handleElementLinkClick & handleIframeLikeCenterClick
+ // (drag-distance & hit checks)
+ this.lastPointerDownEvent = event;
+ }
+ if (this.isNavigationEnabled()) {
+ this.updateGestureOnPointerDown(event);
+ if (!isPanning) {
+ // pans on drag same as view mode (the pan session manages its own
+ // window listeners & teardown)
+ this.handleCanvasPanUsingWheelOrSpaceDrag(event);
+ }
+ }
+ return;
+ }
+
const selectedElements = this.scene.getSelectedElements(this.state);
// If Ctrl is not held, ensure isBindingEnabled reflects the user preference.
@@ -8348,6 +8862,12 @@ class App extends React.Component<AppProps, AppState> {
private handleCanvasPointerUp = (
event: React.PointerEvent<HTMLCanvasElement>,
) => {
+ if (!this.isInteractionEnabled()) {
+ if (this.isLinksEnabled() || this.isEmbedsEnabled()) {
+ this.handleInteractiveContentPointerUp(event);
+ }
+ return;
+ }
if (getFeatureFlag("COMPLEX_BINDINGS")) {
this.resetDelayedBindMode();
}
@@ -8380,26 +8900,10 @@ class App extends React.Component<AppProps, AppState> {
return;
}
- if (this.editorInterface.isTouchScreen) {
- const hitElement = this.getElementAtPosition(
- scenePointer.x,
- scenePointer.y,
- {
- includeLockedElements: true,
- },
- );
- this.hitLinkElement = this.getElementLinkAtPosition(
- scenePointer,
- hitElement,
- );
- }
-
if (
- this.hitLinkElement &&
- !this.state.selectedElementIds[this.hitLinkElement.id]
+ !this.maybeHandleElementLinkClick(event, scenePointer) &&
+ this.state.viewModeEnabled
) {
- this.handleElementLinkClick(event);
- } else if (this.state.viewModeEnabled) {
this.setState({
activeEmbeddable: null,
selectedElementIds: {},
@@ -8581,6 +9085,91 @@ class App extends React.Component<AppProps, AppState> {
}
}
+ /**
+ * Tracks the pointer within the ongoing multi-touch gesture and applies
+ * the two-finger pinch zoom/pan, if any.
+ */
+ private updateMultiTouchGesture = (
+ event: React.PointerEvent<HTMLCanvasElement>,
+ ) => {
+ if (gesture.pointers.has(event.pointerId)) {
+ gesture.pointers.set(event.pointerId, {
+ x: event.clientX,
+ y: event.clientY,
+ });
+ }
+
+ const initialScale = gesture.initialScale;
+ if (
+ gesture.pointers.size === 2 &&
+ gesture.lastCenter &&
+ initialScale &&
+ gesture.initialDistance
+ ) {
+ const center = getCenter(gesture.pointers);
+ const deltaX = center.x - gesture.lastCenter.x;
+ const deltaY = center.y - gesture.lastCenter.y;
+ gesture.lastCenter = center;
+
+ const distance = getDistance(Array.from(gesture.pointers.values()));
+ const scaleFactor =
+ this.state.activeTool.type === "freedraw" && this.state.penMode
+ ? 1
+ : distance / gesture.initialDistance;
+
+ const nextZoom = scaleFactor
+ ? getNormalizedZoom(initialScale * scaleFactor)
+ : this.state.zoom.value;
+
+ this.setState((state) => {
+ // constrain the zoom and pan components separately: the zoom step is
+ // hard-clamped against the scroll lock (sliding the focal point along
+ // the lock edge), while any pre-existing overscroll plus this frame's
+ // pan delta are re-applied on top and rubberband-clamped by
+ // `translateCanvas` — so pinch-zooming and overscroll-panning compose
+ // instead of the zoom yanking the viewport back inside the box.
+ const rest = constrainScrollState(state); // hard clamp (no give)
+ // pre-existing overscroll, in screen px (zoom-independent)
+ const overscrollX = (state.scrollX - rest.scrollX) * state.zoom.value;
+ const overscrollY = (state.scrollY - rest.scrollY) * state.zoom.value;
+
+ const zoomState = getStateForZoom(
+ {
+ viewportX: center.x,
+ viewportY: center.y,
+ nextZoom,
+ },
+ state,
+ );
+ const zoomedViewport = constrainScrollState({ ...state, ...zoomState });
+ const zoomValue = zoomedViewport.zoom.value;
+
+ this.translateCanvas(
+ {
+ zoom: zoomedViewport.zoom,
+ // 2x multiplier is just a magic number that makes this work correctly
+ // on touchscreen devices (note: if we get report that panning is slower/faster
+ // than actual movement, consider swapping with devicePixelRatio)
+ scrollX:
+ zoomedViewport.scrollX + (overscrollX + 2 * deltaX) / zoomValue,
+ scrollY:
+ zoomedViewport.scrollY + (overscrollY + 2 * deltaY) / zoomValue,
+ shouldCacheIgnoreZoom: true,
+ },
+ { zoomPreConstrained: true },
+ );
+
+ return null;
+ });
+ this.resetShouldCacheIgnoreZoomDebounced();
+ } else {
+ gesture.lastCenter =
+ gesture.initialDistance =
+ gesture.initialScale =
+ null;
+ }
+ };
+
private initialPointerDownState(
event: React.PointerEvent<HTMLElement>,
): PointerDownState {
@@ -12300,6 +12889,10 @@ class App extends React.Component<AppProps, AppState> {
};
private handleAppOnDrop = async (event: React.DragEvent<HTMLDivElement>) => {
+ // NOTE no preventDefault so the host page can handle the drop itself
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
event,
this.state,
@@ -12507,6 +13100,10 @@ class App extends React.Component<AppProps, AppState> {
private handleCanvasContextMenu = (
event: React.MouseEvent<HTMLElement | HTMLCanvasElement>,
) => {
+ // NOTE no preventDefault so the browser default context menu applies
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
event.preventDefault();
if (
@@ -13029,6 +13626,10 @@ class App extends React.Component<AppProps, AppState> {
(
event: WheelEvent | React.WheelEvent<HTMLDivElement | HTMLCanvasElement>,
) => {
+ // NOTE no preventDefault so the page can scroll over the editor
+ if (!this.isNavigationEnabled()) {
+ return;
+ }
if (
!(
event.target instanceof HTMLCanvasElement ||
@@ -13149,6 +13750,11 @@ class App extends React.Component<AppProps, AppState> {
}
private savePointer = (x: number, y: number, button: "up" | "down") => {
+ // don't broadcast pointer updates (props.onPointerUpdate) when
+ // non-interactive
+ if (!this.isInteractionEnabled()) {
+ return;
+ }
if (!x || !y) {
return;
}
diff --git a/packages/excalidraw/components/LayerUI.tsx b/packages/excalidraw/components/LayerUI.tsx
index d9ad4abd91..624133226c 100644
--- a/packages/excalidraw/components/LayerUI.tsx
+++ b/packages/excalidraw/components/LayerUI.tsx
@@ -91,6 +91,7 @@ interface LayerUIProps {
renderWelcomeScreen: boolean;
children?: React.ReactNode;
app: AppClassProperties;
+ defaultUIEnabled: boolean;
isCollaborating: boolean;
generateLinkForSelection?: AppProps["generateLinkForSelection"];
}
@@ -149,6 +150,7 @@ const LayerUI = ({
renderWelcomeScreen,
children,
app,
+ defaultUIEnabled,
isCollaborating,
generateLinkForSelection,
}: LayerUIProps) => {
@@ -220,9 +222,10 @@ const LayerUI = ({
const renderCanvasActions = () => (
<div style={{ position: "relative" }}>
- {/* wrapping to Fragment stops React from occasionally complaining
- about identical Keys */}
- <tunnels.MainMenuTunnel.Out />
+ <div className="excalidraw-ui-top-left">
+ {renderTopLeftUI?.(false, appState)}
+ <tunnels.MainMenuTunnel.Out />
+ </div>
{renderWelcomeScreen && <tunnels.WelcomeScreenMenuHintTunnel.Out />}
</div>
);
@@ -280,12 +283,11 @@ const LayerUI = ({
};
const renderFixedSideContainer = () => {
- const shouldRenderSelectedShapeActions = showSelectedShapeActions(
- appState,
- elements,
- );
+ const shouldRenderSelectedShapeActions =
+ defaultUIEnabled && showSelectedShapeActions(appState, elements);
const shouldShowStats =
+ defaultUIEnabled &&
appState.stats.open &&
!appState.zenModeEnabled &&
!appState.viewModeEnabled &&
@@ -299,20 +301,24 @@ const LayerUI = ({
className={clsx("App-menu_top__left")}
>
{renderCanvasActions()}
- <div
- className={clsx("selected-shape-actions-container", {
- "selected-shape-actions-container--compact":
- isCompactStylesPanel,
- })}
- >
- {shouldRenderSelectedShapeActions && renderSelectedShapeActions()}
- </div>
+ {defaultUIEnabled && (
+ <div
+ className={clsx("selected-shape-actions-container", {
+ "selected-shape-actions-container--compact":
+ isCompactStylesPanel,
+ })}
+ >
+ {shouldRenderSelectedShapeActions &&
+ renderSelectedShapeActions()}
+ </div>
+ )}
{/* in compact UI the pen mode button lives outside the toolbar, as
a separate floating button below the compact actions menu
(same as we render it on mobile); shown alongside the compact
actions island, i.e. when a drawing tool or elements are
selected */}
- {isCompactStylesPanel &&
+ {defaultUIEnabled &&
+ isCompactStylesPanel &&
!appState.viewModeEnabled &&
shouldRenderSelectedShapeActions && (
<PenModeButton
@@ -324,7 +330,8 @@ const LayerUI = ({
/>
)}
</Stack.Col>
- {!appState.viewModeEnabled &&
+ {defaultUIEnabled &&
+ !appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector" && (
<Section heading="shapes" className="shapes-section">
{(heading: React.ReactNode) => (
@@ -383,7 +390,7 @@ const LayerUI = ({
},
)}
>
- {appState.collaborators.size > 0 && (
+ {defaultUIEnabled && appState.collaborators.size > 0 && (
<UserList
collaborators={appState.collaborators}
userToFollow={appState.userToFollow?.socketId || null}
@@ -416,6 +423,10 @@ const LayerUI = ({
};
const renderSidebars = () => {
+ if (!defaultUIEnabled) {
+ return null;
+ }
+
return (
<DefaultSidebar
__fallback
@@ -440,81 +451,95 @@ const LayerUI = ({
{/* make sure we render host app components first so that we can detect
them first on initial render to optimize layout shift */}
{children}
- {/* render component fallbacks. Can be rendered anywhere as they'll be
- tunneled away. We only render tunneled components that actually
- have defaults when host do not render anything. */}
- <DefaultMainMenu UIOptions={UIOptions} />
- <DefaultSidebar.Trigger
- __fallback
- icon={sidebarRightIcon}
- title={capitalizeString(t("toolBar.library"))}
- onToggle={(open) => {
- if (open) {
- trackEvent(
- "sidebar",
- `${DEFAULT_SIDEBAR.name} (open)`,
- `button (${
- editorInterface.formFactor === "phone" ? "mobile" : "desktop"
- })`,
- );
- }
- }}
- tab={DEFAULT_SIDEBAR.defaultTab}
- />
+ {/* Fallback entry points are the default UI. Host components above keep
+ rendering into the outlets below even when defaults are disabled. */}
+ {defaultUIEnabled && (
+ <>
+ <DefaultMainMenu UIOptions={UIOptions} />
+ <DefaultSidebar.Trigger
+ __fallback
+ icon={sidebarRightIcon}
+ title={capitalizeString(t("toolBar.library"))}
+ onToggle={(open) => {
+ if (open) {
+ trackEvent(
+ "sidebar",
+ `${DEFAULT_SIDEBAR.name} (open)`,
+ `button (${
+ editorInterface.formFactor === "phone"
+ ? "mobile"
+ : "desktop"
+ })`,
+ );
+ }
+ }}
+ tab={DEFAULT_SIDEBAR.defaultTab}
+ />
+ </>
+ )}
+ {/* Keep supporting surfaces available to host-supplied UI, including
+ MainMenu.DefaultItems. */}
<DefaultOverwriteConfirmDialog />
{appState.openDialog?.name === "ttd" && <TTDDialog __fallback />}
{/* ------------------------------------------------------------------ */}
- {appState.isLoading && <LoadingMessage delay={250} />}
- {appState.errorMessage && (
+ {defaultUIEnabled && appState.isLoading && <LoadingMessage delay={250} />}
+ {defaultUIEnabled && appState.errorMessage && (
<ErrorDialog onClose={() => setAppState({ errorMessage: null })}>
{appState.errorMessage}
</ErrorDialog>
)}
- {eyeDropperState && editorInterface.formFactor !== "phone" && (
- <EyeDropper
- colorPickerType={eyeDropperState.colorPickerType}
- onCancel={() => {
- setEyeDropperState(null);
- }}
- onChange={(colorPickerType, color, selectedElements, { altKey }) => {
- if (
- colorPickerType !== "elementBackground" &&
- colorPickerType !== "elementStroke"
- ) {
- return;
- }
+ {defaultUIEnabled &&
+ eyeDropperState &&
+ editorInterface.formFactor !== "phone" && (
+ <EyeDropper
+ colorPickerType={eyeDropperState.colorPickerType}
+ onCancel={() => {
+ setEyeDropperState(null);
+ }}
+ onChange={(
+ colorPickerType,
+ color,
+ selectedElements,
+ { altKey },
+ ) => {
+ if (
+ colorPickerType !== "elementBackground" &&
+ colorPickerType !== "elementStroke"
+ ) {
+ return;
+ }
- if (selectedElements.length) {
- for (const element of selectedElements) {
- mutateElement(element, arrayToMap(elements), {
- [altKey && eyeDropperState.swapPreviewOnAlt
- ? colorPickerType === "elementBackground"
- ? "strokeColor"
- : "backgroundColor"
- : colorPickerType === "elementBackground"
- ? "backgroundColor"
- : "strokeColor"]: color,
+ if (selectedElements.length) {
+ for (const element of selectedElements) {
+ mutateElement(element, arrayToMap(elements), {
+ [altKey && eyeDropperState.swapPreviewOnAlt
+ ? colorPickerType === "elementBackground"
+ ? "strokeColor"
+ : "backgroundColor"
+ : colorPickerType === "elementBackground"
+ ? "backgroundColor"
+ : "strokeColor"]: color,
+ });
+ ShapeCache.delete(element);
+ }
+ app.scene.triggerUpdate();
+ } else if (colorPickerType === "elementBackground") {
+ setAppState({
+ currentItemBackgroundColor: color,
});
- ShapeCache.delete(element);
+ } else {
+ setAppState({ currentItemStrokeColor: color });
}
- app.scene.triggerUpdate();
- } else if (colorPickerType === "elementBackground") {
- setAppState({
- currentItemBackgroundColor: color,
+ }}
+ onSelect={(color, event) => {
+ setEyeDropperState((state) => {
+ return state?.keepOpenOnAlt && event.altKey ? state : null;
});
- } else {
- setAppState({ currentItemStrokeColor: color });
- }
- }}
- onSelect={(color, event) => {
- setEyeDropperState((state) => {
- return state?.keepOpenOnAlt && event.altKey ? state : null;
- });
- eyeDropperState?.onSelect?.(color, event);
- }}
- />
- )}
+ eyeDropperState?.onSelect?.(color, event);
+ }}
+ />
+ )}
{appState.openDialog?.name === "help" && (
<HelpDialog
onClose={() => {
@@ -523,7 +548,7 @@ const LayerUI = ({
/>
)}
<ActiveConfirmDialog />
- {appState.openDialog?.name === "elementLinkSelector" && (
+ {defaultUIEnabled && appState.openDialog?.name === "elementLinkSelector" && (
<ElementLinkDialog
sourceElementId={appState.openDialog.sourceElementId}
onClose={() => {
@@ -539,7 +564,7 @@ const LayerUI = ({
<tunnels.OverwriteConfirmDialogTunnel.Out />
{renderImageExportDialog()}
{renderJSONExportDialog()}
- {appState.openDialog?.name === "charts" && (
+ {defaultUIEnabled && appState.openDialog?.name === "charts" && (
<PasteChartDialog
data={appState.openDialog.data}
rawText={appState.openDialog.rawText}
@@ -564,6 +589,7 @@ const LayerUI = ({
renderTopRightUI={renderTopRightUI}
renderSidebars={renderSidebars}
renderWelcomeScreen={renderWelcomeScreen}
+ defaultUIEnabled={defaultUIEnabled}
UIOptions={UIOptions}
/>
)}
@@ -586,8 +612,10 @@ const LayerUI = ({
actionManager={actionManager}
showExitZenModeBtn={showExitZenModeBtn}
renderWelcomeScreen={renderWelcomeScreen}
+ defaultUIEnabled={defaultUIEnabled}
/>
- {(appState.toast || appState.scrolledOutside) && (
+ {(appState.toast ||
+ (defaultUIEnabled && appState.scrolledOutside)) && (
<div className="floating-status-stack">
{appState.toast && (
<Toast
@@ -597,19 +625,21 @@ const LayerUI = ({
closable={appState.toast.closable}
/>
)}
- {!appState.toast && appState.scrolledOutside && (
- <button
- type="button"
- className="scroll-back-to-content"
- onClick={() => {
- setAppState((appState) => ({
- ...getScrollToContentState(elements, appState),
- }));
- }}
- >
- {t("buttons.scrollBackToContent")}
- </button>
- )}
+ {!appState.toast &&
+ defaultUIEnabled &&
+ appState.scrolledOutside && (
+ <button
+ type="button"
+ className="scroll-back-to-content"
+ onClick={() => {
+ setAppState((appState) => ({
+ ...getScrollToContentState(elements, appState),
+ }));
+ }}
+ >
+ {t("buttons.scrollBackToContent")}
+ </button>
+ )}
</div>
)}
</div>
diff --git a/packages/excalidraw/components/MobileMenu.tsx b/packages/excalidraw/components/MobileMenu.tsx
index 2702f978b4..32f142125d 100644
--- a/packages/excalidraw/components/MobileMenu.tsx
+++ b/packages/excalidraw/components/MobileMenu.tsx
@@ -43,6 +43,7 @@ type MobileMenuProps = {
) => JSX.Element | null;
renderSidebars: () => JSX.Element | null;
renderWelcomeScreen: boolean;
+ defaultUIEnabled: boolean;
UIOptions: AppProps["UIOptions"];
app: AppClassProperties;
};
@@ -56,6 +57,7 @@ export const MobileMenu = ({
renderTopRightUI,
renderSidebars,
renderWelcomeScreen,
+ defaultUIEnabled,
UIOptions,
app,
onPenModeToggle,
@@ -75,19 +77,23 @@ export const MobileMenu = ({
{renderTopRightUI?.(true, appState) ??
(!appState.viewModeEnabled && (
<>
- <PenModeButton
- checked={appState.penMode}
- onChange={() => onPenModeToggle(null)}
- title={t("toolBar.penMode")}
- isMobile
- penDetected={appState.penDetected}
- />
+ {defaultUIEnabled && (
+ <PenModeButton
+ checked={appState.penMode}
+ onChange={() => onPenModeToggle(null)}
+ title={t("toolBar.penMode")}
+ isMobile
+ penDetected={appState.penDetected}
+ />
+ )}
<DefaultSidebarTriggerTunnel.Out />
</>
))}
- {appState.viewModeEnabled && (
- <ExitViewModeButton actionManager={actionManager} />
- )}
+ {defaultUIEnabled &&
+ appState.viewModeEnabled &&
+ app.isInteractionEnabled() && (
+ <ExitViewModeButton actionManager={actionManager} />
+ )}
</div>
);
@@ -126,7 +132,7 @@ export const MobileMenu = ({
{renderWelcomeScreen && <WelcomeScreenCenterTunnel.Out />}
</div>
- {!appState.viewModeEnabled && (
+ {defaultUIEnabled && !appState.viewModeEnabled && (
<div
className="App-bottom-bar"
style={{
diff --git a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
index 29ac8999ca..1128d46aa1 100644
--- a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
+++ b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
@@ -46,6 +46,8 @@ type InteractiveCanvasProps = {
renderScrollbars: boolean;
editorInterface: EditorInterface;
app: AppClassProperties;
+ interactionEnabled: boolean;
+ navigationEnabled: boolean;
renderInteractiveSceneCallback: (
data: RenderInteractiveSceneCallback,
) => void;
@@ -205,6 +207,7 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
width: props.appState.width,
height: props.appState.height,
cursor:
+ props.navigationEnabled &&
props.appState.viewModeEnabled &&
props.appState.activeTool.type !== "laser"
? CURSOR_TYPE.GRAB
@@ -213,6 +216,10 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
width={props.appState.width * props.scale}
height={props.appState.height * props.scale}
ref={props.handleCanvasRef}
+ // NOTE all the handlers early-exit in App when the editor is
+ // non-interactive (running only a restricted, link-only code path if
+ // `interaction.allowed.links` is enabled), so they're safe to bind
+ // unconditionally
onContextMenu={props.onContextMenu}
onClick={props.onClick}
onPointerMove={props.onPointerMove}
@@ -288,7 +295,9 @@ const areEqual = (
prevProps.elementsMap !== nextProps.elementsMap ||
prevProps.visibleElements !== nextProps.visibleElements ||
prevProps.selectedElements !== nextProps.selectedElements ||
- prevProps.renderScrollbars !== nextProps.renderScrollbars
+ prevProps.renderScrollbars !== nextProps.renderScrollbars ||
+ prevProps.interactionEnabled !== nextProps.interactionEnabled ||
+ prevProps.navigationEnabled !== nextProps.navigationEnabled
) {
return false;
}
diff --git a/packages/excalidraw/components/footer/Footer.tsx b/packages/excalidraw/components/footer/Footer.tsx
index e46253bce2..72955d4c76 100644
--- a/packages/excalidraw/components/footer/Footer.tsx
+++ b/packages/excalidraw/components/footer/Footer.tsx
@@ -3,6 +3,7 @@ import clsx from "clsx";
import { actionShortcuts } from "../../actions";
import { useTunnels } from "../../context/tunnels";
import { ExitZenModeButton, UndoRedoActions, ZoomActions } from "../Actions";
+import { useApp } from "../App";
import { HelpButton } from "../HelpButton";
import { Section } from "../Section";
import Stack from "../Stack";
@@ -15,58 +16,77 @@ const Footer = ({
actionManager,
showExitZenModeBtn,
renderWelcomeScreen,
+ defaultUIEnabled,
}: {
appState: UIAppState;
actionManager: ActionManager;
showExitZenModeBtn: boolean;
renderWelcomeScreen: boolean;
+ defaultUIEnabled: boolean;
}) => {
const { FooterCenterTunnel, WelcomeScreenHelpHintTunnel } = useTunnels();
+ const app = useApp();
return (
<footer
role="contentinfo"
className="layer-ui__wrapper__footer App-menu App-menu_bottom"
>
- <div
- className={clsx("layer-ui__wrapper__footer-left zen-mode-transition", {
- "layer-ui__wrapper__footer-left--transition-left":
- appState.zenModeEnabled,
- })}
- >
- <Stack.Col gap={2}>
- <Section heading="canvasActions">
- <ZoomActions renderAction={actionManager.renderAction} />
+ {defaultUIEnabled && (
+ <div
+ className={clsx(
+ "layer-ui__wrapper__footer-left zen-mode-transition",
+ {
+ "layer-ui__wrapper__footer-left--transition-left":
+ appState.zenModeEnabled,
+ },
+ )}
+ >
+ <Stack.Col gap={2}>
+ <Section heading="canvasActions">
+ {app.isNavigationEnabled() && (
+ <ZoomActions renderAction={actionManager.renderAction} />
+ )}
- {!appState.viewModeEnabled && (
- <UndoRedoActions
- renderAction={actionManager.renderAction}
- className={clsx("zen-mode-transition", {
- "layer-ui__wrapper__footer-left--transition-bottom":
- appState.zenModeEnabled,
- })}
+ {!appState.viewModeEnabled && (
+ <UndoRedoActions
+ renderAction={actionManager.renderAction}
+ className={clsx("zen-mode-transition", {
+ "layer-ui__wrapper__footer-left--transition-bottom":
+ appState.zenModeEnabled,
+ })}
+ />
+ )}
+ </Section>
+ </Stack.Col>
+ </div>
+ )}
+ <FooterCenterTunnel.Out />
+ {(defaultUIEnabled || renderWelcomeScreen) && (
+ <div
+ className={clsx(
+ "layer-ui__wrapper__footer-right zen-mode-transition",
+ {
+ "transition-right": appState.zenModeEnabled,
+ },
+ )}
+ >
+ <div style={{ position: "relative" }}>
+ {renderWelcomeScreen && <WelcomeScreenHelpHintTunnel.Out />}
+ {defaultUIEnabled && (
+ <HelpButton
+ onClick={() => actionManager.executeAction(actionShortcuts)}
/>
)}
- </Section>
- </Stack.Col>
- </div>
- <FooterCenterTunnel.Out />
- <div
- className={clsx("layer-ui__wrapper__footer-right zen-mode-transition", {
- "transition-right": appState.zenModeEnabled,
- })}
- >
- <div style={{ position: "relative" }}>
- {renderWelcomeScreen && <WelcomeScreenHelpHintTunnel.Out />}
- <HelpButton
- onClick={() => actionManager.executeAction(actionShortcuts)}
- />
+ </div>
</div>
- </div>
- <ExitZenModeButton
- actionManager={actionManager}
- showExitZenModeBtn={showExitZenModeBtn}
- />
+ )}
+ {defaultUIEnabled && (
+ <ExitZenModeButton
+ actionManager={actionManager}
+ showExitZenModeBtn={showExitZenModeBtn}
+ />
+ )}
</footer>
);
};
diff --git a/packages/excalidraw/components/main-menu/DefaultItems.tsx b/packages/excalidraw/components/main-menu/DefaultItems.tsx
index fef00c8da4..57098f7704 100644
--- a/packages/excalidraw/components/main-menu/DefaultItems.tsx
+++ b/packages/excalidraw/components/main-menu/DefaultItems.tsx
@@ -566,6 +566,9 @@ const PreferencesToggleViewModeItem = () => {
const { t } = useI18n();
const actionManager = useExcalidrawActionManager();
const appState = useUIAppState();
+ if (!actionManager.isActionEnabled(actionToggleViewMode)) {
+ return null;
+ }
return (
<DropdownMenuItemCheckbox
checked={appState.viewModeEnabled}
diff --git a/packages/excalidraw/css/styles.scss b/packages/excalidraw/css/styles.scss
index 5c3a005576..2ba8831581 100644
--- a/packages/excalidraw/css/styles.scss
+++ b/packages/excalidraw/css/styles.scss
@@ -384,8 +384,13 @@ body.excalidraw-cursor-resize * {
}
}
- .App-menu_top > *:first-child {
- justify-self: flex-start;
+ .App-menu_top > .App-menu_top__left {
+ grid-column: 1;
+ justify-self: start;
+ }
+
+ .App-menu_top > .shapes-section {
+ grid-column: 2;
}
.selected-shape-actions-container {
@@ -396,8 +401,9 @@ body.excalidraw-cursor-resize * {
}
}
- .App-menu_top > *:last-child {
- justify-self: flex-end;
+ .App-menu_top > .layer-ui__wrapper__top-right {
+ grid-column: 3;
+ justify-self: end;
}
.App-menu_bottom {
@@ -616,6 +622,37 @@ body.excalidraw-cursor-resize * {
}
}
+ &.excalidraw--non-interactive {
+ user-select: none;
+
+ canvas {
+ // let the page handle scrolling over the editor, but not the browser
+ // zoom gestures (pinch, double-tap)
+ touch-action: pan-x pan-y;
+ // no !important — inline cursor styles must win so that
+ // `interaction: { enabled: { links: true } }` can show a pointer over
+ // links
+ cursor: default;
+ }
+
+ &.excalidraw--allow-browser-zoom canvas {
+ touch-action: auto;
+ }
+
+ // with navigation allowed, touch input drives the canvas pan/zoom again
+ &.excalidraw--navigation canvas {
+ touch-action: none;
+ }
+
+ // override inline pointer-events set when embeddable is active
+ // (also covers custom `renderEmbeddable` content) — unless embeds are
+ // an allowed interaction, in which case the inline (activation-driven)
+ // pointer-events apply, same as in view mode
+ &:not(.excalidraw--embeds) .excalidraw__embeddable-container__inner {
+ pointer-events: none !important;
+ }
+ }
+
input.is-redacted {
// we don't use type=password because browsers (chrome?) prompt
// you to save it which is annoying
diff --git a/packages/excalidraw/index.tsx b/packages/excalidraw/index.tsx
index 0ebf08cdeb..091b1c4d32 100644
--- a/packages/excalidraw/index.tsx
+++ b/packages/excalidraw/index.tsx
@@ -82,6 +82,8 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
renderTopRightUI,
langCode = defaultLang.code,
viewModeEnabled,
+ interaction,
+ ui,
zenModeEnabled,
gridModeEnabled,
libraryReturnUrl,
@@ -157,6 +159,15 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
[setExcalidrawAPI],
);
+ // whether the browser's own zoom is kept available while the editor is
+ // non-interactive (with navigation allowed, pinch is consumed by the
+ // editor instead, which relies on the pinch prevention below)
+ const browserZoomAllowed =
+ typeof interaction === "object" &&
+ interaction !== null &&
+ interaction.enabled?.browserZoom === true &&
+ interaction.enabled?.navigation !== true;
+
useEffect(() => {
const importPolyfill = async () => {
//@ts-ignore
@@ -165,6 +176,10 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
importPolyfill();
+ if (browserZoomAllowed) {
+ return;
+ }
+
// Block pinch-zooming on iOS outside of the content area
const handleTouchMove = (event: TouchEvent) => {
// @ts-ignore
@@ -180,7 +195,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
return () => {
document.removeEventListener("touchmove", handleTouchMove);
};
- }, []);
+ }, [browserZoomAllowed]);
return (
<EditorJotaiProvider store={editorJotaiStore}>
@@ -202,6 +217,8 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
renderTopRightUI={renderTopRightUI}
langCode={langCode}
viewModeEnabled={viewModeEnabled}
+ interaction={interaction}
+ ui={ui}
zenModeEnabled={zenModeEnabled}
gridModeEnabled={gridModeEnabled}
libraryReturnUrl={libraryReturnUrl}
@@ -245,15 +262,39 @@ const areEqual = (prevProps: ExcalidrawProps, nextProps: ExcalidrawProps) => {
initialData: prevInitialData,
UIOptions: prevUIOptions = {},
imageOptions: prevImageOptions,
+ interaction: prevInteraction,
...prev
} = prevProps;
const {
initialData: nextInitialData,
UIOptions: nextUIOptions = {},
imageOptions: nextImageOptions,
+ interaction: nextInteraction,
...next
} = nextProps;
+ // compare `interaction` semantically so that hosts inlining the config
+ // object (`interaction={{ enabled: { links: true } }}`) don't bust the
+ // memo every render
+ const isInteractionSame =
+ prevInteraction === nextInteraction ||
+ (typeof prevInteraction === "object" &&
+ prevInteraction !== null &&
+ typeof nextInteraction === "object" &&
+ nextInteraction !== null &&
+ !!prevInteraction.enabled?.links === !!nextInteraction.enabled?.links &&
+ !!prevInteraction.enabled?.embeds === !!nextInteraction.enabled?.embeds &&
+ !!prevInteraction.enabled?.interactiveContent ===
+ !!nextInteraction.enabled?.interactiveContent &&
+ !!prevInteraction.enabled?.navigation ===
+ !!nextInteraction.enabled?.navigation &&
+ !!prevInteraction.enabled?.browserZoom ===
+ !!nextInteraction.enabled?.browserZoom);
+
+ if (!isInteractionSame) {
+ return false;
+ }
+
// comparing UIOptions
const prevUIOptionsKeys = Object.keys(prevUIOptions) as (keyof Partial<
typeof DEFAULT_UI_OPTIONS
diff --git a/packages/excalidraw/renderer/staticScene.ts b/packages/excalidraw/renderer/staticScene.ts
index f3f00256c1..278359994e 100644
--- a/packages/excalidraw/renderer/staticScene.ts
+++ b/packages/excalidraw/renderer/staticScene.ts
@@ -376,7 +376,7 @@ const _renderStaticScene = ({
context.restore();
- if (!isExporting) {
+ if (!isExporting && renderConfig.renderLinks !== false) {
renderLinkIcon(element, context, appState, elementsMap);
}
} catch (error: any) {
@@ -427,7 +427,7 @@ const _renderStaticScene = ({
appState,
);
}
- if (!isExporting) {
+ if (!isExporting && renderConfig.renderLinks !== false) {
renderLinkIcon(element, context, appState, elementsMap);
}
};
diff --git a/packages/excalidraw/scene/types.ts b/packages/excalidraw/scene/types.ts
index d77fede4c9..a98dc884d1 100644
--- a/packages/excalidraw/scene/types.ts
+++ b/packages/excalidraw/scene/types.ts
@@ -30,6 +30,9 @@ export type StaticCanvasRenderConfig = {
// ---------------------------------------------------------------------------
imageCache: AppClassProperties["imageCache"];
renderGrid: boolean;
+ /** whether to render link icons on elements with links (never rendered
+ when exporting). @default true */
+ renderLinks?: boolean;
/** when exporting the behavior is slightly different (e.g. we can't use
CSS filters), and we disable render optimizations for best output */
isExporting: boolean;
diff --git a/packages/excalidraw/tests/interactivity.test.tsx b/packages/excalidraw/tests/interactivity.test.tsx
new file mode 100644
index 0000000000..6b60ae98a2
--- /dev/null
+++ b/packages/excalidraw/tests/interactivity.test.tsx
@@ -0,0 +1,1194 @@
+import React from "react";
+import { vi } from "vitest";
+
+import { CODES, CURSOR_TYPE } from "@excalidraw/common";
+
+import type { ExcalidrawElement } from "@excalidraw/element/types";
+
+import { actionZoomIn } from "../actions/actionCanvas";
+import { createPasteEvent, serializeAsClipboardJSON } from "../clipboard";
+import { DefaultSidebar, Excalidraw, Footer, MainMenu } from "../index";
+
+import { API } from "./helpers/api";
+import { Keyboard, Pointer, UI } from "./helpers/ui";
+import { getTextEditor, updateTextEditor } from "./queries/dom";
+import {
+ act,
+ fireEvent,
+ GlobalTestState,
+ mockBoundingClientRect,
+ render,
+ restoreOriginalGetBoundingClientRect,
+ waitFor,
+} from "./test-utils";
+
+import type { MockInstance } from "vitest";
+
+import type { ExcalidrawProps } from "../types";
+
+const { h } = window;
+
+const mouse = new Pointer("mouse");
+
+const sleep = (ms: number) =>
+ new Promise((resolve) => setTimeout(() => resolve(null), ms));
+
+// the wheel listener is attached natively on the excalidraw container
+// (not via React), so we dispatch a bubbling wheel event from the canvas
+const wheelZoom = () => {
+ fireEvent.wheel(GlobalTestState.interactiveCanvas, {
+ ctrlKey: true,
+ deltaY: -100,
+ });
+};
+
+const wheelPan = () => {
+ fireEvent.wheel(GlobalTestState.interactiveCanvas, {
+ deltaX: 30,
+ deltaY: 40,
+ });
+};
+
+// zoom shortcuts' keyTest matches on `event.code` (CODES.EQUAL/MINUS/ZERO)
+const pressZoomShortcut = (code: string) => {
+ Keyboard.withModifierKeys({ ctrl: true }, () => {
+ Keyboard.codePress(code);
+ });
+};
+
+const rightClickCanvas = () => {
+ fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
+ button: 2,
+ clientX: 5,
+ clientY: 5,
+ });
+};
+
+const dispatchPaste = async () => {
+ const clipboardJSON = await serializeAsClipboardJSON({
+ elements: [API.createElement({ type: "rectangle", width: 10, height: 10 })],
+ files: null,
+ });
+ document.dispatchEvent(
+ createPasteEvent({ types: { "text/plain": clipboardJSON } }),
+ );
+};
+
+const queryContainer = (selector: string) =>
+ GlobalTestState.renderResult.container.querySelector(selector);
+
+beforeEach(() => {
+ localStorage.clear();
+ mouse.reset();
+});
+
+describe("baseline (interactive & ui enabled by default)", () => {
+ beforeEach(async () => {
+ mockBoundingClientRect();
+ await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+ Object.assign(document, {
+ elementFromPoint: () => GlobalTestState.canvas,
+ });
+ });
+
+ afterEach(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("user input mechanisms used in this suite actually affect the editor", async () => {
+ expect(h.state.viewModeEnabled).toBe(false);
+
+ // ctrl+wheel zooms
+ const initialZoom = h.state.zoom.value;
+ wheelZoom();
+ expect(h.state.zoom.value).toBeGreaterThan(initialZoom);
+
+ // plain wheel pans
+ const { scrollX, scrollY } = h.state;
+ wheelPan();
+ expect([h.state.scrollX, h.state.scrollY]).not.toEqual([scrollX, scrollY]);
+
+ // ctrl+"=" zooms in
+ const zoomBeforeKeyboard = h.state.zoom.value;
+ pressZoomShortcut(CODES.EQUAL);
+ expect(h.state.zoom.value).toBeGreaterThan(zoomBeforeKeyboard);
+
+ // paste inserts elements
+ await dispatchPaste();
+ await waitFor(() => expect(h.elements.length).toBe(1));
+
+ // right-click opens the context menu
+ rightClickCanvas();
+ expect(h.state.contextMenu).not.toBe(null);
+ expect(UI.queryContextMenu()).not.toBe(null);
+ });
+
+ it("renders UI chrome", () => {
+ expect(queryContainer(".layer-ui__wrapper")).not.toBe(null);
+ expect(queryContainer(".App-toolbar")).not.toBe(null);
+ expect(queryContainer(".excalidraw--non-interactive")).toBe(null);
+ expect(queryContainer(".excalidraw--ui-hidden")).toBe(null);
+ });
+});
+
+describe("interaction={false}", () => {
+ let rectangle: ExcalidrawElement;
+
+ beforeEach(async () => {
+ mockBoundingClientRect();
+ rectangle = API.createElement({
+ type: "rectangle",
+ x: 10,
+ y: 10,
+ width: 50,
+ height: 50,
+ });
+ await render(
+ <Excalidraw
+ interaction={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ initialData={{ elements: [rectangle] }}
+ />,
+ );
+ await waitFor(() => expect(h.state.width).toBe(200));
+ Object.assign(document, {
+ elementFromPoint: () => GlobalTestState.canvas,
+ });
+ });
+
+ afterEach(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("forces viewModeEnabled", () => {
+ expect(h.state.viewModeEnabled).toBe(true);
+ });
+
+ it("container gets the excalidraw--non-interactive class", () => {
+ const container = queryContainer(".excalidraw-container")!;
+ expect(container).not.toBe(null);
+ expect(container.classList.contains("excalidraw--non-interactive")).toBe(
+ true,
+ );
+ });
+
+ it("wheel does not zoom or pan", () => {
+ const { scrollX, scrollY } = h.state;
+ const zoom = h.state.zoom.value;
+
+ wheelZoom();
+ expect(h.state.zoom.value).toBe(zoom);
+
+ wheelPan();
+ expect(h.state.scrollX).toBe(scrollX);
+ expect(h.state.scrollY).toBe(scrollY);
+ });
+
+ it("keyboard zoom shortcuts are inert", () => {
+ // zoom to != 100% first so ctrl+0 (reset zoom) would be observable
+ act(() => {
+ h.app.actionManager.executeAction(actionZoomIn, "api");
+ });
+ const zoom = h.state.zoom.value;
+ expect(zoom).not.toBe(1);
+
+ pressZoomShortcut(CODES.EQUAL);
+ expect(h.state.zoom.value).toBe(zoom);
+
+ pressZoomShortcut(CODES.MINUS);
+ expect(h.state.zoom.value).toBe(zoom);
+
+ pressZoomShortcut(CODES.ZERO);
+ expect(h.state.zoom.value).toBe(zoom);
+ });
+
+ it("pointer down+drag neither selects nor pans", () => {
+ const { scrollX, scrollY } = h.state;
+
+ // drag starting on top of the rectangle
+ mouse.downAt(30, 30);
+ mouse.moveTo(80, 80);
+ mouse.upAt(80, 80);
+
+ expect(h.state.selectedElementIds).toEqual({});
+ expect(h.state.scrollX).toBe(scrollX);
+ expect(h.state.scrollY).toBe(scrollY);
+
+ // plain click on the element doesn't select either
+ mouse.reset();
+ mouse.clickAt(30, 30);
+ expect(h.state.selectedElementIds).toEqual({});
+ });
+
+ it("context menu does not open", () => {
+ rightClickCanvas();
+ expect(h.state.contextMenu).toBe(null);
+ expect(UI.queryContextMenu()).toBe(null);
+ });
+
+ it("paste is inert", async () => {
+ expect(h.elements.length).toBe(1);
+ await dispatchPaste();
+ // paste is async; give it time to (not) insert
+ await act(async () => {
+ await sleep(50);
+ });
+ expect(h.elements.length).toBe(1);
+ });
+
+ it("programmatic viewport API still works", () => {
+ expect(h.state.zoom.value).toBe(1);
+
+ act(() => {
+ h.app.setViewport({
+ target: [0, 0, 1000, 1000],
+ fit: "scale-down",
+ animation: false,
+ });
+ });
+
+ // 200x100 viewport fitted to a 1000x1000 box
+ expect(h.state.zoom.value).toBeCloseTo(0.1);
+ });
+
+ it("programmatic updateScene still works", () => {
+ expect(h.elements.length).toBe(1);
+
+ const other = API.createElement({
+ type: "ellipse",
+ x: 100,
+ y: 100,
+ width: 30,
+ height: 30,
+ });
+ API.updateScene({ elements: [...h.elements, other] });
+
+ expect(h.elements.length).toBe(2);
+ });
+
+ it('executeAction no-ops for user sources but works for "api"', () => {
+ const zoom = h.state.zoom.value;
+
+ act(() => {
+ h.app.actionManager.executeAction(actionZoomIn, "ui");
+ });
+ expect(h.state.zoom.value).toBe(zoom);
+
+ act(() => {
+ h.app.actionManager.executeAction(actionZoomIn, "keyboard");
+ });
+ expect(h.state.zoom.value).toBe(zoom);
+
+ act(() => {
+ h.app.actionManager.executeAction(actionZoomIn, "api");
+ });
+ expect(h.state.zoom.value).toBeGreaterThan(zoom);
+ });
+
+ it("viewModeEnabled cannot be unset while non-interactive", async () => {
+ API.updateScene({ appState: { viewModeEnabled: false } });
+ await waitFor(() => {
+ expect(h.state.viewModeEnabled).toBe(true);
+ });
+ });
+});
+
+describe("browser zoom prevention (non-interactive)", () => {
+ // fireEvent returns `false` when a handler called preventDefault()
+ const firesCtrlWheel = () =>
+ fireEvent.wheel(GlobalTestState.interactiveCanvas, {
+ ctrlKey: true,
+ deltaY: -100,
+ });
+
+ const firesPlainWheel = () =>
+ fireEvent.wheel(GlobalTestState.interactiveCanvas, { deltaY: 40 });
+
+ const firesCtrlZoomKey = () =>
+ fireEvent.keyDown(document, { ctrlKey: true, code: CODES.EQUAL });
+
+ it("prevents ctrl+wheel & keyboard zoom by default, keeps page scroll", async () => {
+ await render(
+ <Excalidraw interaction={false} handleKeyboardGlobally={true} />,
+ );
+
+ // browser zoom vectors get preventDefault-ed...
+ expect(firesCtrlWheel()).toBe(false);
+ expect(firesCtrlZoomKey()).toBe(false);
+ // ...while regular scroll passes through to the page
+ expect(firesPlainWheel()).toBe(true);
+ // and the editor itself didn't zoom either
+ expect(h.state.zoom.value).toBe(1);
+ });
+
+ it("enabled.browserZoom keeps the browser defaults", async () => {
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { browserZoom: true } }}
+ handleKeyboardGlobally={true}
+ />,
+ );
+
+ expect(
+ queryContainer(".excalidraw-container")!.classList.contains(
+ "excalidraw--allow-browser-zoom",
+ ),
+ ).toBe(true);
+
+ expect(firesCtrlWheel()).toBe(true);
+ expect(firesCtrlZoomKey()).toBe(true);
+ expect(firesPlainWheel()).toBe(true);
+ expect(h.state.zoom.value).toBe(1);
+ });
+
+ it("toggling enabled.browserZoom at runtime re-attaches listeners", async () => {
+ await render(
+ <Excalidraw interaction={false} handleKeyboardGlobally={true} />,
+ );
+ expect(firesCtrlWheel()).toBe(false);
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={{ enabled: { browserZoom: true } }}
+ handleKeyboardGlobally={true}
+ />,
+ );
+ expect(firesCtrlWheel()).toBe(true);
+ });
+});
+
+describe("toggling `interaction` at runtime", () => {
+ afterEach(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("clears transient state when disabled and re-enables input when re-enabled", async () => {
+ mockBoundingClientRect();
+ await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ // draw & select an element, open the context menu
+ const rectangle = UI.createElement("rectangle", { x: 10, y: 10, size: 50 });
+ expect(h.state.selectedElementIds[rectangle.id]).toBe(true);
+
+ rightClickCanvas();
+ expect(h.state.contextMenu).not.toBe(null);
+
+ // flip to non-interactive
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+ await waitFor(() => {
+ expect(h.state.viewModeEnabled).toBe(true);
+ });
+ expect(h.state.contextMenu).toBe(null);
+ expect(h.state.selectedElementIds).toEqual({});
+
+ // input is dead now
+ const zoom = h.state.zoom.value;
+ wheelZoom();
+ expect(h.state.zoom.value).toBe(zoom);
+
+ mouse.reset();
+ mouse.clickAt(30, 30);
+ expect(h.state.selectedElementIds).toEqual({});
+
+ // flip back to interactive
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw autoFocus={true} handleKeyboardGlobally={true} />,
+ );
+ await waitFor(() => {
+ expect(h.state.viewModeEnabled).toBe(false);
+ });
+
+ // drawing works again
+ act(() => {
+ h.app.setActiveTool({ type: "rectangle" });
+ });
+ mouse.reset();
+ mouse.downAt(100, 10);
+ mouse.moveTo(150, 60);
+ mouse.upAt(150, 60);
+
+ expect(h.elements.length).toBe(2);
+
+ // and wheel zoom works again
+ wheelZoom();
+ expect(h.state.zoom.value).toBeGreaterThan(zoom);
+ });
+
+ it("deselects when disabled while already in view mode", async () => {
+ mockBoundingClientRect();
+ await render(
+ <Excalidraw
+ viewModeEnabled={true}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ const rectangle = API.createElement({ type: "rectangle" });
+ API.setElements([rectangle]);
+ API.setSelectedElements([rectangle]);
+ expect(h.state.selectedElementIds[rectangle.id]).toBe(true);
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={false}
+ viewModeEnabled={true}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(h.state.selectedElementIds).toEqual({});
+ });
+ });
+
+ it("submits an active text editor when interaction is disabled", async () => {
+ mockBoundingClientRect();
+ await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ const text = API.createElement({
+ type: "text",
+ text: "before",
+ x: 20,
+ y: 20,
+ });
+ API.setElements([text]);
+ API.setSelectedElements([text]);
+ Keyboard.keyPress("Enter");
+
+ const editor = await getTextEditor();
+ updateTextEditor(editor, "committed before disable");
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(h.state.editingTextElement).toBe(null);
+ expect(queryContainer(".excalidraw-wysiwyg")).toBe(null);
+ });
+ expect(h.elements.find((element) => element.id === text.id)).toMatchObject({
+ originalText: "committed before disable",
+ });
+
+ // The detached editor must no longer have a live input listener.
+ editor.value = "changed after disable";
+ fireEvent.input(editor);
+ expect(h.elements.find((element) => element.id === text.id)).toMatchObject({
+ originalText: "committed before disable",
+ });
+ });
+
+ it("commits and closes frame-name editing when interaction is disabled", async () => {
+ mockBoundingClientRect();
+ await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ const frame = API.createElement({
+ type: "frame",
+ x: 20,
+ y: 30,
+ width: 80,
+ height: 50,
+ });
+ API.setElements([frame]);
+ API.updateElement(frame, { name: "before" });
+ act(() => h.setState({ editingFrame: frame.id }));
+
+ const frameNameInput = await waitFor(() => {
+ const input = queryContainer(".frame-name input");
+ expect(input).not.toBe(null);
+ return input as HTMLInputElement;
+ });
+ fireEvent.change(frameNameInput, { target: { value: " committed " } });
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(h.state.editingFrame).toBe(null);
+ expect(queryContainer(".frame-name input")).toBe(null);
+ });
+ expect(h.elements.find((element) => element.id === frame.id)).toMatchObject(
+ { name: "committed" },
+ );
+ });
+
+ it("clears held-key state before interaction is re-enabled", async () => {
+ mockBoundingClientRect();
+ await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ // If the keyup occurs while non-interactive, App's keyup listener is not
+ // attached. The transition itself must therefore clear this state.
+ Keyboard.keyDown(" ");
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+ await waitFor(() => expect(h.state.viewModeEnabled).toBe(true));
+ Keyboard.keyUp(" ");
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw autoFocus={true} handleKeyboardGlobally={true} />,
+ );
+ await waitFor(() => expect(h.state.viewModeEnabled).toBe(false));
+
+ act(() => h.app.setActiveTool({ type: "rectangle" }));
+ mouse.downAt(20, 20);
+ mouse.moveTo(80, 70);
+ mouse.upAt(80, 70);
+ expect(h.elements).toHaveLength(1);
+ });
+
+ it("closes native-listener interaction surfaces when disabled", async () => {
+ mockBoundingClientRect();
+ await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ Keyboard.keyPress("i");
+ await waitFor(() => {
+ expect(queryContainer(".excalidraw-eye-dropper-preview")).not.toBe(null);
+ });
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+ await waitFor(() => {
+ expect(queryContainer(".excalidraw-eye-dropper-preview")).toBe(null);
+ });
+ });
+});
+
+describe("ui={false}", () => {
+ beforeEach(async () => {
+ await render(
+ <Excalidraw
+ ui={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ initialData={{
+ elements: [
+ API.createElement({
+ type: "rectangle",
+ x: 10,
+ y: 10,
+ width: 50,
+ height: 50,
+ }),
+ ],
+ }}
+ >
+ {/* children may be functional (e.g. excalidraw.com's <Collab/>),
+ so they must mount even with the default UI disabled */}
+ <div data-testid="host-child" />
+ </Excalidraw>,
+ );
+ });
+
+ it("renders canvases but no default UI chrome", () => {
+ // canvas layers keep rendering
+ expect(queryContainer("canvas.static")).not.toBe(null);
+ expect(queryContainer("canvas.interactive")).not.toBe(null);
+ expect(queryContainer(".SVGLayer")).not.toBe(null);
+ expect(queryContainer(".excalidraw-textEditorContainer")).not.toBe(null);
+
+ // The placement scaffold remains for host UI, but default controls don't.
+ expect(queryContainer(".App-toolbar")).toBe(null);
+ expect(queryContainer(".dropdown-menu-button")).toBe(null);
+ expect(queryContainer(".default-sidebar-trigger")).toBe(null);
+ expect(queryContainer(".layer-ui__wrapper__footer-left")).toBe(null);
+ expect(queryContainer(".help-icon")).toBe(null);
+ });
+
+ it("host children still mount", () => {
+ // functional children (e.g. collab) keep working
+ expect(queryContainer("[data-testid='host-child']")).not.toBe(null);
+ });
+
+ it("container gets the excalidraw--ui-hidden class", () => {
+ const container = queryContainer(".excalidraw-container")!;
+ expect(container).not.toBe(null);
+ expect(container.classList.contains("excalidraw--ui-hidden")).toBe(true);
+ // ui-only mode must not force view mode / non-interactivity
+ expect(container.classList.contains("excalidraw--non-interactive")).toBe(
+ false,
+ );
+ expect(h.state.viewModeEnabled).toBe(false);
+ });
+
+ it("interaction still works (drawing via pointer)", () => {
+ expect(h.elements.length).toBe(1);
+
+ act(() => {
+ h.app.setActiveTool({ type: "rectangle" });
+ });
+ mouse.downAt(100, 10);
+ mouse.moveTo(150, 60);
+ mouse.upAt(150, 60);
+
+ expect(h.elements.length).toBe(2);
+ expect(h.elements[1].type).toBe("rectangle");
+ });
+
+ it("right-click sets contextMenu state but renders no menu", () => {
+ rightClickCanvas();
+ expect(h.state.contextMenu).not.toBe(null);
+ expect(UI.queryContextMenu()).toBe(null);
+ });
+});
+
+describe("ui={false} with host UI", () => {
+ it("renders host outlets and dialogs invoked by host UI", async () => {
+ const { container } = await render(
+ <Excalidraw
+ ui={false}
+ renderTopLeftUI={() => <div data-testid="host-top-left" />}
+ renderTopRightUI={() => <div data-testid="host-top-right" />}
+ >
+ <MainMenu>
+ <MainMenu.Item onSelect={() => {}}>host menu item</MainMenu.Item>
+ <MainMenu.DefaultItems.SaveAsImage />
+ </MainMenu>
+ <Footer>
+ <div data-testid="host-footer" />
+ </Footer>
+ <DefaultSidebar.Trigger title="host sidebar" />
+ </Excalidraw>,
+ );
+
+ expect(queryContainer("[data-testid='host-top-left']")).not.toBe(null);
+ expect(queryContainer("[data-testid='host-top-right']")).not.toBe(null);
+ expect(queryContainer("[data-testid='host-footer']")).not.toBe(null);
+ expect(queryContainer("[aria-label='host sidebar']")).not.toBe(null);
+
+ fireEvent.click(container.querySelector(".dropdown-menu-button")!);
+ expect(container.textContent).toContain("host menu item");
+ // The internal fallback menu must not be composed.
+ expect(queryContainer("[data-testid='load-button']")).toBe(null);
+
+ fireEvent.click(queryContainer("[data-testid='image-export-button']")!);
+ await waitFor(() => {
+ expect(document.querySelector(".ImageExportModal")).not.toBe(null);
+ });
+ });
+});
+
+describe("interaction={false} ui={false}", () => {
+ beforeEach(async () => {
+ mockBoundingClientRect();
+ await render(
+ <Excalidraw
+ interaction={false}
+ ui={false}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ initialData={{
+ elements: [
+ API.createElement({
+ type: "rectangle",
+ x: 10,
+ y: 10,
+ width: 50,
+ height: 50,
+ }),
+ ],
+ }}
+ />,
+ );
+ await waitFor(() => expect(h.state.width).toBe(200));
+ });
+
+ afterEach(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("renders canvases without chrome and stays fully inert", () => {
+ expect(h.state.viewModeEnabled).toBe(true);
+
+ // canvases and host-placement infrastructure render, default chrome does
+ // not
+ expect(queryContainer("canvas.static")).not.toBe(null);
+ expect(queryContainer("canvas.interactive")).not.toBe(null);
+ expect(queryContainer(".App-toolbar")).toBe(null);
+ expect(queryContainer(".dropdown-menu-button")).toBe(null);
+
+ const container = queryContainer(".excalidraw-container")!;
+ expect(container.classList.contains("excalidraw--non-interactive")).toBe(
+ true,
+ );
+ expect(container.classList.contains("excalidraw--ui-hidden")).toBe(true);
+
+ // wheel / keyboard / pointer / contextmenu are all no-ops
+ const { scrollX, scrollY } = h.state;
+ const zoom = h.state.zoom.value;
+
+ wheelZoom();
+ wheelPan();
+ pressZoomShortcut(CODES.EQUAL);
+ expect(h.state.zoom.value).toBe(zoom);
+ expect(h.state.scrollX).toBe(scrollX);
+ expect(h.state.scrollY).toBe(scrollY);
+
+ mouse.downAt(30, 30);
+ mouse.moveTo(80, 80);
+ mouse.upAt(80, 80);
+ expect(h.state.selectedElementIds).toEqual({});
+ expect(h.state.scrollX).toBe(scrollX);
+ expect(h.state.scrollY).toBe(scrollY);
+
+ rightClickCanvas();
+ expect(h.state.contextMenu).toBe(null);
+ });
+});
+
+describe("interaction={{ enabled: { links } }}", () => {
+ let onLinkOpenSpy: ReturnType<typeof vi.fn>;
+ let windowOpenSpy: MockInstance<typeof window.open>;
+
+ // prevent default inside the handler so the editor doesn't call
+ // window.open (mocked anyway, defensively)
+ const onLinkOpen: NonNullable<ExcalidrawProps["onLinkOpen"]> = (...args) => {
+ onLinkOpenSpy(...args);
+ args[1].preventDefault();
+ };
+
+ beforeEach(() => {
+ onLinkOpenSpy = vi.fn();
+ windowOpenSpy = vi.spyOn(window, "open").mockReturnValue(null);
+ });
+
+ afterEach(() => {
+ windowOpenSpy.mockRestore();
+ });
+
+ // NOTE `API.createElement` does not propagate `link`, so it's set via
+ // `API.updateElement` (same as laser.test.tsx)
+ const addRect = (link: string | null = null) => {
+ const rect = API.createElement({
+ type: "rectangle",
+ x: 20,
+ y: 20,
+ width: 120,
+ height: 90,
+ });
+ API.setElements([rect]);
+ if (link) {
+ API.updateElement(rect, { link });
+ }
+ return rect;
+ };
+
+ // the link-mode pointerup relies on `hitLinkElement` being set during a
+ // preceding pointermove (on non-touchscreen devices), so hover first
+ const clickElementCenter = () => {
+ mouse.reset();
+ mouse.moveTo(80, 65);
+ mouse.clickAt(80, 65);
+ };
+
+ it("{enabled: {links: true}}: editor is otherwise inert", async () => {
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { links: true } }}
+ handleKeyboardGlobally={true}
+ />,
+ );
+
+ expect(h.app.isLinksEnabled()).toBe(true);
+ expect(h.state.viewModeEnabled).toBe(true);
+ expect(queryContainer(".excalidraw--non-interactive")).not.toBe(null);
+
+ const zoom = h.state.zoom.value;
+ wheelZoom();
+ expect(h.state.zoom.value).toBe(zoom);
+ pressZoomShortcut(CODES.EQUAL);
+ expect(h.state.zoom.value).toBe(zoom);
+
+ rightClickCanvas();
+ expect(h.state.contextMenu).toBe(null);
+ });
+
+ it("{enabled: {links: true}}: clicking a linked element opens the link", async () => {
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { links: true } }}
+ onLinkOpen={onLinkOpen}
+ />,
+ );
+ const linkedRect = addRect("https://excalidraw.com");
+
+ // hovering a linked element shows the pointer cursor (view-mode style:
+ // anywhere on the element counts, not just the link icon)
+ mouse.reset();
+ mouse.moveTo(80, 65);
+ expect(GlobalTestState.interactiveCanvas.style.cursor).toBe(
+ CURSOR_TYPE.POINTER,
+ );
+
+ mouse.clickAt(80, 65);
+
+ expect(onLinkOpenSpy).toHaveBeenCalledTimes(1);
+ expect(onLinkOpenSpy.mock.calls[0][0]).toMatchObject({
+ id: linkedRect.id,
+ link: "https://excalidraw.com",
+ });
+ // the custom event was defaultPrevented, so no window.open
+ expect(windowOpenSpy).not.toHaveBeenCalled();
+ // and the click didn't select the element
+ expect(h.state.selectedElementIds).toEqual({});
+ });
+
+ it("{enabled: {links: true}}: clicking an element without a link does nothing", async () => {
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { links: true } }}
+ onLinkOpen={onLinkOpen}
+ />,
+ );
+ addRect(null);
+
+ clickElementCenter();
+
+ expect(onLinkOpenSpy).not.toHaveBeenCalled();
+ expect(windowOpenSpy).not.toHaveBeenCalled();
+ expect(h.state.selectedElementIds).toEqual({});
+ });
+
+ it("{enabled: {links: false}} and {} behave like interaction={false}", async () => {
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { links: false } }}
+ onLinkOpen={onLinkOpen}
+ />,
+ );
+ addRect("https://excalidraw.com");
+
+ expect(h.app.isLinksEnabled()).toBe(false);
+ expect(h.state.viewModeEnabled).toBe(true);
+ expect(queryContainer(".excalidraw--non-interactive")).not.toBe(null);
+
+ clickElementCenter();
+ expect(onLinkOpenSpy).not.toHaveBeenCalled();
+
+ // empty object form is equivalent
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw interaction={{}} onLinkOpen={onLinkOpen} />,
+ );
+ expect(h.app.isLinksEnabled()).toBe(false);
+ expect(h.state.viewModeEnabled).toBe(true);
+
+ clickElementCenter();
+ expect(onLinkOpenSpy).not.toHaveBeenCalled();
+ expect(windowOpenSpy).not.toHaveBeenCalled();
+ });
+
+ it("interaction={false}: links are disabled", async () => {
+ await render(<Excalidraw interaction={false} onLinkOpen={onLinkOpen} />);
+ addRect("https://excalidraw.com");
+
+ expect(h.app.isLinksEnabled()).toBe(false);
+
+ clickElementCenter();
+ expect(onLinkOpenSpy).not.toHaveBeenCalled();
+ expect(windowOpenSpy).not.toHaveBeenCalled();
+ });
+
+ it("toggling enabled.links false → true at runtime enables link clicks", async () => {
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { links: false } }}
+ onLinkOpen={onLinkOpen}
+ />,
+ );
+ const linkedRect = addRect("https://excalidraw.com");
+
+ clickElementCenter();
+ expect(onLinkOpenSpy).not.toHaveBeenCalled();
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={{ enabled: { links: true } }}
+ onLinkOpen={onLinkOpen}
+ />,
+ );
+ expect(h.app.isLinksEnabled()).toBe(true);
+ // still non-interactive overall
+ expect(h.state.viewModeEnabled).toBe(true);
+
+ clickElementCenter();
+ expect(onLinkOpenSpy).toHaveBeenCalledTimes(1);
+ expect(onLinkOpenSpy.mock.calls[0][0]).toMatchObject({
+ id: linkedRect.id,
+ });
+ });
+});
+
+describe("interaction={{ enabled: { navigation } }}", () => {
+ beforeEach(async () => {
+ mockBoundingClientRect();
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { navigation: true } }}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ initialData={{
+ elements: [
+ API.createElement({
+ type: "rectangle",
+ x: 10,
+ y: 10,
+ width: 50,
+ height: 50,
+ }),
+ ],
+ }}
+ />,
+ );
+ await waitFor(() => expect(h.state.width).toBe(200));
+ });
+
+ afterEach(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("wheel pans & ctrl+wheel zooms the canvas", () => {
+ expect(h.app.isNavigationEnabled()).toBe(true);
+ expect(h.state.viewModeEnabled).toBe(true);
+ expect(queryContainer(".excalidraw--navigation")).not.toBe(null);
+
+ const { scrollX, scrollY } = h.state;
+ wheelPan();
+ expect([h.state.scrollX, h.state.scrollY]).not.toEqual([scrollX, scrollY]);
+
+ const zoom = h.state.zoom.value;
+ wheelZoom();
+ expect(h.state.zoom.value).toBeGreaterThan(zoom);
+ });
+
+ it("pointer drag pans without selecting", () => {
+ const { scrollX, scrollY } = h.state;
+
+ mouse.downAt(80, 80);
+ mouse.moveTo(30, 30);
+ mouse.upAt(30, 30);
+
+ expect([h.state.scrollX, h.state.scrollY]).not.toEqual([scrollX, scrollY]);
+ expect(h.state.selectedElementIds).toEqual({});
+ });
+
+ it("supports canvas zoom & zoom-to-fit keyboard shortcuts", () => {
+ // ctrl+"=" zooms in (and is prevented from zooming the browser)
+ const zoom = h.state.zoom.value;
+ expect(
+ fireEvent.keyDown(document, { ctrlKey: true, code: CODES.EQUAL }),
+ ).toBe(false);
+ expect(h.state.zoom.value).toBeGreaterThan(zoom);
+
+ // ctrl+"0" resets zoom
+ fireEvent.keyDown(document, { ctrlKey: true, code: CODES.ZERO });
+ expect(h.state.zoom.value).toBe(1);
+
+ // shift+"1" fits all elements
+ const { scrollX, scrollY } = h.state;
+ fireEvent.keyDown(document, { shiftKey: true, code: CODES.ONE });
+ expect([h.state.scrollX, h.state.scrollY]).not.toEqual([scrollX, scrollY]);
+ });
+
+ it("editor is otherwise inert", () => {
+ // non-navigation shortcuts stay disabled (e.g. select all)
+ fireEvent.keyDown(document, { ctrlKey: true, key: "a", code: "KeyA" });
+ expect(h.state.selectedElementIds).toEqual({});
+
+ // no selection, no context menu
+ mouse.reset();
+ mouse.clickAt(30, 30);
+ expect(h.state.selectedElementIds).toEqual({});
+
+ rightClickCanvas();
+ expect(h.state.contextMenu).toBe(null);
+ });
+
+ it("composes with links", async () => {
+ const onLinkOpenSpy = vi.fn();
+ const windowOpenSpy = vi.spyOn(window, "open").mockReturnValue(null);
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={{ enabled: { navigation: true, links: true } }}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ onLinkOpen={(...args) => {
+ onLinkOpenSpy(...args);
+ args[1].preventDefault();
+ }}
+ />,
+ );
+
+ const rect = API.createElement({
+ type: "rectangle",
+ x: 20,
+ y: 20,
+ width: 120,
+ height: 90,
+ });
+ API.setElements([rect]);
+ API.updateElement(rect, { link: "https://excalidraw.com" });
+
+ mouse.reset();
+ mouse.moveTo(80, 65);
+ mouse.clickAt(80, 65);
+
+ expect(onLinkOpenSpy).toHaveBeenCalledTimes(1);
+ expect(onLinkOpenSpy.mock.calls[0][0]).toMatchObject({ id: rect.id });
+ windowOpenSpy.mockRestore();
+ });
+
+ it("toggling enabled.navigation at runtime re-attaches listeners", () => {
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={{ enabled: { navigation: false } }}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+ const zoom = h.state.zoom.value;
+ wheelZoom();
+ expect(h.state.zoom.value).toBe(zoom);
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={{ enabled: { navigation: true } }}
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ />,
+ );
+ wheelZoom();
+ expect(h.state.zoom.value).toBeGreaterThan(zoom);
+ });
+});
+
+describe("interaction={{ enabled: { embeds / interactiveContent } }}", () => {
+ beforeEach(() => {
+ mockBoundingClientRect();
+ });
+
+ afterEach(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ const addEmbeddable = () => {
+ const embed = API.createElement({
+ type: "embeddable",
+ x: 20,
+ y: 20,
+ width: 120,
+ height: 90,
+ });
+ API.setElements([embed]);
+ API.updateElement(embed, {
+ link: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ });
+ return embed;
+ };
+
+ it("embeds: hovering & clicking an embeddable activates it", async () => {
+ await render(
+ <Excalidraw
+ interaction={{ enabled: { embeds: true } }}
+ validateEmbeddable={true}
+ />,
+ );
+ await waitFor(() => expect(h.state.width).toBe(200));
+ const embed = addEmbeddable();
+
+ expect(h.app.isEmbedsEnabled()).toBe(true);
+ expect(h.app.isLinksEnabled()).toBe(false);
+ expect(queryContainer(".excalidraw--embeds")).not.toBe(null);
+
+ mouse.reset();
+ mouse.moveTo(80, 65);
+ expect(h.state.activeEmbeddable).toMatchObject({
+ element: expect.objectContaining({ id: embed.id }),
+ state: "hover",
+ });
+
+ mouse.clickAt(80, 65);
+ // activation is deferred (see handleIframeLikeCenterClick)
+ await waitFor(() => {
+ expect(h.state.activeEmbeddable).toMatchObject({ state: "active" });
+ });
+
+ // clicking outside deactivates (clicks inside an active embed are
+ // consumed by the embed itself)
+ mouse.clickAt(5, 5);
+ expect(h.state.activeEmbeddable).toBe(null);
+ });
+
+ it("without embeds allowed, embeddables stay inert", async () => {
+ await render(<Excalidraw interaction={false} validateEmbeddable={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+ addEmbeddable();
+
+ expect(h.app.isEmbedsEnabled()).toBe(false);
+ expect(queryContainer(".excalidraw--embeds")).toBe(null);
+
+ mouse.reset();
+ mouse.moveTo(80, 65);
+ mouse.clickAt(80, 65);
+ expect(h.state.activeEmbeddable).toBe(null);
+ });
+
+ it("interactiveContent enables links & embeds together (additive)", async () => {
+ await render(
+ <Excalidraw interaction={{ enabled: { interactiveContent: true } }} />,
+ );
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ expect(h.app.isLinksEnabled()).toBe(true);
+ expect(h.app.isEmbedsEnabled()).toBe(true);
+ // still non-interactive overall
+ expect(h.state.viewModeEnabled).toBe(true);
+ expect(h.app.isInteractionEnabled()).toBe(false);
+
+ // additive: explicit false on individual keys doesn't override the
+ // umbrella
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw
+ interaction={{
+ enabled: { interactiveContent: true, links: false, embeds: false },
+ }}
+ />,
+ );
+ expect(h.app.isLinksEnabled()).toBe(true);
+ expect(h.app.isEmbedsEnabled()).toBe(true);
+ });
+});
diff --git a/packages/excalidraw/tests/scrollConstraints.test.tsx b/packages/excalidraw/tests/scrollConstraints.test.tsx
index 2ad4e952dc..54c5afe26d 100644
--- a/packages/excalidraw/tests/scrollConstraints.test.tsx
+++ b/packages/excalidraw/tests/scrollConstraints.test.tsx
@@ -618,7 +618,7 @@ describe("setViewport lock (integration)", () => {
}
});
- it("disables zoom-to-fit actions while locked, but keeps reset-zoom enabled", async () => {
+ it("keeps zoom-to-fit actions enabled while locked, fitting the locked box", async () => {
await render(<Excalidraw />);
await waitFor(() => expect(h.state.width).toBe(200));
@@ -630,16 +630,37 @@ describe("setViewport lock (integration)", () => {
target: [0, 0, 500, 500],
fit: "scale-down",
animation: false,
- lock: { scroll: true },
+ lock: { scroll: true, zoom: true },
});
});
- // reset-zoom stays available (it re-clamps into the lock)
expect(h.app.actionManager.isActionEnabled(actionResetZoom)).toBe(true);
- expect(h.app.actionManager.isActionEnabled(actionZoomToFit)).toBe(false);
+ expect(h.app.actionManager.isActionEnabled(actionZoomToFit)).toBe(true);
expect(h.app.actionManager.isActionEnabled(actionZoomToFitSelection)).toBe(
- false,
+ true,
);
+
+ const restingViewport = {
+ scrollX: h.state.scrollX,
+ scrollY: h.state.scrollY,
+ zoom: h.state.zoom.value,
+ };
+
+ // zoom & pan away from the resting viewport...
+ React.act(() => {
+ h.app.actionManager.executeAction(actionZoomIn);
+ h.app.actionManager.executeAction(actionZoomIn);
+ });
+ expect(h.state.zoom.value).toBeGreaterThan(restingViewport.zoom);
+
+ // ...then zoom-to-fit → lands back on the locked box, not the elements
+ // (the scene is empty, so fitting elements would be degenerate anyway)
+ React.act(() => {
+ h.app.actionManager.executeAction(actionZoomToFit);
+ });
+ expect(h.state.zoom.value).toBeCloseTo(restingViewport.zoom);
+ expect(h.state.scrollX).toBeCloseTo(restingViewport.scrollX);
+ expect(h.state.scrollY).toBeCloseTo(restingViewport.scrollY);
});
it("resets zoom to the locked minimum zoom when zoom is locked", async () => {
diff --git a/packages/excalidraw/tests/viewMode.test.tsx b/packages/excalidraw/tests/viewMode.test.tsx
index 0a94055c79..38cb6f989e 100644
--- a/packages/excalidraw/tests/viewMode.test.tsx
+++ b/packages/excalidraw/tests/viewMode.test.tsx
@@ -6,7 +6,20 @@ import { Excalidraw } from "../index";
import { API } from "./helpers/api";
import { Keyboard, Pointer, UI } from "./helpers/ui";
-import { render, GlobalTestState } from "./test-utils";
+import { getTextEditor, updateTextEditor } from "./queries/dom";
+import {
+ fireEvent,
+ render,
+ GlobalTestState,
+ mockBoundingClientRect,
+ restoreOriginalGetBoundingClientRect,
+ waitFor,
+} from "./test-utils";
+
+const { h } = window;
+
+const queryContainer = (selector: string) =>
+ GlobalTestState.renderResult.container.querySelector(selector);
const mouse = new Pointer("mouse");
const touch = new Pointer("touch");
@@ -15,7 +28,13 @@ const pointerTypes = [mouse, touch, pen];
describe("view mode", () => {
beforeEach(async () => {
- await render(<Excalidraw />);
+ mockBoundingClientRect();
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+ });
+
+ afterEach(() => {
+ restoreOriginalGetBoundingClientRect();
});
it("after switching to view mode – cursor type should be pointer", async () => {
@@ -67,4 +86,61 @@ describe("view mode", () => {
);
});
});
+
+ it("submits active text editing when entering view mode", async () => {
+ const text = API.createElement({
+ type: "text",
+ text: "before",
+ x: 20,
+ y: 20,
+ });
+ API.setElements([text]);
+ API.setSelectedElements([text]);
+ Keyboard.keyPress(KEYS.ENTER);
+
+ const editor = await getTextEditor();
+ updateTextEditor(editor, "committed before view mode");
+
+ GlobalTestState.renderResult.rerender(
+ <Excalidraw viewModeEnabled={true} handleKeyboardGlobally={true} />,
+ );
+
+ await waitFor(() => {
+ expect(h.state.editingTextElement).toBe(null);
+ expect(queryContainer(".excalidraw-wysiwyg")).toBe(null);
+ });
+ expect(h.elements.find((element) => element.id === text.id)).toMatchObject({
+ originalText: "committed before view mode",
+ });
+ });
+
+ it("commits frame-name editing when entering view mode", async () => {
+ const frame = API.createElement({
+ type: "frame",
+ x: 20,
+ y: 30,
+ width: 80,
+ height: 50,
+ });
+ API.setElements([frame]);
+ API.updateElement(frame, { name: "before" });
+ API.setAppState({ editingFrame: frame.id });
+
+ const frameNameInput = await waitFor(() => {
+ const input = queryContainer(".frame-name input");
+ expect(input).not.toBe(null);
+ return input as HTMLInputElement;
+ });
+ fireEvent.change(frameNameInput, { target: { value: " committed " } });
+
+ API.setAppState({ viewModeEnabled: true });
+
+ await waitFor(() => {
+ expect(h.state.editingFrame).toBe(null);
+ expect(queryContainer(".frame-name input")).toBe(null);
+ });
+ expect(h.elements.find((element) => element.id === frame.id)).toMatchObject(
+ { name: "committed" },
+ );
+ });
});
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index bb0a322dc1..b3625ac0e2 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -370,7 +370,10 @@ export interface AppState {
outline: boolean;
clip: boolean;
};
- editingFrame: string | null;
+ /**
+ * frame-like element whose name is currently being edited
+ */
+ editingFrame: ExcalidrawFrameLikeElement["id"] | null;
elementsToHighlight: readonly NonDeletedExcalidrawElement[] | null;
/**
* set when a new text is created or when an existing text is being edited
@@ -630,6 +633,62 @@ export type OnExportProgress = {
progress?: number;
};
+export type InteractionConfig = {
+ /**
+ * Interactions that stay enabled while the editor is otherwise
+ * non-interactive. Opt-in: anything omitted or `false` is disabled.
+ */
+ enabled?: {
+ /**
+ * Element links render their link icon and stay clickable — clicking
+ * anywhere on a linked element opens the link, same as in view mode.
+ * When disabled, link icons are not rendered at all.
+ *
+ * @default false
+ */
+ links?: boolean;
+ /**
+ * Embeddable & iframe elements stay interactive — hovering & clicking
+ * activates them so their content can be used, same as in view mode.
+ *
+ * @default false
+ */
+ embeds?: boolean;
+ /**
+ * Umbrella for all interactive content on canvas — shorthand for
+ * enabling `links` & `embeds` (and future interactive content kinds)
+ * together. Additive: `interactiveContent: true` enables them
+ * regardless of their individual values.
+ *
+ * @default false
+ */
+ interactiveContent?: boolean;
+ /**
+ * Canvas navigation — panning (pointer drag, wheel) and zooming
+ * (ctrl/cmd + wheel, pinch, and the canvas zoom & zoom-to-fit shortcuts:
+ * ctrl/cmd +/-/0, shift+1/2/3), same as in view mode. Respects
+ * `appState.scrollConstraints` if set, so it composes with viewport
+ * locking. The rest of the keyboard stays disabled. Note the editor
+ * consumes wheel & touch input again when enabled, so the page no
+ * longer scrolls over the editor.
+ *
+ * @default false
+ */
+ navigation?: boolean;
+ /**
+ * Whether the browser's own zoom remains available over the editor —
+ * ctrl/cmd + wheel, pinch, and (while the editor has focus)
+ * ctrl/cmd +/-/0 shortcuts. Prevented by default, mirroring the
+ * interactive editor. Regular page scrolling stays available either way.
+ * With `navigation` enabled, the zoom input (wheel, pinch, keyboard
+ * shortcuts) zooms the canvas instead either way, making this moot.
+ *
+ * @default false
+ */
+ browserZoom?: boolean;
+ };
+};
+
export interface ExcalidrawProps {
onChange?: (
elements: readonly OrderedExcalidrawElement[],
@@ -698,6 +757,39 @@ export interface ExcalidrawProps {
) => JSX.Element | null;
langCode?: Language["code"];
viewModeEnabled?: boolean;
+ /**
+ * Whether the editor accepts user input (pointer, keyboard, wheel, touch,
+ * clipboard, drag&drop). When `false`, the scene still renders and reacts
+ * to programmatic updates (imperative API), but the user cannot affect it
+ * in any way. Implies view mode.
+ *
+ * Pass a config object to keep specific interactions enabled while the
+ * editor is otherwise non-interactive (see `InteractionConfig`):
+ *
+ * ```tsx
+ * <Excalidraw interaction={{ enabled: { links: true } }} />
+ * ```
+ *
+ * @default true
+ */
+ interaction?: boolean | InteractionConfig;
+ /**
+ * Whether Excalidraw's default UI is rendered — toolbar, default menus,
+ * footer controls, sidebars, and canvas popups. Host UI passed through
+ * children (including exported components such as `MainMenu` and `Footer`)
+ * or render props continues to render, together with any supporting dialogs
+ * it opens.
+ *
+ * Canvas content (elements, text editing surface, frame names, embeds) still
+ * renders, and the editor remains interactive unless `interaction` is set to
+ * `false`.
+ *
+ * NOTE: this is WIP and what default UI is/is not rendered when ui=false
+ * may yet change.
+ *
+ * @default true
+ */
+ ui?: boolean;
zenModeEnabled?: boolean;
gridModeEnabled?: boolean;
objectsSnapModeEnabled?: boolean;
@@ -919,6 +1011,9 @@ export type AppClassProperties = {
bindModeHandler: App["bindModeHandler"];
setAppState: App["setAppState"];
+
+ isInteractionEnabled: App["isInteractionEnabled"];
+ isNavigationEnabled: App["isNavigationEnabled"];
};
export type PointerDownState = Readonly<{