Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

refactor(editor): app.selection, and the rest of the selection tool out of App (#12258)

David Luzare65eca999e07
diff --git a/packages/element/src/groups.ts b/packages/element/src/groups.ts
index c090a53d54..f241abec60 100644
--- a/packages/element/src/groups.ts
+++ b/packages/element/src/groups.ts
@@ -1,16 +1,12 @@
import type {
- AppClassProperties,
AppState,
InteractiveCanvasAppState,
} from "@excalidraw/excalidraw/types";
-import type { Mutable } from "@excalidraw/common/utility-types";
import { getBoundTextElement } from "./textElement";
import { isBoundToContainer } from "./typeChecks";
-import { makeNextSelectedElementIds, getSelectedElements } from "./selection";
-
import type {
GroupId,
ExcalidrawElement,
@@ -63,151 +59,6 @@ export const selectGroup = (
};
};
-export const selectGroupsForSelectedElements = (function () {
- type SelectGroupsReturnType = Pick<
- InteractiveCanvasAppState,
- "selectedGroupIds" | "editingGroupId" | "selectedElementIds"
- >;
-
- let lastSelectedElements: readonly NonDeletedExcalidrawElement[] | null =
- null;
- let lastElements: readonly NonDeletedExcalidrawElement[] | null = null;
- let lastReturnValue: SelectGroupsReturnType | null = null;
-
- const _selectGroups = (
- selectedElements: readonly NonDeletedExcalidrawElement[],
- elements: readonly NonDeletedExcalidrawElement[],
- appState: Pick<AppState, "selectedElementIds" | "editingGroupId">,
- prevAppState: InteractiveCanvasAppState,
- ): SelectGroupsReturnType => {
- if (
- lastReturnValue !== undefined &&
- elements === lastElements &&
- selectedElements === lastSelectedElements &&
- appState.editingGroupId === lastReturnValue?.editingGroupId
- ) {
- return lastReturnValue;
- }
-
- const selectedGroupIds: Record<GroupId, boolean> = {};
- // Gather all the groups withing selected elements
- for (const selectedElement of selectedElements) {
- let groupIds = selectedElement.groupIds;
- if (appState.editingGroupId) {
- // handle the case where a group is nested within a group
- const indexOfEditingGroup = groupIds.indexOf(appState.editingGroupId);
- if (indexOfEditingGroup > -1) {
- groupIds = groupIds.slice(0, indexOfEditingGroup);
- }
- }
- if (groupIds.length > 0) {
- const lastSelectedGroup = groupIds[groupIds.length - 1];
- selectedGroupIds[lastSelectedGroup] = true;
- }
- }
-
- // Gather all the elements within selected groups
- const groupElementsIndex: Record<GroupId, string[]> = {};
- const selectedElementIdsInGroups = elements.reduce(
- (acc: Record<string, true>, element) => {
- if (element.isDeleted) {
- return acc;
- }
-
- const groupId = element.groupIds.find((id) => selectedGroupIds[id]);
-
- if (groupId) {
- acc[element.id] = true;
-
- // Populate the index
- if (!Array.isArray(groupElementsIndex[groupId])) {
- groupElementsIndex[groupId] = [element.id];
- } else {
- groupElementsIndex[groupId].push(element.id);
- }
- }
- return acc;
- },
- {},
- );
-
- for (const groupId of Object.keys(groupElementsIndex)) {
- // If there is one element in the group, and the group is selected or it's being edited, it's not a group
- if (groupElementsIndex[groupId].length < 2) {
- if (selectedGroupIds[groupId]) {
- selectedGroupIds[groupId] = false;
- }
- }
- }
-
- lastElements = elements;
- lastSelectedElements = selectedElements;
-
- lastReturnValue = {
- editingGroupId: appState.editingGroupId,
- selectedGroupIds,
- selectedElementIds: makeNextSelectedElementIds(
- {
- ...appState.selectedElementIds,
- ...selectedElementIdsInGroups,
- },
- prevAppState,
- ),
- };
-
- return lastReturnValue;
- };
-
- /**
- * When you select an element, you often want to actually select the whole group it's in, unless
- * you're currently editing that group.
- */
- const selectGroupsForSelectedElements = (
- appState: Pick<AppState, "selectedElementIds" | "editingGroupId">,
- elements: readonly NonDeletedExcalidrawElement[],
- prevAppState: InteractiveCanvasAppState,
- /**
- * supply null in cases where you don't have access to App instance and
- * you don't care about optimizing selectElements retrieval
- */
- app: AppClassProperties | null,
- ): Mutable<
- Pick<
- InteractiveCanvasAppState,
- "selectedGroupIds" | "editingGroupId" | "selectedElementIds"
- >
- > => {
- const selectedElements = app
- ? app.scene.getSelectedElements({
- selectedElementIds: appState.selectedElementIds,
- // supplying elements explicitly in case we're passed non-state elements
- elements,
- })
- : getSelectedElements(elements, appState);
-
- if (!selectedElements.length) {
- return {
- selectedGroupIds: {},
- editingGroupId: null,
- selectedElementIds: makeNextSelectedElementIds(
- appState.selectedElementIds,
- prevAppState,
- ),
- };
- }
-
- return _selectGroups(selectedElements, elements, appState, prevAppState);
- };
-
- selectGroupsForSelectedElements.clearCache = () => {
- lastElements = null;
- lastSelectedElements = null;
- lastReturnValue = null;
- };
-
- return selectGroupsForSelectedElements;
-})();
-
/**
* If the element's group is selected, don't render an individual
* selection border around it.
diff --git a/packages/element/src/selection.ts b/packages/element/src/selection.ts
index bd3a76d029..ab31195cda 100644
--- a/packages/element/src/selection.ts
+++ b/packages/element/src/selection.ts
@@ -1,4 +1,4 @@
-import { arrayToMap, isShallowEqual, type Bounds } from "@excalidraw/common";
+import { isShallowEqual, type Bounds } from "@excalidraw/common";
import type {
AppState,
@@ -11,14 +11,10 @@ import { isElementInViewport } from "./sizeHelpers";
import {
isBoundToContainer,
isFrameLikeElement,
- isLinearElement,
isTextElement,
} from "./typeChecks";
import { getFrameChildren } from "./frame";
-import { LinearElementEditor } from "./linearElementEditor";
-import { selectGroupsForSelectedElements } from "./groups";
-
import { isNonDeletedElement } from ".";
import type {
@@ -245,52 +241,6 @@ export const makeNextSelectedElementIds = (
return nextSelectedElementIds;
};
-const _getLinearElementEditor = (
- targetElements: readonly NonDeletedExcalidrawElement[],
- allElements: readonly NonDeletedExcalidrawElement[],
-) => {
- const linears = targetElements.filter(isLinearElement);
- if (linears.length === 1) {
- const linear = linears[0];
- const boundElements = linear.boundElements?.map((def) => def.id) ?? [];
- const onlySingleLinearSelected = targetElements.every(
- (el) => el.id === linear.id || boundElements.includes(el.id),
- );
-
- if (onlySingleLinearSelected) {
- return new LinearElementEditor(linear, arrayToMap(allElements));
- }
- }
-
- return null;
-};
-
-export const getSelectionStateForElements = (
- targetElements: readonly NonDeletedExcalidrawElement[],
- allElements: readonly NonDeletedExcalidrawElement[],
- appState: AppState,
-) => {
- return {
- selectedLinearElement: _getLinearElementEditor(targetElements, allElements),
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: appState.editingGroupId,
- selectedElementIds: excludeElementsInFramesFromSelection(
- targetElements,
- ).reduce((acc: Record<ExcalidrawElement["id"], true>, element) => {
- if (!isBoundToContainer(element)) {
- acc[element.id] = true;
- }
- return acc;
- }, {}),
- },
- allElements,
- appState,
- null,
- ),
- };
-};
-
/**
* Returns editing or single-selected text element, if any.
*/
diff --git a/packages/element/tests/cropElement.test.tsx b/packages/element/tests/cropElement.test.tsx
index 19e729047f..843e745638 100644
--- a/packages/element/tests/cropElement.test.tsx
+++ b/packages/element/tests/cropElement.test.tsx
@@ -136,7 +136,7 @@ describe("Crop an image", () => {
expect(image.height).toBeLessThan(initialHeight);
});
- it("Dragging a crop handle in the crop editor crops the image", () => {
+ it("In the crop editor, dragging a handle crops the image, and dragging the image moves it within its crop", () => {
const image = API.createElement({
type: "image",
width: 200,
@@ -162,6 +162,14 @@ describe("Crop an image", () => {
expect(API.getElement(image)).toMatchObject({ x: 50, width: 150 });
expect(API.getElement(image).crop).toMatchObject({ x: 100, width: 300 });
+
+ // 20px to the right = 40px of the file, at twice the element's size
+ mouse.downAt(100, 50);
+ mouse.move(20, 0);
+ mouse.upAt();
+
+ expect(API.getElement(image)).toMatchObject({ x: 50, width: 150 });
+ expect(API.getElement(image).crop).toMatchObject({ x: 60, width: 300 });
});
it("Cropping has minimal sizes", async () => {
diff --git a/packages/element/tests/linearElementEditor.test.tsx b/packages/element/tests/linearElementEditor.test.tsx
index aed3e4a78e..9f2c8fc576 100644
--- a/packages/element/tests/linearElementEditor.test.tsx
+++ b/packages/element/tests/linearElementEditor.test.tsx
@@ -1901,7 +1901,9 @@ describe("Test Linear Elements", () => {
]);
mouse.reset();
- mouse.clickAt(0, 0);
+ // (not by a click, whose pointerup would normalize — reroute — this
+ // hand-built elbow arrow)
+ act(() => h.app.selection.select(arrow.id));
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
// inside the label AND within the hit radius of the route point at
diff --git a/packages/element/tests/zindex.test.tsx b/packages/element/tests/zindex.test.tsx
index 31dd32ad11..19614fee7d 100644
--- a/packages/element/tests/zindex.test.tsx
+++ b/packages/element/tests/zindex.test.tsx
@@ -18,9 +18,9 @@ import {
unmountComponent,
} from "@excalidraw/excalidraw/tests/test-utils";
-import type { AppState } from "@excalidraw/excalidraw/types";
+import { selectGroupsForSelectedElements } from "@excalidraw/excalidraw/components/App.selection";
-import { selectGroupsForSelectedElements } from "../src/groups";
+import type { AppState } from "@excalidraw/excalidraw/types";
import type {
ExcalidrawElement,
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index 1a32262965..cd4eab1f51 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -13,6 +13,13 @@ Please add the latest change on the top under the correct section.
## Unreleased
+### Selection API (2026-10-10) [#12258](https://github.com/excalidraw/excalidraw/pull/12258)
+
+- New `excalidrawAPI.selection`: `select(elements, opts?)`, `add(elements, opts?)`, `remove(elements, opts?)` and `clear(opts?)`, taking elements or their ids, one or many. Missing and deleted elements are skipped.
+- It follows the editor's rules: an element is selected with its group, a frame and its children aren't selected at the same time, and locked elements are skipped. Text editing and cropping end, and the link popup of a lone selected element with a link shows.
+- Options: `deep` selects the elements themselves rather than their groups, editing their group if they share one (as Ctrl/Cmd+click does); `includeLocked` selects locked elements too; `captureUpdate` records the change for undo as for `updateScene()` — by default it's recorded along with the next undoable change.
+- Like `updateScene()`, the change applies on the next render: read it back through `onChange()` or `getAppState()` after that. It works in view mode too, where the selection shows without the transform handles.
+
### Wheel navigation (2026-09-13) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)
- Scrolling while holding the wheel (middle) mouse button zooms the canvas around the pointer, the same as ctrl/cmd+wheel — a wheel-button pan can be zoomed one-handed, without reaching for a modifier.
diff --git a/packages/excalidraw/actions/actionDeleteSelected.tsx b/packages/excalidraw/actions/actionDeleteSelected.tsx
index 193f5d86d4..54759ce70c 100644
--- a/packages/excalidraw/actions/actionDeleteSelected.tsx
+++ b/packages/excalidraw/actions/actionDeleteSelected.tsx
@@ -16,10 +16,7 @@ import {
} from "@excalidraw/element";
import { getFrameChildren } from "@excalidraw/element";
-import {
- getElementsInGroup,
- selectGroupsForSelectedElements,
-} from "@excalidraw/element";
+import { getElementsInGroup } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
@@ -32,6 +29,8 @@ import { IconButton } from "../components/IconButton";
import { useStylesPanelMode } from "../components/App";
+import { selectGroupsForSelectedElements } from "../components/App.selection";
+
import { register } from "./register";
import type { AppClassProperties, AppState } from "../types";
diff --git a/packages/excalidraw/actions/actionDeselect.ts b/packages/excalidraw/actions/actionDeselect.ts
index 74e7c98cca..8bc26502ff 100644
--- a/packages/excalidraw/actions/actionDeselect.ts
+++ b/packages/excalidraw/actions/actionDeselect.ts
@@ -2,7 +2,6 @@ import {
getElementsInGroup,
isSomeElementSelected,
makeNextSelectedElementIds,
- selectGroupsForSelectedElements,
} from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
import { KEYS, isWritableElement, updateActiveTool } from "@excalidraw/common";
@@ -11,6 +10,8 @@ import type { GroupId } from "@excalidraw/element/types";
import { TOGGLE_TOOLS } from "../components/Tools";
+import { selectGroupsForSelectedElements } from "../components/App.selection";
+
import { register } from "./register";
import type { AppClassProperties, AppState } from "../types";
diff --git a/packages/excalidraw/actions/actionDuplicateSelection.tsx b/packages/excalidraw/actions/actionDuplicateSelection.tsx
index dea47f7cda..a77cd5da54 100644
--- a/packages/excalidraw/actions/actionDuplicateSelection.tsx
+++ b/packages/excalidraw/actions/actionDuplicateSelection.tsx
@@ -9,10 +9,7 @@ import { getNonDeletedElements } from "@excalidraw/element";
import { LinearElementEditor } from "@excalidraw/element";
-import {
- getSelectedElements,
- getSelectionStateForElements,
-} from "@excalidraw/element";
+import { getSelectedElements } from "@excalidraw/element";
import { syncMovedIndices } from "@excalidraw/element";
@@ -29,6 +26,8 @@ import { getShortcutKey } from "../shortcut";
import { useStylesPanelMode } from "../components/App";
+import { getSelectionStateForElements } from "../components/App.selection";
+
import { register } from "./register";
export const actionDuplicateSelection = register({
diff --git a/packages/excalidraw/actions/actionGroup.tsx b/packages/excalidraw/actions/actionGroup.tsx
index 0bc711044a..8093da019b 100644
--- a/packages/excalidraw/actions/actionGroup.tsx
+++ b/packages/excalidraw/actions/actionGroup.tsx
@@ -19,7 +19,6 @@ import { KEYS, randomId, arrayToMap } from "@excalidraw/common";
import {
getSelectedGroupIds,
selectGroup,
- selectGroupsForSelectedElements,
getElementsInGroup,
addToGroup,
removeFromSelectedGroups,
@@ -45,6 +44,8 @@ import { isSomeElementSelected } from "../scene";
import { getShortcutKey } from "../shortcut";
+import { selectGroupsForSelectedElements } from "../components/App.selection";
+
import { register } from "./register";
import type { AppClassProperties, UIAppState } from "../types";
diff --git a/packages/excalidraw/actions/actionSelectAll.ts b/packages/excalidraw/actions/actionSelectAll.ts
index 9e6a07ff5e..104fde2089 100644
--- a/packages/excalidraw/actions/actionSelectAll.ts
+++ b/packages/excalidraw/actions/actionSelectAll.ts
@@ -4,8 +4,6 @@ import { isLinearElement, isTextElement } from "@excalidraw/element";
import { arrayToMap, KEYS } from "@excalidraw/common";
-import { selectGroupsForSelectedElements } from "@excalidraw/element";
-
import { CaptureUpdateAction } from "@excalidraw/element";
import type {
@@ -14,6 +12,8 @@ import type {
NonDeleted,
} from "@excalidraw/element/types";
+import { selectGroupsForSelectedElements } from "../components/App.selection";
+
import { selectAllIcon } from "../components/icons";
import { register } from "./register";
diff --git a/packages/excalidraw/components/App.duplicate.ts b/packages/excalidraw/components/App.duplicate.ts
index 00cce96c54..88fd7ebf04 100644
--- a/packages/excalidraw/components/App.duplicate.ts
+++ b/packages/excalidraw/components/App.duplicate.ts
@@ -16,7 +16,6 @@ import {
duplicateElements,
filterElementsEligibleAsFrameChildren,
getCommonBounds,
- getSelectionStateForElements,
isBindableElement,
isLinearElement,
isTextElement,
@@ -33,6 +32,8 @@ import type {
ExcalidrawTextElement,
} from "@excalidraw/element/types";
+import { getSelectionStateForElements } from "./App.selection";
+
import type { PointerDownState } from "../types";
import type App from "./App";
diff --git a/packages/excalidraw/components/App.selection.ts b/packages/excalidraw/components/App.selection.ts
new file mode 100644
index 0000000000..e5eccbebbf
--- /dev/null
+++ b/packages/excalidraw/components/App.selection.ts
@@ -0,0 +1,756 @@
+import {
+ arrayToMap,
+ DEFAULT_COLLISION_THRESHOLD,
+ DEFAULT_TRANSFORM_HANDLE_SPACING,
+ isReadonlyArray,
+} from "@excalidraw/common";
+import {
+ getCommonBounds,
+ getSelectedElements,
+ getSelectedGroupForElement,
+ isBoundToContainer,
+ isEmbeddableElement,
+ isFrameLikeElement,
+ isLinearElement,
+ LinearElementEditor,
+ makeNextSelectedElementIds,
+} from "@excalidraw/element";
+
+import type {
+ ExcalidrawElement,
+ GroupId,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
+
+import type { Mutable } from "@excalidraw/common/utility-types";
+import type { CaptureUpdateActionType } from "@excalidraw/element";
+
+import type {
+ AppClassProperties,
+ AppState,
+ InteractiveCanvasAppState,
+} from "../types";
+import type App from "./App";
+
+export const selectGroupsForSelectedElements = (function () {
+ type SelectGroupsReturnType = Pick<
+ InteractiveCanvasAppState,
+ "selectedGroupIds" | "editingGroupId" | "selectedElementIds"
+ >;
+
+ let lastSelectedElements: readonly NonDeletedExcalidrawElement[] | null =
+ null;
+ let lastElements: readonly NonDeletedExcalidrawElement[] | null = null;
+ let lastReturnValue: SelectGroupsReturnType | null = null;
+
+ const _selectGroups = (
+ selectedElements: readonly NonDeletedExcalidrawElement[],
+ elements: readonly NonDeletedExcalidrawElement[],
+ appState: Pick<AppState, "selectedElementIds" | "editingGroupId">,
+ prevAppState: InteractiveCanvasAppState,
+ ): SelectGroupsReturnType => {
+ if (
+ lastReturnValue !== undefined &&
+ elements === lastElements &&
+ selectedElements === lastSelectedElements &&
+ appState.editingGroupId === lastReturnValue?.editingGroupId
+ ) {
+ return lastReturnValue;
+ }
+
+ const selectedGroupIds: Record<GroupId, boolean> = {};
+ // Gather all the groups withing selected elements
+ for (const selectedElement of selectedElements) {
+ let groupIds = selectedElement.groupIds;
+ if (appState.editingGroupId) {
+ // handle the case where a group is nested within a group
+ const indexOfEditingGroup = groupIds.indexOf(appState.editingGroupId);
+ if (indexOfEditingGroup > -1) {
+ groupIds = groupIds.slice(0, indexOfEditingGroup);
+ }
+ }
+ if (groupIds.length > 0) {
+ const lastSelectedGroup = groupIds[groupIds.length - 1];
+ selectedGroupIds[lastSelectedGroup] = true;
+ }
+ }
+
+ // Gather all the elements within selected groups
+ const groupElementsIndex: Record<GroupId, string[]> = {};
+ const selectedElementIdsInGroups = elements.reduce(
+ (acc: Record<string, true>, element) => {
+ if (element.isDeleted) {
+ return acc;
+ }
+
+ const groupId = element.groupIds.find((id) => selectedGroupIds[id]);
+
+ if (groupId) {
+ acc[element.id] = true;
+
+ // Populate the index
+ if (!Array.isArray(groupElementsIndex[groupId])) {
+ groupElementsIndex[groupId] = [element.id];
+ } else {
+ groupElementsIndex[groupId].push(element.id);
+ }
+ }
+ return acc;
+ },
+ {},
+ );
+
+ for (const groupId of Object.keys(groupElementsIndex)) {
+ // If there is one element in the group, and the group is selected or it's being edited, it's not a group
+ if (groupElementsIndex[groupId].length < 2) {
+ if (selectedGroupIds[groupId]) {
+ selectedGroupIds[groupId] = false;
+ }
+ }
+ }
+
+ lastElements = elements;
+ lastSelectedElements = selectedElements;
+
+ lastReturnValue = {
+ editingGroupId: appState.editingGroupId,
+ selectedGroupIds,
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ ...appState.selectedElementIds,
+ ...selectedElementIdsInGroups,
+ },
+ prevAppState,
+ ),
+ };
+
+ return lastReturnValue;
+ };
+
+ /**
+ * When you select an element, you often want to actually select the whole group it's in, unless
+ * you're currently editing that group.
+ */
+ const selectGroupsForSelectedElements = (
+ appState: Pick<AppState, "selectedElementIds" | "editingGroupId">,
+ elements: readonly NonDeletedExcalidrawElement[],
+ prevAppState: InteractiveCanvasAppState,
+ /**
+ * supply null in cases where you don't have access to App instance and
+ * you don't care about optimizing selectElements retrieval
+ */
+ app: AppClassProperties | null,
+ ): Mutable<
+ Pick<
+ InteractiveCanvasAppState,
+ "selectedGroupIds" | "editingGroupId" | "selectedElementIds"
+ >
+ > => {
+ const selectedElements = app
+ ? app.scene.getSelectedElements({
+ selectedElementIds: appState.selectedElementIds,
+ // supplying elements explicitly in case we're passed non-state elements
+ elements,
+ })
+ : getSelectedElements(elements, appState);
+
+ if (!selectedElements.length) {
+ return {
+ selectedGroupIds: {},
+ editingGroupId: null,
+ selectedElementIds: makeNextSelectedElementIds(
+ appState.selectedElementIds,
+ prevAppState,
+ ),
+ };
+ }
+
+ return _selectGroups(selectedElements, elements, appState, prevAppState);
+ };
+
+ selectGroupsForSelectedElements.clearCache = () => {
+ lastElements = null;
+ lastSelectedElements = null;
+ lastReturnValue = null;
+ };
+
+ return selectGroupsForSelectedElements;
+})();
+
+/**
+ * The line editor of a lone selected line or arrow (with its labels) —
+ * the current one if it's already that element's.
+ */
+const getLinearElementEditor = (
+ targetElements: readonly NonDeletedExcalidrawElement[],
+ allElements: readonly NonDeletedExcalidrawElement[],
+ appState: Pick<AppState, "selectedLinearElement">,
+) => {
+ const linears = targetElements.filter(isLinearElement);
+ if (linears.length === 1) {
+ const linear = linears[0];
+ const boundElements = linear.boundElements?.map((def) => def.id) ?? [];
+ const onlySingleLinearSelected = targetElements.every(
+ (el) => el.id === linear.id || boundElements.includes(el.id),
+ );
+
+ if (onlySingleLinearSelected) {
+ // keep the current one, e.g. not to reset its `hoverPointIndex`
+ if (appState.selectedLinearElement?.elementId === linear.id) {
+ return appState.selectedLinearElement;
+ }
+ return new LinearElementEditor(linear, arrayToMap(allElements));
+ }
+ }
+
+ return null;
+};
+
+/**
+ * The selection state with the line editor of what it selects: of a lone
+ * selected line or arrow, once groups are expanded.
+ */
+const withLinearElementEditor = <
+ T extends Pick<AppState, "selectedElementIds">,
+>(
+ selectionState: T,
+ allElements: readonly NonDeletedExcalidrawElement[],
+ appState: Pick<AppState, "selectedLinearElement">,
+) => ({
+ ...selectionState,
+ selectedLinearElement: getLinearElementEditor(
+ getSelectedElements(allElements, selectionState),
+ allElements,
+ appState,
+ ),
+});
+
+/**
+ * The frames that selecting the elements selects through their groups (those
+ * selected along with them, within the edited group) — of the elements
+ * neither frames nor in frames.
+ */
+const getFramesSelectedViaGroups = (
+ elements: readonly ExcalidrawElement[],
+ allElements: readonly NonDeletedExcalidrawElement[],
+ editingGroupId: AppState["editingGroupId"],
+) => {
+ const groupIds = new Set<GroupId>();
+ for (const element of elements) {
+ if (isFrameLikeElement(element) || element.frameId) {
+ continue;
+ }
+ const editingGroupIndex = editingGroupId
+ ? element.groupIds.indexOf(editingGroupId)
+ : -1;
+ const elementGroupIds =
+ editingGroupIndex > -1
+ ? element.groupIds.slice(0, editingGroupIndex)
+ : element.groupIds;
+ if (elementGroupIds.length) {
+ groupIds.add(elementGroupIds[elementGroupIds.length - 1]);
+ }
+ }
+
+ const frameIds = new Set<ExcalidrawElement["id"]>();
+ if (groupIds.size) {
+ for (const element of allElements) {
+ if (
+ isFrameLikeElement(element) &&
+ element.groupIds.some((groupId) => groupIds.has(groupId))
+ ) {
+ frameIds.add(element.id);
+ }
+ }
+ }
+ return frameIds;
+};
+
+/**
+ * The selection of the given elements alone, with their groups (within the
+ * edited group): a frame wins over its children, bound text is left to its
+ * container, and a lone line or arrow gets its line editor.
+ *
+ * @param allElements the (non-deleted) elements the selection is in
+ * @param deep select the elements themselves rather than their groups,
+ * editing their innermost group if they share it (and no group otherwise)
+ * — as Ctrl+click does
+ */
+export const getSelectionStateForElements = (
+ targetElements: readonly NonDeletedExcalidrawElement[],
+ allElements: readonly NonDeletedExcalidrawElement[],
+ appState: AppState,
+ deep = false,
+) => {
+ const elements = targetElements.filter(
+ (element) => !isBoundToContainer(element),
+ );
+
+ let editingGroupId = appState.editingGroupId;
+ if (deep) {
+ const innermostGroupIds = new Set(
+ elements.map((element) => element.groupIds[0] ?? null),
+ );
+ editingGroupId =
+ innermostGroupIds.size === 1 ? [...innermostGroupIds][0] : null;
+ }
+
+ // frames win over their children: frames selected, or selected through
+ // the groups (not when deep, selecting no groups)
+ const selectedFrameIds = deep
+ ? new Set<ExcalidrawElement["id"]>()
+ : getFramesSelectedViaGroups(elements, allElements, editingGroupId);
+ for (const element of elements) {
+ if (isFrameLikeElement(element)) {
+ selectedFrameIds.add(element.id);
+ }
+ }
+ const selectedElementIds: Record<ExcalidrawElement["id"], true> = {};
+ for (const element of elements) {
+ if (!element.frameId || !selectedFrameIds.has(element.frameId)) {
+ selectedElementIds[element.id] = true;
+ }
+ }
+
+ return withLinearElementEditor(
+ deep
+ ? {
+ selectedElementIds: makeNextSelectedElementIds(
+ selectedElementIds,
+ appState,
+ ),
+ selectedGroupIds: {},
+ editingGroupId,
+ }
+ : selectGroupsForSelectedElements(
+ { editingGroupId, selectedElementIds },
+ allElements,
+ appState,
+ null,
+ ),
+ allElements,
+ appState,
+ );
+};
+
+/**
+ * The selection with the given elements added, with their groups (within the
+ * edited group) — and the line editor of a lone selected line or arrow.
+ *
+ * A frame and its children aren't selected at the same time: an added frame
+ * deselects its children, an added child of a selected (or added) frame is
+ * left out, and adding elements grouped with frames deselects those frames'
+ * children (and leaves the added ones out). In the element link selector, the
+ * added elements replace the selection (unless one's group is selected).
+ *
+ * @param allElements the (non-deleted) elements the selection is in
+ */
+export const getSelectionStateAddingElements = (
+ targetElements: readonly NonDeletedExcalidrawElement[],
+ allElements: readonly NonDeletedExcalidrawElement[],
+ appState: AppState,
+) => {
+ const elements = targetElements.filter(
+ (element) => !isBoundToContainer(element),
+ );
+
+ let nextSelectedElementIds: Record<ExcalidrawElement["id"], true> = {
+ ...appState.selectedElementIds,
+ };
+ for (const element of elements) {
+ nextSelectedElementIds[element.id] = true;
+ }
+
+ // frames win over their children: the added frames, and the frames selected
+ // through the groups of the added elements
+ const addedFrameIds = new Set<ExcalidrawElement["id"]>();
+ for (const element of elements) {
+ if (isFrameLikeElement(element)) {
+ addedFrameIds.add(element.id);
+ }
+ }
+ const framesInAddedGroups = getFramesSelectedViaGroups(
+ elements,
+ allElements,
+ appState.editingGroupId,
+ );
+ for (const element of elements) {
+ if (
+ !isFrameLikeElement(element) &&
+ element.frameId &&
+ (nextSelectedElementIds[element.frameId] ||
+ framesInAddedGroups.has(element.frameId))
+ ) {
+ delete nextSelectedElementIds[element.id];
+ }
+ }
+
+ // deselect the previously selected children of those frames (and their
+ // groups)
+ if (addedFrameIds.size || framesInAddedGroups.size) {
+ const deselectedGroupIds = new Set<string>();
+ for (const element of allElements) {
+ const { frameId } = element;
+ if (!frameId || !appState.selectedElementIds[element.id]) {
+ continue;
+ }
+ if (addedFrameIds.has(frameId)) {
+ delete nextSelectedElementIds[element.id];
+ }
+ if (framesInAddedGroups.has(frameId)) {
+ delete nextSelectedElementIds[element.id];
+ for (const groupId of element.groupIds) {
+ deselectedGroupIds.add(groupId);
+ }
+ }
+ }
+ if (deselectedGroupIds.size) {
+ for (const element of allElements) {
+ if (
+ element.groupIds.some((groupId) => deselectedGroupIds.has(groupId))
+ ) {
+ delete nextSelectedElementIds[element.id];
+ }
+ }
+ }
+ }
+
+ // in the element link selector, keep only one shape or group selected at a
+ // time: the added elements replace the selection unless one's group is
+ // selected
+ if (
+ appState.openDialog?.name === "elementLinkSelector" &&
+ !elements.some((element) =>
+ element.groupIds.some((groupId) => appState.selectedGroupIds[groupId]),
+ )
+ ) {
+ nextSelectedElementIds = {};
+ for (const element of elements) {
+ nextSelectedElementIds[element.id] = true;
+ }
+ }
+
+ return withLinearElementEditor(
+ selectGroupsForSelectedElements(
+ {
+ editingGroupId: appState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ allElements,
+ appState,
+ null,
+ ),
+ allElements,
+ appState,
+ );
+};
+
+/**
+ * The selection with the given elements removed — with the group they're
+ * selected via (if any) — and a lone remaining line or arrow getting its
+ * line editor.
+ *
+ * @param allElements the (non-deleted) elements the selection is in
+ */
+export const getSelectionStateRemovingElements = (
+ targetElements: readonly NonDeletedExcalidrawElement[],
+ allElements: readonly NonDeletedExcalidrawElement[],
+ appState: AppState,
+) => {
+ const nextSelectedElementIds = { ...appState.selectedElementIds };
+ const removedGroupIds = new Set<string>();
+ for (const element of targetElements) {
+ delete nextSelectedElementIds[element.id];
+ const groupId = getSelectedGroupForElement(appState, element);
+ if (groupId) {
+ removedGroupIds.add(groupId);
+ }
+ }
+ if (removedGroupIds.size) {
+ for (const element of allElements) {
+ if (element.groupIds.some((groupId) => removedGroupIds.has(groupId))) {
+ delete nextSelectedElementIds[element.id];
+ }
+ }
+ }
+
+ return withLinearElementEditor(
+ selectGroupsForSelectedElements(
+ {
+ editingGroupId: appState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ allElements,
+ appState,
+ null,
+ ),
+ allElements,
+ appState,
+ );
+};
+
+/** elements, or their ids — one or many */
+export type ElementsOrIds =
+ | ExcalidrawElement
+ | ExcalidrawElement["id"]
+ | readonly (ExcalidrawElement | ExcalidrawElement["id"])[];
+
+type SelectionChangeOptions = {
+ /**
+ * how the change is recorded for undo (see `updateScene()`) — by default,
+ * along with the next undoable change
+ */
+ captureUpdate?: CaptureUpdateActionType;
+};
+
+type AddOptions = SelectionChangeOptions & {
+ /**
+ * select locked elements too — e.g. for the context menu to offer unlocking
+ * them
+ */
+ includeLocked?: boolean;
+};
+
+type SelectOptions = AddOptions & {
+ /**
+ * select the elements themselves rather than their groups, editing their
+ * innermost group (if they share it) — as Ctrl+click does
+ */
+ deep?: boolean;
+};
+
+/**
+ * The selection: selecting elements, adding them to or removing them from
+ * the selection, and clearing it — keeping its rules: an element is selected
+ * with its group (but within the edited group), a frame and its children
+ * aren't selected at the same time, locked elements aren't selected, and a
+ * lone line or arrow gets its line editor (see the `getSelectionState*()`
+ * functions above).
+ *
+ * What hangs on the selection follows it: the link popup shows for a lone
+ * selected element with a link (or an embeddable), an embed stays active only
+ * while selected, cropping ends (unless the cropped image is selected again),
+ * and selecting (or adding) anything but the edited text ends text editing,
+ * submitting the text. The line editor ends once its line is deselected (see
+ * `componentDidUpdate()`).
+ *
+ * Elements are taken by id from the scene: missing and deleted ones are
+ * skipped.
+ */
+export class AppSelection {
+ constructor(private app: App) {}
+
+ /**
+ * Selects the elements alone (with their groups, unless `deep`).
+ */
+ select = (elementsOrIds: ElementsOrIds, opts: SelectOptions = {}) => {
+ const elements = this.resolve(elementsOrIds, opts.includeLocked);
+ this.beforeChange(
+ // (a click inside the image in the crop editor selects it again)
+ elements.length === 1 &&
+ elements[0].id === this.app.state.croppingElementId,
+ opts,
+ elements,
+ );
+ this.app.setState((prevState) =>
+ this.withFollowingState(
+ prevState,
+ getSelectionStateForElements(
+ elements,
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ opts.deep,
+ ),
+ ),
+ );
+ };
+
+ /**
+ * Adds the elements (with their groups) to the selection.
+ */
+ add = (elementsOrIds: ElementsOrIds, opts: AddOptions = {}) => {
+ const elements = this.resolve(elementsOrIds, opts.includeLocked);
+ this.beforeChange(false, opts, elements);
+ this.app.setState((prevState) =>
+ this.withFollowingState(
+ prevState,
+ getSelectionStateAddingElements(
+ elements,
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ ),
+ ),
+ );
+ };
+
+ /**
+ * Removes the elements from the selection — with the group they're
+ * selected via.
+ */
+ remove = (
+ elementsOrIds: ElementsOrIds,
+ opts: SelectionChangeOptions = {},
+ ) => {
+ const elements = this.resolve(elementsOrIds, true);
+ this.beforeChange(false, opts);
+ this.app.setState((prevState) =>
+ this.withFollowingState(
+ prevState,
+ getSelectionStateRemovingElements(
+ elements,
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ ),
+ ),
+ );
+ };
+
+ /**
+ * Clears the selection, leaving the edited group and ending cropping.
+ *
+ * (Doesn't end text editing: starting it clears the selection.)
+ */
+ clear = (opts: SelectionChangeOptions = {}) => {
+ this.app.finishImageCropping();
+ if (opts.captureUpdate) {
+ this.app.store.scheduleAction(opts.captureUpdate);
+ }
+ this.app.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.app.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ showHyperlinkPopup: false,
+ });
+ };
+
+ /**
+ * Ends what changing the selection ends — cropping (unless
+ * `keepsCroppedImage`), and text editing (unless selecting the edited text,
+ * or its container) — and records the change for undo as asked.
+ *
+ * @param elements the elements being selected (or added) — none for a
+ * change that leaves text editing be
+ */
+ private beforeChange(
+ keepsCroppedImage: boolean,
+ { captureUpdate }: SelectionChangeOptions,
+ elements?: readonly NonDeletedExcalidrawElement[],
+ ) {
+ const { editingTextElement } = this.app.state;
+ if (
+ elements &&
+ editingTextElement &&
+ !elements.some(
+ (element) =>
+ element.id === editingTextElement.id ||
+ element.id === editingTextElement.containerId,
+ )
+ ) {
+ // after the current event, as the editor submits with a flushSync (and
+ // a pointer event's own blur would end it then anyway) — unless another
+ // editing session started meanwhile
+ const submit = this.app.text.textWysiwygSubmitHandler;
+ queueMicrotask(() => {
+ if (submit && this.app.text.textWysiwygSubmitHandler === submit) {
+ submit();
+ }
+ });
+ }
+ if (!keepsCroppedImage) {
+ this.app.finishImageCropping();
+ }
+ if (captureUpdate) {
+ this.app.store.scheduleAction(captureUpdate);
+ }
+ }
+
+ /**
+ * The next selection state with what follows it: the link popup — shown for
+ * a lone selected element with a link (or an embeddable), the link editor
+ * staying open if it's the same element, and hidden otherwise — and the
+ * active embed, which stays active only while selected.
+ */
+ private withFollowingState<T extends Pick<AppState, "selectedElementIds">>(
+ prevState: AppState,
+ nextState: T,
+ ): T & Pick<AppState, "showHyperlinkPopup" | "activeEmbeddable"> {
+ const activeEmbeddable =
+ prevState.activeEmbeddable &&
+ nextState.selectedElementIds[prevState.activeEmbeddable.element.id]
+ ? prevState.activeEmbeddable
+ : null;
+
+ const ids = Object.keys(nextState.selectedElementIds);
+ const element =
+ ids.length === 1
+ ? this.app.scene.getNonDeletedElementsMap().get(ids[0])
+ : undefined;
+ if (!element || !(element.link || isEmbeddableElement(element))) {
+ return { ...nextState, activeEmbeddable, showHyperlinkPopup: false };
+ }
+ const prevIds = Object.keys(prevState.selectedElementIds);
+ return {
+ ...nextState,
+ activeEmbeddable,
+ showHyperlinkPopup:
+ prevState.showHyperlinkPopup === "editor" &&
+ prevIds.length === 1 &&
+ prevIds[0] === element.id
+ ? "editor"
+ : "info",
+ };
+ }
+
+ 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
+ );
+ }
+
+ /**
+ * The scene's (non-deleted) elements, by id, once each — but locked ones,
+ * unless `includeLocked`
+ */
+ private resolve(elementsOrIds: ElementsOrIds, includeLocked = false) {
+ const elementsMap = this.app.scene.getNonDeletedElementsMap();
+ const elements = new Map<
+ ExcalidrawElement["id"],
+ NonDeletedExcalidrawElement
+ >();
+ for (const elementOrId of (isReadonlyArray(elementsOrIds)
+ ? elementsOrIds
+ : [elementsOrIds]) as readonly (ExcalidrawElement | string)[]) {
+ const id = typeof elementOrId === "string" ? elementOrId : elementOrId.id;
+ const element = elementsMap.get(id);
+ if (element && (includeLocked || !element.locked)) {
+ elements.set(id, element);
+ }
+ }
+ return [...elements.values()];
+ }
+}
diff --git a/packages/excalidraw/components/App.selectionTool.ts b/packages/excalidraw/components/App.selectionTool.ts
index dd7e62c614..265ca51bf9 100644
--- a/packages/excalidraw/components/App.selectionTool.ts
+++ b/packages/excalidraw/components/App.selectionTool.ts
@@ -1,7 +1,5 @@
import {
CURSOR_TYPE,
- DEFAULT_COLLISION_THRESHOLD,
- DEFAULT_TRANSFORM_HANDLE_SPACING,
DRAGGING_THRESHOLD,
getGridPoint,
isSelectionLikeTool,
@@ -10,11 +8,15 @@ import {
shouldResizeFromCenter,
shouldRotateWithDiscreteAngle,
tupleToCoors,
+ viewportCoordsToSceneCoords,
} from "@excalidraw/common";
import {
+ addElementsToFrame,
cropElement,
- editGroupForSelectedElement,
+ dragSelectedElements,
getCommonBounds,
+ getCommonFrameId,
+ getElementAbsoluteCoords,
getElementsInGroup,
getElementsInResizingFrame,
getElementWithTransformHandleType,
@@ -22,10 +24,12 @@ import {
getResizeArrowDirection,
getResizeOffsetXY,
getTransformHandleTypeFromCoords,
+ getUncroppedWidthAndHeight,
handleFocusPointPointerDown,
hitElementBoundingBoxOnly,
isBindingElement,
isElbowArrow,
+ isElementInFrame,
isElementInGroup,
isEmbeddableElement,
isFrameLikeElement,
@@ -37,23 +41,41 @@ import {
isStickyNoteElement,
LinearElementEditor,
makeNextSelectedElementIds,
- selectGroupsForSelectedElements,
transformElements,
updateBoundElements,
+ updateFrameMembershipOfSelectedElements,
} from "@excalidraw/element";
-import { pointDistance, pointFrom } from "@excalidraw/math";
-
+import {
+ clamp,
+ pointDistance,
+ pointFrom,
+ pointRotateRads,
+ vector,
+ vectorDot,
+ vectorFromPoint,
+ vectorNormalize,
+ vectorSubtract,
+} from "@excalidraw/math";
+
+import type { TransformHandleType } from "@excalidraw/element";
import type {
ExcalidrawElement,
NonDeleted,
NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
+ PointerType,
} from "@excalidraw/element/types";
import { actionToggleLinearEditor } from "../actions";
-import { getSelectedElements } from "../scene";
+import {
+ getElementsWithinSelection,
+ getSelectedElements,
+ isSomeElementSelected,
+} from "../scene";
-import { snapResizingElements } from "../snapping";
+import { snapDraggedElements, snapResizingElements } from "../snapping";
+
+import { selectGroupsForSelectedElements } from "./App.selection";
import type React from "react";
import type { PointerDownState } from "../types";
@@ -70,12 +92,7 @@ export class AppSelectionTool {
clearSelectionIfNotUsingSelection = (): void => {
if (!isSelectionLikeTool(this.app.state.activeTool.type)) {
- this.app.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.app.state),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
+ this.app.selection.clear();
}
};
@@ -91,66 +108,28 @@ export class AppSelectionTool {
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;
- }
+ const transformHandle = this.getTransformHandleAt(
+ selectedElements,
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ event.pointerType,
+ );
+ if (transformHandle) {
+ // (in the crop editor, the handles crop the image rather than resize it)
+ if (
+ transformHandle.element &&
+ (transformHandle.transformHandleType === "rotation" ||
+ !this.app.state.croppingElementId)
+ ) {
+ this.app.setState({ resizingElement: transformHandle.element });
}
- } 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,
- );
+ pointerDownState.resize.handleType =
+ transformHandle.transformHandleType;
}
if (pointerDownState.resize.handleType) {
pointerDownState.resize.isResizing = true;
@@ -345,13 +324,14 @@ export class AppSelectionTool {
const hitElement = pointerDownState.hit.element;
const someHitElementIsSelected =
pointerDownState.hit.allHitElements.some((element) =>
- this.isASelectedElement(element),
+ this.app.selection.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));
+ (hitElement !== null &&
+ this.app.selection.isASelectedElement(hitElement));
if (
(hitElement === null || !someHitElementIsSelected) &&
!event.shiftKey &&
@@ -407,10 +387,10 @@ export class AppSelectionTool {
if (!this.app.state.selectedElementIds[hitElement.id]) {
pointerDownState.hit.wasAddedToSelection = true;
}
- this.app.setState((prevState) => ({
- ...editGroupForSelectedElement(prevState, hitElement),
+ this.app.setState({
previousSelectedElementIds: this.app.state.selectedElementIds,
- }));
+ });
+ this.app.selection.select(hitElement, { deep: true });
// mark as not completely handled so as to allow dragging etc.
return false;
}
@@ -425,15 +405,7 @@ export class AppSelectionTool {
this.app.state.editingGroupId &&
!isElementInGroup(hitElement, this.app.state.editingGroupId)
) {
- this.app.setState({
- selectedElementIds: makeNextSelectedElementIds(
- {},
- this.app.state,
- ),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
+ this.app.selection.clear();
}
// Add hit element to selection. At this point if we're not holding
@@ -445,111 +417,7 @@ export class AppSelectionTool {
!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,
- };
- });
+ this.app.selection.add(hitElement);
pointerDownState.hit.wasAddedToSelection = true;
}
}
@@ -823,6 +691,557 @@ export class AppSelectionTool {
return false;
};
+ /**
+ * Drags the selection (or, in the crop editor, the image within its crop) —
+ * duplicating it on an alt-drag past the drag threshold.
+ *
+ * @returns whether the pointer event has been completely handled
+ */
+ handleSelectionDragOnPointerMove = (
+ event: PointerEvent,
+ pointerDownState: PointerDownState,
+ pointerCoords: { x: number; y: number },
+ lastPointerCoords: { x: number; y: number },
+ elementsMap: NonDeletedSceneElementsMap,
+ ): boolean => {
+ const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
+ (element) => this.app.selection.isASelectedElement(element),
+ );
+
+ const isSelectingPointsInLineEditor =
+ this.app.state.selectedLinearElement?.isEditing &&
+ event.shiftKey &&
+ this.app.state.selectedLinearElement.elementId ===
+ pointerDownState.hit.element?.id;
+
+ if (
+ (hasHitASelectedElement ||
+ pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements) &&
+ !isSelectingPointsInLineEditor &&
+ !pointerDownState.drag.blockDragging
+ ) {
+ const selectedElements = this.app.scene.getSelectedElements(
+ this.app.state,
+ );
+ if (
+ selectedElements.length > 0 &&
+ selectedElements.every((element) => element.locked)
+ ) {
+ return true;
+ }
+
+ // 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.app.state.zoom.value <
+ DRAGGING_THRESHOLD
+ ) {
+ return true;
+ }
+
+ const selectedElementsHasAFrame = selectedElements.some((e) =>
+ isFrameLikeElement(e),
+ );
+ const frameToHighlight = selectedElementsHasAFrame
+ ? null
+ : this.app.getTopLayerFrameAtSceneCoords(pointerCoords, {
+ currentFrameId: getCommonFrameId(selectedElements),
+ excludeElementIds: this.app.state.selectedElementIds,
+ });
+ // Only update the state if there is a difference
+ this.app.updateFrameToHighlight(frameToHighlight);
+
+ // Marking that click was used for dragging to check
+ // if elements should be deselected on pointerup
+ pointerDownState.drag.hasOccurred = true;
+
+ // prevent immediate dragging during lasso selection to avoid element displacement
+ // only allow dragging if we're not in the middle of lasso selection
+ // (on mobile, allow dragging if we hit an element)
+ if (
+ this.app.state.activeTool.type === "lasso" &&
+ this.app.lassoTrail.hasCurrentTrail &&
+ !(
+ this.app.editorInterface.formFactor !== "desktop" &&
+ pointerDownState.hit.element
+ ) &&
+ !this.app.state.activeTool.fromSelection
+ ) {
+ return true;
+ }
+
+ // Clear lasso trail when starting to drag selected elements with lasso tool
+ // Only clear if we're actually dragging (not during lasso selection)
+ if (
+ this.app.state.activeTool.type === "lasso" &&
+ selectedElements.length > 0 &&
+ pointerDownState.drag.hasOccurred &&
+ !this.app.state.activeTool.fromSelection
+ ) {
+ this.app.lassoTrail.endPath();
+ }
+
+ // prevent dragging even if we're no longer holding cmd/ctrl otherwise
+ // it would have weird results (stuff jumping all over the screen)
+ // Checking for editingTextElement to avoid jump while editing on mobile #6503
+ if (
+ selectedElements.length > 0 &&
+ !pointerDownState.withCmdOrCtrl &&
+ !this.app.state.editingTextElement &&
+ this.app.state.activeEmbeddable?.state !== "active"
+ ) {
+ const dragOffset = {
+ x: pointerCoords.x - pointerDownState.drag.origin.x,
+ y: pointerCoords.y - pointerDownState.drag.origin.y,
+ };
+
+ const originalElements = [
+ ...pointerDownState.originalElements.values(),
+ ];
+
+ // We only drag in one direction if shift is pressed
+ const lockDirection = event.shiftKey;
+
+ if (lockDirection) {
+ const distanceX = Math.abs(dragOffset.x);
+ const distanceY = Math.abs(dragOffset.y);
+
+ const lockX = lockDirection && distanceX < distanceY;
+ const lockY = lockDirection && distanceX > distanceY;
+
+ if (lockX) {
+ dragOffset.x = 0;
+ }
+
+ if (lockY) {
+ dragOffset.y = 0;
+ }
+ }
+
+ // #region move crop region
+ if (this.app.state.croppingElementId) {
+ const croppingElement = this.app.scene
+ .getNonDeletedElementsMap()
+ .get(this.app.state.croppingElementId);
+
+ if (
+ croppingElement &&
+ isImageElement(croppingElement) &&
+ croppingElement.crop !== null &&
+ pointerDownState.hit.element === croppingElement
+ ) {
+ const crop = croppingElement.crop;
+ const image =
+ isInitializedImageElement(croppingElement) &&
+ this.app.imageCache.get(croppingElement.fileId)?.image;
+
+ if (image && !(image instanceof Promise)) {
+ const uncroppedSize = getUncroppedWidthAndHeight(croppingElement);
+ const instantDragOffset = vector(
+ pointerCoords.x - lastPointerCoords.x,
+ pointerCoords.y - lastPointerCoords.y,
+ );
+
+ // to reduce cursor:image drift, we need to take into account
+ // the canvas image element scaling so we can accurately
+ // track the pixels on movement
+ instantDragOffset[0] *= image.naturalWidth / uncroppedSize.width;
+ instantDragOffset[1] *=
+ image.naturalHeight / uncroppedSize.height;
+
+ const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
+ croppingElement,
+ elementsMap,
+ );
+
+ const topLeft = vectorFromPoint(
+ pointRotateRads(
+ pointFrom(x1, y1),
+ pointFrom(cx, cy),
+ croppingElement.angle,
+ ),
+ );
+ const topRight = vectorFromPoint(
+ pointRotateRads(
+ pointFrom(x2, y1),
+ pointFrom(cx, cy),
+ croppingElement.angle,
+ ),
+ );
+ const bottomLeft = vectorFromPoint(
+ pointRotateRads(
+ pointFrom(x1, y2),
+ pointFrom(cx, cy),
+ croppingElement.angle,
+ ),
+ );
+ const topEdge = vectorNormalize(
+ vectorSubtract(topRight, topLeft),
+ );
+ const leftEdge = vectorNormalize(
+ vectorSubtract(bottomLeft, topLeft),
+ );
+
+ // project instantDrafOffset onto leftEdge and topEdge to decompose
+ const offsetVector = vector(
+ vectorDot(instantDragOffset, topEdge),
+ vectorDot(instantDragOffset, leftEdge),
+ );
+
+ const nextCrop = {
+ ...crop,
+ x: clamp(
+ crop.x -
+ offsetVector[0] * Math.sign(croppingElement.scale[0]),
+ 0,
+ image.naturalWidth - crop.width,
+ ),
+ y: clamp(
+ crop.y -
+ offsetVector[1] * Math.sign(croppingElement.scale[1]),
+ 0,
+ image.naturalHeight - crop.height,
+ ),
+ };
+
+ this.app.scene.mutateElement(croppingElement, {
+ crop: nextCrop,
+ });
+
+ return true;
+ }
+ }
+ }
+
+ // Snap cache *must* be synchronously popuplated before initial drag,
+ // otherwise the first drag even will not snap, causing a jump before
+ // it snaps to its position if previously snapped already.
+ this.app.maybeCacheVisibleGaps(event, selectedElements);
+ this.app.maybeCacheReferenceSnapPoints(event, selectedElements);
+
+ const { snapOffset, snapLines } = snapDraggedElements(
+ originalElements,
+ dragOffset,
+ this.app,
+ event,
+ this.app.scene.getNonDeletedElementsMap(),
+ );
+
+ this.app.setState({ snapLines });
+
+ // when we're editing the name of a frame, we want the user to be
+ // able to select and interact with the text input
+ if (!this.app.state.editingFrame) {
+ dragSelectedElements(
+ pointerDownState,
+ selectedElements,
+ dragOffset,
+ this.app.scene,
+ snapOffset,
+ event[KEYS.CTRL_OR_CMD] ? null : this.app.getEffectiveGridSize(),
+ );
+ }
+
+ this.app.setState({
+ selectedElementsAreBeingDragged: true,
+ // element is being dragged and selectionElement that was created on pointer down
+ // should be removed
+ selectionElement: null,
+ });
+
+ // We duplicate the selected element if alt is pressed on pointer move
+ if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
+ this.app.duplicate.duplicateDraggedSelection(pointerDownState, event);
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+ };
+
+ /**
+ * Box-selects with the selection tool — the line editor's points, while
+ * editing a line.
+ */
+ handleBoxSelectionOnPointerMove = (
+ event: PointerEvent,
+ pointerDownState: PointerDownState,
+ ) => {
+ if (this.app.state.activeTool.type === "selection") {
+ pointerDownState.boxSelection.hasOccurred = true;
+
+ const elements = this.app.scene.getNonDeletedElements();
+
+ // box-select line editor points
+ if (this.app.state.selectedLinearElement?.isEditing) {
+ LinearElementEditor.handleBoxSelection(
+ event,
+ this.app.state,
+ this.app.setState.bind(this.app),
+ this.app.scene.getNonDeletedElementsMap(),
+ );
+ // regular box-select
+ } else {
+ let shouldReuseSelection = true;
+
+ if (
+ !event.shiftKey &&
+ isSomeElementSelected(elements, this.app.state)
+ ) {
+ if (pointerDownState.withCmdOrCtrl && pointerDownState.hit.element) {
+ this.app.setState((prevState) =>
+ selectGroupsForSelectedElements(
+ {
+ ...prevState,
+ selectedElementIds: {
+ [pointerDownState.hit.element!.id]: true,
+ },
+ },
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ this.app,
+ ),
+ );
+ } else {
+ shouldReuseSelection = false;
+ }
+ }
+ const elementsWithinSelection = this.app.state.selectionElement
+ ? getElementsWithinSelection(
+ elements,
+ this.app.state.selectionElement,
+ this.app.scene.getNonDeletedElementsMap(),
+ false,
+ this.app.state.boxSelectionMode,
+ )
+ : [];
+
+ this.app.setState((prevState) => {
+ const nextSelectedElementIds = {
+ ...(shouldReuseSelection && prevState.selectedElementIds),
+ ...elementsWithinSelection.reduce(
+ (acc: Record<ExcalidrawElement["id"], true>, element) => {
+ acc[element.id] = true;
+ return acc;
+ },
+ {},
+ ),
+ };
+
+ if (pointerDownState.hit.element) {
+ // if using ctrl/cmd, select the hitElement only if we
+ // haven't box-selected anything else
+ if (!elementsWithinSelection.length) {
+ nextSelectedElementIds[pointerDownState.hit.element.id] = true;
+ } else {
+ delete nextSelectedElementIds[pointerDownState.hit.element.id];
+ }
+ }
+
+ prevState = !shouldReuseSelection
+ ? { ...prevState, selectedGroupIds: {}, editingGroupId: null }
+ : prevState;
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ this.app.scene.getNonDeletedElements(),
+ prevState,
+ this.app,
+ ),
+ // select linear element only when we haven't box-selected anything else
+ selectedLinearElement:
+ elementsWithinSelection.length === 1 &&
+ isLinearElement(elementsWithinSelection[0])
+ ? new LinearElementEditor(
+ elementsWithinSelection[0],
+ this.app.scene.getNonDeletedElementsMap(),
+ )
+ : null,
+ showHyperlinkPopup:
+ elementsWithinSelection.length === 1 &&
+ (elementsWithinSelection[0].link ||
+ isEmbeddableElement(elementsWithinSelection[0]))
+ ? "info"
+ : false,
+ };
+ });
+ }
+ }
+ };
+
+ /**
+ * After dragging the selection: the dragged elements join the frame they're
+ * dropped in, or leave theirs (and the edited group, if they leave it).
+ */
+ handleSelectionDragOnPointerUp = (childEvent: PointerEvent) => {
+ const sceneCoords = viewportCoordsToSceneCoords(childEvent, this.app.state);
+ // update the relationships between selected elements and frames
+ const selectedElements = this.app.scene.getSelectedElements(this.app.state);
+ const topLayerFrame = this.app.getTopLayerFrameAtSceneCoords(sceneCoords, {
+ currentFrameId: getCommonFrameId(selectedElements),
+ excludeElementIds: this.app.state.selectedElementIds,
+ });
+ let nextElements = this.app.scene.getElementsMapIncludingDeleted();
+
+ const updateGroupIdsAfterEditingGroup = (elements: ExcalidrawElement[]) => {
+ if (elements.length > 0) {
+ for (const element of elements) {
+ const index = element.groupIds.indexOf(
+ this.app.state.editingGroupId!,
+ );
+
+ this.app.scene.mutateElement(
+ element,
+ {
+ groupIds: element.groupIds.slice(0, index),
+ },
+ { informMutation: false, isDragging: false },
+ );
+ }
+
+ nextElements.forEach((element) => {
+ if (
+ element.groupIds.length &&
+ getElementsInGroup(
+ nextElements,
+ element.groupIds[element.groupIds.length - 1],
+ ).length < 2
+ ) {
+ this.app.scene.mutateElement(
+ element,
+ {
+ groupIds: [],
+ },
+ { informMutation: false, isDragging: false },
+ );
+ }
+ });
+
+ this.app.setState({
+ editingGroupId: null,
+ });
+ }
+ };
+
+ if (topLayerFrame && !this.app.state.selectedElementIds[topLayerFrame.id]) {
+ const elementsToAdd = selectedElements.filter((element) =>
+ isElementInFrame(element, nextElements, this.app.state),
+ );
+
+ if (this.app.state.editingGroupId) {
+ updateGroupIdsAfterEditingGroup(elementsToAdd);
+ }
+
+ nextElements = addElementsToFrame(
+ nextElements,
+ elementsToAdd,
+ topLayerFrame,
+ );
+ } else if (!topLayerFrame) {
+ if (this.app.state.editingGroupId) {
+ const elementsToRemove = selectedElements.filter(
+ (element) =>
+ element.frameId &&
+ !isElementInFrame(element, nextElements, this.app.state),
+ );
+
+ updateGroupIdsAfterEditingGroup(elementsToRemove);
+ }
+ }
+
+ nextElements = updateFrameMembershipOfSelectedElements(
+ nextElements,
+ this.app.state,
+ this.app,
+ );
+
+ this.app.scene.replaceAllElements(nextElements);
+ };
+
+ /**
+ * The selection's transform handle at the scene point, if any — with its
+ * element, for a lone selected element.
+ *
+ * A lone selected element has none while the line editor is open or one of
+ * its line points is hovered, nor does an elbow arrow, a two-point line or
+ * arrow, or (on mobile devices) any line or arrow. The selection has none in
+ * the element link selector.
+ */
+ getTransformHandleAt(
+ selectedElements: readonly NonDeletedExcalidrawElement[],
+ sceneX: number,
+ sceneY: number,
+ pointerType: PointerType,
+ ): {
+ element?: NonDeletedExcalidrawElement;
+ transformHandleType: TransformHandleType;
+ } | null {
+ const { state, editorInterface } = this.app;
+ if (state.openDialog?.name === "elementLinkSelector") {
+ return null;
+ }
+
+ if (selectedElements.length === 1) {
+ const [element] = selectedElements;
+ if (
+ state.selectedLinearElement?.isEditing ||
+ (state.selectedLinearElement &&
+ state.selectedLinearElement.hoverPointIndex !== -1) ||
+ isElbowArrow(element) ||
+ // HACK: Disable transform handles for linear elements on mobile until a
+ // better way of showing them is found
+ (isLinearElement(element) &&
+ (editorInterface.userAgent.isMobileDevice ||
+ element.points.length === 2))
+ ) {
+ return null;
+ }
+ const elementWithTransformHandleType = getElementWithTransformHandleType(
+ this.app.scene.getNonDeletedElements(),
+ state,
+ sceneX,
+ sceneY,
+ state.zoom,
+ pointerType,
+ this.app.scene.getNonDeletedElementsMap(),
+ editorInterface,
+ );
+ return elementWithTransformHandleType?.transformHandleType
+ ? {
+ element: elementWithTransformHandleType.element,
+ transformHandleType:
+ elementWithTransformHandleType.transformHandleType,
+ }
+ : null;
+ }
+
+ if (selectedElements.length > 1) {
+ const transformHandleType = getTransformHandleTypeFromCoords(
+ getCommonBounds(selectedElements),
+ sceneX,
+ sceneY,
+ state.zoom,
+ pointerType,
+ editorInterface,
+ );
+ return transformHandleType ? { transformHandleType } : null;
+ }
+
+ return null;
+ }
+
/**
* 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
@@ -844,31 +1263,7 @@ export class AppSelectionTool {
? 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,
- };
- });
+ this.app.selection.select(cycleTarget);
}
if (
@@ -890,74 +1285,12 @@ export class AppSelectionTool {
!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 (
+ isSelectedViaGroup(this.app.state, hitElement) ||
// 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,
- };
- });
+ !this.app.state.selectedLinearElement?.isDragging
+ ) {
+ this.app.selection.remove(hitElement);
}
} else if (
hitElement.frameId &&
@@ -1013,27 +1346,7 @@ export class AppSelectionTool {
}));
}
} 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,
- }));
+ this.app.selection.select(hitElement);
}
}
@@ -1072,12 +1385,7 @@ export class AppSelectionTool {
this.app.actionManager.executeAction(actionToggleLinearEditor);
} else {
// Deselect selected elements
- this.app.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.app.state),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
+ this.app.selection.clear();
}
// reset cursor
this.app.cursor.set(CURSOR_TYPE.AUTO);
@@ -1109,36 +1417,6 @@ export class AppSelectionTool {
});
}
- 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;
diff --git a/packages/excalidraw/components/App.text.ts b/packages/excalidraw/components/App.text.ts
index 2c5d679436..496e2867d4 100644
--- a/packages/excalidraw/components/App.text.ts
+++ b/packages/excalidraw/components/App.text.ts
@@ -370,7 +370,7 @@ export class AppText {
autoSelect: !this.app.editorInterface.isTouchScreen,
});
// deselect all other elements when inserting text
- this.app.deselectElements();
+ this.app.selection.clear();
// (the linear element editor stays up, to come back to on submit — but
// without the hover affordances, which are for the selection)
if (this.app.state.selectedLinearElement) {
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index 2c9a8eaa53..beec1feb50 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -5,17 +5,7 @@ import { flushSync } from "react-dom";
import rough from "roughjs/bin/rough";
import { nanoid } from "nanoid";
-import {
- clamp,
- pointFrom,
- pointDistance,
- vector,
- pointRotateRads,
- vectorFromPoint,
- vectorSubtract,
- vectorDot,
- vectorNormalize,
-} from "@excalidraw/math";
+import { clamp, pointFrom, pointDistance } from "@excalidraw/math";
import {
COLOR_PALETTE,
@@ -107,7 +97,6 @@ import {
import {
getObservedAppState,
getCommonBounds,
- getElementAbsoluteCoords,
bindOrUnbindBindingElements,
getHoveredElementForBinding,
isBindingEnabled,
@@ -166,8 +155,6 @@ import {
isValidTextContainer,
redrawTextBoundingBox,
hasBoundingBox,
- getCommonFrameId,
- getFrameChildren,
getFrameChildrenInsertionIndex,
isCursorInFrame,
addElementsToFrame,
@@ -178,7 +165,6 @@ import {
getContainingFrame,
elementOverlapsWithFrame,
updateFrameMembershipOfSelectedElements,
- isElementInFrame,
getFrameLikeTitle,
getElementsOverlappingFrame,
hitElementBoundText,
@@ -189,19 +175,13 @@ import {
ShapeCache,
resolveElementRenderState,
getRenderElementWithPositionOverride,
- getElementsInGroup,
getSelectedGroupIdForElement,
getSelectedGroupIds,
- selectGroupsForSelectedElements,
syncInvalidIndices,
excludeElementsInFramesFromSelection,
- getSelectionStateForElements,
makeNextSelectedElementIds,
getCursorForResizingElement,
- getElementWithTransformHandleType,
- getTransformHandleTypeFromCoords,
dragNewElement,
- dragSelectedElements,
getDragOffsetXY,
Scene,
Store,
@@ -224,7 +204,6 @@ import {
handleFocusPointHover,
handleFocusPointPointerUp,
maybeHandleArrowPointlikeDrag,
- getUncroppedWidthAndHeight,
isEligibleFrameChildType,
getBindingStrategyForDraggingBindingElementEndpoints,
isNonDeletedElement,
@@ -331,7 +310,6 @@ import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
import {
getScrollToContentState,
- getElementsWithinSelection,
getNormalizedZoom,
getSelectedElements,
hasBackground,
@@ -363,7 +341,6 @@ import { editorJotaiStore, type WritableAtom } from "../editor-jotai";
import { ImageSceneDataError } from "../errors";
import {
getSnapLinesAtPointer,
- snapDraggedElements,
isActiveToolNonLinearSnappable,
snapNewElement,
isSnappingEnabled,
@@ -411,6 +388,11 @@ import { AppModifiers } from "./App.modifiers";
import { AppPan } from "./App.pan";
import { AppViewport, RIGHT_SIDEBAR_WIDTH } from "./App.viewport";
import { AppWheel } from "./App.wheel";
+import {
+ AppSelection,
+ getSelectionStateForElements,
+ selectGroupsForSelectedElements,
+} from "./App.selection";
import { AppSelectionTool } from "./App.selectionTool";
import BraveMeasureTextError from "./BraveMeasureTextError";
import { ContextMenu, CONTEXT_MENU_SEPARATOR } from "./ContextMenu";
@@ -700,6 +682,7 @@ class App extends React.Component<AppProps, AppState> {
isGestureActive: () => gesture.pointers.size >= 2 || this.pan.isActive(),
});
public wheel: AppWheel = new AppWheel(this);
+ public selection: AppSelection = new AppSelection(this);
public selectionTool: AppSelectionTool = new AppSelectionTool(this);
bindModeHandler: ReturnType<typeof setTimeout> | null = null;
@@ -803,6 +786,7 @@ class App extends React.Component<AppProps, AppState> {
history: {
clear: this.resetHistory,
},
+ selection: this.selection,
setViewport: this.viewport.setViewport,
getViewportOffsets: this.viewport.getOffsets,
setElementRenderOverrides: this.setElementRenderOverrides,
@@ -3371,7 +3355,7 @@ class App extends React.Component<AppProps, AppState> {
snapLines: [],
showHyperlinkPopup: false,
});
- this.deselectElements();
+ this.selection.clear();
if (!this.isInteractionEnabled()) {
this.setState({ originSnapOffset: null });
this.cursor.reset();
@@ -3474,7 +3458,7 @@ class App extends React.Component<AppProps, AppState> {
this.addEventListeners();
}
if (!this.state.viewModeEnabled) {
- this.deselectElements();
+ this.selection.clear();
}
this.cursor.reset();
}
@@ -4393,7 +4377,7 @@ class App extends React.Component<AppProps, AppState> {
this.state.openDialog?.name === "elementLinkSelector") &&
prevState.openDialog?.name !== this.state.openDialog?.name
) {
- this.deselectElements();
+ this.selection.clear();
this.setState({
hoveredElementIds: {},
});
@@ -4558,7 +4542,7 @@ class App extends React.Component<AppProps, AppState> {
if (distance <= DOUBLE_TAP_POSITION_THRESHOLD) {
// end lasso trail and deselect elements just in case
this.lassoTrail.endPath();
- this.deselectElements();
+ this.selection.clear();
this.handleCanvasDoubleClick({
clientX: touch.clientX,
@@ -5615,12 +5599,7 @@ class App extends React.Component<AppProps, AppState> {
this.cursor.reset();
} else {
this.cursor.applyForTool();
- this.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.state),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
+ this.selection.clear();
}
this.pan.setSpaceHeld(false);
}
@@ -5965,15 +5944,6 @@ class App extends React.Component<AppProps, AppState> {
gesture.initialScale = null;
});
- public deselectElements() {
- this.setState({
- selectedElementIds: makeNextSelectedElementIds({}, this.state),
- selectedGroupIds: {},
- editingGroupId: null,
- activeEmbeddable: null,
- });
- }
-
// NOTE: Hot path for hit testing, so avoid unnecessary computations
public getElementAtPosition(
x: number,
@@ -6751,9 +6721,7 @@ class App extends React.Component<AppProps, AppState> {
return topLayerFrame;
};
- private updateFrameToHighlight = (
- frameToHighlight: AppState["frameToHighlight"],
- ) => {
+ updateFrameToHighlight = (frameToHighlight: AppState["frameToHighlight"]) => {
if (this.state.frameToHighlight !== frameToHighlight) {
this.setState({ frameToHighlight });
}
@@ -7184,8 +7152,6 @@ class App extends React.Component<AppProps, AppState> {
return;
}
- const elements = this.scene.getNonDeletedElements();
-
const selectedElements = this.scene.getSelectedElements(this.state);
if (
@@ -7195,14 +7161,14 @@ class App extends React.Component<AppProps, AppState> {
return;
}
- if (
- selectedElements.length === 1 &&
- !isOverScrollBar &&
- !this.state.selectedLinearElement?.isEditing
- ) {
+ if (!isOverScrollBar) {
// for linear elements, we'd like to prioritize point dragging over edge resizing
// therefore, we update and check hovered point index first
- if (this.state.selectedLinearElement) {
+ if (
+ selectedElements.length === 1 &&
+ !this.state.selectedLinearElement?.isEditing &&
+ this.state.selectedLinearElement
+ ) {
this.handleHoverSelectedLinearElement(
this.state.selectedLinearElement,
scenePointerX,
@@ -7210,59 +7176,14 @@ class App extends React.Component<AppProps, AppState> {
);
}
- if (
- (!this.state.selectedLinearElement ||
- this.state.selectedLinearElement.hoverPointIndex === -1) &&
- this.state.openDialog?.name !== "elementLinkSelector" &&
- !(selectedElements.length === 1 && isElbowArrow(selectedElements[0])) &&
- // HACK: Disable transform handles for linear elements on mobile until a
- // better way of showing them is found
- !(
- isLinearElement(selectedElements[0]) &&
- (this.editorInterface.userAgent.isMobileDevice ||
- selectedElements[0].points.length === 2)
- )
- ) {
- const elementWithTransformHandleType =
- getElementWithTransformHandleType(
- elements,
- this.state,
- scenePointerX,
- scenePointerY,
- this.state.zoom,
- event.pointerType,
- this.scene.getNonDeletedElementsMap(),
- this.editorInterface,
- );
- if (
- elementWithTransformHandleType &&
- elementWithTransformHandleType.transformHandleType
- ) {
- this.cursor.set(
- getCursorForResizingElement(elementWithTransformHandleType),
- );
- return;
- }
- }
- } else if (
- selectedElements.length > 1 &&
- !isOverScrollBar &&
- this.state.openDialog?.name !== "elementLinkSelector"
- ) {
- const transformHandleType = getTransformHandleTypeFromCoords(
- getCommonBounds(selectedElements),
+ const transformHandle = this.selectionTool.getTransformHandleAt(
+ selectedElements,
scenePointerX,
scenePointerY,
- this.state.zoom,
event.pointerType,
- this.editorInterface,
);
- if (transformHandleType) {
- this.cursor.set(
- getCursorForResizingElement({
- transformHandleType,
- }),
- );
+ if (transformHandle) {
+ this.cursor.set(getCursorForResizingElement(transformHandle));
return;
}
}
@@ -7316,7 +7237,7 @@ class App extends React.Component<AppProps, AppState> {
this.cursor.set(this.textTool.cursorFor(textToolTarget));
} else if (
!event[KEYS.CTRL_OR_CMD] &&
- this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selection.isHittingCommonBoundingBoxOfSelectedElements(
scenePointer,
selectedElements,
)
@@ -7336,7 +7257,7 @@ class App extends React.Component<AppProps, AppState> {
) {
if (
(hitElement ||
- this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selection.isHittingCommonBoundingBoxOfSelectedElements(
scenePointer,
selectedElements,
)) &&
@@ -7848,7 +7769,7 @@ class App extends React.Component<AppProps, AppState> {
if (this.state.activeTool.type === "lasso") {
const hitSelectedElement =
pointerDownState.hit.element &&
- this.selectionTool.isASelectedElement(pointerDownState.hit.element);
+ this.selection.isASelectedElement(pointerDownState.hit.element);
const shouldForceLassoReselect =
event.altKey &&
event[KEYS.CTRL_OR_CMD] &&
@@ -7880,89 +7801,7 @@ class App extends React.Component<AppProps, AppState> {
pointerDownState.hit.element &&
!hitSelectedElement
) {
- this.setState((prevState) => {
- const nextSelectedElementIds: { [id: string]: true } = {
- ...prevState.selectedElementIds,
- [pointerDownState.hit.element!.id]: true,
- };
-
- const previouslySelectedElements: ExcalidrawElement[] = [];
-
- Object.keys(prevState.selectedElementIds).forEach((id) => {
- const element = this.scene.getElement(id);
- element && previouslySelectedElements.push(element);
- });
-
- const hitElement = pointerDownState.hit.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];
- });
- }
- });
- }
- }
-
- return {
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: prevState.editingGroupId,
- selectedElementIds: nextSelectedElementIds,
- },
- this.scene.getNonDeletedElements(),
- prevState,
- this,
- ),
- showHyperlinkPopup:
- hitElement.link || isEmbeddableElement(hitElement)
- ? "info"
- : false,
- };
- });
+ this.selection.add(pointerDownState.hit.element);
pointerDownState.hit.wasAddedToSelection = true;
}
} else if (this.state.activeTool.type === "text") {
@@ -8310,7 +8149,7 @@ class App extends React.Component<AppProps, AppState> {
editedTextId: this.duplicate.handedOverTextId,
arrowLabel: false,
hasHitCommonBoundingBoxOfSelectedElements:
- this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selection.isHittingCommonBoundingBoxOfSelectedElements(
origin,
selectedElements,
),
@@ -9376,264 +9215,16 @@ class App extends React.Component<AppProps, AppState> {
}
}
- const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
- (element) => this.selectionTool.isASelectedElement(element),
- );
-
- const isSelectingPointsInLineEditor =
- this.state.selectedLinearElement?.isEditing &&
- event.shiftKey &&
- this.state.selectedLinearElement.elementId ===
- pointerDownState.hit.element?.id;
-
if (
- (hasHitASelectedElement ||
- pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements) &&
- !isSelectingPointsInLineEditor &&
- !pointerDownState.drag.blockDragging
+ this.selectionTool.handleSelectionDragOnPointerMove(
+ event,
+ pointerDownState,
+ pointerCoords,
+ lastPointerCoords,
+ elementsMap,
+ )
) {
- const selectedElements = this.scene.getSelectedElements(this.state);
- if (
- selectedElements.length > 0 &&
- selectedElements.every((element) => element.locked)
- ) {
- 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),
- );
- const frameToHighlight = selectedElementsHasAFrame
- ? null
- : this.getTopLayerFrameAtSceneCoords(pointerCoords, {
- currentFrameId: getCommonFrameId(selectedElements),
- excludeElementIds: this.state.selectedElementIds,
- });
- // Only update the state if there is a difference
- this.updateFrameToHighlight(frameToHighlight);
-
- // Marking that click was used for dragging to check
- // if elements should be deselected on pointerup
- pointerDownState.drag.hasOccurred = true;
-
- // prevent immediate dragging during lasso selection to avoid element displacement
- // only allow dragging if we're not in the middle of lasso selection
- // (on mobile, allow dragging if we hit an element)
- if (
- this.state.activeTool.type === "lasso" &&
- this.lassoTrail.hasCurrentTrail &&
- !(
- this.editorInterface.formFactor !== "desktop" &&
- pointerDownState.hit.element
- ) &&
- !this.state.activeTool.fromSelection
- ) {
- return;
- }
-
- // Clear lasso trail when starting to drag selected elements with lasso tool
- // Only clear if we're actually dragging (not during lasso selection)
- if (
- this.state.activeTool.type === "lasso" &&
- selectedElements.length > 0 &&
- pointerDownState.drag.hasOccurred &&
- !this.state.activeTool.fromSelection
- ) {
- this.lassoTrail.endPath();
- }
-
- // prevent dragging even if we're no longer holding cmd/ctrl otherwise
- // it would have weird results (stuff jumping all over the screen)
- // Checking for editingTextElement to avoid jump while editing on mobile #6503
- if (
- selectedElements.length > 0 &&
- !pointerDownState.withCmdOrCtrl &&
- !this.state.editingTextElement &&
- this.state.activeEmbeddable?.state !== "active"
- ) {
- const dragOffset = {
- x: pointerCoords.x - pointerDownState.drag.origin.x,
- y: pointerCoords.y - pointerDownState.drag.origin.y,
- };
-
- const originalElements = [
- ...pointerDownState.originalElements.values(),
- ];
-
- // We only drag in one direction if shift is pressed
- const lockDirection = event.shiftKey;
-
- if (lockDirection) {
- const distanceX = Math.abs(dragOffset.x);
- const distanceY = Math.abs(dragOffset.y);
-
- const lockX = lockDirection && distanceX < distanceY;
- const lockY = lockDirection && distanceX > distanceY;
-
- if (lockX) {
- dragOffset.x = 0;
- }
-
- if (lockY) {
- dragOffset.y = 0;
- }
- }
-
- // #region move crop region
- if (this.state.croppingElementId) {
- const croppingElement = this.scene
- .getNonDeletedElementsMap()
- .get(this.state.croppingElementId);
-
- if (
- croppingElement &&
- isImageElement(croppingElement) &&
- croppingElement.crop !== null &&
- pointerDownState.hit.element === croppingElement
- ) {
- const crop = croppingElement.crop;
- const image =
- isInitializedImageElement(croppingElement) &&
- this.imageCache.get(croppingElement.fileId)?.image;
-
- if (image && !(image instanceof Promise)) {
- const uncroppedSize =
- getUncroppedWidthAndHeight(croppingElement);
- const instantDragOffset = vector(
- pointerCoords.x - lastPointerCoords.x,
- pointerCoords.y - lastPointerCoords.y,
- );
-
- // to reduce cursor:image drift, we need to take into account
- // the canvas image element scaling so we can accurately
- // track the pixels on movement
- instantDragOffset[0] *=
- image.naturalWidth / uncroppedSize.width;
- instantDragOffset[1] *=
- image.naturalHeight / uncroppedSize.height;
-
- const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
- croppingElement,
- elementsMap,
- );
-
- const topLeft = vectorFromPoint(
- pointRotateRads(
- pointFrom(x1, y1),
- pointFrom(cx, cy),
- croppingElement.angle,
- ),
- );
- const topRight = vectorFromPoint(
- pointRotateRads(
- pointFrom(x2, y1),
- pointFrom(cx, cy),
- croppingElement.angle,
- ),
- );
- const bottomLeft = vectorFromPoint(
- pointRotateRads(
- pointFrom(x1, y2),
- pointFrom(cx, cy),
- croppingElement.angle,
- ),
- );
- const topEdge = vectorNormalize(
- vectorSubtract(topRight, topLeft),
- );
- const leftEdge = vectorNormalize(
- vectorSubtract(bottomLeft, topLeft),
- );
-
- // project instantDrafOffset onto leftEdge and topEdge to decompose
- const offsetVector = vector(
- vectorDot(instantDragOffset, topEdge),
- vectorDot(instantDragOffset, leftEdge),
- );
-
- const nextCrop = {
- ...crop,
- x: clamp(
- crop.x -
- offsetVector[0] * Math.sign(croppingElement.scale[0]),
- 0,
- image.naturalWidth - crop.width,
- ),
- y: clamp(
- crop.y -
- offsetVector[1] * Math.sign(croppingElement.scale[1]),
- 0,
- image.naturalHeight - crop.height,
- ),
- };
-
- this.scene.mutateElement(croppingElement, {
- crop: nextCrop,
- });
-
- return;
- }
- }
- }
-
- // Snap cache *must* be synchronously popuplated before initial drag,
- // otherwise the first drag even will not snap, causing a jump before
- // it snaps to its position if previously snapped already.
- this.maybeCacheVisibleGaps(event, selectedElements);
- this.maybeCacheReferenceSnapPoints(event, selectedElements);
-
- const { snapOffset, snapLines } = snapDraggedElements(
- originalElements,
- dragOffset,
- this,
- event,
- this.scene.getNonDeletedElementsMap(),
- );
-
- this.setState({ snapLines });
-
- // when we're editing the name of a frame, we want the user to be
- // able to select and interact with the text input
- if (!this.state.editingFrame) {
- dragSelectedElements(
- pointerDownState,
- selectedElements,
- dragOffset,
- this.scene,
- snapOffset,
- event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
- );
- }
-
- this.setState({
- selectedElementsAreBeingDragged: true,
- // element is being dragged and selectionElement that was created on pointer down
- // should be removed
- selectionElement: null,
- });
-
- // We duplicate the selected element if alt is pressed on pointer move
- if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
- this.duplicate.duplicateDraggedSelection(pointerDownState, event);
- }
-
- return;
- }
+ return;
}
if (this.state.selectionElement) {
@@ -9768,110 +9359,10 @@ class App extends React.Component<AppProps, AppState> {
}
}
- if (this.state.activeTool.type === "selection") {
- pointerDownState.boxSelection.hasOccurred = true;
-
- const elements = this.scene.getNonDeletedElements();
-
- // box-select line editor points
- if (this.state.selectedLinearElement?.isEditing) {
- LinearElementEditor.handleBoxSelection(
- event,
- this.state,
- this.setState.bind(this),
- this.scene.getNonDeletedElementsMap(),
- );
- // regular box-select
- } else {
- let shouldReuseSelection = true;
-
- if (!event.shiftKey && isSomeElementSelected(elements, this.state)) {
- if (
- pointerDownState.withCmdOrCtrl &&
- pointerDownState.hit.element
- ) {
- this.setState((prevState) =>
- selectGroupsForSelectedElements(
- {
- ...prevState,
- selectedElementIds: {
- [pointerDownState.hit.element!.id]: true,
- },
- },
- this.scene.getNonDeletedElements(),
- prevState,
- this,
- ),
- );
- } else {
- shouldReuseSelection = false;
- }
- }
- const elementsWithinSelection = this.state.selectionElement
- ? getElementsWithinSelection(
- elements,
- this.state.selectionElement,
- this.scene.getNonDeletedElementsMap(),
- false,
- this.state.boxSelectionMode,
- )
- : [];
-
- this.setState((prevState) => {
- const nextSelectedElementIds = {
- ...(shouldReuseSelection && prevState.selectedElementIds),
- ...elementsWithinSelection.reduce(
- (acc: Record<ExcalidrawElement["id"], true>, element) => {
- acc[element.id] = true;
- return acc;
- },
- {},
- ),
- };
-
- if (pointerDownState.hit.element) {
- // if using ctrl/cmd, select the hitElement only if we
- // haven't box-selected anything else
- if (!elementsWithinSelection.length) {
- nextSelectedElementIds[pointerDownState.hit.element.id] = true;
- } else {
- delete nextSelectedElementIds[pointerDownState.hit.element.id];
- }
- }
-
- prevState = !shouldReuseSelection
- ? { ...prevState, selectedGroupIds: {}, editingGroupId: null }
- : prevState;
-
- return {
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: prevState.editingGroupId,
- selectedElementIds: nextSelectedElementIds,
- },
- this.scene.getNonDeletedElements(),
- prevState,
- this,
- ),
- // select linear element only when we haven't box-selected anything else
- selectedLinearElement:
- elementsWithinSelection.length === 1 &&
- isLinearElement(elementsWithinSelection[0])
- ? new LinearElementEditor(
- elementsWithinSelection[0],
- this.scene.getNonDeletedElementsMap(),
- )
- : null,
- showHyperlinkPopup:
- elementsWithinSelection.length === 1 &&
- (elementsWithinSelection[0].link ||
- isEmbeddableElement(elementsWithinSelection[0]))
- ? "info"
- : false,
- };
- });
- }
- }
+ this.selectionTool.handleBoxSelectionOnPointerMove(
+ event,
+ pointerDownState,
+ );
});
}
@@ -10461,8 +9952,6 @@ class App extends React.Component<AppProps, AppState> {
}
if (pointerDownState.drag.hasOccurred) {
- const sceneCoords = viewportCoordsToSceneCoords(childEvent, this.state);
-
// when editing the points of a linear element, we check if the
// linear element still is in the frame afterwards
// if not, the linear element will be removed from its frame (if any)
@@ -10501,95 +9990,7 @@ class App extends React.Component<AppProps, AppState> {
}
}
} else {
- // update the relationships between selected elements and frames
- const selectedElements = this.scene.getSelectedElements(this.state);
- const topLayerFrame = this.getTopLayerFrameAtSceneCoords(
- sceneCoords,
- {
- currentFrameId: getCommonFrameId(selectedElements),
- excludeElementIds: this.state.selectedElementIds,
- },
- );
- let nextElements = this.scene.getElementsMapIncludingDeleted();
-
- const updateGroupIdsAfterEditingGroup = (
- elements: ExcalidrawElement[],
- ) => {
- if (elements.length > 0) {
- for (const element of elements) {
- const index = element.groupIds.indexOf(
- this.state.editingGroupId!,
- );
-
- this.scene.mutateElement(
- element,
- {
- groupIds: element.groupIds.slice(0, index),
- },
- { informMutation: false, isDragging: false },
- );
- }
-
- nextElements.forEach((element) => {
- if (
- element.groupIds.length &&
- getElementsInGroup(
- nextElements,
- element.groupIds[element.groupIds.length - 1],
- ).length < 2
- ) {
- this.scene.mutateElement(
- element,
- {
- groupIds: [],
- },
- { informMutation: false, isDragging: false },
- );
- }
- });
-
- this.setState({
- editingGroupId: null,
- });
- }
- };
-
- if (
- topLayerFrame &&
- !this.state.selectedElementIds[topLayerFrame.id]
- ) {
- const elementsToAdd = selectedElements.filter((element) =>
- isElementInFrame(element, nextElements, this.state),
- );
-
- if (this.state.editingGroupId) {
- updateGroupIdsAfterEditingGroup(elementsToAdd);
- }
-
- nextElements = addElementsToFrame(
- nextElements,
- elementsToAdd,
- topLayerFrame,
- );
- } else if (!topLayerFrame) {
- if (this.state.editingGroupId) {
- const elementsToRemove = selectedElements.filter(
- (element) =>
- element.frameId &&
- !isElementInFrame(element, nextElements, this.state),
- );
-
- updateGroupIdsAfterEditingGroup(elementsToRemove);
- }
- }
-
- nextElements = updateFrameMembershipOfSelectedElements(
- nextElements,
- this.state,
- this,
- );
-
- this.scene.replaceAllElements(nextElements);
+ this.selectionTool.handleSelectionDragOnPointerUp(childEvent);
}
}
@@ -11610,7 +11011,7 @@ class App extends React.Component<AppProps, AppState> {
const selectedElements = this.scene.getSelectedElements(this.state);
const isHittingCommonBoundBox =
- this.selectionTool.isHittingCommonBoundingBoxOfSelectedElements(
+ this.selection.isHittingCommonBoundingBoxOfSelectedElements(
{ x, y },
selectedElements,
);
@@ -11625,28 +11026,12 @@ class App extends React.Component<AppProps, AppState> {
trackEvent("contextMenu", "openContextMenu", type);
+ if (element && !this.state.selectedElementIds[element.id]) {
+ // (locked ones too, for the menu to offer unlocking them)
+ this.selection.select(element, { includeLocked: true });
+ }
this.setState(
{
- ...(element && !this.state.selectedElementIds[element.id]
- ? {
- ...this.state,
- ...selectGroupsForSelectedElements(
- {
- editingGroupId: this.state.editingGroupId,
- selectedElementIds: { [element.id]: true },
- },
- this.scene.getNonDeletedElements(),
- this.state,
- this,
- ),
- selectedLinearElement: isLinearElement(element)
- ? new LinearElementEditor(
- element,
- this.scene.getNonDeletedElementsMap(),
- )
- : null,
- }
- : this.state),
showHyperlinkPopup: false,
},
() => {
diff --git a/packages/excalidraw/lasso/index.ts b/packages/excalidraw/lasso/index.ts
index fd1f7f1a84..6dbdb3a9d3 100644
--- a/packages/excalidraw/lasso/index.ts
+++ b/packages/excalidraw/lasso/index.ts
@@ -9,7 +9,6 @@ import { LinearElementEditor } from "@excalidraw/element";
import { isFrameLikeElement, isLinearElement } from "@excalidraw/element";
import { getFrameChildren } from "@excalidraw/element";
-import { selectGroupsForSelectedElements } from "@excalidraw/element";
import {
arrayToMap,
@@ -24,6 +23,8 @@ import type {
NonDeleted,
} from "@excalidraw/element/types";
+import { selectGroupsForSelectedElements } from "../components/App.selection";
+
import { AnimatedTrail } from "../animatedTrail";
import { getSelectionColor } from "../renderer/helpers";
diff --git a/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap
index b6d7b5cab7..6a6f3596a3 100644
--- a/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap
+++ b/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap
@@ -550,12 +550,7 @@ exports[`given element A and group of elements B and given both are selected whe
"id3": true,
},
"selectedElementsAreBeingDragged": false,
- "selectedGroupIds": {
- "id0": true,
- "id12": false,
- "id3": true,
- "id6": true,
- },
+ "selectedGroupIds": {},
"selectedLinearElement": null,
"selectionElement": null,
"shouldCacheIgnoreZoom": false,
@@ -846,12 +841,7 @@ exports[`given element A and group of elements B and given both are selected whe
"delta": Delta {
"deleted": {
"selectedElementIds": {},
- "selectedGroupIds": {
- "id0": true,
- "id12": false,
- "id3": true,
- "id6": true,
- },
+ "selectedGroupIds": {},
},
"inserted": {
"selectedElementIds": {
diff --git a/packages/excalidraw/tests/helpers/api.ts b/packages/excalidraw/tests/helpers/api.ts
index 39845b9511..b80db5410a 100644
--- a/packages/excalidraw/tests/helpers/api.ts
+++ b/packages/excalidraw/tests/helpers/api.ts
@@ -27,7 +27,7 @@ import {
} from "@excalidraw/element";
import { isUsingAdaptiveRadius, getSelectedElements } from "@excalidraw/element";
-import { selectGroupsForSelectedElements } from "@excalidraw/element";
+
import { FONT_SIZES } from "@excalidraw/common";
@@ -52,6 +52,8 @@ import type {
import type { Mutable } from "@excalidraw/common/utility-types";
+import { selectGroupsForSelectedElements } from "../../components/App.selection";
+
import { getMimeType } from "../../data/blob";
import { createTestHook } from "../../components/App";
import { getDefaultAppState } from "../../appState";
diff --git a/packages/excalidraw/tests/move.test.tsx b/packages/excalidraw/tests/move.test.tsx
index 0178c70a9f..55ae99ca75 100644
--- a/packages/excalidraw/tests/move.test.tsx
+++ b/packages/excalidraw/tests/move.test.tsx
@@ -14,6 +14,7 @@ import { Excalidraw } from "../index";
import * as InteractiveCanvas from "../renderer/interactiveScene";
import * as StaticScene from "../renderer/staticScene";
+import { API } from "./helpers/api";
import { UI, Pointer, Keyboard } from "./helpers/ui";
import { render, fireEvent, act, unmountComponent } from "./test-utils";
@@ -73,6 +74,28 @@ describe("move element", () => {
h.elements.forEach((element) => expect(element).toMatchSnapshot());
});
+ it("shift-drag moves along one axis only", async () => {
+ await render(<Excalidraw />);
+ const rectangle = API.createElement({
+ type: "rectangle",
+ width: 100,
+ height: 100,
+ backgroundColor: "red",
+ fillStyle: "solid",
+ });
+ API.setElements([rectangle]);
+ API.setSelectedElements([rectangle]);
+
+ const mouse = new Pointer("mouse");
+ Keyboard.withModifierKeys({ shift: true }, () => {
+ mouse.downAt(50, 50);
+ mouse.moveTo(90, 60);
+ mouse.upAt();
+ });
+
+ expect(API.getElement(rectangle)).toMatchObject({ x: 40, y: 0 });
+ });
+
it("rectangles with binding arrow", async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
diff --git a/packages/excalidraw/tests/selection.test.tsx b/packages/excalidraw/tests/selection.test.tsx
index 96f471b56d..b14a288fd8 100644
--- a/packages/excalidraw/tests/selection.test.tsx
+++ b/packages/excalidraw/tests/selection.test.tsx
@@ -3,6 +3,7 @@ import { vi } from "vitest";
import { KEYS, ROUNDNESS, arrayToMap, reseed } from "@excalidraw/common";
import {
+ CaptureUpdateAction,
getElementBounds,
getElementLineSegments,
getElementsWithinSelection,
@@ -16,6 +17,7 @@ import * as InteractiveCanvas from "../renderer/interactiveScene";
import * as StaticScene from "../renderer/staticScene";
import { API } from "./helpers/api";
+import { getTextEditor, updateTextEditor } from "./queries/dom";
import { Keyboard, Pointer, UI } from "./helpers/ui";
import {
act,
@@ -26,6 +28,7 @@ import {
restoreOriginalGetBoundingClientRect,
assertSelectedElements,
unmountComponent,
+ waitFor,
} from "./test-utils";
unmountComponent();
@@ -202,6 +205,31 @@ describe("lasso reselection", () => {
});
});
+describe("lasso on touch devices", () => {
+ it("a tap selects the element", async () => {
+ await render(<Excalidraw UIOptions={{ getFormFactor: () => "tablet" }} />);
+ fireEvent.resize(window);
+ await waitFor(() =>
+ expect(h.app.editorInterface.formFactor).toBe("tablet"),
+ );
+ const rectangle = API.createElement({
+ type: "rectangle",
+ width: 100,
+ height: 100,
+ backgroundColor: "red",
+ fillStyle: "solid",
+ });
+ API.setElements([rectangle]);
+ act(() => {
+ h.app.setActiveTool({ type: "lasso" });
+ });
+
+ mouse.clickAt(50, 50);
+
+ assertSelectedElements([rectangle.id]);
+ });
+});
+
describe("alt-click cycling", () => {
beforeEach(async () => {
await render(<Excalidraw />);
@@ -1294,6 +1322,323 @@ describe("inner box-selection", () => {
});
});
+describe("app.selection", () => {
+ beforeEach(async () => {
+ await render(<Excalidraw />);
+ });
+
+ const createFrame = (groupIds: string[] = []) => {
+ const frame = API.createElement({
+ type: "frame",
+ width: 200,
+ height: 200,
+ groupIds,
+ });
+ const child = API.createElement({
+ type: "rectangle",
+ x: 10,
+ y: 10,
+ frameId: frame.id,
+ });
+ return { frame, child };
+ };
+
+ it("add() of a frame deselects its children", () => {
+ const { frame, child } = createFrame();
+ const other = API.createElement({ type: "rectangle", x: 300 });
+ API.setElements([child, frame, other]);
+ API.setSelectedElements([child, other]);
+
+ act(() => h.app.selection.add(frame));
+
+ assertSelectedElements([other.id, frame.id]);
+ });
+
+ it("add() doesn't add a child of a selected frame", () => {
+ const { frame, child } = createFrame();
+ API.setElements([child, frame]);
+ API.setSelectedElements([frame]);
+
+ act(() => h.app.selection.add(child));
+
+ assertSelectedElements([frame.id]);
+ });
+
+ it("add() of an element grouped with a frame deselects that frame's children", () => {
+ const { frame, child } = createFrame(["group"]);
+ const grouped = API.createElement({
+ type: "rectangle",
+ x: 300,
+ groupIds: ["group"],
+ });
+ API.setElements([child, frame, grouped]);
+ API.setSelectedElements([child]);
+
+ act(() => h.app.selection.add(grouped));
+ assertSelectedElements([frame.id, grouped.id]);
+
+ // the child added along with it, too
+ act(() => h.app.selection.clear());
+ act(() => h.app.selection.add([child, grouped]));
+ assertSelectedElements([frame.id, grouped.id]);
+ act(() => h.app.selection.select([child, grouped]));
+ assertSelectedElements([frame.id, grouped.id]);
+ });
+
+ it("add() replaces the selection in the element link selector", () => {
+ const source = API.createElement({ type: "rectangle" });
+ const target = API.createElement({ type: "rectangle", x: 300 });
+ const linked = API.createElement({ type: "rectangle", x: 600 });
+ API.setElements([source, target, linked]);
+ API.setAppState({
+ openDialog: { name: "elementLinkSelector", sourceElementId: source.id },
+ });
+ // (opening the selector clears the selection)
+ API.setSelectedElements([linked]);
+ assertSelectedElements([linked.id]);
+
+ act(() => h.app.selection.add(target));
+
+ assertSelectedElements([target.id]);
+ });
+
+ it("sets up the line editor of a lone selected arrow — not of one selected with its group", () => {
+ const [arrow, groupedArrow] = [0, 200].map((y) =>
+ API.createElement({
+ type: "arrow",
+ y,
+ width: 100,
+ height: 0,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],
+ groupIds: y ? ["group"] : [],
+ }),
+ );
+ const sibling = API.createElement({
+ type: "rectangle",
+ x: 300,
+ y: 200,
+ groupIds: ["group"],
+ });
+ const rectangle = API.createElement({ type: "rectangle", x: 300 });
+ API.setElements([arrow, rectangle, groupedArrow, sibling]);
+
+ act(() => h.app.selection.select(arrow));
+ assertSelectedElements([arrow.id]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+
+ act(() => h.app.selection.select(rectangle));
+ assertSelectedElements([rectangle.id]);
+ expect(h.state.selectedLinearElement).toBe(null);
+
+ act(() => h.app.selection.clear());
+ act(() => h.app.selection.add(arrow));
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+
+ act(() => h.app.selection.select(groupedArrow));
+ assertSelectedElements([groupedArrow.id, sibling.id]);
+ expect(h.state.selectedLinearElement).toBe(null);
+ });
+
+ it("takes elements or ids, one or many, skipping missing ones", () => {
+ const [a, b, c] = [0, 100, 200].map((x) =>
+ API.createElement({ type: "rectangle", x }),
+ );
+ API.setElements([a, b, c]);
+
+ act(() => h.app.selection.select([a.id, "missing", b, a]));
+ assertSelectedElements([a.id, b.id]);
+
+ act(() => h.app.selection.add(c.id));
+ assertSelectedElements([a.id, b.id, c.id]);
+
+ act(() => h.app.selection.remove([a, b.id]));
+ assertSelectedElements([c.id]);
+ });
+
+ it("add() of a frame along with its child selects the frame, in either order", () => {
+ const { frame, child } = createFrame();
+ API.setElements([child, frame]);
+
+ act(() => h.app.selection.add([child, frame]));
+ assertSelectedElements([frame.id]);
+
+ act(() => h.app.selection.clear());
+ act(() => h.app.selection.add([frame, child]));
+ assertSelectedElements([frame.id]);
+ });
+
+ it("remove() of an element selected via its group keeps the other selected groups", () => {
+ const [a1, a2, b1, b2] = ["a", "a", "b", "b"].map((groupId, index) =>
+ API.createElement({
+ type: "rectangle",
+ x: index * 100,
+ groupIds: [groupId],
+ }),
+ );
+ API.setElements([a1, a2, b1, b2]);
+ API.setSelectedElements([a1, a2, b1, b2]);
+
+ act(() => h.app.selection.remove(a1));
+
+ assertSelectedElements([b1.id, b2.id]);
+ expect(h.state.selectedGroupIds).toEqual({ b: true });
+ });
+
+ it("shows the link popup of a lone selected element with a link, whatever was selected before", () => {
+ const linked = API.createElement({ type: "rectangle" });
+ const other = API.createElement({ type: "rectangle", x: 300 });
+ API.setElements([linked, other]);
+ API.updateElement(linked, { link: "https://excalidraw.com" });
+
+ act(() => h.app.selection.select(linked.id));
+ expect(h.state.showHyperlinkPopup).toBe("info");
+
+ act(() => h.app.selection.select(other));
+ expect(h.state.showHyperlinkPopup).toBe(false);
+
+ act(() => h.app.selection.select(linked));
+ expect(h.state.showHyperlinkPopup).toBe("info");
+
+ act(() => h.app.selection.add(other));
+ expect(h.state.showHyperlinkPopup).toBe(false);
+
+ act(() => h.app.selection.remove(other));
+ expect(h.state.showHyperlinkPopup).toBe("info");
+
+ act(() => h.app.selection.clear());
+ expect(h.state.showHyperlinkPopup).toBe(false);
+ });
+
+ it("skips locked elements, unless includeLocked", () => {
+ const locked = API.createElement({ type: "rectangle", locked: true });
+ const other = API.createElement({ type: "rectangle", x: 300 });
+ API.setElements([locked, other]);
+
+ act(() => h.app.selection.select([locked, other]));
+ assertSelectedElements([other.id]);
+
+ act(() => h.app.selection.add(locked, { includeLocked: true }));
+ assertSelectedElements([locked.id, other.id]);
+ });
+
+ it("ends the cropping and deactivates the embed of what it deselects", () => {
+ const image = API.createElement({ type: "image" });
+ const embed = API.createElement({ type: "embeddable", x: 300 });
+ const other = API.createElement({ type: "rectangle", x: 600 });
+ API.setElements([image, embed, other]);
+
+ API.setSelectedElements([image]);
+ API.setAppState({ croppingElementId: image.id });
+ act(() => h.app.selection.select(image));
+ expect(h.state.croppingElementId).toBe(image.id);
+ act(() => h.app.selection.select(other));
+ expect(h.state.croppingElementId).toBe(null);
+
+ API.setSelectedElements([embed]);
+ API.setAppState({ activeEmbeddable: { element: embed, state: "active" } });
+ act(() => h.app.selection.add(other));
+ expect(h.state.activeEmbeddable?.element.id).toBe(embed.id);
+ act(() => h.app.selection.remove(embed));
+ expect(h.state.activeEmbeddable).toBe(null);
+ });
+
+ it("ends text editing (after the event), submitting the text, unless selecting the edited text", async () => {
+ const rectangle = API.createElement({ type: "rectangle", x: 300, y: 300 });
+ API.setElements([rectangle]);
+ const text = UI.createElement("text");
+ updateTextEditor(await getTextEditor(), "hello");
+
+ act(() => h.app.selection.add(text));
+ await act(async () => {});
+ expect(h.state.editingTextElement?.id).toBe(text.id);
+
+ act(() => h.app.selection.select(rectangle));
+ await act(async () => {});
+ expect(h.state.editingTextElement).toBe(null);
+ expect(API.getElement(text).text).toBe("hello");
+ assertSelectedElements([rectangle.id]);
+ });
+
+ it("records the change for undo with captureUpdate", () => {
+ const [a, b] = [0, 300].map((x) =>
+ API.createElement({ type: "rectangle", x }),
+ );
+ API.setElements([a, b]);
+ const { IMMEDIATELY } = CaptureUpdateAction;
+
+ act(() => h.app.selection.select(a, { captureUpdate: IMMEDIATELY }));
+ act(() => h.app.selection.select(b, { captureUpdate: IMMEDIATELY }));
+ act(() => {
+ h.app.actionManager.executeAction(h.app.actionManager.actions.undo);
+ });
+
+ assertSelectedElements([a.id]);
+ });
+
+ it("deep-selects the elements themselves, editing their shared group", () => {
+ const [a, b, c] = [0, 100, 200].map((x) =>
+ API.createElement({ type: "rectangle", x, groupIds: ["group"] }),
+ );
+ API.setElements([a, b, c]);
+
+ act(() => h.app.selection.select([a, b], { deep: true }));
+ assertSelectedElements([a.id, b.id]);
+ expect(h.state.editingGroupId).toBe("group");
+
+ // not sharing a group: none of their groups
+ const [d, e] = [0, 100].map((x) =>
+ API.createElement({ type: "rectangle", x, y: 200, groupIds: ["other"] }),
+ );
+ API.setElements([a, b, c, d, e]);
+ act(() => h.app.selection.select([a, d], { deep: true }));
+ assertSelectedElements([a.id, d.id]);
+ expect(h.state.editingGroupId).toBe(null);
+ });
+
+ it("remove() leaving an arrow alone sets up its line editor", () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ width: 100,
+ height: 0,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],
+ });
+ const rectangle = API.createElement({ type: "rectangle", x: 300 });
+ API.setElements([arrow, rectangle]);
+ API.setSelectedElements([arrow, rectangle]);
+
+ act(() => h.app.selection.remove(rectangle));
+
+ assertSelectedElements([arrow.id]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+ });
+});
+
+describe("transform handles", () => {
+ beforeEach(async () => {
+ await render(<Excalidraw />);
+ });
+
+ it("show the resize cursor over the selection's handles", () => {
+ const [a, b] = [0, 200].map((x) =>
+ API.createElement({ type: "rectangle", x, width: 100, height: 100 }),
+ );
+ API.setElements([a, b]);
+ const cursor = () => GlobalTestState.interactiveCanvas.style.cursor;
+
+ // a lone element's right edge
+ API.setSelectedElements([a]);
+ mouse.moveTo(103, 50);
+ expect(cursor()).toBe("ew-resize");
+
+ // the selection's right edge
+ API.setSelectedElements([a, b]);
+ mouse.moveTo(303, 50);
+ expect(cursor()).toBe("ew-resize");
+ mouse.moveTo(150, 50);
+ expect(cursor()).not.toBe("ew-resize");
+ });
+});
+
describe("selection element", () => {
it("create selection element on pointer down", async () => {
const { getByToolName, container } = await render(<Excalidraw />);
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index 9950f0c048..c34cfc9c97 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -1374,6 +1374,24 @@ export interface ExcalidrawImperativeAPI {
history: {
clear: InstanceType<typeof App>["resetHistory"];
};
+ /**
+ * Selects elements (or their ids — one or many), adds them to or removes
+ * them from the selection, or clears it — as the editor does: an element is
+ * selected with its group (unless `deep`), a frame and its children aren't
+ * selected at the same time, and locked elements are skipped (unless
+ * `includeLocked`). Text editing and cropping end, and the link popup of a
+ * lone selected element shows. Missing and deleted elements are skipped.
+ *
+ * By default the change is recorded for undo along with the next undoable
+ * change — pass `captureUpdate` as for `updateScene()` otherwise. Like
+ * `updateScene()`, it applies on the next render: read it back through
+ * `onChange()` or `getAppState()` after that. Works in view mode too, where
+ * the selection shows without transform handles.
+ */
+ selection: Pick<
+ InstanceType<typeof App>["selection"],
+ "select" | "add" | "remove" | "clear"
+ >;
getSceneElements: InstanceType<typeof App>["getSceneElements"];
getAppState: () => InstanceType<typeof App>["state"];
getFiles: () => InstanceType<typeof App>["files"];