Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): alt-click to cycle the selection through overlapping elements (#12237)

David Luzar53973c3a423f
diff --git a/packages/element/tests/cropElement.test.tsx b/packages/element/tests/cropElement.test.tsx
index 6c03ec1265..19e729047f 100644
--- a/packages/element/tests/cropElement.test.tsx
+++ b/packages/element/tests/cropElement.test.tsx
@@ -136,6 +136,34 @@ describe("Crop an image", () => {
expect(image.height).toBeLessThan(initialHeight);
});
+ it("Dragging a crop handle in the crop editor crops the image", () => {
+ const image = API.createElement({
+ type: "image",
+ width: 200,
+ height: 100,
+ fileId: "file",
+ });
+ API.setElements([image]);
+ // the file loaded, at twice the element's size
+ const htmlImage = new Image();
+ Object.defineProperties(htmlImage, {
+ naturalWidth: { value: 400 },
+ naturalHeight: { value: 200 },
+ });
+ h.app.imageCache.set(image.fileId!, {
+ image: htmlImage,
+ mimeType: "image/png",
+ });
+ API.setSelectedElements([image]);
+ Keyboard.keyDown(KEYS.ENTER);
+ expect(h.state.croppingElementId).toBe(image.id);
+
+ UI.resize(image, "w", [50, 0]);
+
+ expect(API.getElement(image)).toMatchObject({ x: 50, width: 150 });
+ expect(API.getElement(image).crop).toMatchObject({ x: 100, width: 300 });
+ });
+
it("Cropping has minimal sizes", async () => {
const image = h.elements[0] as ExcalidrawImageElement;
const initialWidth = image.width;
diff --git a/packages/element/tests/duplicate.test.tsx b/packages/element/tests/duplicate.test.tsx
index 98b28fe392..80403fa135 100644
--- a/packages/element/tests/duplicate.test.tsx
+++ b/packages/element/tests/duplicate.test.tsx
@@ -634,7 +634,7 @@ describe("duplication z-order", () => {
mouse.select(rectangle1);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle1.x + 5, rectangle1.y + 5);
- mouse.up(rectangle1.x + 5, rectangle1.y + 5);
+ mouse.up(rectangle1.x + 10, rectangle1.y + 10);
});
assertElements(h.elements, [
@@ -700,7 +700,7 @@ describe("duplication z-order", () => {
mouse.select(rectangle1);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle1.x + 5, rectangle1.y + 5);
- mouse.up(rectangle1.x + 5, rectangle1.y + 5);
+ mouse.up(rectangle1.x + 10, rectangle1.y + 10);
});
assertElements(h.elements, [
diff --git a/packages/excalidraw/components/App.cursor.ts b/packages/excalidraw/components/App.cursor.ts
index dcab3ff10f..cf5419dcbc 100644
--- a/packages/excalidraw/components/App.cursor.ts
+++ b/packages/excalidraw/components/App.cursor.ts
@@ -1,4 +1,4 @@
-import { CURSOR_TYPE, MIME_TYPES, THEME } from "@excalidraw/common";
+import { CURSOR_TYPE, KEYS, MIME_TYPES, THEME } from "@excalidraw/common";
import { isHandToolActive, isEraserActive } from "../appState";
@@ -185,12 +185,17 @@ export class AppCursor {
const EventConstructor =
typeof PointerEvent !== "undefined" ? PointerEvent : MouseEvent;
+ // with the modifiers held now, which the move would otherwise release
+ const modifiers = this.app.modifiers.get();
this.canvas.dispatchEvent(
new EventConstructor("pointermove", {
bubbles: true,
cancelable: true,
clientX: lastEvent.clientX,
clientY: lastEvent.clientY,
+ altKey: modifiers.alt,
+ shiftKey: modifiers.shift,
+ [KEYS.CTRL_OR_CMD]: modifiers.ctrlOrCmd,
}),
);
};
diff --git a/packages/excalidraw/components/App.modifiers.ts b/packages/excalidraw/components/App.modifiers.ts
new file mode 100644
index 0000000000..14aa5111de
--- /dev/null
+++ b/packages/excalidraw/components/App.modifiers.ts
@@ -0,0 +1,82 @@
+import { useEffect, useState } from "react";
+
+import { Emitter, KEYS } from "@excalidraw/common";
+
+export type HeldModifiers = Readonly<{
+ alt: boolean;
+ shift: boolean;
+ /** Ctrl, or Cmd on macOS */
+ ctrlOrCmd: boolean;
+}>;
+
+const NONE_HELD: HeldModifiers = {
+ alt: false,
+ shift: false,
+ ctrlOrCmd: false,
+};
+
+const pick = (held: HeldModifiers, modifier?: keyof HeldModifiers) =>
+ modifier ? held[modifier] : held;
+
+/**
+ * The modifier keys held over the editor, synced from the flags of its
+ * keyboard and pointer events. Kept out of appState so that pressing one
+ * re-renders only its subscribers (e.g. the hint).
+ */
+export class AppModifiers {
+ private held = NONE_HELD;
+ /** fires with a new snapshot whenever a modifier is pressed or released */
+ readonly onChange = new Emitter<[held: HeldModifiers]>();
+
+ get = (): HeldModifiers => this.held;
+
+ /* eslint-disable react-hooks/rules-of-hooks -- called from function
+ components; the lint takes any class method for a class component */
+ /**
+ * A hook re-rendering on the held modifiers: all of them, or with
+ * `modifier`, only on that one being pressed or released.
+ */
+ useHeld(): HeldModifiers;
+ useHeld(modifier: keyof HeldModifiers): boolean;
+ useHeld(modifier?: keyof HeldModifiers) {
+ const [held, setHeld] = useState(() => pick(this.held, modifier));
+ useEffect(() => {
+ // (setting a boolean that didn't change doesn't re-render)
+ const update = () => setHeld(pick(this.held, modifier));
+ // catches a change between the render and subscribing
+ update();
+ return this.onChange.on(update);
+ }, [modifier]);
+ return held;
+ }
+ /* eslint-enable react-hooks/rules-of-hooks */
+
+ sync = (event: {
+ altKey: boolean;
+ shiftKey: boolean;
+ ctrlKey: boolean;
+ metaKey: boolean;
+ }) => {
+ this.set({
+ alt: event.altKey,
+ shift: event.shiftKey,
+ ctrlOrCmd: event[KEYS.CTRL_OR_CMD],
+ });
+ };
+
+ /** releases them all — e.g. on blur, as Alt+Tab never delivers the keyup */
+ reset = () => {
+ this.set(NONE_HELD);
+ };
+
+ private set(held: HeldModifiers) {
+ if (
+ held.alt !== this.held.alt ||
+ held.shift !== this.held.shift ||
+ held.ctrlOrCmd !== this.held.ctrlOrCmd
+ ) {
+ this.held = held;
+ this.onChange.trigger(held);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/App.selectionTool.ts b/packages/excalidraw/components/App.selectionTool.ts
new file mode 100644
index 0000000000..dd7e62c614
--- /dev/null
+++ b/packages/excalidraw/components/App.selectionTool.ts
@@ -0,0 +1,1223 @@
+import {
+ CURSOR_TYPE,
+ DEFAULT_COLLISION_THRESHOLD,
+ DEFAULT_TRANSFORM_HANDLE_SPACING,
+ DRAGGING_THRESHOLD,
+ getGridPoint,
+ isSelectionLikeTool,
+ KEYS,
+ shouldMaintainAspectRatio,
+ shouldResizeFromCenter,
+ shouldRotateWithDiscreteAngle,
+ tupleToCoors,
+} from "@excalidraw/common";
+import {
+ cropElement,
+ editGroupForSelectedElement,
+ getCommonBounds,
+ getElementsInGroup,
+ getElementsInResizingFrame,
+ getElementWithTransformHandleType,
+ getFrameChildren,
+ getResizeArrowDirection,
+ getResizeOffsetXY,
+ getTransformHandleTypeFromCoords,
+ handleFocusPointPointerDown,
+ hitElementBoundingBoxOnly,
+ isBindingElement,
+ isElbowArrow,
+ isElementInGroup,
+ isEmbeddableElement,
+ isFrameLikeElement,
+ isImageElement,
+ isInitializedImageElement,
+ isLinearElement,
+ isNonDeletedElement,
+ isSelectedViaGroup,
+ isStickyNoteElement,
+ LinearElementEditor,
+ makeNextSelectedElementIds,
+ selectGroupsForSelectedElements,
+ transformElements,
+ updateBoundElements,
+} from "@excalidraw/element";
+import { pointDistance, pointFrom } from "@excalidraw/math";
+
+import type {
+ ExcalidrawElement,
+ NonDeleted,
+ NonDeletedExcalidrawElement,
+ NonDeletedSceneElementsMap,
+} from "@excalidraw/element/types";
+
+import { actionToggleLinearEditor } from "../actions";
+import { getSelectedElements } from "../scene";
+
+import { snapResizingElements } from "../snapping";
+
+import type React from "react";
+import type { PointerDownState } from "../types";
+import type App from "./App";
+
+/**
+ * The selection tool's (and the lasso's) selection: what a pointer down
+ * selects, what a click (a pointer up without a drag) does to the selection —
+ * including alt-click cycling through the overlapping elements — and the
+ * selection's transform handles (resizing, rotating, cropping).
+ */
+export class AppSelectionTool {
+ constructor(private app: App) {}
+
+ clearSelectionIfNotUsingSelection = (): void => {
+ if (!isSelectionLikeTool(this.app.state.activeTool.type)) {
+ this.app.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.app.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+ };
+
+ /**
+ * @returns whether the pointer event has been completely handled
+ */
+ handleSelectionOnPointerDown = (
+ event: React.PointerEvent<HTMLElement>,
+ pointerDownState: PointerDownState,
+ ): boolean => {
+ if (isSelectionLikeTool(this.app.state.activeTool.type)) {
+ if (this.app.duplicate.hitEditedElement(pointerDownState)) {
+ return false;
+ }
+
+ const elements = this.app.scene.getNonDeletedElements();
+ const elementsMap = this.app.scene.getNonDeletedElementsMap();
+ const selectedElements = this.app.scene.getSelectedElements(
+ this.app.state,
+ );
+
+ if (
+ selectedElements.length === 1 &&
+ !this.app.state.selectedLinearElement?.isEditing &&
+ !isElbowArrow(selectedElements[0]) &&
+ !(
+ isLinearElement(selectedElements[0]) &&
+ (this.app.editorInterface.userAgent.isMobileDevice ||
+ selectedElements[0].points.length === 2)
+ ) &&
+ !(
+ this.app.state.selectedLinearElement &&
+ this.app.state.selectedLinearElement.hoverPointIndex !== -1
+ )
+ ) {
+ const elementWithTransformHandleType =
+ getElementWithTransformHandleType(
+ elements,
+ this.app.state,
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ this.app.state.zoom,
+ event.pointerType,
+ this.app.scene.getNonDeletedElementsMap(),
+ this.app.editorInterface,
+ );
+ if (elementWithTransformHandleType != null) {
+ if (
+ elementWithTransformHandleType.transformHandleType === "rotation"
+ ) {
+ this.app.setState({
+ resizingElement: elementWithTransformHandleType.element,
+ });
+ pointerDownState.resize.handleType =
+ elementWithTransformHandleType.transformHandleType;
+ } else if (this.app.state.croppingElementId) {
+ pointerDownState.resize.handleType =
+ elementWithTransformHandleType.transformHandleType;
+ } else {
+ this.app.setState({
+ resizingElement: elementWithTransformHandleType.element,
+ });
+ pointerDownState.resize.handleType =
+ elementWithTransformHandleType.transformHandleType;
+ }
+ }
+ } else if (selectedElements.length > 1) {
+ pointerDownState.resize.handleType = getTransformHandleTypeFromCoords(
+ getCommonBounds(selectedElements),
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ this.app.state.zoom,
+ event.pointerType,
+ this.app.editorInterface,
+ );
+ }
+ if (pointerDownState.resize.handleType) {
+ pointerDownState.resize.isResizing = true;
+ pointerDownState.resize.offset = tupleToCoors(
+ getResizeOffsetXY(
+ pointerDownState.resize.handleType,
+ selectedElements,
+ elementsMap,
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ ),
+ );
+ if (
+ selectedElements.length === 1 &&
+ isLinearElement(selectedElements[0]) &&
+ selectedElements[0].points.length === 2
+ ) {
+ pointerDownState.resize.arrowDirection = getResizeArrowDirection(
+ pointerDownState.resize.handleType,
+ selectedElements[0],
+ );
+ }
+ // an alt-click on a resize handle (over the selected element) cycles
+ // the selection too — alt-resizing starts past the drag threshold
+ if (pointerDownState.resize.handleType !== "rotation") {
+ pointerDownState.hit.cycleTarget = this.getSelectionCycleTarget(
+ event,
+ this.app.getElementsAtPosition(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ ),
+ );
+ }
+ } else {
+ if (this.app.state.selectedLinearElement) {
+ const linearElementEditor = this.app.state.selectedLinearElement;
+ const ret = LinearElementEditor.handlePointerDown(
+ event,
+ this.app,
+ this.app.store,
+ pointerDownState.origin,
+ linearElementEditor,
+ this.app.scene,
+ );
+
+ if (ret.hitElement) {
+ pointerDownState.hit.element = ret.hitElement;
+ }
+ pointerDownState.hit.arrowLabel = ret.hitBoundText;
+ if (ret.linearElementEditor) {
+ this.app.setState({
+ selectedLinearElement: ret.linearElementEditor,
+ });
+ }
+ if (ret.didAddPoint) {
+ return true;
+ }
+
+ // Also check at current pointer position if focus point is being hovered
+ // (in case we're clicking directly without a prior move event)
+ const elementsMap = this.app.scene.getNonDeletedElementsMap();
+ const arrow = LinearElementEditor.getElement(
+ linearElementEditor.elementId,
+ elementsMap,
+ ) as any;
+
+ if (arrow && isBindingElement(arrow)) {
+ const {
+ hitFocusPoint,
+ pointerOffset,
+ arrowOtherEndpointInitialBinding,
+ } = handleFocusPointPointerDown(
+ arrow,
+ pointerDownState,
+ elementsMap,
+ this.app.state,
+ );
+
+ // If focus point is hit, update state and prevent element selection
+ if (hitFocusPoint) {
+ this.app.setState({
+ selectedLinearElement: {
+ ...linearElementEditor,
+ hoveredFocusPointBinding: hitFocusPoint,
+ draggedFocusPointBinding: hitFocusPoint,
+ pointerOffset,
+ initialState: {
+ ...linearElementEditor.initialState,
+ arrowOtherEndpointInitialBinding,
+ },
+ },
+ });
+ return false;
+ }
+ }
+ }
+
+ const allHitElements = this.app.getElementsAtPosition(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ {
+ includeLockedElements: true,
+ },
+ );
+ const unlockedHitElements = allHitElements.filter((e) => !e.locked);
+
+ // Cannot set preferSelected in getElementAtPosition as we do in pointer move; consider:
+ // A & B: both unlocked, A selected, B on top, A & B overlaps in some way
+ // we want to select B when clicking on the overlapping area
+ const hitElementMightBeLocked = this.app.getElementAtPosition(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ {
+ allHitElements,
+ },
+ );
+
+ if (
+ !hitElementMightBeLocked ||
+ hitElementMightBeLocked.id !== this.app.state.activeLockedId
+ ) {
+ this.app.setState({
+ activeLockedId: null,
+ });
+ }
+
+ if (
+ hitElementMightBeLocked &&
+ hitElementMightBeLocked.locked &&
+ !unlockedHitElements.some(
+ (el) => this.app.state.selectedElementIds[el.id],
+ )
+ ) {
+ pointerDownState.hit.element = null;
+ } else {
+ // hitElement may already be set above, so check first
+ pointerDownState.hit.element =
+ pointerDownState.hit.element ??
+ this.app.getElementAtPosition(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ );
+ }
+
+ this.app.hitLinkElement = this.app.getElementLinkAtPosition(
+ pointerDownState.origin,
+ hitElementMightBeLocked,
+ );
+
+ if (this.app.hitLinkElement) {
+ return true;
+ }
+
+ if (
+ this.app.state.croppingElementId &&
+ pointerDownState.hit.element?.id !== this.app.state.croppingElementId
+ ) {
+ this.app.finishImageCropping();
+ }
+
+ if (pointerDownState.hit.element) {
+ // Early return if pointer is hitting link icon
+ const hitLinkElement = this.app.getElementLinkAtPosition(
+ {
+ x: pointerDownState.origin.x,
+ y: pointerDownState.origin.y,
+ },
+ pointerDownState.hit.element,
+ );
+ if (hitLinkElement) {
+ return false;
+ }
+ }
+
+ // For overlapped elements one position may hit
+ // multiple elements
+ pointerDownState.hit.allHitElements = unlockedHitElements;
+
+ pointerDownState.hit.cycleTarget = this.getSelectionCycleTarget(
+ event,
+ unlockedHitElements,
+ );
+ // the selection cycles on pointerup — or, on an alt-drag, is what's
+ // duplicated
+ if (pointerDownState.hit.cycleTarget) {
+ this.app.setState({
+ previousSelectedElementIds: this.app.state.selectedElementIds,
+ });
+ return false;
+ }
+
+ const hitElement = pointerDownState.hit.element;
+ const someHitElementIsSelected =
+ pointerDownState.hit.allHitElements.some((element) =>
+ this.isASelectedElement(element),
+ ) ||
+ // the selected linear element's point handles, midpoint knob and
+ // label extend beyond its own hit area, so a hit reported by
+ // `LinearElementEditor.handlePointerDown` counts even when the
+ // position-based hit test above missed the element
+ (hitElement !== null && this.isASelectedElement(hitElement));
+ if (
+ (hitElement === null || !someHitElementIsSelected) &&
+ !event.shiftKey &&
+ !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements &&
+ (!this.app.state.selectedLinearElement?.isEditing ||
+ (hitElement &&
+ hitElement?.id !==
+ this.app.state.selectedLinearElement?.elementId))
+ ) {
+ this.clearSelection(hitElement);
+ }
+
+ if (this.app.state.selectedLinearElement?.isEditing) {
+ this.app.setState((prevState) => ({
+ selectedLinearElement: prevState.selectedLinearElement
+ ? {
+ ...prevState.selectedLinearElement,
+ isEditing:
+ !!hitElement &&
+ hitElement.id ===
+ this.app.state.selectedLinearElement?.elementId,
+ }
+ : null,
+ selectedElementIds: prevState.selectedLinearElement
+ ? makeNextSelectedElementIds(
+ {
+ [prevState.selectedLinearElement.elementId]: true,
+ },
+ this.app.state,
+ )
+ : makeNextSelectedElementIds({}, prevState),
+ }));
+ // If we click on something
+ } else if (hitElement != null) {
+ // == deep selection ==
+ // on CMD/CTRL, drill down to hit element regardless of groups etc.
+ if (event[KEYS.CTRL_OR_CMD]) {
+ if (event.altKey) {
+ // ctrl + alt means we're lasso selecting - start lasso trail and switch to lasso tool
+
+ // Close any open dialogs that might interfere with lasso selection
+ if (this.app.state.openDialog?.name === "elementLinkSelector") {
+ this.app.setOpenDialog(null);
+ }
+ this.app.lassoTrail.startPath(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ event.shiftKey,
+ );
+ this.app.setActiveTool({ type: "lasso", fromSelection: true });
+ return false;
+ }
+ if (!this.app.state.selectedElementIds[hitElement.id]) {
+ pointerDownState.hit.wasAddedToSelection = true;
+ }
+ this.app.setState((prevState) => ({
+ ...editGroupForSelectedElement(prevState, hitElement),
+ previousSelectedElementIds: this.app.state.selectedElementIds,
+ }));
+ // mark as not completely handled so as to allow dragging etc.
+ return false;
+ }
+
+ // deselect if item is selected
+ // if shift is not clicked, this will always return true
+ // otherwise, it will trigger selection based on current
+ // state of the box
+ if (!this.app.state.selectedElementIds[hitElement.id]) {
+ // if we are currently editing a group, exiting editing mode and deselect the group.
+ if (
+ this.app.state.editingGroupId &&
+ !isElementInGroup(hitElement, this.app.state.editingGroupId)
+ ) {
+ this.app.setState({
+ selectedElementIds: makeNextSelectedElementIds(
+ {},
+ this.app.state,
+ ),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+
+ // Add hit element to selection. At this point if we're not holding
+ // SHIFT the previously selected element(s) were deselected above
+ // (make sure you use setState updater to use latest state)
+ // With shift-selection, we want to make sure that frames and their containing
+ // elements are not selected at the same time.
+ if (
+ !someHitElementIsSelected &&
+ !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
+ ) {
+ this.app.setState((prevState) => {
+ let nextSelectedElementIds: { [id: string]: true } = {
+ ...prevState.selectedElementIds,
+ [hitElement.id]: true,
+ };
+
+ const previouslySelectedElements: ExcalidrawElement[] = [];
+
+ Object.keys(prevState.selectedElementIds).forEach((id) => {
+ const element = this.app.scene.getElement(id);
+ element && previouslySelectedElements.push(element);
+ });
+
+ // if hitElement is frame-like, deselect all of its elements
+ // if they are selected
+ if (isFrameLikeElement(hitElement)) {
+ getFrameChildren(
+ previouslySelectedElements,
+ hitElement.id,
+ ).forEach((element) => {
+ delete nextSelectedElementIds[element.id];
+ });
+ } else if (hitElement.frameId) {
+ // if hitElement is in a frame and its frame has been selected
+ // disable selection for the given element
+ if (nextSelectedElementIds[hitElement.frameId]) {
+ delete nextSelectedElementIds[hitElement.id];
+ }
+ } else {
+ // hitElement is neither a frame nor an element in a frame
+ // but since hitElement could be in a group with some frames
+ // this means selecting hitElement will have the frames selected as well
+ // because we want to keep the invariant:
+ // - frames and their elements are not selected at the same time
+ // we deselect elements in those frames that were previously selected
+
+ const groupIds = hitElement.groupIds;
+ const framesInGroups = new Set(
+ groupIds
+ .flatMap((gid) =>
+ getElementsInGroup(
+ this.app.scene.getNonDeletedElements(),
+ gid,
+ ),
+ )
+ .filter((element) => isFrameLikeElement(element))
+ .map((frame) => frame.id),
+ );
+
+ if (framesInGroups.size > 0) {
+ previouslySelectedElements.forEach((element) => {
+ if (
+ element.frameId &&
+ framesInGroups.has(element.frameId)
+ ) {
+ // deselect element and groups containing the element
+ delete nextSelectedElementIds[element.id];
+ element.groupIds
+ .flatMap((gid) =>
+ getElementsInGroup(
+ this.app.scene.getNonDeletedElements(),
+ gid,
+ ),
+ )
+ .forEach((element) => {
+ delete nextSelectedElementIds[element.id];
+ });
+ }
+ });
+ }
+ }
+
+ // Finally, in shape selection mode, we'd like to
+ // keep only one shape or group selected at a time.
+ // This means, if the hitElement is a different shape or group
+ // than the previously selected ones, we deselect the previous ones
+ // and select the hitElement
+ if (prevState.openDialog?.name === "elementLinkSelector") {
+ if (
+ !hitElement.groupIds.some(
+ (gid) => prevState.selectedGroupIds[gid],
+ )
+ ) {
+ nextSelectedElementIds = {
+ [hitElement.id]: true,
+ };
+ }
+ }
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ this.app,
+ ),
+ showHyperlinkPopup:
+ hitElement.link || isEmbeddableElement(hitElement)
+ ? "info"
+ : false,
+ };
+ });
+ pointerDownState.hit.wasAddedToSelection = true;
+ }
+ }
+ }
+
+ this.app.setState({
+ previousSelectedElementIds: this.app.state.selectedElementIds,
+ });
+ }
+ }
+ return false;
+ };
+
+ maybeHandleCrop = (
+ pointerDownState: PointerDownState,
+ event: MouseEvent | KeyboardEvent,
+ ): boolean => {
+ // to crop, we must already be in the cropping mode, where croppingElement has been set
+ if (!this.app.state.croppingElementId) {
+ return false;
+ }
+
+ const transformHandleType = pointerDownState.resize.handleType;
+ const pointerCoords = pointerDownState.lastCoords;
+ const [x, y] = getGridPoint(
+ pointerCoords.x - pointerDownState.resize.offset.x,
+ pointerCoords.y - pointerDownState.resize.offset.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.app.getEffectiveGridSize(),
+ );
+
+ const croppingElement = this.app.scene
+ .getNonDeletedElementsMap()
+ .get(this.app.state.croppingElementId);
+
+ if (
+ transformHandleType &&
+ croppingElement &&
+ isImageElement(croppingElement)
+ ) {
+ const croppingAtStateStart = pointerDownState.originalElements.get(
+ croppingElement.id,
+ );
+
+ const image =
+ isInitializedImageElement(croppingElement) &&
+ this.app.imageCache.get(croppingElement.fileId)?.image;
+
+ if (
+ croppingAtStateStart &&
+ isImageElement(croppingAtStateStart) &&
+ image &&
+ !(image instanceof Promise)
+ ) {
+ const [gridX, gridY] = getGridPoint(
+ pointerCoords.x,
+ pointerCoords.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.app.getEffectiveGridSize(),
+ );
+
+ const dragOffset = {
+ x: gridX - pointerDownState.originInGrid.x,
+ y: gridY - pointerDownState.originInGrid.y,
+ };
+
+ this.app.maybeCacheReferenceSnapPoints(event, [croppingElement]);
+
+ const { snapOffset, snapLines } = snapResizingElements(
+ [croppingElement],
+ [croppingAtStateStart],
+ this.app,
+ event,
+ dragOffset,
+ transformHandleType,
+ );
+
+ this.app.scene.mutateElement(
+ croppingElement,
+ cropElement(
+ croppingElement,
+ this.app.scene.getNonDeletedElementsMap(),
+ transformHandleType,
+ image.naturalWidth,
+ image.naturalHeight,
+ x + snapOffset.x,
+ y + snapOffset.y,
+ event.shiftKey
+ ? croppingAtStateStart.width / croppingAtStateStart.height
+ : undefined,
+ ),
+ );
+
+ updateBoundElements(croppingElement, this.app.scene);
+
+ this.app.setState({
+ isCropping: transformHandleType && transformHandleType !== "rotation",
+ snapLines,
+ });
+ }
+
+ return true;
+ }
+
+ return false;
+ };
+
+ maybeHandleResize = (
+ pointerDownState: PointerDownState,
+ event: MouseEvent | KeyboardEvent,
+ ): boolean => {
+ const selectedElements = this.app.scene.getSelectedElements(this.app.state);
+ const selectedFrames = selectedElements.filter(isFrameLikeElement);
+
+ const transformHandleType = pointerDownState.resize.handleType;
+
+ if (
+ // Frames cannot be rotated.
+ (selectedFrames.length > 0 && transformHandleType === "rotation") ||
+ // Elbow arrows cannot be transformed (resized or rotated).
+ (selectedElements.length === 1 && isElbowArrow(selectedElements[0])) ||
+ // Do not resize when in crop mode
+ this.app.state.croppingElementId
+ ) {
+ return false;
+ }
+
+ // an alt-resize resizes only once it's a deliberate drag, leaving
+ // alt-clicks to cycle the selection
+ if (
+ event.altKey &&
+ transformHandleType &&
+ transformHandleType !== "rotation" &&
+ !this.app.state.isResizing &&
+ pointDistance(
+ pointFrom(pointerDownState.origin.x, pointerDownState.origin.y),
+ pointFrom(pointerDownState.lastCoords.x, pointerDownState.lastCoords.y),
+ ) *
+ this.app.state.zoom.value <
+ DRAGGING_THRESHOLD
+ ) {
+ return true;
+ }
+
+ this.app.activeResizeHandle =
+ transformHandleType && transformHandleType !== "rotation"
+ ? transformHandleType
+ : null;
+ this.app.setState({
+ // TODO: rename this state field to "isScaling" to distinguish
+ // it from the generic "isResizing" which includes scaling and
+ // rotating
+ isResizing: transformHandleType && transformHandleType !== "rotation",
+ isRotating: transformHandleType === "rotation",
+ activeEmbeddable: null,
+ });
+ const pointerCoords = pointerDownState.lastCoords;
+ let [resizeX, resizeY] = getGridPoint(
+ pointerCoords.x - pointerDownState.resize.offset.x,
+ pointerCoords.y - pointerDownState.resize.offset.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.app.getEffectiveGridSize(),
+ );
+
+ const frameElementsOffsetsMap = new Map<
+ string,
+ {
+ x: number;
+ y: number;
+ }
+ >();
+
+ selectedFrames.forEach((frame) => {
+ const elementsInFrame = getFrameChildren(
+ this.app.scene.getNonDeletedElements(),
+ frame.id,
+ );
+
+ elementsInFrame.forEach((element) => {
+ frameElementsOffsetsMap.set(frame.id + element.id, {
+ x: element.x - frame.x,
+ y: element.y - frame.y,
+ });
+ });
+ });
+
+ // check needed for avoiding flickering when a key gets pressed
+ // during dragging
+ if (!this.app.state.selectedElementsAreBeingDragged) {
+ const [gridX, gridY] = getGridPoint(
+ pointerCoords.x,
+ pointerCoords.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.app.getEffectiveGridSize(),
+ );
+
+ const dragOffset = {
+ x: gridX - pointerDownState.originInGrid.x,
+ y: gridY - pointerDownState.originInGrid.y,
+ };
+
+ const originalElements = [...pointerDownState.originalElements.values()];
+
+ this.app.maybeCacheReferenceSnapPoints(event, selectedElements);
+
+ const { snapOffset, snapLines } = snapResizingElements(
+ selectedElements,
+ getSelectedElements(originalElements, this.app.state),
+ this.app,
+ event,
+ dragOffset,
+ transformHandleType,
+ );
+
+ resizeX += snapOffset.x;
+ resizeY += snapOffset.y;
+
+ this.app.setState({
+ snapLines,
+ });
+ }
+
+ // images are proportional by default, and so is a sticky note's corner
+ // (its label's font ceiling scales with it); Shift frees them. A note's
+ // edges stay free by default — Shift constrains them like any shape.
+ const proportionalByDefault =
+ selectedElements.some((element) => isImageElement(element)) ||
+ (selectedElements.length === 1 &&
+ isStickyNoteElement(selectedElements[0]) &&
+ typeof transformHandleType === "string" &&
+ transformHandleType.length === 2);
+
+ if (
+ transformElements(
+ pointerDownState.originalElements,
+ transformHandleType,
+ selectedElements,
+ this.app.scene,
+ shouldRotateWithDiscreteAngle(event),
+ shouldResizeFromCenter(event),
+ proportionalByDefault
+ ? !shouldMaintainAspectRatio(event)
+ : shouldMaintainAspectRatio(event),
+ resizeX,
+ resizeY,
+ pointerDownState.resize.center.x,
+ pointerDownState.resize.center.y,
+ )
+ ) {
+ const elementsToHighlight = new Set<NonDeletedExcalidrawElement>();
+ selectedFrames.forEach((frame) => {
+ getElementsInResizingFrame(
+ this.app.scene.getNonDeletedElements(),
+ frame,
+ this.app.state,
+ this.app.scene.getNonDeletedElementsMap(),
+ ).forEach((element) => {
+ if (isNonDeletedElement(element)) {
+ elementsToHighlight.add(element);
+ } else {
+ // SAFETY: This should never happen, but log it just in case
+ console.error(
+ "[NONDELETED][INVARIANT] Skipped highlighting deleted element in resizing frame",
+ );
+ }
+ });
+ });
+
+ this.app.setState({
+ elementsToHighlight: [...elementsToHighlight],
+ });
+
+ return true;
+ }
+ return false;
+ };
+
+ /**
+ * Updates the selection on a click (no drag): the element below the
+ * selected one on an alt-click, the clicked element added to or removed
+ * from the selection with shift, or selected, and the selection cleared
+ * by a click hitting only a bounding box.
+ *
+ * @returns whether the pointer event has been completely handled
+ */
+ handleSelectionOnPointerUp = (
+ childEvent: PointerEvent,
+ pointerDownState: PointerDownState,
+ elementsMap: NonDeletedSceneElementsMap,
+ ): boolean => {
+ const hitElement = pointerDownState.hit.element;
+
+ // alt-click: select the element below the selected one
+ const cycleTarget =
+ !pointerDownState.drag.hasOccurred && !this.app.state.isResizing
+ ? pointerDownState.hit.cycleTarget
+ : null;
+ if (cycleTarget) {
+ this.app.setState((prevState) => {
+ const nextState = selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: { [cycleTarget.id]: true },
+ },
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ this.app,
+ );
+ return {
+ ...nextState,
+ selectedLinearElement:
+ isLinearElement(cycleTarget) &&
+ Object.keys(nextState.selectedElementIds).length === 1
+ ? prevState.selectedLinearElement?.elementId === cycleTarget.id
+ ? prevState.selectedLinearElement
+ : new LinearElementEditor(
+ cycleTarget,
+ this.app.scene.getNonDeletedElementsMap(),
+ )
+ : null,
+ showHyperlinkPopup: false,
+ };
+ });
+ }
+
+ if (
+ !cycleTarget &&
+ hitElement &&
+ !pointerDownState.drag.hasOccurred &&
+ !pointerDownState.hit.wasAddedToSelection &&
+ // if we're editing a line, pointerup shouldn't switch selection if
+ // box selected
+ (!this.app.state.selectedLinearElement?.isEditing ||
+ !pointerDownState.boxSelection.hasOccurred) &&
+ // hitElement can be set when alt + ctrl to toggle lasso and we will
+ // just respect the selected elements from lasso instead
+ this.app.state.activeTool.type !== "lasso"
+ ) {
+ // when inside line editor, shift selects points instead
+ if (
+ childEvent.shiftKey &&
+ !this.app.state.selectedLinearElement?.isEditing
+ ) {
+ if (this.app.state.selectedElementIds[hitElement.id]) {
+ if (isSelectedViaGroup(this.app.state, hitElement)) {
+ this.app.setState((_prevState) => {
+ const nextSelectedElementIds = {
+ ..._prevState.selectedElementIds,
+ };
+
+ // We want to unselect all groups hitElement is part of
+ // as well as all elements that are part of the groups
+ // hitElement is part of
+ for (const groupedElement of hitElement.groupIds.flatMap(
+ (groupId) =>
+ getElementsInGroup(
+ this.app.scene.getNonDeletedElements(),
+ groupId,
+ ),
+ )) {
+ delete nextSelectedElementIds[groupedElement.id];
+ }
+
+ return {
+ selectedGroupIds: {
+ ..._prevState.selectedElementIds,
+ ...hitElement.groupIds
+ .map((gId) => ({ [gId]: false }))
+ .reduce((prev, acc) => ({ ...prev, ...acc }), {}),
+ },
+ selectedElementIds: makeNextSelectedElementIds(
+ nextSelectedElementIds,
+ _prevState,
+ ),
+ };
+ });
+ // if not dragging a linear element point (outside editor)
+ } else if (!this.app.state.selectedLinearElement?.isDragging) {
+ // remove element from selection while
+ // keeping prev elements selected
+
+ this.app.setState((prevState) => {
+ const newSelectedElementIds = {
+ ...prevState.selectedElementIds,
+ };
+ delete newSelectedElementIds[hitElement!.id];
+ const newSelectedElements = getSelectedElements(
+ this.app.scene.getNonDeletedElements(),
+ { selectedElementIds: newSelectedElementIds },
+ );
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: newSelectedElementIds,
+ },
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ this.app,
+ ),
+ // set selectedLinearElement only if thats the only element selected
+ selectedLinearElement:
+ newSelectedElements.length === 1 &&
+ isLinearElement(newSelectedElements[0])
+ ? new LinearElementEditor(
+ newSelectedElements[0],
+ this.app.scene.getNonDeletedElementsMap(),
+ )
+ : prevState.selectedLinearElement,
+ };
+ });
+ }
+ } else if (
+ hitElement.frameId &&
+ this.app.state.selectedElementIds[hitElement.frameId]
+ ) {
+ // when hitElement is part of a selected frame, deselect the frame
+ // to avoid frame and containing elements selected simultaneously
+ this.app.setState((prevState) => {
+ const nextSelectedElementIds: {
+ [id: string]: true;
+ } = {
+ ...prevState.selectedElementIds,
+ [hitElement.id]: true,
+ };
+ // deselect the frame
+ delete nextSelectedElementIds[hitElement.frameId!];
+
+ // deselect groups containing the frame
+ (this.app.scene.getElement(hitElement.frameId!)?.groupIds ?? [])
+ .flatMap((gid) =>
+ getElementsInGroup(this.app.scene.getNonDeletedElements(), gid),
+ )
+ .forEach((element) => {
+ delete nextSelectedElementIds[element.id];
+ });
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ this.app,
+ ),
+ showHyperlinkPopup:
+ hitElement.link || isEmbeddableElement(hitElement)
+ ? "info"
+ : false,
+ };
+ });
+ } else {
+ // add element to selection while keeping prev elements selected
+ this.app.setState((_prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ ..._prevState.selectedElementIds,
+ [hitElement!.id]: true,
+ },
+ _prevState,
+ ),
+ }));
+ }
+ } else {
+ this.app.setState((prevState) => ({
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: { [hitElement.id]: true },
+ },
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ this.app,
+ ),
+ selectedLinearElement:
+ isLinearElement(hitElement) &&
+ // Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
+ // Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
+ prevState.selectedLinearElement?.elementId !== hitElement.id
+ ? new LinearElementEditor(
+ hitElement,
+ this.app.scene.getNonDeletedElementsMap(),
+ )
+ : prevState.selectedLinearElement,
+ }));
+ }
+ }
+
+ if (
+ !cycleTarget &&
+ // do not clear selection if lasso is active
+ this.app.state.activeTool.type !== "lasso" &&
+ // not elbow midpoint dragged
+ !(hitElement && isElbowArrow(hitElement)) &&
+ // not dragged
+ !pointerDownState.drag.hasOccurred &&
+ // not resized
+ !this.app.state.isResizing &&
+ // only hitting the bounding box of the previous hit element
+ ((hitElement &&
+ hitElementBoundingBoxOnly(
+ {
+ point: pointFrom(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ ),
+ element: hitElement,
+ elementsMap,
+ threshold: this.app.getElementHitThreshold(hitElement),
+ frameNameBound: isFrameLikeElement(hitElement)
+ ? this.app.frameNameBoundsCache.get(hitElement)
+ : null,
+ },
+ elementsMap,
+ )) ||
+ (!hitElement &&
+ pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements))
+ ) {
+ if (this.app.state.selectedLinearElement?.isEditing) {
+ // Exit editing mode but keep the element selected
+ this.app.actionManager.executeAction(actionToggleLinearEditor);
+ } else {
+ // Deselect selected elements
+ this.app.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.app.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+ // reset cursor
+ this.app.cursor.set(CURSOR_TYPE.AUTO);
+ return true;
+ }
+
+ return false;
+ };
+
+ clearSelection(hitElement: ExcalidrawElement | null): void {
+ this.app.setState((prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds({}, prevState),
+ activeEmbeddable: null,
+ selectedGroupIds: {},
+ // Continue editing the same group if the user selected a different
+ // element from it
+ editingGroupId:
+ prevState.editingGroupId &&
+ hitElement != null &&
+ isElementInGroup(hitElement, prevState.editingGroupId)
+ ? prevState.editingGroupId
+ : null,
+ }));
+ this.app.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.app.state),
+ activeEmbeddable: null,
+ previousSelectedElementIds: this.app.state.selectedElementIds,
+ selectedLinearElement: null,
+ });
+ }
+
+ isASelectedElement(hitElement: ExcalidrawElement | null): boolean {
+ return (
+ hitElement != null && this.app.state.selectedElementIds[hitElement.id]
+ );
+ }
+
+ isHittingCommonBoundingBoxOfSelectedElements(
+ point: Readonly<{ x: number; y: number }>,
+ selectedElements: readonly ExcalidrawElement[],
+ ): boolean {
+ if (selectedElements.length < 2) {
+ return false;
+ }
+
+ // How many pixels off the shape boundary we still consider a hit
+ const threshold = Math.max(
+ DEFAULT_COLLISION_THRESHOLD / this.app.state.zoom.value,
+ 1,
+ );
+ const boundsPadding =
+ (DEFAULT_TRANSFORM_HANDLE_SPACING * 2) / this.app.state.zoom.value;
+ const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
+ return (
+ point.x > x1 - boundsPadding - threshold &&
+ point.x < x2 + boundsPadding + threshold &&
+ point.y > y1 - boundsPadding - threshold &&
+ point.y < y2 + boundsPadding + threshold
+ );
+ }
+
+ /** whether an alt-click on the selection (over other elements) cycles it */
+ canCycleSelection = () => this.getCyclableSelectedUnit() !== null;
+
+ /**
+ * The selectable unit (an element, or the group a click would select) an
+ * element belongs to. Inside an edited group, its elements are units of
+ * their own.
+ */
+ private getSelectableUnit(element: ExcalidrawElement) {
+ const { editingGroupId } = this.app.state;
+ const editingGroupIndex = editingGroupId
+ ? element.groupIds.indexOf(editingGroupId)
+ : -1;
+ const groupIds =
+ editingGroupIndex > -1
+ ? element.groupIds.slice(0, editingGroupIndex)
+ : element.groupIds;
+ return groupIds.length ? groupIds[groupIds.length - 1] : element.id;
+ }
+
+ /**
+ * The selected unit, if an alt-click can cycle away from it: exactly one
+ * is selected, and neither the linear nor the crop editor is open.
+ */
+ private getCyclableSelectedUnit(): string | null {
+ if (
+ this.app.state.selectedLinearElement?.isEditing ||
+ this.app.state.croppingElementId
+ ) {
+ return null;
+ }
+ const selectedUnits = new Set(
+ this.app.scene
+ .getSelectedElements(this.app.state)
+ .map((element) => this.getSelectableUnit(element)),
+ );
+ return selectedUnits.size === 1 ? [...selectedUnits][0] : null;
+ }
+
+ /**
+ * The element an alt-click selects: the selectable unit below the selected
+ * one among the hit elements, wrapping around to the topmost — or `null`
+ * unless it's an alt-click, the selection can cycle, and it's under the
+ * pointer. Inside an edited group, it cycles through the group's elements
+ * only, never leaving the group.
+ */
+ private getSelectionCycleTarget(
+ event: React.PointerEvent<HTMLElement>,
+ hitElements: readonly NonDeleted<ExcalidrawElement>[],
+ ): NonDeleted<ExcalidrawElement> | null {
+ if (!event.altKey || event[KEYS.CTRL_OR_CMD] || event.shiftKey) {
+ return null;
+ }
+ const selectedUnit = this.getCyclableSelectedUnit();
+ if (!selectedUnit) {
+ return null;
+ }
+
+ const { editingGroupId } = this.app.state;
+ if (editingGroupId) {
+ hitElements = hitElements.filter((element) =>
+ isElementInGroup(element, editingGroupId),
+ );
+ }
+
+ // topmost first, each unit at its topmost hit element
+ const units = new Map<string, NonDeleted<ExcalidrawElement>>();
+ for (let index = hitElements.length - 1; index > -1; index--) {
+ const unit = this.getSelectableUnit(hitElements[index]);
+ if (!units.has(unit)) {
+ units.set(unit, hitElements[index]);
+ }
+ }
+ const order = [...units.keys()];
+ const selectedIndex = order.indexOf(selectedUnit);
+ if (selectedIndex === -1) {
+ return null;
+ }
+ // (the selected unit itself if alone)
+ return units.get(order[(selectedIndex + 1) % order.length])!;
+ }
+}
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index ca4da03c1c..848532a8fd 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -29,7 +29,6 @@ import {
CURSOR_TYPE,
DEFAULT_STROKE_STREAMLINE,
DEFAULT_STROKE_STREAMLINE_PRECISE,
- DEFAULT_TRANSFORM_HANDLE_SPACING,
DRAGGING_THRESHOLD,
ELEMENT_SHIFT_TRANSLATE_AMOUNT,
ELEMENT_TRANSLATE_AMOUNT,
@@ -183,29 +182,21 @@ import {
getFrameLikeTitle,
getElementsOverlappingFrame,
hitElementBoundText,
- hitElementBoundingBoxOnly,
hitElementItself,
- cropElement,
isElementLink,
isMeasureTextSupported,
getMinTextElementWidth,
ShapeCache,
resolveElementRenderState,
getRenderElementWithPositionOverride,
- editGroupForSelectedElement,
getElementsInGroup,
getSelectedGroupIdForElement,
getSelectedGroupIds,
- isElementInGroup,
- isSelectedViaGroup,
selectGroupsForSelectedElements,
syncInvalidIndices,
excludeElementsInFramesFromSelection,
getSelectionStateForElements,
makeNextSelectedElementIds,
- getResizeOffsetXY,
- getResizeArrowDirection,
- transformElements,
getCursorForResizingElement,
getElementWithTransformHandleType,
getTransformHandleTypeFromCoords,
@@ -231,7 +222,6 @@ import {
getSnapOutlineMidPoint,
handleFocusPointDrag,
handleFocusPointHover,
- handleFocusPointPointerDown,
handleFocusPointPointerUp,
maybeHandleArrowPointlikeDrag,
getUncroppedWidthAndHeight,
@@ -376,7 +366,6 @@ import {
snapDraggedElements,
isActiveToolNonLinearSnappable,
snapNewElement,
- snapResizingElements,
isSnappingEnabled,
getVisibleGaps,
getReferenceSnapPoints,
@@ -418,9 +407,11 @@ import { AppCursor } from "./App.cursor";
import { AppDrawShape } from "./App.drawshape";
import { AppDuplicate } from "./App.duplicate";
import { AppFlowchart } from "./App.flowchart";
+import { AppModifiers } from "./App.modifiers";
import { AppPan } from "./App.pan";
import { AppViewport, RIGHT_SIDEBAR_WIDTH } from "./App.viewport";
import { AppWheel } from "./App.wheel";
+import { AppSelectionTool } from "./App.selectionTool";
import BraveMeasureTextError from "./BraveMeasureTextError";
import { ContextMenu, CONTEXT_MENU_SEPARATOR } from "./ContextMenu";
import { activeEyeDropperAtom } from "./EyeDropper";
@@ -704,6 +695,7 @@ class App extends React.Component<AppProps, AppState> {
isGestureActive: () => gesture.pointers.size >= 2 || this.pan.isActive(),
});
public wheel: AppWheel = new AppWheel(this);
+ public selectionTool: AppSelectionTool = new AppSelectionTool(this);
bindModeHandler: ReturnType<typeof setTimeout> | null = null;
@@ -769,6 +761,8 @@ class App extends React.Component<AppProps, AppState> {
>();
onRemoveEventListenersEmitter = new Emitter<[]>();
+ modifiers = new AppModifiers();
+
api: ExcalidrawImperativeAPI;
private elementRenderOverrides: ElementRenderOverrides = new Map();
/** offsets of `elementRenderOverrides`; keeps its identity while they don't change */
@@ -3200,6 +3194,7 @@ class App extends React.Component<AppProps, AppState> {
private onBlur = withBatchedUpdates(() => {
this.pan.setSpaceHeld(false);
+ this.modifiers.reset();
this.setState({
isBindingEnabled: this.state.bindingPreference === "enabled",
});
@@ -3289,6 +3284,7 @@ class App extends React.Component<AppProps, AppState> {
this.maybeCleanupAfterMissingPointerUp(null);
this.pan.setSpaceHeld(false);
+ this.modifiers.reset();
isDraggingScrollBar = false;
lastPointerUp = null;
@@ -5255,6 +5251,8 @@ class App extends React.Component<AppProps, AppState> {
return;
}
+ this.modifiers.sync(event);
+
// Handle Alt key for bind mode
if (event.key === KEYS.ALT) {
if (this.state.activeTool.type === "bucketfill") {
@@ -5581,6 +5579,7 @@ class App extends React.Component<AppProps, AppState> {
);
private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
+ this.modifiers.sync(event);
if (!this.isInteractionEnabled()) {
return;
}
@@ -6144,7 +6143,7 @@ class App extends React.Component<AppProps, AppState> {
});
};
- private finishImageCropping = () => {
+ finishImageCropping = () => {
if (this.state.croppingElementId) {
this.store.scheduleCapture();
this.setState({
@@ -6196,6 +6195,11 @@ class App extends React.Component<AppProps, AppState> {
) {
return;
}
+ // alt-clicks cycle the selection, so their double-click does nothing
+ // (autoshape doesn't select, alt is its free-text-at-point escape hatch)
+ if (event.altKey && this.state.activeTool.type !== "autoshape") {
+ return;
+ }
// case: double-clicking with arrow/line tool selected would both create
// text and enter multiElement mode
if (this.state.multiElement) {
@@ -6420,7 +6424,7 @@ class App extends React.Component<AppProps, AppState> {
];
};
- private getElementLinkAtPosition = (
+ getElementLinkAtPosition = (
scenePointer: Readonly<{ x: number; y: number }>,
hitElementMightBeLocked: NonDeletedExcalidrawElement | null,
): NonDeletedExcalidrawElement | undefined => {
@@ -6826,6 +6830,8 @@ class App extends React.Component<AppProps, AppState> {
}
this.savePointer(event.clientX, event.clientY, this.state.cursorButton);
this.lastPointerMoveEvent = event.nativeEvent;
+ // corrects a missed keydown/keyup (e.g. pressed outside the editor)
+ this.modifiers.sync(event);
const scenePointer = viewportCoordsToSceneCoords(event, this.state);
const { x: scenePointerX, y: scenePointerY } = scenePointer;
this.lastPointerMoveCoords = {
@@ -7289,7 +7295,7 @@ class App extends React.Component<AppProps, AppState> {
this.cursor.set(this.textTool.cursorFor(textToolTarget));
} else if (
!event[KEYS.CTRL_OR_CMD] &&
- this.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
scenePointer,
selectedElements,
)
@@ -7309,7 +7315,7 @@ class App extends React.Component<AppProps, AppState> {
) {
if (
(hitElement ||
- this.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
scenePointer,
selectedElements,
)) &&
@@ -7798,9 +7804,11 @@ class App extends React.Component<AppProps, AppState> {
return;
}
- this.clearSelectionIfNotUsingSelection();
+ this.selectionTool.clearSelectionIfNotUsingSelection();
- if (this.handleSelectionOnPointerDown(event, pointerDownState)) {
+ if (
+ this.selectionTool.handleSelectionOnPointerDown(event, pointerDownState)
+ ) {
return;
}
@@ -7819,7 +7827,7 @@ class App extends React.Component<AppProps, AppState> {
if (this.state.activeTool.type === "lasso") {
const hitSelectedElement =
pointerDownState.hit.element &&
- this.isASelectedElement(pointerDownState.hit.element);
+ this.selectionTool.isASelectedElement(pointerDownState.hit.element);
const shouldForceLassoReselect =
event.altKey &&
event[KEYS.CTRL_OR_CMD] &&
@@ -8275,12 +8283,13 @@ class App extends React.Component<AppProps, AppState> {
element: null,
allHitElements: [],
wasAddedToSelection: false,
+ cycleTarget: null,
hasBeenDuplicated: false,
advancedListMarkers: [],
editedTextId: this.duplicate.handedOverTextId,
arrowLabel: false,
hasHitCommonBoundingBoxOfSelectedElements:
- this.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
origin,
selectedElements,
),
@@ -8344,497 +8353,6 @@ class App extends React.Component<AppProps, AppState> {
return true;
}
- private clearSelectionIfNotUsingSelection = (): void => {
- if (!isSelectionLikeTool(this.state.activeTool.type)) {
- this.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.state),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
- }
- };
-
- /**
- * @returns whether the pointer event has been completely handled
- */
- private handleSelectionOnPointerDown = (
- event: React.PointerEvent<HTMLElement>,
- pointerDownState: PointerDownState,
- ): boolean => {
- if (isSelectionLikeTool(this.state.activeTool.type)) {
- if (this.duplicate.hitEditedElement(pointerDownState)) {
- return false;
- }
-
- const elements = this.scene.getNonDeletedElements();
- const elementsMap = this.scene.getNonDeletedElementsMap();
- const selectedElements = this.scene.getSelectedElements(this.state);
-
- if (
- selectedElements.length === 1 &&
- !this.state.selectedLinearElement?.isEditing &&
- !isElbowArrow(selectedElements[0]) &&
- !(
- isLinearElement(selectedElements[0]) &&
- (this.editorInterface.userAgent.isMobileDevice ||
- selectedElements[0].points.length === 2)
- ) &&
- !(
- this.state.selectedLinearElement &&
- this.state.selectedLinearElement.hoverPointIndex !== -1
- )
- ) {
- const elementWithTransformHandleType =
- getElementWithTransformHandleType(
- elements,
- this.state,
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- this.state.zoom,
- event.pointerType,
- this.scene.getNonDeletedElementsMap(),
- this.editorInterface,
- );
- if (elementWithTransformHandleType != null) {
- if (
- elementWithTransformHandleType.transformHandleType === "rotation"
- ) {
- this.setState({
- resizingElement: elementWithTransformHandleType.element,
- });
- pointerDownState.resize.handleType =
- elementWithTransformHandleType.transformHandleType;
- } else if (this.state.croppingElementId) {
- pointerDownState.resize.handleType =
- elementWithTransformHandleType.transformHandleType;
- } else {
- this.setState({
- resizingElement: elementWithTransformHandleType.element,
- });
- pointerDownState.resize.handleType =
- elementWithTransformHandleType.transformHandleType;
- }
- }
- } else if (selectedElements.length > 1) {
- pointerDownState.resize.handleType = getTransformHandleTypeFromCoords(
- getCommonBounds(selectedElements),
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- this.state.zoom,
- event.pointerType,
- this.editorInterface,
- );
- }
- if (pointerDownState.resize.handleType) {
- pointerDownState.resize.isResizing = true;
- pointerDownState.resize.offset = tupleToCoors(
- getResizeOffsetXY(
- pointerDownState.resize.handleType,
- selectedElements,
- elementsMap,
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- ),
- );
- if (
- selectedElements.length === 1 &&
- isLinearElement(selectedElements[0]) &&
- selectedElements[0].points.length === 2
- ) {
- pointerDownState.resize.arrowDirection = getResizeArrowDirection(
- pointerDownState.resize.handleType,
- selectedElements[0],
- );
- }
- } else {
- if (this.state.selectedLinearElement) {
- const linearElementEditor = this.state.selectedLinearElement;
- const ret = LinearElementEditor.handlePointerDown(
- event,
- this,
- this.store,
- pointerDownState.origin,
- linearElementEditor,
- this.scene,
- );
-
- if (ret.hitElement) {
- pointerDownState.hit.element = ret.hitElement;
- }
- pointerDownState.hit.arrowLabel = ret.hitBoundText;
- if (ret.linearElementEditor) {
- this.setState({ selectedLinearElement: ret.linearElementEditor });
- }
- if (ret.didAddPoint) {
- return true;
- }
-
- // Also check at current pointer position if focus point is being hovered
- // (in case we're clicking directly without a prior move event)
- const elementsMap = this.scene.getNonDeletedElementsMap();
- const arrow = LinearElementEditor.getElement(
- linearElementEditor.elementId,
- elementsMap,
- ) as any;
-
- if (arrow && isBindingElement(arrow)) {
- const {
- hitFocusPoint,
- pointerOffset,
- arrowOtherEndpointInitialBinding,
- } = handleFocusPointPointerDown(
- arrow,
- pointerDownState,
- elementsMap,
- this.state,
- );
-
- // If focus point is hit, update state and prevent element selection
- if (hitFocusPoint) {
- this.setState({
- selectedLinearElement: {
- ...linearElementEditor,
- hoveredFocusPointBinding: hitFocusPoint,
- draggedFocusPointBinding: hitFocusPoint,
- pointerOffset,
- initialState: {
- ...linearElementEditor.initialState,
- arrowOtherEndpointInitialBinding,
- },
- },
- });
- return false;
- }
- }
- }
-
- const allHitElements = this.getElementsAtPosition(
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- {
- includeLockedElements: true,
- },
- );
- const unlockedHitElements = allHitElements.filter((e) => !e.locked);
-
- // Cannot set preferSelected in getElementAtPosition as we do in pointer move; consider:
- // A & B: both unlocked, A selected, B on top, A & B overlaps in some way
- // we want to select B when clicking on the overlapping area
- const hitElementMightBeLocked = this.getElementAtPosition(
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- {
- allHitElements,
- },
- );
-
- if (
- !hitElementMightBeLocked ||
- hitElementMightBeLocked.id !== this.state.activeLockedId
- ) {
- this.setState({
- activeLockedId: null,
- });
- }
-
- if (
- hitElementMightBeLocked &&
- hitElementMightBeLocked.locked &&
- !unlockedHitElements.some(
- (el) => this.state.selectedElementIds[el.id],
- )
- ) {
- pointerDownState.hit.element = null;
- } else {
- // hitElement may already be set above, so check first
- pointerDownState.hit.element =
- pointerDownState.hit.element ??
- this.getElementAtPosition(
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- );
- }
-
- this.hitLinkElement = this.getElementLinkAtPosition(
- pointerDownState.origin,
- hitElementMightBeLocked,
- );
-
- if (this.hitLinkElement) {
- return true;
- }
-
- if (
- this.state.croppingElementId &&
- pointerDownState.hit.element?.id !== this.state.croppingElementId
- ) {
- this.finishImageCropping();
- }
-
- if (pointerDownState.hit.element) {
- // Early return if pointer is hitting link icon
- const hitLinkElement = this.getElementLinkAtPosition(
- {
- x: pointerDownState.origin.x,
- y: pointerDownState.origin.y,
- },
- pointerDownState.hit.element,
- );
- if (hitLinkElement) {
- return false;
- }
- }
-
- // For overlapped elements one position may hit
- // multiple elements
- pointerDownState.hit.allHitElements = unlockedHitElements;
-
- const hitElement = pointerDownState.hit.element;
- const someHitElementIsSelected =
- pointerDownState.hit.allHitElements.some((element) =>
- this.isASelectedElement(element),
- ) ||
- // the selected linear element's point handles, midpoint knob and
- // label extend beyond its own hit area, so a hit reported by
- // `LinearElementEditor.handlePointerDown` counts even when the
- // position-based hit test above missed the element
- (hitElement !== null && this.isASelectedElement(hitElement));
- if (
- (hitElement === null || !someHitElementIsSelected) &&
- !event.shiftKey &&
- !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements &&
- (!this.state.selectedLinearElement?.isEditing ||
- (hitElement &&
- hitElement?.id !== this.state.selectedLinearElement?.elementId))
- ) {
- this.clearSelection(hitElement);
- }
-
- if (this.state.selectedLinearElement?.isEditing) {
- this.setState((prevState) => ({
- selectedLinearElement: prevState.selectedLinearElement
- ? {
- ...prevState.selectedLinearElement,
- isEditing:
- !!hitElement &&
- hitElement.id ===
- this.state.selectedLinearElement?.elementId,
- }
- : null,
- selectedElementIds: prevState.selectedLinearElement
- ? makeNextSelectedElementIds(
- {
- [prevState.selectedLinearElement.elementId]: true,
- },
- this.state,
- )
- : makeNextSelectedElementIds({}, prevState),
- }));
- // If we click on something
- } else if (hitElement != null) {
- // == deep selection ==
- // on CMD/CTRL, drill down to hit element regardless of groups etc.
- if (event[KEYS.CTRL_OR_CMD]) {
- if (event.altKey) {
- // ctrl + alt means we're lasso selecting - start lasso trail and switch to lasso tool
-
- // Close any open dialogs that might interfere with lasso selection
- if (this.state.openDialog?.name === "elementLinkSelector") {
- this.setOpenDialog(null);
- }
- this.lassoTrail.startPath(
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- event.shiftKey,
- );
- this.setActiveTool({ type: "lasso", fromSelection: true });
- return false;
- }
- if (!this.state.selectedElementIds[hitElement.id]) {
- pointerDownState.hit.wasAddedToSelection = true;
- }
- this.setState((prevState) => ({
- ...editGroupForSelectedElement(prevState, hitElement),
- previousSelectedElementIds: this.state.selectedElementIds,
- }));
- // mark as not completely handled so as to allow dragging etc.
- return false;
- }
-
- // deselect if item is selected
- // if shift is not clicked, this will always return true
- // otherwise, it will trigger selection based on current
- // state of the box
- if (!this.state.selectedElementIds[hitElement.id]) {
- // if we are currently editing a group, exiting editing mode and deselect the group.
- if (
- this.state.editingGroupId &&
- !isElementInGroup(hitElement, this.state.editingGroupId)
- ) {
- this.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.state),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
- }
-
- // Add hit element to selection. At this point if we're not holding
- // SHIFT the previously selected element(s) were deselected above
- // (make sure you use setState updater to use latest state)
- // With shift-selection, we want to make sure that frames and their containing
- // elements are not selected at the same time.
- if (
- !someHitElementIsSelected &&
- !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
- ) {
- this.setState((prevState) => {
- let nextSelectedElementIds: { [id: string]: true } = {
- ...prevState.selectedElementIds,
- [hitElement.id]: true,
- };
-
- const previouslySelectedElements: ExcalidrawElement[] = [];
-
- Object.keys(prevState.selectedElementIds).forEach((id) => {
- const element = this.scene.getElement(id);
- element && previouslySelectedElements.push(element);
- });
-
- // if hitElement is frame-like, deselect all of its elements
- // if they are selected
- if (isFrameLikeElement(hitElement)) {
- getFrameChildren(
- previouslySelectedElements,
- hitElement.id,
- ).forEach((element) => {
- delete nextSelectedElementIds[element.id];
- });
- } else if (hitElement.frameId) {
- // if hitElement is in a frame and its frame has been selected
- // disable selection for the given element
- if (nextSelectedElementIds[hitElement.frameId]) {
- delete nextSelectedElementIds[hitElement.id];
- }
- } else {
- // hitElement is neither a frame nor an element in a frame
- // but since hitElement could be in a group with some frames
- // this means selecting hitElement will have the frames selected as well
- // because we want to keep the invariant:
- // - frames and their elements are not selected at the same time
- // we deselect elements in those frames that were previously selected
-
- const groupIds = hitElement.groupIds;
- const framesInGroups = new Set(
- groupIds
- .flatMap((gid) =>
- getElementsInGroup(
- this.scene.getNonDeletedElements(),
- gid,
- ),
- )
- .filter((element) => isFrameLikeElement(element))
- .map((frame) => frame.id),
- );
-
- if (framesInGroups.size > 0) {
- previouslySelectedElements.forEach((element) => {
- if (
- element.frameId &&
- framesInGroups.has(element.frameId)
- ) {
- // deselect element and groups containing the element
- delete nextSelectedElementIds[element.id];
- element.groupIds
- .flatMap((gid) =>
- getElementsInGroup(
- this.scene.getNonDeletedElements(),
- gid,
- ),
- )
- .forEach((element) => {
- delete nextSelectedElementIds[element.id];
- });
- }
- });
- }
- }
-
- // Finally, in shape selection mode, we'd like to
- // keep only one shape or group selected at a time.
- // This means, if the hitElement is a different shape or group
- // than the previously selected ones, we deselect the previous ones
- // and select the hitElement
- if (prevState.openDialog?.name === "elementLinkSelector") {
- if (
- !hitElement.groupIds.some(
- (gid) => prevState.selectedGroupIds[gid],
- )
- ) {
- nextSelectedElementIds = {
- [hitElement.id]: true,
- };
- }
- }
-
- return {
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: prevState.editingGroupId,
- selectedElementIds: nextSelectedElementIds,
- },
- this.scene.getNonDeletedElements(),
- prevState,
- this,
- ),
- showHyperlinkPopup:
- hitElement.link || isEmbeddableElement(hitElement)
- ? "info"
- : false,
- };
- });
- pointerDownState.hit.wasAddedToSelection = true;
- }
- }
- }
-
- this.setState({
- previousSelectedElementIds: this.state.selectedElementIds,
- });
- }
- }
- return false;
- };
-
- private isASelectedElement(hitElement: ExcalidrawElement | null): boolean {
- return hitElement != null && this.state.selectedElementIds[hitElement.id];
- }
-
- private isHittingCommonBoundingBoxOfSelectedElements(
- point: Readonly<{ x: number; y: number }>,
- selectedElements: readonly ExcalidrawElement[],
- ): boolean {
- if (selectedElements.length < 2) {
- return false;
- }
-
- // How many pixels off the shape boundary we still consider a hit
- const threshold = Math.max(
- DEFAULT_COLLISION_THRESHOLD / this.state.zoom.value,
- 1,
- );
- const boundsPadding =
- (DEFAULT_TRANSFORM_HANDLE_SPACING * 2) / this.state.zoom.value;
- const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
- return (
- point.x > x1 - boundsPadding - threshold &&
- point.x < x2 + boundsPadding + threshold &&
- point.y > y1 - boundsPadding - threshold &&
- point.y < y2 + boundsPadding + threshold
- );
- }
-
private handleFreeDrawElementOnPointerDown = (
event: React.PointerEvent<HTMLElement>,
elementType: ExcalidrawFreeDrawElement["type"],
@@ -9535,7 +9053,7 @@ class App extends React.Component<AppProps, AppState> {
pointerDownState: PointerDownState,
): (event: KeyboardEvent) => void {
return withBatchedUpdates((event: KeyboardEvent) => {
- if (this.maybeHandleResize(pointerDownState, event)) {
+ if (this.selectionTool.maybeHandleResize(pointerDownState, event)) {
return;
}
this.maybeDragNewGenericElement(pointerDownState, event);
@@ -9548,7 +9066,7 @@ class App extends React.Component<AppProps, AppState> {
return withBatchedUpdates((event: KeyboardEvent) => {
// Prevents focus from escaping excalidraw tab
event.key === KEYS.ALT && event.preventDefault();
- if (this.maybeHandleResize(pointerDownState, event)) {
+ if (this.selectionTool.maybeHandleResize(pointerDownState, event)) {
return;
}
this.maybeDragNewGenericElement(pointerDownState, event);
@@ -9674,10 +9192,10 @@ class App extends React.Component<AppProps, AppState> {
if (pointerDownState.resize.isResizing) {
pointerDownState.lastCoords.x = pointerCoords.x;
pointerDownState.lastCoords.y = pointerCoords.y;
- if (this.maybeHandleCrop(pointerDownState, event)) {
+ if (this.selectionTool.maybeHandleCrop(pointerDownState, event)) {
return true;
}
- if (this.maybeHandleResize(pointerDownState, event)) {
+ if (this.selectionTool.maybeHandleResize(pointerDownState, event)) {
return true;
}
}
@@ -9838,7 +9356,7 @@ class App extends React.Component<AppProps, AppState> {
}
const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
- (element) => this.isASelectedElement(element),
+ (element) => this.selectionTool.isASelectedElement(element),
);
const isSelectingPointsInLineEditor =
@@ -9861,6 +9379,21 @@ class App extends React.Component<AppProps, AppState> {
return;
}
+ // an alt-drag duplicates only once it's a deliberate drag, leaving
+ // alt-clicks to cycle the selection
+ if (
+ event.altKey &&
+ !pointerDownState.drag.hasOccurred &&
+ pointDistance(
+ pointFrom(pointerDownState.origin.x, pointerDownState.origin.y),
+ pointFrom(pointerCoords.x, pointerCoords.y),
+ ) *
+ this.state.zoom.value <
+ DRAGGING_THRESHOLD
+ ) {
+ return;
+ }
+
const selectedElementsHasAFrame = selectedElements.some((e) =>
isFrameLikeElement(e),
);
@@ -11149,213 +10682,12 @@ class App extends React.Component<AppProps, AppState> {
}
if (
- hitElement &&
- !pointerDownState.drag.hasOccurred &&
- !pointerDownState.hit.wasAddedToSelection &&
- // if we're editing a line, pointerup shouldn't switch selection if
- // box selected
- (!this.state.selectedLinearElement?.isEditing ||
- !pointerDownState.boxSelection.hasOccurred) &&
- // hitElement can be set when alt + ctrl to toggle lasso and we will
- // just respect the selected elements from lasso instead
- this.state.activeTool.type !== "lasso"
- ) {
- // when inside line editor, shift selects points instead
- if (
- childEvent.shiftKey &&
- !this.state.selectedLinearElement?.isEditing
- ) {
- if (this.state.selectedElementIds[hitElement.id]) {
- if (isSelectedViaGroup(this.state, hitElement)) {
- this.setState((_prevState) => {
- const nextSelectedElementIds = {
- ..._prevState.selectedElementIds,
- };
-
- // We want to unselect all groups hitElement is part of
- // as well as all elements that are part of the groups
- // hitElement is part of
- for (const groupedElement of hitElement.groupIds.flatMap(
- (groupId) =>
- getElementsInGroup(
- this.scene.getNonDeletedElements(),
- groupId,
- ),
- )) {
- delete nextSelectedElementIds[groupedElement.id];
- }
-
- return {
- selectedGroupIds: {
- ..._prevState.selectedElementIds,
- ...hitElement.groupIds
- .map((gId) => ({ [gId]: false }))
- .reduce((prev, acc) => ({ ...prev, ...acc }), {}),
- },
- selectedElementIds: makeNextSelectedElementIds(
- nextSelectedElementIds,
- _prevState,
- ),
- };
- });
- // if not dragging a linear element point (outside editor)
- } else if (!this.state.selectedLinearElement?.isDragging) {
- // remove element from selection while
- // keeping prev elements selected
-
- this.setState((prevState) => {
- const newSelectedElementIds = {
- ...prevState.selectedElementIds,
- };
- delete newSelectedElementIds[hitElement!.id];
- const newSelectedElements = getSelectedElements(
- this.scene.getNonDeletedElements(),
- { selectedElementIds: newSelectedElementIds },
- );
-
- return {
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: prevState.editingGroupId,
- selectedElementIds: newSelectedElementIds,
- },
- this.scene.getNonDeletedElements(),
- prevState,
- this,
- ),
- // set selectedLinearElement only if thats the only element selected
- selectedLinearElement:
- newSelectedElements.length === 1 &&
- isLinearElement(newSelectedElements[0])
- ? new LinearElementEditor(
- newSelectedElements[0],
- this.scene.getNonDeletedElementsMap(),
- )
- : prevState.selectedLinearElement,
- };
- });
- }
- } else if (
- hitElement.frameId &&
- this.state.selectedElementIds[hitElement.frameId]
- ) {
- // when hitElement is part of a selected frame, deselect the frame
- // to avoid frame and containing elements selected simultaneously
- this.setState((prevState) => {
- const nextSelectedElementIds: {
- [id: string]: true;
- } = {
- ...prevState.selectedElementIds,
- [hitElement.id]: true,
- };
- // deselect the frame
- delete nextSelectedElementIds[hitElement.frameId!];
-
- // deselect groups containing the frame
- (this.scene.getElement(hitElement.frameId!)?.groupIds ?? [])
- .flatMap((gid) =>
- getElementsInGroup(this.scene.getNonDeletedElements(), gid),
- )
- .forEach((element) => {
- delete nextSelectedElementIds[element.id];
- });
-
- return {
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: prevState.editingGroupId,
- selectedElementIds: nextSelectedElementIds,
- },
- this.scene.getNonDeletedElements(),
- prevState,
- this,
- ),
- showHyperlinkPopup:
- hitElement.link || isEmbeddableElement(hitElement)
- ? "info"
- : false,
- };
- });
- } else {
- // add element to selection while keeping prev elements selected
- this.setState((_prevState) => ({
- selectedElementIds: makeNextSelectedElementIds(
- {
- ..._prevState.selectedElementIds,
- [hitElement!.id]: true,
- },
- _prevState,
- ),
- }));
- }
- } else {
- this.setState((prevState) => ({
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: prevState.editingGroupId,
- selectedElementIds: { [hitElement.id]: true },
- },
- this.scene.getNonDeletedElements(),
- prevState,
- this,
- ),
- selectedLinearElement:
- isLinearElement(hitElement) &&
- // Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
- // Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
- prevState.selectedLinearElement?.elementId !== hitElement.id
- ? new LinearElementEditor(
- hitElement,
- this.scene.getNonDeletedElementsMap(),
- )
- : prevState.selectedLinearElement,
- }));
- }
- }
-
- if (
- // do not clear selection if lasso is active
- this.state.activeTool.type !== "lasso" &&
- // not elbow midpoint dragged
- !(hitElement && isElbowArrow(hitElement)) &&
- // not dragged
- !pointerDownState.drag.hasOccurred &&
- // not resized
- !this.state.isResizing &&
- // only hitting the bounding box of the previous hit element
- ((hitElement &&
- hitElementBoundingBoxOnly(
- {
- point: pointFrom(
- pointerDownState.origin.x,
- pointerDownState.origin.y,
- ),
- element: hitElement,
- elementsMap,
- threshold: this.getElementHitThreshold(hitElement),
- frameNameBound: isFrameLikeElement(hitElement)
- ? this.frameNameBoundsCache.get(hitElement)
- : null,
- },
- elementsMap,
- )) ||
- (!hitElement &&
- pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements))
+ this.selectionTool.handleSelectionOnPointerUp(
+ childEvent,
+ pointerDownState,
+ elementsMap,
+ )
) {
- if (this.state.selectedLinearElement?.isEditing) {
- // Exit editing mode but keep the element selected
- this.actionManager.executeAction(actionToggleLinearEditor);
- } else {
- // Deselect selected elements
- this.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.state),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
- }
- // reset cursor
- this.cursor.set(CURSOR_TYPE.AUTO);
return;
}
@@ -11863,28 +11195,6 @@ class App extends React.Component<AppProps, AppState> {
this.addNewImagesToImageCache();
}, IMAGE_RENDER_TIMEOUT);
- private clearSelection(hitElement: ExcalidrawElement | null): void {
- this.setState((prevState) => ({
- selectedElementIds: makeNextSelectedElementIds({}, prevState),
- activeEmbeddable: null,
- selectedGroupIds: {},
- // Continue editing the same group if the user selected a different
- // element from it
- editingGroupId:
- prevState.editingGroupId &&
- hitElement != null &&
- isElementInGroup(hitElement, prevState.editingGroupId)
- ? prevState.editingGroupId
- : null,
- }));
- this.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.state),
- activeEmbeddable: null,
- previousSelectedElementIds: this.state.selectedElementIds,
- selectedLinearElement: null,
- });
- }
-
private handleInteractiveCanvasRef = (canvas: HTMLCanvasElement | null) => {
// canvas is null when unmounting
if (canvas !== null) {
@@ -12279,7 +11589,7 @@ class App extends React.Component<AppProps, AppState> {
const selectedElements = this.scene.getSelectedElements(this.state);
const isHittingCommonBoundBox =
- this.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
{ x, y },
selectedElements,
);
@@ -12450,249 +11760,6 @@ class App extends React.Component<AppProps, AppState> {
}
};
- private maybeHandleCrop = (
- pointerDownState: PointerDownState,
- event: MouseEvent | KeyboardEvent,
- ): boolean => {
- // to crop, we must already be in the cropping mode, where croppingElement has been set
- if (!this.state.croppingElementId) {
- return false;
- }
-
- const transformHandleType = pointerDownState.resize.handleType;
- const pointerCoords = pointerDownState.lastCoords;
- const [x, y] = getGridPoint(
- pointerCoords.x - pointerDownState.resize.offset.x,
- pointerCoords.y - pointerDownState.resize.offset.y,
- event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
- );
-
- const croppingElement = this.scene
- .getNonDeletedElementsMap()
- .get(this.state.croppingElementId);
-
- if (
- transformHandleType &&
- croppingElement &&
- isImageElement(croppingElement)
- ) {
- const croppingAtStateStart = pointerDownState.originalElements.get(
- croppingElement.id,
- );
-
- const image =
- isInitializedImageElement(croppingElement) &&
- this.imageCache.get(croppingElement.fileId)?.image;
-
- if (
- croppingAtStateStart &&
- isImageElement(croppingAtStateStart) &&
- image &&
- !(image instanceof Promise)
- ) {
- const [gridX, gridY] = getGridPoint(
- pointerCoords.x,
- pointerCoords.y,
- event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
- );
-
- const dragOffset = {
- x: gridX - pointerDownState.originInGrid.x,
- y: gridY - pointerDownState.originInGrid.y,
- };
-
- this.maybeCacheReferenceSnapPoints(event, [croppingElement]);
-
- const { snapOffset, snapLines } = snapResizingElements(
- [croppingElement],
- [croppingAtStateStart],
- this,
- event,
- dragOffset,
- transformHandleType,
- );
-
- this.scene.mutateElement(
- croppingElement,
- cropElement(
- croppingElement,
- this.scene.getNonDeletedElementsMap(),
- transformHandleType,
- image.naturalWidth,
- image.naturalHeight,
- x + snapOffset.x,
- y + snapOffset.y,
- event.shiftKey
- ? croppingAtStateStart.width / croppingAtStateStart.height
- : undefined,
- ),
- );
-
- updateBoundElements(croppingElement, this.scene);
-
- this.setState({
- isCropping: transformHandleType && transformHandleType !== "rotation",
- snapLines,
- });
- }
-
- return true;
- }
-
- return false;
- };
-
- private maybeHandleResize = (
- pointerDownState: PointerDownState,
- event: MouseEvent | KeyboardEvent,
- ): boolean => {
- const selectedElements = this.scene.getSelectedElements(this.state);
- const selectedFrames = selectedElements.filter(isFrameLikeElement);
-
- const transformHandleType = pointerDownState.resize.handleType;
-
- if (
- // Frames cannot be rotated.
- (selectedFrames.length > 0 && transformHandleType === "rotation") ||
- // Elbow arrows cannot be transformed (resized or rotated).
- (selectedElements.length === 1 && isElbowArrow(selectedElements[0])) ||
- // Do not resize when in crop mode
- this.state.croppingElementId
- ) {
- return false;
- }
-
- this.activeResizeHandle =
- transformHandleType && transformHandleType !== "rotation"
- ? transformHandleType
- : null;
- this.setState({
- // TODO: rename this state field to "isScaling" to distinguish
- // it from the generic "isResizing" which includes scaling and
- // rotating
- isResizing: transformHandleType && transformHandleType !== "rotation",
- isRotating: transformHandleType === "rotation",
- activeEmbeddable: null,
- });
- const pointerCoords = pointerDownState.lastCoords;
- let [resizeX, resizeY] = getGridPoint(
- pointerCoords.x - pointerDownState.resize.offset.x,
- pointerCoords.y - pointerDownState.resize.offset.y,
- event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
- );
-
- const frameElementsOffsetsMap = new Map<
- string,
- {
- x: number;
- y: number;
- }
- >();
-
- selectedFrames.forEach((frame) => {
- const elementsInFrame = getFrameChildren(
- this.scene.getNonDeletedElements(),
- frame.id,
- );
-
- elementsInFrame.forEach((element) => {
- frameElementsOffsetsMap.set(frame.id + element.id, {
- x: element.x - frame.x,
- y: element.y - frame.y,
- });
- });
- });
-
- // check needed for avoiding flickering when a key gets pressed
- // during dragging
- if (!this.state.selectedElementsAreBeingDragged) {
- const [gridX, gridY] = getGridPoint(
- pointerCoords.x,
- pointerCoords.y,
- event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
- );
-
- const dragOffset = {
- x: gridX - pointerDownState.originInGrid.x,
- y: gridY - pointerDownState.originInGrid.y,
- };
-
- const originalElements = [...pointerDownState.originalElements.values()];
-
- this.maybeCacheReferenceSnapPoints(event, selectedElements);
-
- const { snapOffset, snapLines } = snapResizingElements(
- selectedElements,
- getSelectedElements(originalElements, this.state),
- this,
- event,
- dragOffset,
- transformHandleType,
- );
-
- resizeX += snapOffset.x;
- resizeY += snapOffset.y;
-
- this.setState({
- snapLines,
- });
- }
-
- // images are proportional by default, and so is a sticky note's corner
- // (its label's font ceiling scales with it); Shift frees them. A note's
- // edges stay free by default — Shift constrains them like any shape.
- const proportionalByDefault =
- selectedElements.some((element) => isImageElement(element)) ||
- (selectedElements.length === 1 &&
- isStickyNoteElement(selectedElements[0]) &&
- typeof transformHandleType === "string" &&
- transformHandleType.length === 2);
-
- if (
- transformElements(
- pointerDownState.originalElements,
- transformHandleType,
- selectedElements,
- this.scene,
- shouldRotateWithDiscreteAngle(event),
- shouldResizeFromCenter(event),
- proportionalByDefault
- ? !shouldMaintainAspectRatio(event)
- : shouldMaintainAspectRatio(event),
- resizeX,
- resizeY,
- pointerDownState.resize.center.x,
- pointerDownState.resize.center.y,
- )
- ) {
- const elementsToHighlight = new Set<NonDeletedExcalidrawElement>();
- selectedFrames.forEach((frame) => {
- getElementsInResizingFrame(
- this.scene.getNonDeletedElements(),
- frame,
- this.state,
- this.scene.getNonDeletedElementsMap(),
- ).forEach((element) => {
- if (isNonDeletedElement(element)) {
- elementsToHighlight.add(element);
- } else {
- // SAFETY: This should never happen, but log it just in case
- console.error(
- "[NONDELETED][INVARIANT] Skipped highlighting deleted element in resizing frame",
- );
- }
- });
- });
-
- this.setState({
- elementsToHighlight: [...elementsToHighlight],
- });
-
- return true;
- }
- return false;
- };
-
private getContextMenuItems = (
type: "canvas" | "element",
): ContextMenuItems => {
diff --git a/packages/excalidraw/components/HintViewer.tsx b/packages/excalidraw/components/HintViewer.tsx
index eb7191a00c..7ca24d58ce 100644
--- a/packages/excalidraw/components/HintViewer.tsx
+++ b/packages/excalidraw/components/HintViewer.tsx
@@ -1,4 +1,8 @@
-import { CANVAS_SEARCH_TAB, DEFAULT_SIDEBAR } from "@excalidraw/common";
+import {
+ CANVAS_SEARCH_TAB,
+ DEFAULT_SIDEBAR,
+ isSelectionLikeTool,
+} from "@excalidraw/common";
import {
isArrowElement,
@@ -41,7 +45,8 @@ const getHints = ({
isMobile,
editorInterface,
app,
-}: HintViewerProps): null | string | string[] => {
+ altHeld,
+}: HintViewerProps & { altHeld: boolean }): null | string | string[] => {
const { activeTool, isResizing, isRotating, lastPointerDownWith } = appState;
const multiMode = appState.multiElement !== null;
@@ -152,6 +157,23 @@ const getHints = ({
});
}
+ if (
+ // as the alt-click that cycles it (Shift and Ctrl/Cmd don't re-render
+ // the hint, they're read as they are when Alt does)
+ altHeld &&
+ !app.modifiers.get().shift &&
+ !app.modifiers.get().ctrlOrCmd &&
+ !isMobile &&
+ isSelectionLikeTool(activeTool.type) &&
+ !appState.editingTextElement &&
+ !appState.selectedElementsAreBeingDragged &&
+ app.selectionTool.canCycleSelection()
+ ) {
+ return t("hints.cycleSelection", {
+ shortcut: getTaggedShortcutKey("Alt"),
+ });
+ }
+
if (selectedElements.length === 1 && isTextElement(selectedElements[0])) {
return t("hints.text_selected", {
shortcut: getTaggedShortcutKey("Enter"),
@@ -273,6 +295,8 @@ export const HintViewer = ({
editorInterface,
app,
}: HintViewerProps) => {
+ const altHeld = app.modifiers.useHeld("alt");
+
if (!appState.showHints) {
return null;
}
@@ -282,6 +306,7 @@ export const HintViewer = ({
isMobile,
editorInterface,
app,
+ altHeld,
});
if (!hints) {
diff --git a/packages/excalidraw/locales/en.json b/packages/excalidraw/locales/en.json
index 5041881a1f..f21d507559 100644
--- a/packages/excalidraw/locales/en.json
+++ b/packages/excalidraw/locales/en.json
@@ -403,6 +403,7 @@
"bindTextToElement": "{{shortcut}} to add text",
"createFlowchart": "{{shortcut}} to create a flowchart",
"deepBoxSelect": "Hold {{shortcut}} to deep select, and to prevent dragging",
+ "cycleSelection": "{{shortcut}}-click to cycle selection, or drag to duplicate",
"eraserRevert": "Hold {{shortcut}} to revert the elements marked for deletion",
"firefox_clipboard_write": "This feature can likely be enabled by setting the \"dom.events.asyncClipboard.clipboardItem\" flag to \"true\". To change the browser flags in Firefox, visit the \"about:config\" page.",
"disableSnapping": "Hold {{shortcut}} to disable snapping",
diff --git a/packages/excalidraw/tests/helpers/api.ts b/packages/excalidraw/tests/helpers/api.ts
index 5b4a21a66f..39845b9511 100644
--- a/packages/excalidraw/tests/helpers/api.ts
+++ b/packages/excalidraw/tests/helpers/api.ts
@@ -153,8 +153,7 @@ export class API {
static clearSelection = () => {
act(() => {
- // @ts-ignore
- h.app.clearSelection(null);
+ h.app.selectionTool.clearSelection(null);
});
expect(API.getSelectedElements().length).toBe(0);
};
diff --git a/packages/excalidraw/tests/selection.test.tsx b/packages/excalidraw/tests/selection.test.tsx
index a016a2eb98..96f471b56d 100644
--- a/packages/excalidraw/tests/selection.test.tsx
+++ b/packages/excalidraw/tests/selection.test.tsx
@@ -21,6 +21,7 @@ import {
act,
render,
fireEvent,
+ GlobalTestState,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
assertSelectedElements,
@@ -201,6 +202,192 @@ describe("lasso reselection", () => {
});
});
+describe("alt-click cycling", () => {
+ beforeEach(async () => {
+ await render(<Excalidraw />);
+ });
+
+ // bottom to top, all three overlapping at (50, 50)
+ const createStack = (groupIds: { bottom?: string[]; middle?: string[] }) => {
+ const [bottom, middle, top] = (["bottom", "middle", "top"] as const).map(
+ (name, index) =>
+ API.createElement({
+ type: "rectangle",
+ x: index * 10,
+ y: index * 10,
+ width: 100,
+ height: 100,
+ backgroundColor: "red",
+ fillStyle: "solid",
+ groupIds: name === "top" ? [] : groupIds[name] ?? [],
+ }),
+ );
+ API.setElements([bottom, middle, top]);
+ return { bottom, middle, top };
+ };
+
+ it("selects the element below the selected one, wrapping around to the topmost", () => {
+ const { bottom, middle, top } = createStack({});
+
+ mouse.clickAt(50, 50);
+ assertSelectedElements([top.id]);
+
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.clickAt(50, 50);
+ assertSelectedElements([middle.id]);
+ mouse.clickAt(50, 50);
+ assertSelectedElements([bottom.id]);
+ mouse.clickAt(50, 50);
+ assertSelectedElements([top.id]);
+ });
+ });
+
+ it("cycles through the edited group's elements only", () => {
+ const { bottom, middle } = createStack({
+ bottom: ["group"],
+ middle: ["group"],
+ });
+
+ // deep select the middle one where the top one isn't
+ Keyboard.withModifierKeys({ ctrl: true }, () => {
+ mouse.clickAt(15, 15);
+ });
+ assertSelectedElements([middle.id]);
+ expect(h.state.editingGroupId).toBe("group");
+
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.clickAt(50, 50);
+ assertSelectedElements([bottom.id]);
+ mouse.clickAt(50, 50);
+ assertSelectedElements([middle.id]);
+ });
+ expect(h.state.editingGroupId).toBe("group");
+ });
+
+ it("cycles on the selected element's resize handle, alt-resizing only past the drag threshold", () => {
+ const { middle, top } = createStack({});
+
+ // the middle one's right resize handle, over the top one (a bit of a
+ // drag still being a click)
+ API.setSelectedElements([middle]);
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.downAt(113, 60);
+ mouse.moveTo(118, 60);
+ mouse.upAt();
+ });
+ assertSelectedElements([top.id]);
+ expect(API.getElement(middle).width).toBe(100);
+
+ API.setSelectedElements([middle]);
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.downAt(113, 60);
+ mouse.moveTo(153, 60);
+ mouse.upAt();
+ });
+ assertSelectedElements([middle.id]);
+ // (resized from its center)
+ expect(API.getElement(middle)).toMatchObject({ x: -30, width: 180 });
+ });
+
+ it("sets up the line editor of an arrow it selects", () => {
+ const rectangle = API.createElement({
+ type: "rectangle",
+ width: 100,
+ height: 100,
+ backgroundColor: "red",
+ fillStyle: "solid",
+ });
+ const arrow = API.createElement({
+ type: "arrow",
+ x: 20,
+ y: 50,
+ width: 60,
+ height: 0,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(60, 0)],
+ });
+ API.setElements([rectangle, arrow]);
+
+ // (off the arrow's midpoint knob)
+ mouse.clickAt(35, 50);
+ assertSelectedElements([arrow.id]);
+
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.clickAt(35, 50);
+ assertSelectedElements([rectangle.id]);
+ mouse.clickAt(35, 50);
+ });
+ assertSelectedElements([arrow.id]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+ });
+
+ it("alt+double-click doesn't create or edit text", () => {
+ createStack({});
+ mouse.clickAt(50, 50);
+
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.doubleClickAt(50, 50);
+ });
+
+ expect(h.state.editingTextElement).toBe(null);
+ expect(h.elements.length).toBe(3);
+ });
+
+ it("hints at cycling while Alt is held over a single selection", () => {
+ const { middle, top } = createStack({});
+ const hint = () =>
+ h.app.ownerDocument.querySelector(".HintViewer")?.textContent ?? "";
+ const cycleHint = "to cycle selection";
+ const press = (modifiers: { alt?: boolean; ctrl?: boolean }) =>
+ Keyboard.withModifierKeys(modifiers, () => {
+ Keyboard.keyDown(KEYS.ALT, GlobalTestState.interactiveCanvas);
+ });
+ const release = () =>
+ Keyboard.keyUp(KEYS.ALT, GlobalTestState.interactiveCanvas);
+
+ mouse.clickAt(50, 50);
+ expect(hint()).not.toContain(cycleHint);
+ press({ alt: true });
+ expect(hint()).toContain(cycleHint);
+ // (the hover refresh after the click doesn't release Alt)
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.clickAt(50, 50);
+ });
+ assertSelectedElements([middle.id]);
+ expect(hint()).toContain(cycleHint);
+ release();
+ expect(hint()).not.toContain(cycleHint);
+
+ // Alt+Tab never delivers the keyup
+ press({ alt: true });
+ fireEvent.blur(window);
+ expect(hint()).not.toContain(cycleHint);
+
+ // (AltGr on Windows) alt-clicks with Ctrl don't cycle
+ press({ alt: true, ctrl: true });
+ expect(hint()).not.toContain(cycleHint);
+ release();
+
+ API.setSelectedElements([middle, top]);
+ press({ alt: true });
+ expect(hint()).not.toContain(cycleHint);
+ release();
+ });
+
+ it("alt-drag duplicates only past the drag threshold", () => {
+ const { top } = createStack({});
+ mouse.clickAt(50, 50);
+
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.downAt(50, 50);
+ mouse.moveTo(55, 55);
+ mouse.upAt();
+ });
+
+ expect(h.elements.length).toBe(3);
+ expect(API.getElement(top)).toMatchObject({ x: top.x, y: top.y });
+ });
+});
+
describe("box-selection overlap mode", () => {
const boxSelect = (
startX: number,
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index e7a999787f..9950f0c048 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -1225,6 +1225,8 @@ export type AppClassProperties = {
duplicate: App["duplicate"];
toolDrag: App["toolDrag"];
activeResizeHandle: App["activeResizeHandle"];
+ selectionTool: App["selectionTool"];
+ modifiers: App["modifiers"];
isToolLocked: App["isToolLocked"];
getEffectiveGridSize: App["getEffectiveGridSize"];
setPlugins: App["setPlugins"];
@@ -1284,6 +1286,10 @@ export type PointerDownState = Readonly<{
allHitElements: NonDeleted<ExcalidrawElement>[];
// This is determined on the initial pointer down event
wasAddedToSelection: boolean;
+ // The element an alt-click selects instead: the one below the selected
+ // one, cycling through the elements under the pointer (determined on the
+ // initial pointer down event)
+ cycleTarget: NonDeleted<ExcalidrawElement> | null;
// Whether selected element(s) were duplicated, might change during the
// pointer interaction
hasBeenDuplicated: boolean;