Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

fix(editor): improve UX around locked animations (#11671)

David Luzar374716304a7d
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index 2e2ad18c7d..653bfdbf94 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -15,11 +15,11 @@ Please add the latest change on the top under the correct section.
## Excalidraw API
-### Host-controlled active tool (2026-07-14)
+### Host-controlled active tool (2026-07-14) [#11665](https://github.com/excalidraw/excalidraw/pull/11665)
- Added `activeTool` prop (`{ type: ToolType } | { type: "custom"; customType: string }`) for forcing the active editor tool (controlled). While set, user- and API-driven tool switching is ignored — `setActiveTool` refuses non-matching activations with a console warning, non-forced toolbar buttons render disabled, and the tool-lock toggle (`Q`) is inert — and the editor snaps back if internal flows reset the tool (e.g. `restore()` on scene load). The forced tool behaves as if locked — it doesn't revert to selection after use and drawn elements aren't auto-selected — without mutating `appState.activeTool.locked`, so the user's persisted padlock preference stays untouched. Unset the prop to return tool control to the editor (the current tool stays active). The forced tool must be activatable to take effect — not disabled via `UIOptions.tools`, and (while non-interactive) allowed via `interaction.enabled.tools`; otherwise the editor stays on the `selection` tool and applies the forced tool once it becomes activatable. `image` cannot be forced (its activation opens the file picker). Composes with `interaction.enabled.tools` for presentation-style hosts: force `laser` for the presenter, `selection` + `interaction={false}` for viewers.
-### User-driven tools while non-interactive (2026-07-14)
+### User-driven tools while non-interactive (2026-07-14) [#11665](https://github.com/excalidraw/excalidraw/pull/11665)
- Added `interaction.enabled.tools` (`{ laser?: boolean; custom?: boolean }`) — the listed tools stay user-driven while the editor is otherwise non-interactive: pointer input keeps driving the tool when it's the active tool. With `laser` enabled, pointer strokes draw laser trails and pointer positions keep broadcasting through `onPointerUpdate`, so e.g. collaborators see a presenter's laser & cursor while the presenter's editor is otherwise inert. With `custom` enabled, custom tools (`activeTool.type === "custom"`) keep receiving `onPointerDown` / `onPointerUp` — activate them with `locked: true` or they revert to the selection tool (and go inert) after the first pointer interaction. Enabling a tool does not enable user-driven tool _switching_ — the keyboard stays disabled and tool selection remains host-driven (`ExcalidrawAPI.setActiveTool`). Composes with `enabled.navigation`: the enabled tool wins the primary-pointer drag, while wheel input (and wheel-button drag) still pans/zooms. The editor consumes touch input over the canvas while the active tool is enabled (strokes don't scroll the page).
@@ -31,7 +31,7 @@ Please add the latest change on the top under the correct section.
- 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
+### Tool system & toolbar rework [#11649](https://github.com/excalidraw/excalidraw/pull/11649)
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.
@@ -88,9 +88,9 @@ The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>
#### Features
-- `setViewport({ ..., lock })` locks the viewport to the resolved target: `lock.scroll` constrains panning to the target box and `lock.zoom` makes the resolved zoom the minimum zoom (zooming in stays allowed). When the navigation is animated, the lock is installed once the viewport settles. `setViewport(null)` clears an active lock without navigating; a navigation without `lock` also supersedes a previously installed one.
+- `setViewport({ ..., lock })` locks the viewport to the resolved target: `lock.scroll` constrains panning to the target box and `lock.zoom` makes the resolved zoom the minimum zoom (zooming in stays allowed). During an animated navigation into a locked viewport, user pan, zoom, fit, and page-navigation input is consumed without mutating or cancelling the transition; the destination lock is installed together with the final viewport once the animation settles. A newer `setViewport(...)` supersedes the transition and starts from the currently rendered viewport. `setViewport(null)` cancels a pending transition and clears any pending or active lock without navigating; a navigation without `lock` likewise supersedes any lock.
-- `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.
+- `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 wheel input settles or the active pointer or multi-finger gesture is released. Defaults to `true` = `DEFAULT_OVERSCROLL` (150px, exported from the package root); pass a number to customize, or `false` / `0` for a rigid lock. Zooming itself remains hard-clamped against the lock, gliding along its edge instead of overscrolling, and stays available during snap-back without cancelling the rubberband animation or discarding its existing screen-space overscroll.
- 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)
diff --git a/packages/excalidraw/actions/actionCanvas.tsx b/packages/excalidraw/actions/actionCanvas.tsx
index c97b110239..7033ca9025 100644
--- a/packages/excalidraw/actions/actionCanvas.tsx
+++ b/packages/excalidraw/actions/actionCanvas.tsx
@@ -33,8 +33,11 @@ import { useAppStateValue } from "../hooks/useAppStateValue";
import { t } from "../i18n";
import { getNormalizedZoom } from "../scene";
-import { getStateForZoom } from "../scene/zoom";
-import { constrainScrollState, zoomToFitBounds } from "../viewport";
+import {
+ constrainScrollState,
+ getViewportForZoomWithScrollConstraints,
+ zoomToFitBounds,
+} from "../viewport";
import { getShortcutKey } from "../shortcut";
import { register } from "./register";
@@ -132,7 +135,7 @@ export const actionZoomIn = register({
perform: (_elements, appState, _, app) => {
const nextState = {
...appState,
- ...getStateForZoom(
+ ...getViewportForZoomWithScrollConstraints(
{
viewportX: appState.width / 2 + appState.offsetLeft,
viewportY: appState.height / 2 + appState.offsetTop,
@@ -143,7 +146,7 @@ export const actionZoomIn = register({
userToFollow: null,
};
return {
- appState: { ...nextState, ...constrainScrollState(nextState) },
+ appState: nextState,
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
},
@@ -179,7 +182,7 @@ export const actionZoomOut = register({
perform: (_elements, appState, _, app) => {
const nextState = {
...appState,
- ...getStateForZoom(
+ ...getViewportForZoomWithScrollConstraints(
{
viewportX: appState.width / 2 + appState.offsetLeft,
viewportY: appState.height / 2 + appState.offsetTop,
@@ -190,7 +193,7 @@ export const actionZoomOut = register({
userToFollow: null,
};
return {
- appState: { ...nextState, ...constrainScrollState(nextState) },
+ appState: nextState,
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
},
@@ -231,7 +234,7 @@ export const actionResetZoom = register({
: 1;
const nextState = {
...appState,
- ...getStateForZoom(
+ ...getViewportForZoomWithScrollConstraints(
{
viewportX: appState.width / 2 + appState.offsetLeft,
viewportY: appState.height / 2 + appState.offsetTop,
@@ -242,8 +245,7 @@ export const actionResetZoom = register({
userToFollow: null,
};
return {
- // re-clamp so the reset can't escape an active scroll/zoom lock
- appState: { ...nextState, ...constrainScrollState(nextState) },
+ appState: nextState,
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
},
@@ -311,7 +313,7 @@ export const actionZoomToFitSelectionInViewport = register({
userToFollow: null,
},
fit: "scale-down",
- canvasOffsets: app.getViewportOffsets(),
+ canvasOffsets: app.viewport.getOffsets(),
});
return {
...result,
@@ -356,7 +358,7 @@ export const actionZoomToFitSelection = register({
userToFollow: null,
},
fit: "contain",
- canvasOffsets: app.getViewportOffsets(),
+ canvasOffsets: app.viewport.getOffsets(),
});
return {
...result,
@@ -395,7 +397,7 @@ export const actionZoomToFit = register({
userToFollow: null,
},
fit: "scale-down",
- canvasOffsets: app.getViewportOffsets(),
+ canvasOffsets: app.viewport.getOffsets(),
});
return {
...result,
diff --git a/packages/excalidraw/actions/manager.tsx b/packages/excalidraw/actions/manager.tsx
index e4e037c6b6..75d31e4773 100644
--- a/packages/excalidraw/actions/manager.tsx
+++ b/packages/excalidraw/actions/manager.tsx
@@ -86,6 +86,9 @@ export class ActionManager {
actions.forEach((action) => this.registerAction(action));
}
+ private isActionBlockedByViewportTransition = (action: Action) =>
+ action.navigation === true && this.app.viewport.isLockedTransitionPending;
+
handleKeyDown(event: React.KeyboardEvent | KeyboardEvent) {
if (!this.app.isInteractionEnabled() && !this.app.isNavigationEnabled()) {
return false;
@@ -127,6 +130,12 @@ export class ActionManager {
return false;
}
+ if (this.isActionBlockedByViewportTransition(action)) {
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ }
+
const elements = this.getElementsIncludingDeleted();
const appState = this.getAppState();
const value = null;
@@ -155,6 +164,10 @@ export class ActionManager {
return;
}
+ if (this.isActionBlockedByViewportTransition(action)) {
+ return;
+ }
+
const elements = this.getElementsIncludingDeleted();
const appState = this.getAppState();
@@ -182,6 +195,10 @@ export class ActionManager {
const elements = this.getElementsIncludingDeleted();
const appState = this.getAppState();
const updateData = (formState?: any) => {
+ if (this.isActionBlockedByViewportTransition(action)) {
+ return;
+ }
+
trackAction(action, "ui", appState, elements, this.app, formState);
this.updater(
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index 191336a170..4aade19fac 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -369,7 +369,6 @@ import {
hasBackground,
isSomeElementSelected,
} from "../scene";
-import { getStateForZoom } from "../scene/zoom";
import {
dataURLToString,
generateIdFromFile,
@@ -410,13 +409,7 @@ import {
import { Renderer } from "../scene/Renderer";
import {
type SetViewportOptions,
- SCROLL_TO_CONTENT_ANIMATION_KEY,
- setViewportToBounds,
- resolveViewportTarget,
- getConstrainedTargetViewport,
- constrainScrollState,
- animateToConstraints,
- isViewportOverscrolled,
+ getViewportForZoomWithScrollConstraints,
} from "../viewport";
import { ElementCanvasButtons } from "../components/ElementCanvasButtons";
import { LaserTrails } from "../laserTrails";
@@ -429,7 +422,6 @@ import { LassoTrail } from "../lasso";
import { EraserTrail } from "../eraser";
import { getShortcutKey } from "../shortcut";
import { tryParseSpreadsheet } from "../charts";
-import { AnimationController } from "../renderer/animation";
import ConvertElementTypePopup, {
getConversionTypeFromElements,
@@ -440,6 +432,7 @@ import ConvertElementTypePopup, {
import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";
import { AppCursor } from "./App.cursor";
import { AppFlowchart } from "./App.flowchart";
+import { AppViewport, RIGHT_SIDEBAR_WIDTH } from "./App.viewport";
import BraveMeasureTextError from "./BraveMeasureTextError";
import { ContextMenu, CONTEXT_MENU_SEPARATOR } from "./ContextMenu";
import { activeEyeDropperAtom } from "./EyeDropper";
@@ -496,11 +489,6 @@ import type {
ExcalidrawImperativeAPIEventMap,
GenerateDiagramToCode,
NullableGridSize,
- Offsets,
- ViewportOffsets,
- ViewportOffsetsOptions,
- ViewportUIDock,
- ViewportUIName,
} from "../types";
import type { RoughCanvas } from "roughjs/bin/canvas";
import type { Action, ActionResult } from "../actions/types";
@@ -508,18 +496,6 @@ import type { Action, ActionResult } from "../actions/types";
const AppContext = React.createContext<AppClassProperties>(null!);
const AppPropsContext = React.createContext<AppProps>(null!);
-/** single source of truth for the `--right-sidebar-width` CSS variable */
-const RIGHT_SIDEBAR_WIDTH = 302;
-
-/**
- * Approximate styles panel footprints (panel width + editor edge inset),
- * used by `getViewportOffsets` to reserve space for the panel before it was
- * ever rendered (= measured). Keep roughly in sync with the CSS
- * (`.App-menu__left` width / `.compact-shape-actions-island` min-width +
- * `--editor-container-padding`).
- */
-const STYLES_PANEL_APPROX_WIDTH = { full: 216, compact: 64 };
-
const editorInterfaceContextInitialValue: EditorInterface = {
formFactor: "desktop",
desktopUIMode: "full",
@@ -623,10 +599,6 @@ const YOUTUBE_VIDEO_STATES = new Map<
const MAX_EMBEDDABLE_VIEWPORT_SCALE = 4;
-/** how long after the last pan/zoom we animate the rubberband back into the
- * scroll constraints box */
-const SCROLL_CONSTRAINTS_SNAP_BACK_DELAY = 200;
-
let IS_PLAIN_PASTE = false;
let IS_PLAIN_PASTE_TIMER = 0;
let PLAIN_PASTE_TOAST_SHOWN = false;
@@ -651,16 +623,6 @@ class App extends React.Component<AppProps, AppState> {
editorInterfaceContextInitialValue,
);
- /**
- * Last-measured footprints of named viewport UI surfaces
- * (`data-viewport-ui-name`), so `getViewportOffsets` can reserve space
- * for them while they're hidden.
- */
- private viewportUILastMeasured = new Map<
- ViewportUIName,
- { side: "left" | "right"; offset: number }
- >();
-
private excalidrawContainerRef = React.createRef<HTMLDivElement>();
public scene: Scene;
@@ -717,6 +679,11 @@ class App extends React.Component<AppProps, AppState> {
public flowchart: AppFlowchart = new AppFlowchart(this);
public cursor: AppCursor = new AppCursor(this);
+ public viewport: AppViewport = new AppViewport(this, {
+ getContainer: () => this.excalidrawContainerRef.current,
+ getStylesPanelMode: () => this.stylesPanelMode,
+ isGestureActive: () => gesture.pointers.size >= 2 || isPanning,
+ });
bindModeHandler: ReturnType<typeof setTimeout> | null = null;
private textWysiwygSubmitHandler: ReturnType<typeof textWysiwyg> | null =
@@ -740,8 +707,6 @@ class App extends React.Component<AppProps, AppState> {
private removedArrowheads = new Map<string, Arrowhead>();
/** previous frame pointer coords */
previousPointerMoveCoords: { x: number; y: number } | null = null;
- lastViewportPosition = { x: 0, y: 0 };
-
laserTrails = new LaserTrails(this);
eraserTrail = new EraserTrail(this);
lassoTrail = new LassoTrail(this);
@@ -797,8 +762,8 @@ class App extends React.Component<AppProps, AppState> {
history: {
clear: this.resetHistory,
},
- setViewport: this.setViewport,
- getViewportOffsets: this.getViewportOffsets,
+ setViewport: this.viewport.setViewport,
+ getViewportOffsets: this.viewport.getOffsets,
getSceneElements: this.getSceneElements,
getAppState: () => this.state,
getFiles: () => this.files,
@@ -3144,7 +3109,7 @@ class App extends React.Component<AppProps, AppState> {
/**
* PageUp/PageDown scroll the canvas by a page — vertically, or
* horizontally with shift. Respects `appState.scrollConstraints`
- * (via `translateCanvas`).
+ * (via `viewport.translate`).
*/
private maybeHandlePageScrollKeyDown = (
event: KeyboardEvent | React.KeyboardEvent,
@@ -3159,11 +3124,11 @@ class App extends React.Component<AppProps, AppState> {
offset = -offset;
}
if (event.shiftKey) {
- this.translateCanvas((state) => ({
+ this.viewport.translate((state) => ({
scrollX: state.scrollX + offset,
}));
} else {
- this.translateCanvas((state) => ({
+ this.viewport.translate((state) => ({
scrollY: state.scrollY + offset,
}));
}
@@ -3549,21 +3514,16 @@ class App extends React.Component<AppProps, AppState> {
restoredNonDeletedElements,
) as NonDeletedSceneElementsMap;
- const { bounds } = resolveViewportTarget(
- initialViewport.target,
+ const initialViewportState = this.viewport.resolveInitialViewport(
+ initialViewport,
restoredElementsMap,
viewportAppState,
);
- if (bounds) {
+ if (initialViewportState) {
restoredAppState = {
...restoredAppState,
- ...getConstrainedTargetViewport(viewportAppState, bounds, {
- ...initialViewport,
- // resolved here (post-mount) so ui-derived offsets measure the
- // actually-rendered editor UI
- offsets: this.resolveViewportOffsets(initialViewport.offsets),
- }),
+ ...initialViewportState,
};
}
} else if (initialData?.scrollToContent) {
@@ -3592,7 +3552,7 @@ class App extends React.Component<AppProps, AppState> {
});
if (isElementLink(window.location.href)) {
- this.setViewport({
+ this.viewport.setViewport({
target: window.location.href,
fit: "scale-down",
animation: false,
@@ -3648,7 +3608,7 @@ class App extends React.Component<AppProps, AppState> {
// the panel footprint differs between modes (compact vs full), so a
// measurement taken in the previous mode no longer applies
- this.viewportUILastMeasured.delete("stylesPanel");
+ this.viewport.invalidateUIOffset("stylesPanel");
if (prevStylesPanelMode !== "full" && nextStylesPanelMode === "full") {
this.setState((prevState) => ({
@@ -3807,6 +3767,7 @@ class App extends React.Component<AppProps, AppState> {
this.imageCache.clear();
this.resizeObserver?.disconnect();
this.unmounted = true;
+ this.viewport.destroy();
this.removeEventListeners();
this.library.destroy();
this.laserTrails.stop();
@@ -3910,7 +3871,7 @@ class App extends React.Component<AppProps, AppState> {
this.handleNavigationModeKeyDown as EventListener,
false,
),
- // wheel zoom is anchored on `lastViewportPosition`
+ // wheel zoom is anchored on `viewport.lastPosition`
addEventListener(
document,
EVENT.POINTER_MOVE,
@@ -4239,8 +4200,7 @@ class App extends React.Component<AppProps, AppState> {
// on the target viewport.
const scrolledOutside =
// hide when editing text
- this.state.editingTextElement ||
- AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)
+ this.state.editingTextElement || this.viewport.isAnimating
? false
: !this.visibleElements.length && this.hasRenderableElements;
if (this.state.scrolledOutside !== scrolledOutside) {
@@ -4407,8 +4367,8 @@ class App extends React.Component<AppProps, AppState> {
) {
const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
{
- clientX: this.lastViewportPosition.x,
- clientY: this.lastViewportPosition.y,
+ clientX: this.viewport.lastPosition.x,
+ clientY: this.viewport.lastPosition.y,
},
this.state,
);
@@ -4584,8 +4544,8 @@ class App extends React.Component<AppProps, AppState> {
}
const elementUnderCursor = document.elementFromPoint(
- this.lastViewportPosition.x,
- this.lastViewportPosition.y,
+ this.viewport.lastPosition.x,
+ this.viewport.lastPosition.y,
);
if (
event &&
@@ -4644,13 +4604,13 @@ class App extends React.Component<AppProps, AppState> {
typeof opts.position === "object"
? opts.position.clientX
: opts.position === "cursor"
- ? this.lastViewportPosition.x
+ ? this.viewport.lastPosition.x
: this.state.width / 2 + this.state.offsetLeft;
const clientY =
typeof opts.position === "object"
? opts.position.clientY
: opts.position === "cursor"
- ? this.lastViewportPosition.y
+ ? this.viewport.lastPosition.y
: this.state.height / 2 + this.state.offsetTop;
const { x, y } = viewportCoordsToSceneCoords(
@@ -4775,7 +4735,7 @@ class App extends React.Component<AppProps, AppState> {
);
if (opts.fit) {
- this.setViewport({
+ this.viewport.setViewport({
target: duplicatedElements,
fit: opts.fit,
animation: false,
@@ -4840,8 +4800,8 @@ class App extends React.Component<AppProps, AppState> {
private addTextFromPaste(text: string, isPlainPaste = false) {
const { x, y } = viewportCoordsToSceneCoords(
{
- clientX: this.lastViewportPosition.x,
- clientY: this.lastViewportPosition.y,
+ clientX: this.viewport.lastPosition.x,
+ clientY: this.viewport.lastPosition.y,
},
this.state,
);
@@ -4979,8 +4939,7 @@ class App extends React.Component<AppProps, AppState> {
gesture.pointers.size < 2 &&
this.state.scrollConstraints
) {
- this.snapBackToScrollConstraintsDebounced.cancel();
- this.snapBackToScrollConstraints();
+ this.viewport.releaseOverscroll();
}
};
@@ -5047,138 +5006,6 @@ class App extends React.Component<AppProps, AppState> {
});
};
- /**
- * Zooms on canvas viewport center
- */
- zoomCanvas = (
- /**
- * Decimal fraction, auto-clamped between MIN_ZOOM and MAX_ZOOM.
- * 1 = 100% zoom, 2 = 200% zoom, 0.5 = 50% zoom
- */
- value: number,
- ) => {
- this.setState((state) => {
- const nextState = {
- ...state,
- ...getStateForZoom(
- {
- viewportX: state.width / 2 + state.offsetLeft,
- viewportY: state.height / 2 + state.offsetTop,
- nextZoom: getNormalizedZoom(value),
- },
- state,
- ),
- };
- // re-clamp so a programmatic zoom can't escape an active scroll/zoom lock
- return { ...nextState, ...constrainScrollState(nextState) };
- });
- };
-
- /**
- * Navigates the viewport to a target and, optionally, locks pan/zoom to it.
- * The resolved target box drives both the navigation (pan + zoom per
- * `fit`) and the lock: the operations chain — the viewport animates onto
- * the target, then the lock is installed against the settled viewport.
- *
- * Passing `null` clears any active lock without navigating.
- */
- /**
- * Resolves user-supplied viewport offsets ({@link ViewportOffsets}) into
- * concrete per-side pixel values: static sides are used as-is, and when
- * `ui` is set, the remaining sides are derived from the currently
- * rendered editor UI (via `getViewportOffsets`).
- *
- * Must be called at the time the offsets are applied (not e.g. cached at
- * props-definition time), so the UI-derived values reflect the actual
- * rendered UI.
- */
- private resolveViewportOffsets = (
- offsets: ViewportOffsets | undefined,
- ): Offsets | undefined => {
- if (!offsets) {
- return offsets;
- }
-
- const { ui, ...staticOffsets } = offsets;
-
- if (!ui) {
- return staticOffsets;
- }
-
- const uiOffsets = this.getViewportOffsets(ui === true ? undefined : ui);
-
- // static sides win over the ui-derived values (incl. `ui`'s own
- // side overrides)
- return {
- top: staticOffsets.top ?? uiOffsets.top,
- right: staticOffsets.right ?? uiOffsets.right,
- bottom: staticOffsets.bottom ?? uiOffsets.bottom,
- left: staticOffsets.left ?? uiOffsets.left,
- };
- };
-
- setViewport = (opts: SetViewportOptions | null) => {
- // `null` clears all active locks
- if (opts === null) {
- if (this.state.scrollConstraints) {
- this.setState({ scrollConstraints: null });
- }
- return;
- }
-
- const { target, fit, lock, animation } = opts;
- const offsets = this.resolveViewportOffsets(opts.offsets);
-
- // resolve the target to a scene-coordinate box.
- const { bounds, type } = resolveViewportTarget(
- target,
- this.scene.getNonDeletedElementsMap(),
- this.state,
- );
-
- if (!bounds) {
- if (type === "link") {
- this.setState({
- toast: {
- message: t("elementLink.notFound"),
- duration: 3000,
- closable: true,
- },
- });
- }
- return;
- }
-
- // capture the viewport we'll land on now, so the lock can be installed
- // against the intended final state even if the last animation frame hasn't
- // committed yet.
- const viewportUpdate = getConstrainedTargetViewport(this.state, bounds, {
- fit,
- offsets,
- lock,
- });
-
- // chain: once the scroll/zoom has settled, install (or clear) the lock
- const installLock = () => {
- if (!viewportUpdate.scrollConstraints && !this.state.scrollConstraints) {
- // no lock requested and none to supersede
- return;
- }
-
- flushSync(() => {
- this.setState(viewportUpdate);
- });
- };
-
- setViewportToBounds(
- this.state,
- bounds,
- { fit, animation, offsets },
- this.setState.bind(this),
- installLock,
- );
- };
-
// scroll `elements` into view only if they aren't already fully visible.
// Targets their bounds rather than the elements so it also works for
// elements not yet committed to the canvas.
@@ -5197,13 +5024,13 @@ class App extends React.Component<AppProps, AppState> {
zoom: this.state.zoom,
},
this.scene.getNonDeletedElementsMap(),
- this.getViewportOffsets(),
+ this.viewport.getOffsets(),
)
) {
return;
}
- this.setViewport({
+ this.viewport.setViewport({
target: getCommonBounds(elements),
fit: "scale-down",
animation: { duration: 300 },
@@ -5217,80 +5044,6 @@ class App extends React.Component<AppProps, AppState> {
}
};
- /** use when changing scrollX/scrollY/zoom based on user interaction */
- private translateCanvas = <K extends keyof AppState>(
- state:
- | AppState
- | Pick<AppState, K>
- | null
- | ((
- prevState: Readonly<AppState>,
- props: Readonly<AppProps>,
- ) => AppState | Pick<AppState, K> | null),
- opts?: {
- /** set when the caller has already hard-clamped the update's zoom
- * component against the scroll lock — the update then gets the pan
- * rubberband give instead of the zoom hard clamp (see the touch
- * pinch handler, which composes both in one update) */
- zoomPreConstrained?: boolean;
- },
- ) => {
- AnimationController.cancel(SCROLL_TO_CONTENT_ANIMATION_KEY);
- this.setState({ shouldCacheIgnoreZoom: false });
- this.maybeUnfollowRemoteUser();
-
- const prevZoom = this.state.zoom.value;
- this.setState(state);
-
- // constrain against the scroll lock; queued so it sees the update above
- this.setState((prevState) => {
- if (!prevState.scrollConstraints) {
- return null;
- }
- // zoom changes are hard-clamped (no rubberband give): the post-zoom
- // scroll is a continuous function of the zoom origin, so clamping it
- // effectively slides the origin to the nearest focal point that keeps
- // the viewport within bounds — zooming glides along the lock edge
- // instead of overscrolling and snapping back on every zoom tick.
- // Panning keeps the soft give, snapping back once interaction settles.
- const zoomed =
- !opts?.zoomPreConstrained && prevState.zoom.value !== prevZoom;
- const overscroll = zoomed ? 0 : prevState.scrollConstraints.overscroll;
- if (overscroll > 0) {
- this.snapBackToScrollConstraintsDebounced();
- }
- return constrainScrollState(prevState, overscroll);
- });
- };
-
- /** clamps scroll/zoom back into `appState.scrollConstraints` (no-op when
- * unconstrained). Runs as a queued update, so it sees the preceding change.
- * `overscroll` (screen px) relaxes the bounds for rubberbanding. */
- private constrainViewportToScrollConstraints = (overscroll = 0) => {
- this.setState((prevState) =>
- prevState.scrollConstraints
- ? constrainScrollState(prevState, overscroll)
- : null,
- );
- };
-
- /** animates an overscrolled viewport back inside the constraint box */
- private snapBackToScrollConstraints = () => {
- // withhold the rubberband while a multi-touch gesture is still engaged —
- // snapping back mid-gesture (e.g. while holding a pinch or between
- // two-finger pans) fights the user's fingers and reads as jerky. It is
- // released on gesture end instead (see `removePointer`).
- if (this.unmounted || gesture.pointers.size >= 2) {
- return;
- }
- animateToConstraints(this.state, (viewport) => this.setState(viewport));
- };
-
- private snapBackToScrollConstraintsDebounced = debounce(
- this.snapBackToScrollConstraints,
- SCROLL_CONSTRAINTS_SNAP_BACK_DELAY,
- );
-
setToast = (toast: AppState["toast"]) => {
this.setState({ toast });
};
@@ -5497,144 +5250,11 @@ class App extends React.Component<AppProps, AppState> {
private updateCurrentCursorPosition = withBatchedUpdates(
(event: MouseEvent) => {
- this.lastViewportPosition.x = event.clientX;
- this.lastViewportPosition.y = event.clientY;
+ this.viewport.lastPosition.x = event.clientX;
+ this.viewport.lastPosition.y = event.clientY;
},
);
- /**
- * top/right/bottom/left override the final offsets for those sides.
- *
- * Default side offsets are measured from the currently rendered UI
- * surfaces marked with the `data-viewport-ui` attribute (see
- * {@link ViewportUIDock}), plus padding.
- *
- * See {@link ViewportOffsetsOptions} for the individual options
- * (padding, per-side overrides, reserving space for hidden surfaces).
- */
- public getViewportOffsets = (opts?: ViewportOffsetsOptions): Offsets => {
- const excalidrawContainer = this.excalidrawContainerRef?.current;
- const excalidrawContainerRect =
- excalidrawContainer?.getBoundingClientRect();
- const isRTL = getLanguage().rtl;
-
- const measuredOffsets = { top: 0, right: 0, bottom: 0, left: 0 };
- const renderedSurfaces = new Set<ViewportUIName>();
-
- if (excalidrawContainer && excalidrawContainerRect) {
- for (const node of excalidrawContainer.querySelectorAll<HTMLElement>(
- "[data-viewport-ui]",
- )) {
- const domRect = node.getBoundingClientRect();
- // measured relative to the excalidraw container (which the offsets
- // are relative to), so that embedding the editor at a viewport
- // offset doesn't skew the values
- const rect = {
- top: domRect.top - excalidrawContainerRect.top,
- right: domRect.right - excalidrawContainerRect.left,
- bottom: domRect.bottom - excalidrawContainerRect.top,
- left: domRect.left - excalidrawContainerRect.left,
- width: domRect.width,
- };
-
- // offsets start at 0, so surfaces translated off-canvas (e.g.
- // zen-mode transitions) never contribute negative values
- switch (node.dataset.viewportUi as ViewportUIDock) {
- case "top":
- measuredOffsets.top = Math.max(measuredOffsets.top, rect.bottom);
- break;
- case "bottom":
- measuredOffsets.bottom = Math.max(
- measuredOffsets.bottom,
- this.state.height - rect.top,
- );
- break;
- case "side": {
- // which side a panel docks to is resolved from its rendered
- // position (RTL / host-configured docking flip sides), by
- // checking which half of the viewport its center sits in;
- // the offset is then its intrusion depth from that edge
- const [side, offset] =
- rect.left + rect.width / 2 < this.state.width / 2
- ? (["left", rect.right] as const)
- : (["right", this.state.width - rect.left] as const);
-
- measuredOffsets[side] = Math.max(measuredOffsets[side], offset);
-
- const name = node.dataset.viewportUiName as
- | ViewportUIName
- | undefined;
- if (name) {
- renderedSurfaces.add(name);
- // don't cache degenerate measurements (surface translated
- // off-canvas, e.g. during zen-mode transitions)
- if (offset > 0) {
- this.viewportUILastMeasured.set(name, { side, offset });
- }
- }
- break;
- }
- }
- }
- }
-
- // reserve space for requested surfaces that aren't currently rendered,
- // using their last-measured footprint (or an approximate default if
- // they weren't rendered yet); no-op for currently-rendered surfaces
- // (already measured above) and on phones
- if (opts?.reserve && this.editorInterface.formFactor !== "phone") {
- const reserveSurface = (
- name: ViewportUIName,
- fallback: { side: "left" | "right"; offset: number },
- ) => {
- if (renderedSurfaces.has(name)) {
- return;
- }
- const { side, offset } =
- this.viewportUILastMeasured.get(name) ?? fallback;
- measuredOffsets[side] = Math.max(measuredOffsets[side], offset);
- };
-
- if (opts.reserve.stylesPanel) {
- reserveSurface("stylesPanel", {
- side: isRTL ? "right" : "left",
- offset:
- this.stylesPanelMode === "compact"
- ? STYLES_PANEL_APPROX_WIDTH.compact
- : STYLES_PANEL_APPROX_WIDTH.full,
- });
- }
- if (opts.reserve.sidebar) {
- reserveSurface("sidebar", {
- side: isRTL ? "left" : "right",
- offset: RIGHT_SIDEBAR_WIDTH,
- });
- }
- }
-
- const padding = opts?.padding ?? 24;
- const topPadding = opts?.paddingTop ?? padding;
- const rightPadding =
- (isRTL ? opts?.paddingLeft : opts?.paddingRight) ?? padding;
- const bottomPadding = opts?.paddingBottom ?? padding;
- const leftPadding =
- (isRTL ? opts?.paddingRight : opts?.paddingLeft) ?? padding;
-
- const editorOffsets = {
- top: measuredOffsets.top + topPadding,
- right: measuredOffsets.right + rightPadding,
- bottom: measuredOffsets.bottom + bottomPadding,
- left: measuredOffsets.left + leftPadding,
- };
-
- return {
- top: opts?.top ?? editorOffsets.top,
- right: (isRTL ? opts?.left : opts?.right) ?? editorOffsets.right,
- bottom: opts?.bottom ?? editorOffsets.bottom,
- left: (isRTL ? opts?.right : opts?.left) ?? editorOffsets.left,
- };
- };
-
// Input handling
private onKeyDown = withBatchedUpdates(
(event: React.KeyboardEvent | KeyboardEvent) => {
@@ -5790,7 +5410,12 @@ class App extends React.Component<AppProps, AppState> {
return;
}
- this.maybeHandlePageScrollKeyDown(event);
+ if (this.maybeHandlePageScrollKeyDown(event)) {
+ // Page navigation belongs to the canvas even when a pending locked
+ // viewport transition is temporarily withholding the mutation.
+ event.preventDefault();
+ return;
+ }
if (this.state.openDialog?.name === "elementLinkSelector") {
return;
@@ -6423,24 +6048,24 @@ class App extends React.Component<AppProps, AppState> {
return;
}
- // while rubberband-overscrolled past the scroll constraints, suppress
- // zooming until the viewport has snapped back inside the box
- if (isViewportOverscrolled(this.state)) {
- return;
- }
-
const initialScale = gesture.initialScale;
if (initialScale) {
- this.translateCanvas((state) => ({
- ...getStateForZoom(
- {
- viewportX: this.lastViewportPosition.x,
- viewportY: this.lastViewportPosition.y,
- nextZoom: getNormalizedZoom(initialScale * event.scale),
- },
- state,
- ),
- }));
+ this.viewport.translate(
+ (state) => ({
+ ...getViewportForZoomWithScrollConstraints(
+ {
+ viewportX: this.viewport.lastPosition.x,
+ viewportY: this.viewport.lastPosition.y,
+ nextZoom: getNormalizedZoom(initialScale * event.scale),
+ },
+ state,
+ ),
+ }),
+ {
+ zoomPreConstrained: true,
+ preserveScrollConstraintsSnapBack: true,
+ },
+ );
}
});
@@ -9229,7 +8854,7 @@ class App extends React.Component<AppProps, AppState> {
window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
}
- this.translateCanvas({
+ this.viewport.translate({
scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
});
@@ -9241,9 +8866,14 @@ class App extends React.Component<AppProps, AppState> {
if (!isHoldingSpace) {
this.cursor.reset();
}
- this.setState({
- cursorButton: "up",
- });
+ this.setState(
+ {
+ cursorButton: "up",
+ },
+ // Runs after the trailing throttled pointer move has committed, so
+ // the snap-back starts from the pan's actual final viewport.
+ this.viewport.releaseOverscroll,
+ );
this.savePointer(event.clientX, event.clientY, "up");
window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
window.removeEventListener(EVENT.POINTER_UP, teardown);
@@ -9313,18 +8943,10 @@ class App extends React.Component<AppProps, AppState> {
: 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(
+ // Preserve any existing screen-space overscroll through the zoom,
+ // then apply this frame's pan delta on top. `viewport.translate`
+ // rubberband-clamps the combined result against the scroll lock.
+ const zoomedViewport = getViewportForZoomWithScrollConstraints(
{
viewportX: center.x,
viewportY: center.y,
@@ -9332,19 +8954,16 @@ class App extends React.Component<AppProps, AppState> {
},
state,
);
- const zoomedViewport = constrainScrollState({ ...state, ...zoomState });
const zoomValue = zoomedViewport.zoom.value;
- this.translateCanvas(
+ this.viewport.translate(
{
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,
+ scrollX: zoomedViewport.scrollX + (2 * deltaX) / zoomValue,
+ scrollY: zoomedViewport.scrollY + (2 * deltaY) / zoomValue,
shouldCacheIgnoreZoom: true,
},
{ zoomPreConstrained: true },
@@ -9352,7 +8971,9 @@ class App extends React.Component<AppProps, AppState> {
return null;
});
- this.resetShouldCacheIgnoreZoomDebounced();
+ if (!this.viewport.isLockedTransitionPending) {
+ this.resetShouldCacheIgnoreZoomDebounced();
+ }
} else {
gesture.lastCenter =
gesture.initialDistance =
@@ -11598,7 +11219,7 @@ class App extends React.Component<AppProps, AppState> {
if (pointerDownState.scrollbars.isOverHorizontal) {
const x = event.clientX;
const dx = x - pointerDownState.lastCoords.x;
- this.translateCanvas({
+ this.viewport.translate({
scrollX:
this.state.scrollX -
(dx * (currentScrollBars.horizontal?.deltaMultiplier || 1)) /
@@ -11611,7 +11232,7 @@ class App extends React.Component<AppProps, AppState> {
if (pointerDownState.scrollbars.isOverVertical) {
const y = event.clientY;
const dy = y - pointerDownState.lastCoords.y;
- this.translateCanvas({
+ this.viewport.translate({
scrollY:
this.state.scrollY -
(dy * (currentScrollBars.vertical?.deltaMultiplier || 1)) /
@@ -13867,12 +13488,6 @@ class App extends React.Component<AppProps, AppState> {
const { deltaX, deltaY } = event;
// note that event.ctrlKey is necessary to handle pinch zooming
if (event.metaKey || event.ctrlKey) {
- // while rubberband-overscrolled past the scroll constraints, suppress
- // zooming until the viewport has snapped back inside the box
- if (isViewportOverscrolled(this.state)) {
- return;
- }
-
const sign = Math.sign(deltaY);
const MAX_STEP = ZOOM_STEP * 100;
const absDelta = Math.abs(deltaY);
@@ -13894,31 +13509,39 @@ class App extends React.Component<AppProps, AppState> {
: MIN_ZOOM;
newZoom = Math.max(newZoom, minZoom);
- this.translateCanvas((state) => ({
- ...getStateForZoom(
- {
- viewportX: this.lastViewportPosition.x,
- viewportY: this.lastViewportPosition.y,
- nextZoom: getNormalizedZoom(newZoom),
- },
- state,
- ),
- shouldCacheIgnoreZoom: true,
- }));
- this.resetShouldCacheIgnoreZoomDebounced();
+ const didTranslate = this.viewport.translate(
+ (state) => ({
+ ...getViewportForZoomWithScrollConstraints(
+ {
+ viewportX: this.viewport.lastPosition.x,
+ viewportY: this.viewport.lastPosition.y,
+ nextZoom: getNormalizedZoom(newZoom),
+ },
+ state,
+ ),
+ shouldCacheIgnoreZoom: true,
+ }),
+ {
+ zoomPreConstrained: true,
+ preserveScrollConstraintsSnapBack: true,
+ },
+ );
+ if (didTranslate) {
+ this.resetShouldCacheIgnoreZoomDebounced();
+ }
return;
}
// scroll horizontally when shift pressed
if (event.shiftKey) {
- this.translateCanvas(({ zoom, scrollX }) => ({
+ this.viewport.translate(({ zoom, scrollX }) => ({
// on Mac, shift+wheel tends to result in deltaX
scrollX: scrollX - (deltaY || deltaX) / zoom.value,
}));
return;
}
- this.translateCanvas(({ zoom, scrollX, scrollY }) => ({
+ this.viewport.translate(({ zoom, scrollX, scrollY }) => ({
scrollX: scrollX - deltaX / zoom.value,
scrollY: scrollY - deltaY / zoom.value,
}));
@@ -14042,7 +13665,7 @@ class App extends React.Component<AppProps, AppState> {
},
);
// a smaller viewport may push the min zoom up / shrink the pan range
- this.constrainViewportToScrollConstraints();
+ this.viewport.constrain();
}
};
diff --git a/packages/excalidraw/components/App.viewport.ts b/packages/excalidraw/components/App.viewport.ts
new file mode 100644
index 0000000000..f621db60fc
--- /dev/null
+++ b/packages/excalidraw/components/App.viewport.ts
@@ -0,0 +1,817 @@
+import {
+ debounce,
+ easeOut,
+ isBounds,
+ type Bounds,
+ type StylesPanelMode,
+} from "@excalidraw/common";
+import { clamp } from "@excalidraw/math";
+
+import {
+ getCommonBounds,
+ getElementsInGroup,
+ isElementLink,
+ isExcalidrawElement,
+ parseElementLinkFromURL,
+} from "@excalidraw/element";
+
+import type {
+ ExcalidrawElement,
+ NonDeleted,
+ NonDeletedSceneElementsMap,
+} from "@excalidraw/element/types";
+
+import { getLanguage, t } from "../i18n";
+import { AnimationController } from "../renderer/animation";
+import {
+ constrainScrollState,
+ DEFAULT_OVERSCROLL,
+ type SetViewportOptions,
+ type SetViewportRect,
+ zoomToFitBounds,
+} from "../viewport";
+
+import type {
+ AppProps,
+ AppState,
+ NormalizedZoomValue,
+ Offsets,
+ ScrollConstraints,
+ ViewportOffsets,
+ ViewportOffsetsOptions,
+ ViewportUIDock,
+ ViewportUIName,
+} from "../types";
+import type App from "./App";
+
+export const SCROLL_TO_CONTENT_ANIMATION_KEY = "animateScrollToContent";
+export const SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY =
+ "animateScrollConstraintsSnapBack";
+
+const DEFAULT_SCROLL_ANIMATION_DURATION = 500;
+
+/** rubberband snap-back animation duration, in ms — kept snappier than the
+ * default scroll animation so releasing an overscroll feels responsive */
+const SNAP_BACK_ANIMATION_DURATION = 250;
+
+/** how long after the last pan/zoom we animate the rubberband back into the
+ * scroll constraints box */
+const SCROLL_CONSTRAINTS_SNAP_BACK_DELAY = 200;
+
+/** single source of truth for the `--right-sidebar-width` CSS variable */
+export const RIGHT_SIDEBAR_WIDTH = 302;
+
+/**
+ * Approximate styles panel footprints (panel width + editor edge inset),
+ * used by `getOffsets` to reserve space for the panel before it was ever
+ * rendered (= measured). Keep roughly in sync with the CSS
+ * (`.App-menu__left` width / `.compact-shape-actions-island` min-width +
+ * `--editor-container-padding`).
+ */
+const STYLES_PANEL_APPROX_WIDTH = { full: 216, compact: 64 };
+
+type Viewport = Pick<AppState, "scrollX" | "scrollY" | "zoom">;
+
+const isSetViewportRect = (target: unknown): target is SetViewportRect => {
+ if (!target || typeof target !== "object" || Array.isArray(target)) {
+ return false;
+ }
+
+ const rect = target as Partial<SetViewportRect>;
+ return (
+ typeof rect.x === "number" &&
+ typeof rect.y === "number" &&
+ (rect.width == null || typeof rect.width === "number") &&
+ (rect.height == null || typeof rect.height === "number")
+ );
+};
+
+const getElementsFromId = (
+ id: string,
+ elementsMap: NonDeletedSceneElementsMap,
+) => {
+ const element = elementsMap.get(id);
+ if (element) {
+ return [element];
+ }
+
+ return getElementsInGroup(elementsMap, id);
+};
+
+type ResolvedViewportTarget = {
+ /** null when the target couldn't be resolved (unknown id/link, or all
+ * supplied elements deleted) */
+ bounds: Bounds | null;
+ /** how the target was specified, so callers can react to unresolved
+ * targets themselves (e.g. toast on a broken element link) */
+ type: "element" | "area" | "link";
+};
+
+/** Resolves a `setViewport` target to a scene-coordinate box. */
+const resolveViewportTarget = (
+ target: SetViewportOptions["target"],
+ elementsMap: NonDeletedSceneElementsMap,
+ appState: Pick<AppState, "width" | "height">,
+): ResolvedViewportTarget => {
+ if (typeof target === "string") {
+ const isLink = isElementLink(target);
+ const type = isLink ? ("link" as const) : ("element" as const);
+ const id = isLink ? parseElementLinkFromURL(target) : target;
+ const resolved = id ? getElementsFromId(id, elementsMap) : [];
+
+ if (!resolved.length) {
+ return { bounds: null, type };
+ }
+
+ return { bounds: getCommonBounds(resolved, elementsMap), type };
+ }
+
+ if (isBounds(target)) {
+ return { bounds: target, type: "area" };
+ }
+
+ if (isSetViewportRect(target) && !isExcalidrawElement(target)) {
+ const width = target.width ?? appState.width;
+ const height = target.height ?? appState.height;
+ return {
+ bounds: [target.x, target.y, target.x + width, target.y + height],
+ type: "area",
+ };
+ }
+
+ // widening to null values in case the host app doesn't have
+ // noUncheckedIndexedAccess enabled
+ const targetElements: (ExcalidrawElement | undefined | null)[] =
+ Array.isArray(target) ? target : [target];
+ const elements = targetElements.reduce<NonDeleted<ExcalidrawElement>[]>(
+ (acc, element) => {
+ if (element && !element.isDeleted) {
+ const sceneElement = elementsMap.get(element.id);
+ if (sceneElement) {
+ acc.push(sceneElement);
+ }
+ }
+ return acc;
+ },
+ [],
+ );
+
+ const hasNoElements = !elements.length;
+ if (elements.length !== targetElements.length || hasNoElements) {
+ console.warn(
+ "supplied element target(s) for setViewport contain deleted or non-existent elements which have been filtered out",
+ );
+ }
+
+ if (hasNoElements) {
+ return { bounds: null, type: "element" };
+ }
+
+ return { bounds: getCommonBounds(elements, elementsMap), type: "element" };
+};
+
+const resolveOverscroll = (
+ overscroll: boolean | number | undefined,
+): number => {
+ if (overscroll === false) {
+ return 0;
+ }
+ if (overscroll === true || overscroll == null) {
+ return DEFAULT_OVERSCROLL;
+ }
+ return Math.max(overscroll, 0);
+};
+
+/** Computes the viewport (scroll + zoom) that brings the target box into view,
+ * based on the requested fit behavior. */
+const getTargetViewport = (
+ state: AppState,
+ bounds: Bounds,
+ fit: SetViewportOptions["fit"] = "scale-down",
+ offsets?: Offsets,
+): Viewport => {
+ const { appState } = zoomToFitBounds({
+ bounds,
+ appState: state,
+ fit,
+ canvasOffsets: offsets,
+ steppedZoom: false,
+ });
+
+ return {
+ scrollX: appState.scrollX,
+ scrollY: appState.scrollY,
+ zoom: appState.zoom,
+ };
+};
+
+/** Computes the viewport patch for landing on `bounds`: the target
+ * scroll/zoom, plus the scroll lock to install — or `scrollConstraints: null`
+ * to clear a previous lock when none is requested. */
+const getConstrainedTargetViewport = (
+ appState: AppState,
+ bounds: Bounds,
+ // NOTE offsets must be resolved (see `AppViewport.resolveOffsets`)
+ {
+ fit,
+ offsets,
+ lock,
+ }: Pick<SetViewportOptions, "fit" | "lock"> & { offsets?: Offsets },
+): Viewport & { scrollConstraints: ScrollConstraints | null } => {
+ const viewport = getTargetViewport(appState, bounds, fit, offsets);
+
+ if (!lock?.scroll && !lock?.zoom) {
+ return { ...viewport, scrollConstraints: null };
+ }
+
+ const [x1, y1, x2, y2] = bounds;
+ const scrollConstraints: ScrollConstraints = {
+ x: x1,
+ y: y1,
+ width: x2 - x1,
+ height: y2 - y1,
+ lockScroll: !!lock.scroll,
+ lockZoom: !!lock.zoom,
+ zoom: viewport.zoom.value,
+ overscroll: resolveOverscroll(lock.overscroll),
+ offsets,
+ };
+
+ return {
+ ...constrainScrollState({ ...appState, ...viewport, scrollConstraints }),
+ scrollConstraints,
+ };
+};
+
+/**
+ * Interpolates the viewport from `from` to `target` at the (already-eased)
+ * blend amount `factor` (0 = `from`, 1 = `target`).
+ *
+ * Zoom is interpolated geometrically (so it feels uniform), but the pan can't
+ * simply lerp alongside it: pairing a geometric zoom with a linear scroll (or
+ * a linearly-tweened focal point) makes scene points swoop along curved,
+ * non-monotone screen paths once the zoom ratio exceeds ~e (the destination
+ * visibly drifts away before converging). Instead we interpolate the view
+ * transform affinely — a scene point maps to screen as
+ * `(scenePt + scroll) * zoom`, and requiring every point to travel a straight
+ * screen line forces `zoom` to be a convex blend `(1-m)*z0 + m*z1` with
+ * `scroll * zoom` lerped by that same weight. Deriving `m` from the geometric
+ * zoom keeps its pacing while making all screen trajectories straight and
+ * monotone.
+ */
+const interpolateViewport = ({
+ from,
+ target,
+ factor,
+}: {
+ from: Viewport;
+ target: Viewport;
+ factor: number;
+}): Viewport => {
+ if (factor >= 1) {
+ // land bit-exactly on the target (`z0 * (z1/z0)^1` can be off by an ulp)
+ return { ...target };
+ }
+
+ const zoom = (from.zoom.value *
+ Math.pow(
+ target.zoom.value / from.zoom.value,
+ factor,
+ )) as NormalizedZoomValue;
+
+ // pan blend weight derived from the zoom blend (0/0 for pure pans, hence
+ // the `factor` fallback; near-equal zooms are fine — the ratio limits to
+ // `factor` smoothly)
+ const m =
+ target.zoom.value === from.zoom.value
+ ? factor
+ : (zoom - from.zoom.value) / (target.zoom.value - from.zoom.value);
+
+ return {
+ scrollX:
+ ((1 - m) * from.scrollX * from.zoom.value +
+ m * target.scrollX * target.zoom.value) /
+ zoom,
+ scrollY:
+ ((1 - m) * from.scrollY * from.zoom.value +
+ m * target.scrollY * target.zoom.value) /
+ zoom,
+ zoom: { value: zoom },
+ };
+};
+
+type AppViewportDependencies = {
+ getContainer: () => HTMLDivElement | null;
+ getStylesPanelMode: () => StylesPanelMode;
+ isGestureActive: () => boolean;
+};
+
+const resolveAnimationDuration = (
+ animation: SetViewportOptions["animation"],
+): number | null => {
+ if (animation === false) {
+ return null;
+ }
+ if (animation === true || animation == null) {
+ return DEFAULT_SCROLL_ANIMATION_DURATION;
+ }
+ return animation.duration ?? DEFAULT_SCROLL_ANIMATION_DURATION;
+};
+
+/** Eases the viewport from its current position to `target` over `duration`,
+ * driving the transition through the shared AnimationController so it doesn't
+ * slow down other processes. */
+const animateToViewport = (
+ from: Viewport,
+ target: Viewport,
+ duration: number,
+ onFrame: (
+ state: Pick<
+ AppState,
+ "scrollX" | "scrollY" | "zoom" | "shouldCacheIgnoreZoom"
+ >,
+ ) => void,
+ onComplete: () => void,
+) => {
+ AnimationController.start<{ elapsed: number }>(
+ SCROLL_TO_CONTENT_ANIMATION_KEY,
+ ({ deltaTime, state }) => {
+ const elapsed = (state?.elapsed ?? 0) + deltaTime;
+ const progress = Math.min(elapsed / duration, 1);
+ const factor = easeOut(clamp(progress, 0, 1));
+
+ if (progress < 1) {
+ onFrame({
+ ...interpolateViewport({ from, target, factor }),
+ shouldCacheIgnoreZoom: true,
+ });
+ return { elapsed };
+ }
+
+ onComplete();
+
+ return null;
+ },
+ );
+};
+
+/**
+ * Rubberband snap-back: animates the viewport from its current (possibly
+ * overscrolled) position back inside the lock box via the shared
+ * AnimationController. No-op when already within the hard bounds (or when
+ * there is no lock).
+ */
+export const snapBackToConstraints = (
+ state: Pick<
+ AppState,
+ "scrollX" | "scrollY" | "zoom" | "width" | "height" | "scrollConstraints"
+ >,
+ onFrame: (
+ updater: (
+ state: Pick<
+ AppState,
+ | "scrollX"
+ | "scrollY"
+ | "zoom"
+ | "width"
+ | "height"
+ | "scrollConstraints"
+ >,
+ ) => Viewport | null,
+ ) => void,
+ duration = SNAP_BACK_ANIMATION_DURATION,
+) => {
+ const target = constrainScrollState(state);
+
+ if (
+ target.scrollX === state.scrollX &&
+ target.scrollY === state.scrollY &&
+ target.zoom.value === state.zoom.value
+ ) {
+ return;
+ }
+
+ // A programmatic navigation owns the viewport until it settles. A stale
+ // rubberband debounce must not supersede it.
+ if (AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)) {
+ return;
+ }
+
+ // Keep the displacement zoom-independent. Each animation frame resolves
+ // the resting viewport from the latest state, allowing zoom to update the
+ // underlying viewport while the same on-screen rubberband distance decays.
+ const overscrollX = (state.scrollX - target.scrollX) * state.zoom.value;
+ const overscrollY = (state.scrollY - target.scrollY) * state.zoom.value;
+
+ AnimationController.start<{ elapsed: number }>(
+ SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY,
+ ({ deltaTime, state: animationState }) => {
+ const elapsed = (animationState?.elapsed ?? 0) + deltaTime;
+ const progress = Math.min(elapsed / duration, 1);
+ const remaining = 1 - easeOut(clamp(progress, 0, 1));
+
+ onFrame((currentState) => {
+ if (!currentState.scrollConstraints) {
+ return null;
+ }
+
+ const restingViewport = constrainScrollState(currentState);
+ const zoom = restingViewport.zoom.value;
+ return {
+ scrollX: restingViewport.scrollX + (overscrollX * remaining) / zoom,
+ scrollY: restingViewport.scrollY + (overscrollY * remaining) / zoom,
+ zoom: restingViewport.zoom,
+ };
+ });
+
+ return progress < 1 ? { elapsed } : null;
+ },
+ );
+};
+
+/**
+ * Owns viewport state transitions and App-bound viewport concerns. Pure
+ * viewport geometry remains in `viewport.ts` so actions and public helpers can
+ * calculate state without an App instance.
+ */
+export class AppViewport {
+ public lastPosition = { x: 0, y: 0 };
+
+ private activeTransition: {
+ target: Viewport & Pick<AppState, "scrollConstraints">;
+ } | null = null;
+
+ private uiLastMeasured = new Map<
+ ViewportUIName,
+ { side: "left" | "right"; offset: number }
+ >();
+
+ constructor(
+ private app: App,
+ private dependencies: AppViewportDependencies,
+ ) {}
+
+ get isAnimating() {
+ return (
+ AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY) ||
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY)
+ );
+ }
+
+ /** Whether a programmatic transition into a locked viewport currently owns
+ * user pan/zoom input. */
+ get isLockedTransitionPending() {
+ return !!this.activeTransition?.target.scrollConstraints;
+ }
+
+ invalidateUIOffset = (name: ViewportUIName) => {
+ this.uiLastMeasured.delete(name);
+ };
+
+ /**
+ * Resolves user-supplied viewport offsets into concrete per-side pixel
+ * values. Static sides take precedence over UI-derived sides.
+ */
+ resolveOffsets = (
+ offsets: ViewportOffsets | undefined,
+ ): Offsets | undefined => {
+ if (!offsets) {
+ return offsets;
+ }
+
+ const { ui, ...staticOffsets } = offsets;
+
+ if (!ui) {
+ return staticOffsets;
+ }
+
+ const uiOffsets = this.getOffsets(ui === true ? undefined : ui);
+
+ return {
+ top: staticOffsets.top ?? uiOffsets.top,
+ right: staticOffsets.right ?? uiOffsets.right,
+ bottom: staticOffsets.bottom ?? uiOffsets.bottom,
+ left: staticOffsets.left ?? uiOffsets.left,
+ };
+ };
+
+ /**
+ * Measures the currently rendered editor UI and returns the usable viewport
+ * offsets, including optional padding and reserved hidden surfaces.
+ */
+ getOffsets = (opts?: ViewportOffsetsOptions): Offsets => {
+ const excalidrawContainer = this.dependencies.getContainer();
+ const excalidrawContainerRect =
+ excalidrawContainer?.getBoundingClientRect();
+ const isRTL = getLanguage().rtl;
+
+ const measuredOffsets = { top: 0, right: 0, bottom: 0, left: 0 };
+ const renderedSurfaces = new Set<ViewportUIName>();
+
+ if (excalidrawContainer && excalidrawContainerRect) {
+ for (const node of excalidrawContainer.querySelectorAll<HTMLElement>(
+ "[data-viewport-ui]",
+ )) {
+ const domRect = node.getBoundingClientRect();
+ const rect = {
+ top: domRect.top - excalidrawContainerRect.top,
+ right: domRect.right - excalidrawContainerRect.left,
+ bottom: domRect.bottom - excalidrawContainerRect.top,
+ left: domRect.left - excalidrawContainerRect.left,
+ width: domRect.width,
+ };
+
+ switch (node.dataset.viewportUi as ViewportUIDock) {
+ case "top":
+ measuredOffsets.top = Math.max(measuredOffsets.top, rect.bottom);
+ break;
+ case "bottom":
+ measuredOffsets.bottom = Math.max(
+ measuredOffsets.bottom,
+ this.app.state.height - rect.top,
+ );
+ break;
+ case "side": {
+ const [side, offset] =
+ rect.left + rect.width / 2 < this.app.state.width / 2
+ ? (["left", rect.right] as const)
+ : (["right", this.app.state.width - rect.left] as const);
+
+ measuredOffsets[side] = Math.max(measuredOffsets[side], offset);
+
+ const name = node.dataset.viewportUiName as
+ | ViewportUIName
+ | undefined;
+ if (name) {
+ renderedSurfaces.add(name);
+ if (offset > 0) {
+ this.uiLastMeasured.set(name, { side, offset });
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ if (opts?.reserve && this.app.editorInterface.formFactor !== "phone") {
+ const reserveSurface = (
+ name: ViewportUIName,
+ fallback: { side: "left" | "right"; offset: number },
+ ) => {
+ if (renderedSurfaces.has(name)) {
+ return;
+ }
+ const { side, offset } = this.uiLastMeasured.get(name) ?? fallback;
+ measuredOffsets[side] = Math.max(measuredOffsets[side], offset);
+ };
+
+ if (opts.reserve.stylesPanel) {
+ reserveSurface("stylesPanel", {
+ side: isRTL ? "right" : "left",
+ offset:
+ this.dependencies.getStylesPanelMode() === "compact"
+ ? STYLES_PANEL_APPROX_WIDTH.compact
+ : STYLES_PANEL_APPROX_WIDTH.full,
+ });
+ }
+ if (opts.reserve.sidebar) {
+ reserveSurface("sidebar", {
+ side: isRTL ? "left" : "right",
+ offset: RIGHT_SIDEBAR_WIDTH,
+ });
+ }
+ }
+
+ const padding = opts?.padding ?? 24;
+ const topPadding = opts?.paddingTop ?? padding;
+ const rightPadding =
+ (isRTL ? opts?.paddingLeft : opts?.paddingRight) ?? padding;
+ const bottomPadding = opts?.paddingBottom ?? padding;
+ const leftPadding =
+ (isRTL ? opts?.paddingRight : opts?.paddingLeft) ?? padding;
+
+ const editorOffsets = {
+ top: measuredOffsets.top + topPadding,
+ right: measuredOffsets.right + rightPadding,
+ bottom: measuredOffsets.bottom + bottomPadding,
+ left: measuredOffsets.left + leftPadding,
+ };
+
+ return {
+ top: opts?.top ?? editorOffsets.top,
+ right: (isRTL ? opts?.left : opts?.right) ?? editorOffsets.right,
+ bottom: opts?.bottom ?? editorOffsets.bottom,
+ left: (isRTL ? opts?.right : opts?.left) ?? editorOffsets.left,
+ };
+ };
+
+ /** Resolves the host-supplied initial viewport against restored scene data. */
+ resolveInitialViewport = (
+ opts: Omit<SetViewportOptions, "animation">,
+ elementsMap: NonDeletedSceneElementsMap,
+ appState: AppState,
+ ) => {
+ const { bounds } = resolveViewportTarget(
+ opts.target,
+ elementsMap,
+ appState,
+ );
+
+ if (!bounds) {
+ return null;
+ }
+
+ return getConstrainedTargetViewport(appState, bounds, {
+ ...opts,
+ // Initial state is resolved post-mount so UI-derived offsets measure
+ // the actually-rendered editor UI.
+ offsets: this.resolveOffsets(opts.offsets),
+ });
+ };
+
+ /** Navigates to a target and optionally installs scroll/zoom constraints. */
+ setViewport = (opts: SetViewportOptions | null) => {
+ if (opts === null) {
+ this.cancelTransition();
+ AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ this.snapBackDebounced.cancel();
+ this.app.setState({
+ scrollConstraints: null,
+ shouldCacheIgnoreZoom: false,
+ });
+ return;
+ }
+
+ const { target, fit, lock, animation } = opts;
+ const offsets = this.resolveOffsets(opts.offsets);
+ const { bounds, type } = resolveViewportTarget(
+ target,
+ this.app.scene.getNonDeletedElementsMap(),
+ this.app.state,
+ );
+
+ if (!bounds) {
+ if (type === "link") {
+ this.app.setState({
+ toast: {
+ message: t("elementLink.notFound"),
+ duration: 3000,
+ closable: true,
+ },
+ });
+ }
+ return;
+ }
+
+ const viewportUpdate = getConstrainedTargetViewport(
+ this.app.state,
+ bounds,
+ { fit, offsets, lock },
+ );
+ const duration = resolveAnimationDuration(animation);
+ const from = {
+ scrollX: this.app.state.scrollX,
+ scrollY: this.app.state.scrollY,
+ zoom: this.app.state.zoom,
+ };
+
+ // A new programmatic navigation supersedes the previous one and starts
+ // from whatever viewport its last rendered frame reached.
+ this.cancelTransition();
+ AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ this.snapBackDebounced.cancel();
+
+ if (duration === null) {
+ this.app.setState({
+ ...viewportUpdate,
+ shouldCacheIgnoreZoom: false,
+ });
+ return;
+ }
+
+ const transition = {
+ target: viewportUpdate,
+ };
+ this.activeTransition = transition;
+
+ // The old lock has been superseded. Keep the new lock pending outside
+ // AppState so it cannot constrain animation frames back toward either
+ // endpoint, and install it together with the final viewport.
+ if (this.app.state.scrollConstraints) {
+ this.app.setState({ scrollConstraints: null });
+ }
+
+ animateToViewport(
+ from,
+ viewportUpdate,
+ duration,
+ (state) => {
+ if (this.activeTransition === transition) {
+ this.app.setState(state);
+ }
+ },
+ () => {
+ if (this.activeTransition !== transition) {
+ return;
+ }
+
+ this.activeTransition = null;
+ this.app.setState({
+ ...transition.target,
+ shouldCacheIgnoreZoom: false,
+ });
+ },
+ );
+ };
+
+ /** Use when changing scrollX/scrollY/zoom based on user interaction. */
+ translate = <K extends keyof AppState>(
+ state:
+ | AppState
+ | Pick<AppState, K>
+ | null
+ | ((
+ prevState: Readonly<AppState>,
+ props: Readonly<AppProps>,
+ ) => AppState | Pick<AppState, K> | null),
+ opts?: {
+ zoomPreConstrained?: boolean;
+ preserveScrollConstraintsSnapBack?: boolean;
+ },
+ ) => {
+ if (this.isLockedTransitionPending) {
+ return false;
+ }
+
+ this.cancelTransition();
+ if (!opts?.preserveScrollConstraintsSnapBack) {
+ AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ }
+ this.app.setState({ shouldCacheIgnoreZoom: false });
+ if (this.app.state.userToFollow) {
+ this.app.setState({ userToFollow: null });
+ }
+
+ const prevZoom = this.app.state.zoom.value;
+ this.app.setState(state);
+
+ this.app.setState((prevState) => {
+ if (!prevState.scrollConstraints) {
+ return null;
+ }
+ const zoomed =
+ !opts?.zoomPreConstrained && prevState.zoom.value !== prevZoom;
+ const overscroll = zoomed ? 0 : prevState.scrollConstraints.overscroll;
+ if (overscroll > 0) {
+ this.snapBackDebounced();
+ }
+ return constrainScrollState(prevState, overscroll);
+ });
+
+ return true;
+ };
+
+ /** Clamps the viewport into the active scroll constraints. */
+ constrain = (overscroll = 0) => {
+ this.app.setState((prevState) =>
+ prevState.scrollConstraints
+ ? constrainScrollState(prevState, overscroll)
+ : null,
+ );
+ };
+
+ /** Releases a held rubberband overscroll. */
+ releaseOverscroll = () => {
+ if (!this.app.state.scrollConstraints) {
+ return;
+ }
+ this.snapBackDebounced.cancel();
+ this.snapBack();
+ };
+
+ private snapBack = () => {
+ if (this.app.unmounted || this.dependencies.isGestureActive()) {
+ return;
+ }
+ snapBackToConstraints(this.app.state, (updater) =>
+ this.app.setState((state) => updater(state)),
+ );
+ };
+
+ private snapBackDebounced = debounce(
+ this.snapBack,
+ SCROLL_CONSTRAINTS_SNAP_BACK_DELAY,
+ );
+
+ private cancelTransition = () => {
+ this.activeTransition = null;
+ AnimationController.cancel(SCROLL_TO_CONTENT_ANIMATION_KEY);
+ };
+
+ destroy = () => {
+ this.cancelTransition();
+ AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ this.snapBackDebounced.cancel();
+ };
+}
diff --git a/packages/excalidraw/components/CursorHint.tsx b/packages/excalidraw/components/CursorHint.tsx
index 3cf3b8c405..9f6a2b775c 100644
--- a/packages/excalidraw/components/CursorHint.tsx
+++ b/packages/excalidraw/components/CursorHint.tsx
@@ -63,10 +63,10 @@ export class CursorHints {
* the timer.
*/
show = (content: React.ReactNode) => {
- // `lastViewportPosition` stays at its initial (0, 0) until the first
+ // `viewport.lastPosition` stays at its initial (0, 0) until the first
// pointermove, so in pointer-less flows (e.g. keyboard-only session so
// far) we don't know where to show the hint — don't show it at all
- const { x, y } = this.app.lastViewportPosition;
+ const { x, y } = this.app.viewport.lastPosition;
if (x === 0 && y === 0) {
return;
}
@@ -139,7 +139,7 @@ export const CursorHint = () => {
element.style.transform = `translate(${x}px, ${y}px)`;
};
- updatePosition(app.lastViewportPosition.x, app.lastViewportPosition.y);
+ updatePosition(app.viewport.lastPosition.x, app.viewport.lastPosition.y);
const onPointerMove = (event: PointerEvent) => {
updatePosition(event.clientX, event.clientY);
diff --git a/packages/excalidraw/components/EyeDropper.tsx b/packages/excalidraw/components/EyeDropper.tsx
index f7f98123d5..654de4af2a 100644
--- a/packages/excalidraw/components/EyeDropper.tsx
+++ b/packages/excalidraw/components/EyeDropper.tsx
@@ -167,8 +167,8 @@ export const EyeDropper: React.FC<{
// init color preview else it would show only after the first mouse move
mouseMoveListener({
- clientX: stableProps.app.lastViewportPosition.x,
- clientY: stableProps.app.lastViewportPosition.y,
+ clientX: stableProps.app.viewport.lastPosition.x,
+ clientY: stableProps.app.viewport.lastPosition.y,
altKey: false,
});
diff --git a/packages/excalidraw/components/LibraryMenu.tsx b/packages/excalidraw/components/LibraryMenu.tsx
index 9a4f29f179..81427cf29f 100644
--- a/packages/excalidraw/components/LibraryMenu.tsx
+++ b/packages/excalidraw/components/LibraryMenu.tsx
@@ -296,7 +296,7 @@ export const LibraryMenu = memo(() => {
app.focusContainer();
}
} else if (selectedItems.length > 0) {
- const { x, y } = app.lastViewportPosition;
+ const { x, y } = app.viewport.lastPosition;
const elementUnderCursor = document.elementFromPoint(x, y);
// also deselect elements if sidebar doesn't have focus but the
// cursor is over it
diff --git a/packages/excalidraw/components/SearchMenu.tsx b/packages/excalidraw/components/SearchMenu.tsx
index e2b3c891f8..3ecb79e4e2 100644
--- a/packages/excalidraw/components/SearchMenu.tsx
+++ b/packages/excalidraw/components/SearchMenu.tsx
@@ -231,7 +231,7 @@ export const SearchMenu = () => {
zoom: app.state.zoom,
},
app.scene.getNonDeletedElementsMap(),
- app.getViewportOffsets(),
+ app.viewport.getOffsets(),
) ||
isTextTiny
) {
@@ -242,7 +242,7 @@ export const SearchMenu = () => {
? "contain"
: "scale-down";
- app.setViewport({
+ app.viewport.setViewport({
target: getCommonBounds([matchAsElement]),
fit: behavior,
animation: { duration: 300 },
diff --git a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
index de28dcc215..f5360e485d 100644
--- a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
+++ b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
@@ -161,7 +161,7 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
selectionColor,
renderScrollbars: props.renderScrollbars,
// NOTE not memoized on so we don't rerender on cursor move
- lastViewportPosition: props.app.lastViewportPosition,
+ lastViewportPosition: props.app.viewport.lastPosition,
},
editorInterface: props.editorInterface,
callback: props.renderInteractiveSceneCallback,
diff --git a/packages/excalidraw/scene/zoom.ts b/packages/excalidraw/scene/zoom.ts
deleted file mode 100644
index 5decf11490..0000000000
--- a/packages/excalidraw/scene/zoom.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { AppState, NormalizedZoomValue } from "../types";
-
-export const getStateForZoom = (
- {
- viewportX,
- viewportY,
- nextZoom,
- }: {
- viewportX: number;
- viewportY: number;
- nextZoom: NormalizedZoomValue;
- },
- appState: AppState,
-) => {
- const appLayerX = viewportX - appState.offsetLeft;
- const appLayerY = viewportY - appState.offsetTop;
-
- const currentZoom = appState.zoom.value;
-
- // get original scroll position without zoom
- const baseScrollX = appState.scrollX + (appLayerX - appLayerX / currentZoom);
- const baseScrollY = appState.scrollY + (appLayerY - appLayerY / currentZoom);
-
- // get scroll offsets for target zoom level
- const zoomOffsetScrollX = -(appLayerX - appLayerX / nextZoom);
- const zoomOffsetScrollY = -(appLayerY - appLayerY / nextZoom);
-
- return {
- scrollX: baseScrollX + zoomOffsetScrollX,
- scrollY: baseScrollY + zoomOffsetScrollY,
- zoom: {
- value: nextZoom,
- },
- };
-};
diff --git a/packages/excalidraw/tests/cursorHint.test.tsx b/packages/excalidraw/tests/cursorHint.test.tsx
index 00894a45e6..e952a6bade 100644
--- a/packages/excalidraw/tests/cursorHint.test.tsx
+++ b/packages/excalidraw/tests/cursorHint.test.tsx
@@ -182,8 +182,8 @@ describe("cursor hint", () => {
it("does not show hint when pointer position is unknown", () => {
// simulate no pointermove having happened yet
- h.app.lastViewportPosition.x = 0;
- h.app.lastViewportPosition.y = 0;
+ h.app.viewport.lastPosition.x = 0;
+ h.app.viewport.lastPosition.y = 0;
UI.clickTool("arrow");
pressKey(KEYS.A);
diff --git a/packages/excalidraw/tests/fitToContent.test.tsx b/packages/excalidraw/tests/fitToContent.test.tsx
index 7b8092367c..f920daaba8 100644
--- a/packages/excalidraw/tests/fitToContent.test.tsx
+++ b/packages/excalidraw/tests/fitToContent.test.tsx
@@ -1,9 +1,9 @@
import React from "react";
import { Excalidraw } from "../index";
+import { SCROLL_TO_CONTENT_ANIMATION_KEY } from "../components/App.viewport";
import { AnimationController } from "../renderer/animation";
import { getNormalizedZoom } from "../scene";
-import { SCROLL_TO_CONTENT_ANIMATION_KEY } from "../viewport";
import { API } from "./helpers/api";
import { act, render } from "./test-utils";
@@ -80,7 +80,7 @@ describe("scale-down", () => {
expect(h.state.zoom.value).toBe(1);
act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rectElement,
fit: "scale-down",
animation: false,
@@ -116,7 +116,7 @@ describe("scale-down", () => {
expect(h.state.zoom.value).toBe(1);
act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [topLeft, bottomRight],
fit: "scale-down",
animation: false,
@@ -147,7 +147,7 @@ describe("scale-down", () => {
act(() => {
// navigating by element id (a string target) with zoomToFit
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rectElement.id,
fit: "scale-down",
animation: false,
@@ -178,7 +178,7 @@ describe("scale-down", () => {
expect(h.state.scrollY).toBe(0);
act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rectElement,
fit: "contain",
animation: false,
@@ -213,7 +213,7 @@ describe("none", () => {
});
act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rectElement,
fit: "none",
animation: false,
@@ -258,7 +258,7 @@ describe("scale-down animated", () => {
API.setElements([rectElement]);
act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rectElement,
fit: "scale-down",
animation: { duration: LONG_ANIMATION_DURATION },
@@ -302,7 +302,7 @@ describe("scale-down animated", () => {
expect(h.state.scrollY).toBe(0);
act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rectElement,
fit: "scale-down",
animation: { duration: LONG_ANIMATION_DURATION },
@@ -339,7 +339,7 @@ describe("scale-down animated", () => {
act(() => {
// a short duration so the animation completes within a few frames
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rectElement,
fit: "scale-down",
animation: { duration: 10 },
diff --git a/packages/excalidraw/tests/interactivity.test.tsx b/packages/excalidraw/tests/interactivity.test.tsx
index f784499731..237e3a6b90 100644
--- a/packages/excalidraw/tests/interactivity.test.tsx
+++ b/packages/excalidraw/tests/interactivity.test.tsx
@@ -247,7 +247,7 @@ describe("interaction={false}", () => {
expect(h.state.zoom.value).toBe(1);
act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 1000, 1000],
fit: "scale-down",
animation: false,
diff --git a/packages/excalidraw/tests/scrollConstraints.test.tsx b/packages/excalidraw/tests/scrollConstraints.test.tsx
index 54c5afe26d..814271abe7 100644
--- a/packages/excalidraw/tests/scrollConstraints.test.tsx
+++ b/packages/excalidraw/tests/scrollConstraints.test.tsx
@@ -12,19 +12,23 @@ import {
actionZoomToFitSelection,
} from "../actions/actionCanvas";
import { getNormalizedZoom } from "../scene";
-import { getStateForZoom } from "../scene/zoom";
import {
- animateToConstraints,
+ snapBackToConstraints,
+ SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY,
+ SCROLL_TO_CONTENT_ANIMATION_KEY,
+} from "../components/App.viewport";
+import {
constrainScrollState,
DEFAULT_OVERSCROLL,
- isViewportOverscrolled,
- SCROLL_TO_CONTENT_ANIMATION_KEY,
+ getViewportForZoomWithScrollConstraints,
} from "../viewport";
import { AnimationController } from "../renderer/animation";
import { API } from "./helpers/api";
import { Keyboard, Pointer } from "./helpers/ui";
import {
+ fireEvent,
+ GlobalTestState,
mockBoundingClientRect,
render,
restoreOriginalGetBoundingClientRect,
@@ -67,6 +71,23 @@ const makeLock = (
...overrides,
});
+const waitForAnimationToStop = (key: string, maxFrames = 200) => {
+ return React.act(
+ () =>
+ new Promise<void>((resolve) => {
+ let remaining = maxFrames;
+ const check = () => {
+ if (!AnimationController.running(key) || --remaining <= 0) {
+ resolve();
+ } else {
+ requestAnimationFrame(check);
+ }
+ };
+ requestAnimationFrame(check);
+ }),
+ );
+};
+
describe("constrainScrollState (pure)", () => {
it("returns scroll/zoom unchanged when there is no lock", () => {
const state = makeState({
@@ -334,53 +355,6 @@ describe("rubberband overscroll (pure)", () => {
});
});
-describe("isViewportOverscrolled (pure)", () => {
- const base = { x: 0, y: 0, width: 1000, height: 1000 } as const;
-
- it("is false when there is no lock", () => {
- expect(
- isViewportOverscrolled(
- makeState({ scrollX: 9999, scrollConstraints: null }),
- ),
- ).toBe(false);
- });
-
- it("is false when the viewport is within the hard bounds", () => {
- expect(
- isViewportOverscrolled(
- makeState({
- scrollX: -100,
- scrollY: -100,
- scrollConstraints: makeLock({ ...base, lockScroll: true }),
- }),
- ),
- ).toBe(false);
- });
-
- it("is true when panned past an edge (scroll lock)", () => {
- // scrollX 30 is past the hard max of 0
- expect(
- isViewportOverscrolled(
- makeState({
- scrollX: 30,
- scrollConstraints: makeLock({ ...base, lockScroll: true }),
- }),
- ),
- ).toBe(true);
- });
-
- it("is true when zoomed out below the locked zoom (zoom lock)", () => {
- expect(
- isViewportOverscrolled(
- makeState({
- zoom: { value: getNormalizedZoom(0.1) },
- scrollConstraints: makeLock({ ...base, lockZoom: true, zoom: 0.2 }),
- }),
- ),
- ).toBe(true);
- });
-});
-
describe("animateToConstraints (rubberband snap-back)", () => {
afterEach(() => {
AnimationController.reset();
@@ -397,26 +371,77 @@ describe("animateToConstraints (rubberband snap-back)", () => {
it("starts an animation toward the box when overscrolled", () => {
const onFrame = vi.fn();
// scrollX 200 is outside the hard range [-800, 0]
- animateToConstraints(
+ snapBackToConstraints(
makeState({ scrollX: 200, scrollConstraints: lock }),
onFrame,
);
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- true,
- );
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(true);
expect(onFrame).toHaveBeenCalled();
});
it("is a no-op when already within the box", () => {
const onFrame = vi.fn();
- animateToConstraints(
+ snapBackToConstraints(
makeState({ scrollX: -100, scrollConstraints: lock }),
onFrame,
);
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(false);
+ expect(onFrame).not.toHaveBeenCalled();
+ });
+
+ it("does not supersede an active viewport navigation", () => {
+ AnimationController.start(SCROLL_TO_CONTENT_ANIMATION_KEY, () => ({}));
+
+ snapBackToConstraints(
+ makeState({ scrollX: 200, scrollConstraints: lock }),
+ vi.fn(),
+ );
+
expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- false,
+ true,
);
- expect(onFrame).not.toHaveBeenCalled();
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(false);
+ });
+});
+
+describe("getViewportForZoomWithScrollConstraints", () => {
+ it("preserves the screen-space overscroll distance while zooming", () => {
+ const state = {
+ ...makeState({
+ scrollY: 50,
+ scrollConstraints: makeLock({
+ x: 0,
+ y: 0,
+ width: 1000,
+ height: 1000,
+ lockScroll: true,
+ overscroll: 50,
+ }),
+ }),
+ offsetLeft: 0,
+ offsetTop: 0,
+ } as AppState;
+
+ const viewport = getViewportForZoomWithScrollConstraints(
+ {
+ viewportX: 0,
+ viewportY: 0,
+ nextZoom: getNormalizedZoom(2),
+ },
+ state,
+ );
+ const restingViewport = constrainScrollState({ ...state, ...viewport });
+
+ expect(viewport.zoom.value).toBe(2);
+ expect(
+ (viewport.scrollY - restingViewport.scrollY) * viewport.zoom.value,
+ ).toBeCloseTo(50);
});
});
@@ -435,7 +460,7 @@ describe("setViewport lock (integration)", () => {
await waitFor(() => expect(h.state.width).toBe(200));
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 1000, 1000],
fit: "scale-down",
animation: false,
@@ -453,7 +478,7 @@ describe("setViewport lock (integration)", () => {
// clearing the lock lets it scroll freely again
React.act(() => {
- h.app.setViewport(null);
+ h.app.viewport.setViewport(null);
});
expect(h.state.scrollConstraints).toBe(null);
const before = h.state.scrollY;
@@ -461,8 +486,8 @@ describe("setViewport lock (integration)", () => {
expect(h.state.scrollY).toBeLessThan(before);
});
- it("defers installing the lock until an animated scroll settles", async () => {
- await render(<Excalidraw />);
+ it("withholds user viewport input until an animated lock settles", async () => {
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
await waitFor(() => expect(h.state.width).toBe(200));
const rect = API.createElement({
@@ -475,20 +500,234 @@ describe("setViewport lock (integration)", () => {
API.setElements([rect]);
React.act(() => {
- h.app.setViewport({
- target: rect,
+ h.app.viewport.setViewport({
+ target: [0, 0, 1000, 1000],
fit: "scale-down",
- animation: { duration: 300 },
+ animation: false,
lock: { scroll: true },
});
});
+ expect(h.state.scrollConstraints).not.toBe(null);
+
+ window.EXCALIDRAW_THROTTLE_RENDER = true;
+ try {
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: rect,
+ fit: "scale-down",
+ animation: { duration: 10 },
+ lock: { scroll: true },
+ });
+ });
+
+ // the animation is in flight and the lock has NOT been installed yet —
+ // it's chained to run once the scroll settles
+ expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
+ true,
+ );
+ // The previous active lock is superseded immediately; the destination
+ // lock is held internally until the animation lands.
+ expect(h.state.scrollConstraints).toBe(null);
+ expect(h.app.viewport.isLockedTransitionPending).toBe(true);
+
+ const viewportDuringTransition = {
+ scrollX: h.state.scrollX,
+ scrollY: h.state.scrollY,
+ zoom: h.state.zoom.value,
+ };
+
+ // Pan, wheel/pinch zoom, zoom controls, and fit actions are all
+ // consumed while the pending lock owns the viewport. None may cancel
+ // the animation or perturb its current frame.
+ Keyboard.keyPress(KEYS.PAGE_DOWN);
+ fireEvent.wheel(GlobalTestState.interactiveCanvas, {
+ ctrlKey: true,
+ deltaY: -10,
+ });
+ React.act(() => {
+ h.app.actionManager.executeAction(actionZoomIn, "ui");
+ h.app.actionManager.executeAction(actionResetZoom, "ui");
+ h.app.actionManager.executeAction(actionZoomToFit, "ui");
+ h.app.actionManager.executeAction(actionZoomToFitSelection, "ui");
+ });
+
+ expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
+ true,
+ );
+ expect({
+ scrollX: h.state.scrollX,
+ scrollY: h.state.scrollY,
+ zoom: h.state.zoom.value,
+ }).toEqual(viewportDuringTransition);
+
+ await waitForAnimationToStop(SCROLL_TO_CONTENT_ANIMATION_KEY);
+
+ expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
+ false,
+ );
+ expect(h.app.viewport.isLockedTransitionPending).toBe(false);
+ expect(h.state.scrollConstraints).toMatchObject({
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ lockScroll: true,
+ });
+ } finally {
+ window.EXCALIDRAW_THROTTLE_RENDER = undefined;
+ }
+ });
+
+ it("lets a newer animated lock supersede an older one", async () => {
+ await render(<Excalidraw />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ const firstTarget = API.createElement({
+ type: "rectangle",
+ x: 1000,
+ y: 1000,
+ width: 100,
+ height: 100,
+ });
+ const secondTarget = API.createElement({
+ type: "rectangle",
+ x: 3000,
+ y: 3000,
+ width: 200,
+ height: 200,
+ });
+ API.setElements([firstTarget, secondTarget]);
+
+ window.EXCALIDRAW_THROTTLE_RENDER = true;
+ try {
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: firstTarget,
+ animation: { duration: 1000 },
+ lock: { scroll: true },
+ });
+ });
+
+ expect(h.app.viewport.isLockedTransitionPending).toBe(true);
+
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: secondTarget,
+ animation: { duration: 10 },
+ lock: { scroll: true, zoom: true },
+ });
+ });
+
+ expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
+ true,
+ );
+ expect(h.app.viewport.isLockedTransitionPending).toBe(true);
+
+ await waitForAnimationToStop(SCROLL_TO_CONTENT_ANIMATION_KEY);
+
+ expect(h.app.viewport.isLockedTransitionPending).toBe(false);
+ expect(h.state.scrollConstraints).toMatchObject({
+ x: secondTarget.x,
+ y: secondTarget.y,
+ width: secondTarget.width,
+ height: secondTarget.height,
+ lockScroll: true,
+ lockZoom: true,
+ });
+ } finally {
+ window.EXCALIDRAW_THROTTLE_RENDER = undefined;
+ }
+ });
+
+ it("clears both active and pending locks with setViewport(null)", async () => {
+ await render(<Excalidraw />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: [0, 0, 1000, 1000],
+ animation: false,
+ lock: { scroll: true },
+ });
+ });
+ expect(h.state.scrollConstraints).not.toBe(null);
+
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: [2000, 2000, 3000, 3000],
+ animation: { duration: 1000 },
+ lock: { scroll: true, zoom: true },
+ });
+ });
+
+ // The superseded active lock is removed while the target lock is pending.
+ expect(h.state.scrollConstraints).toBe(null);
+ expect(h.app.viewport.isLockedTransitionPending).toBe(true);
+
+ React.act(() => {
+ h.app.viewport.setViewport(null);
+ });
+
+ expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
+ false,
+ );
+ expect(h.app.viewport.isLockedTransitionPending).toBe(false);
+ expect(h.state.scrollConstraints).toBe(null);
+ expect(h.state.shouldCacheIgnoreZoom).toBe(false);
+ });
+
+ it("still lets user input cancel an unlocked viewport animation", async () => {
+ await render(<Excalidraw />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: [2000, 2000, 3000, 3000],
+ animation: { duration: 1000 },
+ });
+ });
- // the animation is in flight and the lock has NOT been installed yet —
- // it's chained to run once the scroll settles
expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
true,
);
+ expect(h.app.viewport.isLockedTransitionPending).toBe(false);
+
+ React.act(() => {
+ h.app.viewport.translate({ scrollX: 123, scrollY: 456 });
+ });
+
+ expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
+ false,
+ );
+ expect(h.state.scrollX).toBe(123);
+ expect(h.state.scrollY).toBe(456);
+ });
+
+ it("applies back-to-back lock updates in call order", async () => {
+ await render(<Excalidraw />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: [0, 0, 1000, 1000],
+ animation: false,
+ lock: { scroll: true },
+ });
+ h.app.viewport.setViewport({
+ target: [1000, 1000, 2000, 2000],
+ animation: false,
+ lock: { scroll: true, zoom: true },
+ });
+ h.app.viewport.setViewport({
+ target: [2000, 2000, 3000, 3000],
+ animation: false,
+ });
+ });
+
expect(h.state.scrollConstraints).toBe(null);
+ expect(h.state.zoom.value).toBeCloseTo(0.1);
+ expect(h.state.scrollX).toBeCloseTo(-1500);
+ expect(h.state.scrollY).toBeCloseTo(-2000);
});
it("supports rect targets and defaults missing dimensions to the viewport", async () => {
@@ -496,7 +735,7 @@ describe("setViewport lock (integration)", () => {
await waitFor(() => expect(h.state.width).toBe(200));
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: { x: 10, y: 20, width: 50 },
fit: "scale-down",
animation: false,
@@ -512,7 +751,7 @@ describe("setViewport lock (integration)", () => {
});
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: { x: 30, y: 40, height: 60 },
fit: "scale-down",
animation: false,
@@ -528,7 +767,7 @@ describe("setViewport lock (integration)", () => {
});
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: { x: 70, y: 80 },
fit: "scale-down",
animation: false,
@@ -570,7 +809,7 @@ describe("setViewport lock (integration)", () => {
API.setElements([validRect, deletedRect]);
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [
validRect,
deletedRect,
@@ -597,7 +836,7 @@ describe("setViewport lock (integration)", () => {
warnSpy.mockClear();
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [
deletedRect,
missingRect,
@@ -626,7 +865,7 @@ describe("setViewport lock (integration)", () => {
expect(h.app.actionManager.isActionEnabled(actionZoomToFit)).toBe(true);
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 500, 500],
fit: "scale-down",
animation: false,
@@ -678,7 +917,7 @@ describe("setViewport lock (integration)", () => {
API.setElements([rect]);
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rect,
fit: "contain",
animation: false,
@@ -715,7 +954,7 @@ describe("setViewport lock (integration)", () => {
API.setElements([rect]);
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: rect,
fit: "contain",
animation: false,
@@ -751,7 +990,7 @@ describe("rubberband overscroll (integration)", () => {
await waitFor(() => expect(h.state.width).toBe(200));
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 1000, 1000],
fit: "scale-down",
animation: false,
@@ -776,7 +1015,7 @@ describe("rubberband overscroll (integration)", () => {
await waitFor(() => expect(h.state.width).toBe(200));
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 1000, 1000],
fit: "scale-down",
animation: false,
@@ -794,9 +1033,8 @@ describe("rubberband overscroll (integration)", () => {
// outside the 50px give. The zoom must be hard-clamped (equivalent to
// sliding the zoom origin back into bounds), not rubberbanded.
React.act(() => {
- // eslint-disable-next-line dot-notation -- private method; bracket access is the TS escape hatch
- h.app["translateCanvas"]((state: AppState) => ({
- ...getStateForZoom(
+ h.app.viewport.translate((state: AppState) => ({
+ ...getViewportForZoomWithScrollConstraints(
{ viewportX: 0, viewportY: 0, nextZoom: getNormalizedZoom(0.2) },
state,
),
@@ -805,7 +1043,6 @@ describe("rubberband overscroll (integration)", () => {
expect(h.state.zoom.value).toBeCloseTo(0.2);
expect(h.state.scrollX).toBeCloseTo(0);
- expect(isViewportOverscrolled(h.state)).toBe(false);
// panning, by contrast, still gets the rubberband give
Keyboard.keyPress(KEYS.PAGE_UP);
@@ -820,7 +1057,7 @@ describe("rubberband overscroll (integration)", () => {
await waitFor(() => expect(h.state.width).toBe(200));
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 1000, 1000],
fit: "scale-down",
animation: false,
@@ -851,7 +1088,6 @@ describe("rubberband overscroll (integration)", () => {
expect(h.state.scrollY).toBeLessThanOrEqual(
50 / h.state.zoom.value + 0.001,
);
- expect(isViewportOverscrolled(h.state)).toBe(true);
// zooming must keep working while overscrolled (used to be pinned),
// without yanking the viewport back inside the box
@@ -870,7 +1106,7 @@ describe("rubberband overscroll (integration)", () => {
await waitFor(() => expect(h.state.width).toBe(200));
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 1000, 1000],
fit: "scale-down",
animation: false,
@@ -886,35 +1122,140 @@ describe("rubberband overscroll (integration)", () => {
finger2.downAt(60, 2);
finger1.move(0, 5);
finger2.move(0, 5);
- expect(isViewportOverscrolled(h.state)).toBe(true);
+ const heldScrollY = h.state.scrollY;
+ expect(heldScrollY).toBeGreaterThan(0);
// the debounced snap-back elapses while the fingers are still down —
// it must be withheld, not fight the held gesture
React.act(() => {
// eslint-disable-next-line dot-notation -- private; simulates the debounce delay elapsing
- h.app["snapBackToScrollConstraintsDebounced"].flush();
+ h.app.viewport["snapBackDebounced"].flush();
});
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- false,
- );
- expect(isViewportOverscrolled(h.state)).toBe(true);
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(false);
+ expect(h.state.scrollY).toBe(heldScrollY);
// lifting one finger ends the gesture → the rubberband releases
finger1.up();
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- true,
- );
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(true);
finger2.up();
});
+ it("withholds the rubberband snap-back until a desktop pan ends", async () => {
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: [0, 0, 1000, 1000],
+ fit: "scale-down",
+ animation: false,
+ lock: { scroll: true, overscroll: 50 },
+ });
+ h.app.setActiveTool({ type: "hand" });
+ });
+
+ const mouse = new Pointer("mouse");
+
+ // Drag down past the top edge and hold the mouse button there.
+ mouse.downAt(50, 2);
+ mouse.move(0, 5);
+ const heldScrollY = h.state.scrollY;
+ expect(heldScrollY).toBeGreaterThan(0);
+
+ // The debounce may elapse while the mouse is still held, but the viewport
+ // must remain attached to the pointer until the pan session ends.
+ React.act(() => {
+ // eslint-disable-next-line dot-notation -- private; simulates the debounce delay elapsing
+ h.app.viewport["snapBackDebounced"].flush();
+ });
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(false);
+ expect(h.state.scrollY).toBe(heldScrollY);
+
+ mouse.up();
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(true);
+
+ // Direct manipulation takes ownership of the viewport again.
+ mouse.downAt(50, 7);
+ mouse.move(0, 1);
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(false);
+ mouse.up();
+ });
+
+ it("continues rubberband snap-back while wheel-zooming", async () => {
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
+ await waitFor(() => expect(h.state.width).toBe(200));
+
+ React.act(() => {
+ h.app.viewport.setViewport({
+ target: [0, 0, 1000, 1000],
+ fit: "scale-down",
+ animation: false,
+ lock: { scroll: true, overscroll: 50 },
+ });
+ h.app.setActiveTool({ type: "hand" });
+ });
+
+ const mouse = new Pointer("mouse");
+ window.EXCALIDRAW_THROTTLE_RENDER = true;
+ try {
+ mouse.downAt(50, 2);
+ mouse.move(0, 5);
+ mouse.up();
+
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(true);
+ expect(h.state.scrollY).toBeGreaterThan(
+ constrainScrollState(h.state).scrollY,
+ );
+
+ const zoomBefore = h.state.zoom.value;
+ fireEvent.wheel(GlobalTestState.interactiveCanvas, {
+ ctrlKey: true,
+ deltaY: -10,
+ });
+
+ expect(h.state.zoom.value).toBeGreaterThan(zoomBefore);
+ expect(h.state.scrollY).toBeGreaterThan(
+ constrainScrollState(h.state).scrollY,
+ );
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(true);
+
+ await waitForAnimationToStop(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+
+ expect(
+ AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ ).toBe(false);
+ expect(h.state.zoom.value).toBeGreaterThan(zoomBefore);
+ const restingViewport = constrainScrollState(h.state);
+ expect(h.state.scrollX).toBeCloseTo(restingViewport.scrollX);
+ expect(h.state.scrollY).toBeCloseTo(restingViewport.scrollY);
+ expect(h.state.zoom.value).toBeCloseTo(restingViewport.zoom.value);
+ } finally {
+ window.EXCALIDRAW_THROTTLE_RENDER = undefined;
+ }
+ });
+
it("defaults to DEFAULT_OVERSCROLL when omitted or `true`, 0 when `false`", async () => {
await render(<Excalidraw />);
await waitFor(() => expect(h.state.width).toBe(200));
const install = (overscroll?: boolean | number) => {
React.act(() => {
- h.app.setViewport({
+ h.app.viewport.setViewport({
target: [0, 0, 1000, 1000],
fit: "scale-down",
animation: false,
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index 6a4584a009..543a345b18 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -1031,8 +1031,7 @@ export type AppClassProperties = {
id: App["id"];
onInsertElements: App["onInsertElements"];
onExportImage: App["onExportImage"];
- lastViewportPosition: App["lastViewportPosition"];
- setViewport: App["setViewport"];
+ viewport: App["viewport"];
addFiles: App["addFiles"];
addElementsFromPasteOrLibrary: App["addElementsFromPasteOrLibrary"];
togglePenMode: App["togglePenMode"];
@@ -1049,7 +1048,6 @@ export type AppClassProperties = {
getEffectiveGridSize: App["getEffectiveGridSize"];
setPlugins: App["setPlugins"];
plugins: App["plugins"];
- getViewportOffsets: App["getViewportOffsets"];
visibleElements: App["visibleElements"];
excalidrawContainerValue: App["excalidrawContainerValue"];
@@ -1180,8 +1178,8 @@ export interface ExcalidrawImperativeAPI {
getAppState: () => InstanceType<typeof App>["state"];
getFiles: () => InstanceType<typeof App>["files"];
getName: InstanceType<typeof App>["getName"];
- setViewport: InstanceType<typeof App>["setViewport"];
- getViewportOffsets: InstanceType<typeof App>["getViewportOffsets"];
+ setViewport: InstanceType<typeof App>["viewport"]["setViewport"];
+ getViewportOffsets: InstanceType<typeof App>["viewport"]["getOffsets"];
registerAction: (action: Action) => void;
refresh: InstanceType<typeof App>["refresh"];
setToast: InstanceType<typeof App>["setToast"];
diff --git a/packages/excalidraw/viewport.ts b/packages/excalidraw/viewport.ts
index 417b8442c8..e6abf78de3 100644
--- a/packages/excalidraw/viewport.ts
+++ b/packages/excalidraw/viewport.ts
@@ -1,7 +1,10 @@
+// this file contains viewport-related utilities that are stateless or
+// reused throughout the codebase not just directly by App.tsx or AppViewport
+//
+// for editor instance specific, see App.viewport.ts
+
import {
arrayToMap,
- easeOut,
- isBounds,
MAX_ZOOM,
MIN_ZOOM,
viewportCoordsToSceneCoords,
@@ -13,23 +16,14 @@ import {
CaptureUpdateAction,
getCommonBounds,
getElementBounds,
- getElementsInGroup,
getVisibleElements,
- isElementLink,
- isExcalidrawElement,
- parseElementLinkFromURL,
} from "@excalidraw/element";
import type { SceneBounds } from "@excalidraw/element";
import type { Bounds } from "@excalidraw/common";
-import type {
- ExcalidrawElement,
- NonDeleted,
- NonDeletedSceneElementsMap,
-} from "@excalidraw/element/types";
+import type { ExcalidrawElement } from "@excalidraw/element/types";
-import { AnimationController } from "./renderer/animation";
import { getNormalizedZoom } from "./scene";
import type {
@@ -42,17 +36,15 @@ import type {
Zoom,
} from "./types";
-export const SCROLL_TO_CONTENT_ANIMATION_KEY = "animateScrollToContent";
-
-const DEFAULT_SCROLL_ANIMATION_DURATION = 500;
-
-/** rubberband snap-back animation duration, in ms — kept snappier than the
- * default scroll animation so releasing an overscroll feels responsive */
-const SNAP_BACK_ANIMATION_DURATION = 250;
-
/** default rubberband overscroll give for scroll locks, in viewport px */
export const DEFAULT_OVERSCROLL = 150;
+type ZoomOptions = {
+ viewportX: number;
+ viewportY: number;
+ nextZoom: NormalizedZoomValue;
+};
+
export type AnimationOptions = {
duration?: number;
};
@@ -64,22 +56,6 @@ export type SetViewportRect = {
height?: number;
};
-export const isSetViewportRect = (
- target: unknown,
-): target is SetViewportRect => {
- if (!target || typeof target !== "object" || Array.isArray(target)) {
- return false;
- }
-
- const rect = target as Partial<SetViewportRect>;
- return (
- typeof rect.x === "number" &&
- typeof rect.y === "number" &&
- (rect.width == null || typeof rect.width === "number") &&
- (rect.height == null || typeof rect.height === "number")
- );
-};
-
export type SetViewportOptions = {
/**
* what to show in the viewport: an explicit scene-coordinate box/rect,
@@ -132,30 +108,6 @@ export type SetViewportOptions = {
type Viewport = Pick<AppState, "scrollX" | "scrollY" | "zoom">;
-const resolveAnimationDuration = (
- animation: AnimationOptions | boolean | undefined,
-): number | null => {
- if (animation === false) {
- return null;
- }
- if (animation === true || animation == null) {
- return DEFAULT_SCROLL_ANIMATION_DURATION;
- }
- return animation.duration ?? DEFAULT_SCROLL_ANIMATION_DURATION;
-};
-
-const resolveOverscroll = (
- overscroll: boolean | number | undefined,
-): number => {
- if (overscroll === false) {
- return 0;
- }
- if (overscroll === true || overscroll == null) {
- return DEFAULT_OVERSCROLL;
- }
- return Math.max(overscroll, 0);
-};
-
/**
* Clamps a single scroll axis so the visible scene span stays inside the box.
* The visible span is `[-scroll, -scroll + visibleSize]`; we keep it within
@@ -248,89 +200,68 @@ export const constrainScrollState = (
};
};
-export const isViewportOverscrolled = (
- state: Pick<
- AppState,
- "scrollX" | "scrollY" | "zoom" | "width" | "height" | "scrollConstraints"
- >,
-): boolean => {
- if (!state.scrollConstraints) {
- return false;
- }
+/** private helper. Use {@link getViewportForZoomWithScrollConstraints} instead */
+const getViewportForZoom = (
+ { viewportX, viewportY, nextZoom }: ZoomOptions,
+ appState: AppState,
+): Viewport => {
+ const appLayerX = viewportX - appState.offsetLeft;
+ const appLayerY = viewportY - appState.offsetTop;
- const target = constrainScrollState(state); // hard clamp (no overscroll give)
+ const currentZoom = appState.zoom.value;
- return (
- target.scrollX !== state.scrollX ||
- target.scrollY !== state.scrollY ||
- target.zoom.value !== state.zoom.value
- );
-};
+ // get original scroll position without zoom
+ const baseScrollX = appState.scrollX + (appLayerX - appLayerX / currentZoom);
+ const baseScrollY = appState.scrollY + (appLayerY - appLayerY / currentZoom);
-/**
- * Rubberband snap-back: animates the viewport from its current (possibly
- * overscrolled) position back inside the lock box via the shared
- * AnimationController. No-op when already within the hard bounds (or when there
- * is no lock).
- */
-export const animateToConstraints = (
- state: Pick<
- AppState,
- "scrollX" | "scrollY" | "zoom" | "width" | "height" | "scrollConstraints"
- >,
- onFrame: (
- viewport: Pick<
- AppState,
- "scrollX" | "scrollY" | "zoom" | "shouldCacheIgnoreZoom"
- >,
- ) => void,
- duration = SNAP_BACK_ANIMATION_DURATION,
-) => {
- const target = constrainScrollState(state); // hard clamp (no overscroll give)
-
- if (
- target.scrollX === state.scrollX &&
- target.scrollY === state.scrollY &&
- target.zoom.value === state.zoom.value
- ) {
- return;
- }
+ // get scroll offsets for target zoom level
+ const zoomOffsetScrollX = -(appLayerX - appLayerX / nextZoom);
+ const zoomOffsetScrollY = -(appLayerY - appLayerY / nextZoom);
- animateToViewport(state, target, duration, onFrame);
+ return {
+ scrollX: baseScrollX + zoomOffsetScrollX,
+ scrollY: baseScrollY + zoomOffsetScrollY,
+ zoom: {
+ value: nextZoom,
+ },
+ };
};
/**
- * Scrolls (and, per `fit`, zooms) the viewport so the given target box is in
- * view, optionally animating the transition. `onComplete` runs once the
- * viewport has settled on the target.
+ * Resolves a focal-point zoom against the active scroll constraints while
+ * preserving the current rubberband displacement in screen pixels. This lets
+ * zoom and scroll-constraint snap-back compose without either visually
+ * cancelling the other.
*/
-export const setViewportToBounds = (
+export const getViewportForZoomWithScrollConstraints = (
+ opts: ZoomOptions,
state: AppState,
- bounds: Bounds,
- // NOTE offsets must be resolved (see `App.resolveViewportOffsets`)
- opts: Pick<SetViewportOptions, "fit" | "animation"> & { offsets?: Offsets },
- onFrame: (
- state: Pick<
- AppState,
- "scrollX" | "scrollY" | "zoom" | "shouldCacheIgnoreZoom"
- >,
- ) => void,
- onComplete?: () => void,
-) => {
- AnimationController.cancel(SCROLL_TO_CONTENT_ANIMATION_KEY);
-
- const viewport = getTargetViewport(state, bounds, opts.fit, opts.offsets);
-
- const duration = resolveAnimationDuration(opts.animation);
+): Viewport => {
+ const restingViewport = constrainScrollState(state);
+ const overscrollX =
+ (state.scrollX - restingViewport.scrollX) * state.zoom.value;
+ const overscrollY =
+ (state.scrollY - restingViewport.scrollY) * state.zoom.value;
+
+ const zoomedViewport = constrainScrollState({
+ ...state,
+ ...getViewportForZoom(opts, state),
+ });
- if (duration === null) {
- // no animation: jump straight to the target. Re-enable zoom caching in
- // case we just cancelled an in-flight animation that had suppressed it.
- onFrame({ ...viewport, shouldCacheIgnoreZoom: false });
- onComplete?.();
- } else {
- animateToViewport(state, viewport, duration, onFrame, onComplete);
+ if (!state.scrollConstraints?.lockScroll || (!overscrollX && !overscrollY)) {
+ return zoomedViewport;
}
+
+ const zoom = zoomedViewport.zoom.value;
+ return constrainScrollState(
+ {
+ ...state,
+ ...zoomedViewport,
+ scrollX: zoomedViewport.scrollX + overscrollX / zoom,
+ scrollY: zoomedViewport.scrollY + overscrollY / zoom,
+ },
+ state.scrollConstraints.overscroll,
+ );
};
const zoomValueToFitBoundsOnViewport = (
@@ -428,246 +359,6 @@ export const zoomToFitBounds = ({
};
};
-/** Computes the viewport (scroll + zoom) that brings the target box into view,
- * based on the requested fit behavior. */
-export const getTargetViewport = (
- state: AppState,
- bounds: Bounds,
- fit: SetViewportOptions["fit"] = "scale-down",
- offsets?: Offsets,
-): Viewport => {
- const { appState } = zoomToFitBounds({
- bounds,
- appState: state,
- fit,
- canvasOffsets: offsets,
- steppedZoom: false,
- });
-
- return {
- scrollX: appState.scrollX,
- scrollY: appState.scrollY,
- zoom: appState.zoom,
- };
-};
-
-const getElementsFromId = (
- id: string,
- elementsMap: NonDeletedSceneElementsMap,
-) => {
- const element = elementsMap.get(id);
- if (element) {
- return [element];
- }
-
- return getElementsInGroup(elementsMap, id);
-};
-
-export type ResolvedViewportTarget = {
- /** null when the target couldn't be resolved (unknown id/link, or all
- * supplied elements deleted) */
- bounds: Bounds | null;
- /** how the target was specified, so callers can react to unresolved
- * targets themselves (e.g. toast on a broken element link) */
- type: "element" | "area" | "link";
-};
-
-/** Resolves a `setViewport` target to a scene-coordinate box. */
-export const resolveViewportTarget = (
- target: SetViewportOptions["target"],
- elementsMap: NonDeletedSceneElementsMap,
- appState: Pick<AppState, "width" | "height">,
-): ResolvedViewportTarget => {
- if (typeof target === "string") {
- const isLink = isElementLink(target);
- const type = isLink ? ("link" as const) : ("element" as const);
- const id = isLink ? parseElementLinkFromURL(target) : target;
- const resolved = id ? getElementsFromId(id, elementsMap) : [];
-
- if (!resolved.length) {
- return { bounds: null, type };
- }
-
- return { bounds: getCommonBounds(resolved, elementsMap), type };
- }
-
- if (isBounds(target)) {
- return { bounds: target, type: "area" };
- }
-
- if (isSetViewportRect(target) && !isExcalidrawElement(target)) {
- const width = target.width ?? appState.width;
- const height = target.height ?? appState.height;
- return {
- bounds: [target.x, target.y, target.x + width, target.y + height],
- type: "area",
- };
- }
-
- // widening to null values in case the host app doesn't have
- // noUncheckedIndexedAccess enabled
- const targetElements: (ExcalidrawElement | undefined | null)[] =
- Array.isArray(target) ? target : [target];
- const elements = targetElements.reduce<NonDeleted<ExcalidrawElement>[]>(
- (acc, element) => {
- if (element && !element.isDeleted) {
- const sceneElement = elementsMap.get(element.id);
- if (sceneElement) {
- acc.push(sceneElement);
- }
- }
- return acc;
- },
- [],
- );
-
- const hasNoElements = !elements.length;
- if (elements.length !== targetElements.length || hasNoElements) {
- console.warn(
- "supplied element target(s) for setViewport contain deleted or non-existent elements which have been filtered out",
- );
- }
-
- if (hasNoElements) {
- return { bounds: null, type: "element" };
- }
-
- return { bounds: getCommonBounds(elements, elementsMap), type: "element" };
-};
-
-/** Computes the viewport patch for landing on `bounds`: the target
- * scroll/zoom, plus the scroll lock to install — or `scrollConstraints: null`
- * to clear a previous lock when none is requested. */
-export const getConstrainedTargetViewport = (
- appState: AppState,
- bounds: Bounds,
- // NOTE offsets must be resolved (see `App.resolveViewportOffsets`)
- {
- fit,
- offsets,
- lock,
- }: Pick<SetViewportOptions, "fit" | "lock"> & { offsets?: Offsets },
-): Viewport & { scrollConstraints: ScrollConstraints | null } => {
- const viewport = getTargetViewport(appState, bounds, fit, offsets);
-
- if (!lock?.scroll && !lock?.zoom) {
- return { ...viewport, scrollConstraints: null };
- }
-
- const [x1, y1, x2, y2] = bounds;
- const scrollConstraints: ScrollConstraints = {
- x: x1,
- y: y1,
- width: x2 - x1,
- height: y2 - y1,
- lockScroll: !!lock.scroll,
- lockZoom: !!lock.zoom,
- zoom: viewport.zoom.value,
- overscroll: resolveOverscroll(lock.overscroll),
- offsets,
- };
-
- return {
- ...constrainScrollState({ ...appState, ...viewport, scrollConstraints }),
- scrollConstraints,
- };
-};
-
-/**
- * Interpolates the viewport from `from` to `target` at the (already-eased)
- * blend amount `factor` (0 = `from`, 1 = `target`).
- *
- * Zoom is interpolated geometrically (so it feels uniform), but the pan can't
- * simply lerp alongside it: pairing a geometric zoom with a linear scroll (or
- * a linearly-tweened focal point) makes scene points swoop along curved,
- * non-monotone screen paths once the zoom ratio exceeds ~e (the destination
- * visibly drifts away before converging). Instead we interpolate the view
- * transform affinely — a scene point maps to screen as
- * `(scenePt + scroll) * zoom`, and requiring every point to travel a straight
- * screen line forces `zoom` to be a convex blend `(1-m)*z0 + m*z1` with
- * `scroll * zoom` lerped by that same weight. Deriving `m` from the geometric
- * zoom keeps its pacing while making all screen trajectories straight and
- * monotone.
- */
-export const interpolateViewport = ({
- from,
- target,
- factor,
-}: {
- from: Viewport;
- target: Viewport;
- factor: number;
-}): Viewport => {
- if (factor >= 1) {
- // land bit-exactly on the target (`z0 * (z1/z0)^1` can be off by an ulp)
- return { ...target };
- }
-
- const zoom = (from.zoom.value *
- Math.pow(
- target.zoom.value / from.zoom.value,
- factor,
- )) as NormalizedZoomValue;
-
- // pan blend weight derived from the zoom blend (0/0 for pure pans, hence
- // the `factor` fallback; near-equal zooms are fine — the ratio limits to
- // `factor` smoothly)
- const m =
- target.zoom.value === from.zoom.value
- ? factor
- : (zoom - from.zoom.value) / (target.zoom.value - from.zoom.value);
-
- return {
- scrollX:
- ((1 - m) * from.scrollX * from.zoom.value +
- m * target.scrollX * target.zoom.value) /
- zoom,
- scrollY:
- ((1 - m) * from.scrollY * from.zoom.value +
- m * target.scrollY * target.zoom.value) /
- zoom,
- zoom: { value: zoom },
- };
-};
-
-/** Eases the viewport from its current position to `target` over `duration`,
- * driving the transition through the shared AnimationController so it doesn't
- * slow down other processes. */
-const animateToViewport = (
- from: Viewport,
- target: Viewport,
- duration: number,
- onFrame: (
- state: Pick<
- AppState,
- "scrollX" | "scrollY" | "zoom" | "shouldCacheIgnoreZoom"
- >,
- ) => void,
- onComplete?: () => void,
-) => {
- AnimationController.start<{ elapsed: number }>(
- SCROLL_TO_CONTENT_ANIMATION_KEY,
- ({ deltaTime, state }) => {
- const elapsed = (state?.elapsed ?? 0) + deltaTime;
- const progress = Math.min(elapsed / duration, 1);
- const factor = easeOut(clamp(progress, 0, 1));
-
- onFrame({
- ...interpolateViewport({ from, target, factor }),
- shouldCacheIgnoreZoom: progress < 1, // ignore zoom caching while animating
- });
-
- if (progress < 1) {
- return { elapsed };
- }
-
- onComplete?.();
-
- return null;
- },
- );
-};
-
const doBoundsExceedViewport = (appState: AppState, bounds: Bounds) => {
const [x1, y1, x2, y2] = bounds;
return (