mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-12-03 10:00:31 +03:00
refactor(editor): app.selection, and the rest of the selection tool out of App (#12258)
* refactor(editor): add AppSelection (app.selection) to select, add to, remove from and clear the selection - select(element) for click-select, the alt-click cycle and the context menu; add(element) for the selection tool and the lasso's touch select (was a near-copy); remove(element) for shift-click; clear() replaces App.deselectElements and three inline copies - isASelectedElement / isHittingCommonBoundingBoxOfSelectedElements move from the selection tool - select() drops a stale line editor of a no longer selected arrow; the context menu no longer spreads all of this.state into its setState - tests for the selection's frame, link selector and line editor rules Claude Opus 5.5 (1M), xhigh effort * refactor(editor): make the app.selection API generic over elements or ids, one or many - select / add / remove take elements or ids, one or many (missing and deleted ones skipped) - their rules become pure functions in App.selection.ts, for callers that need the next selection state rather than a setState (actions, duplication): getSelectionStateForElements (moved from @excalidraw/element, now keeping the current line editor), getSelectionStateAddingElements, getSelectionStateRemovingElements — one pass over the elements however many are added or removed - remove() recomputes selectedGroupIds (it put element ids into it and lost the other selected groups' flags), and leaves group editing once nothing is selected - the link popup on adding an element is the pointer's, not add()'s Claude Opus 5.5 (1M), xhigh effort * refactor(editor): move selectGroupsForSelectedElements from @excalidraw/element into App.selection.ts - editor state (selected group ids, the edited group), used by the editor only; moved as is - also ends the groups.ts <-> selection.ts import cycle in @excalidraw/element Claude Opus 5.5 (1M), xhigh effort * refactor(editor): move dragging the selection and box selection out of App into AppSelectionTool - handleSelectionDragOnPointerMove: dragging the selection (or the image within its crop), alt-drag duplicating past the threshold - handleBoxSelectionOnPointerMove: box selection (and of the line editor's points) - handleSelectionDragOnPointerUp: frame membership of the dragged selection - pure moves, verified mechanically - tests for shift-dragging along one axis and moving the image within its crop (both untested through the pointer) Claude Opus 5.5 (1M), xhigh effort * refactor(editor): one check for the selection's transform handle under the pointer - selectionTool.getTransformHandleAt() replaces the two copies in the hover cursor and on pointer down (line editor, elbow arrows, two-point lines, mobile lines, hovered line points; a lone element's or the selection's common bounds) - pointer down now also ignores the handles in the element link selector, as the hover cursor did - test for the resize cursor over the handles (untested) Claude Opus 5.5 (1M), xhigh effort * fix(editor): app.selection shows the link popup of what it selects - select / add / remove show the link popup of a lone selected element with a link (or an embeddable) and hide it otherwise; clear hides it — it was left as is, so select() showed it only if a previous selection had - the link editor stays open when its element is selected again - the pointer and lasso call sites no longer set it themselves Claude Opus 5.5 (1M), xhigh effort * feat(editor): app.selection ends what hangs on the deselected elements and skips locked ones - cropping ends unless the cropped image stays the selection, and an active embed is deactivated once deselected (the line editor already ended once its line is deselected) - select / add skip locked elements, unless includeLocked — which the context menu passes, to offer unlocking them - captureUpdate option, as updateScene's, to record the change for undo - deep option on select (the elements themselves, editing their shared group), which Ctrl+click now goes through - text editing isn't ended here: the editor ends itself on blur, and submitting it mid pointer event would commit half the event's state Claude Opus 5.5 (1M), xhigh effort * feat(editor): app.selection ends text editing, and add / remove / clear always end cropping - select / add of anything but the edited text (or its container) submit the text editor — after the current event (it submits with a flushSync), and only if that editing session is still open; clear / remove leave it (starting text editing clears the selection) - add / remove / clear end cropping; select keeps it only when selecting the cropped image again (a click inside it in the crop editor) Claude Opus 5.5 (1M), xhigh effort * fix(editor): app.selection derives the line editor from the final selection, and frame / deep fixes - the line editor is set from the selection once groups are expanded: an arrow selected with its group (e.g. by alt-click cycling) gets none, so dragging from its point moves the group rather than reshaping the arrow; add() sets it too (adding a lone arrow left Edit / Cmd+Enter throwing) - children of frames selected through the groups of the selected (or added) elements are left out, also ones selected in the same call — and adding within an edited group no longer deselects as if the edited group's frames were selected - deep selection never expands groups (it did for elements not sharing one) - a click-selected elbow arrow now gets its line editor on pointerdown, so that click's pointerup normalizes a hand-built route one gesture earlier Claude Opus 5.5 (1M), xhigh effort * feat(packages/excalidraw): excalidrawAPI.selection - app.selection on the imperative API — select / add / remove / clear, taking elements or ids, one or many, with the deep / includeLocked / captureUpdate options; the type exposes only those four - they're arrow properties, so they keep `this` when taken off the object - changelog entry Claude Opus 5.5 (1M), xhigh effort
This commit is contained in:
1 parent
4c00f31ddc
commit
e65eca999e
22 files changed
+1846
-1229
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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()];
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
() => {
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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} />);
|
||||
|
||||
|
||||
@@ -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 />);
|
||||
|
||||
@@ -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"];
|
||||
|
||||
Reference in new issue
Block a user