Files
excalidraw/packages/element/src/groups.ts
T
David Luzar e65eca999e 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
2026-10-10 23:34:00 +02:00

318 lines
9.1 KiB
TypeScript

import type {
AppState,
InteractiveCanvasAppState,
} from "@excalidraw/excalidraw/types";
import { getBoundTextElement } from "./textElement";
import { isBoundToContainer } from "./typeChecks";
import type {
GroupId,
ExcalidrawElement,
NonDeleted,
ElementsMapOrArray,
ElementsMap,
NonDeletedExcalidrawElement,
NonDeletedElementsMapOrArray,
} from "./types";
export const selectGroup = (
groupId: GroupId,
appState: InteractiveCanvasAppState,
elements: readonly NonDeletedExcalidrawElement[],
): Pick<
InteractiveCanvasAppState,
"selectedGroupIds" | "selectedElementIds" | "editingGroupId"
> => {
const elementsInGroup = elements.reduce(
(acc: Record<string, true>, element) => {
if (element.groupIds.includes(groupId)) {
acc[element.id] = true;
}
return acc;
},
{},
);
if (Object.keys(elementsInGroup).length < 2) {
if (
appState.selectedGroupIds[groupId] ||
appState.editingGroupId === groupId
) {
return {
selectedElementIds: appState.selectedElementIds,
selectedGroupIds: { ...appState.selectedGroupIds, [groupId]: false },
editingGroupId: null,
};
}
return appState;
}
return {
editingGroupId: appState.editingGroupId,
selectedGroupIds: { ...appState.selectedGroupIds, [groupId]: true },
selectedElementIds: {
...appState.selectedElementIds,
...elementsInGroup,
},
};
};
/**
* If the element's group is selected, don't render an individual
* selection border around it.
*/
export const isSelectedViaGroup = (
appState: Pick<
InteractiveCanvasAppState,
"editingGroupId" | "selectedGroupIds"
>,
element: ExcalidrawElement,
) => getSelectedGroupForElement(appState, element) != null;
export const getSelectedGroupForElement = (
appState: Pick<
InteractiveCanvasAppState,
"editingGroupId" | "selectedGroupIds"
>,
element: ExcalidrawElement,
) =>
element.groupIds
.filter((groupId) => groupId !== appState.editingGroupId)
.find((groupId) => appState.selectedGroupIds[groupId]);
export const getSelectedGroupIds = (
appState: Pick<InteractiveCanvasAppState, "selectedGroupIds">,
): GroupId[] =>
Object.entries(appState.selectedGroupIds)
.filter(([groupId, isSelected]) => isSelected)
.map(([groupId, isSelected]) => groupId);
// given a list of elements, return the the actual group ids that should be selected
// or used to update the elements
export const selectGroupsFromGivenElements = (
elements: readonly NonDeletedExcalidrawElement[],
appState: InteractiveCanvasAppState,
) => {
let nextAppState: InteractiveCanvasAppState = {
...appState,
selectedGroupIds: {},
};
for (const element of elements) {
let groupIds = element.groupIds;
if (appState.editingGroupId) {
const indexOfEditingGroup = groupIds.indexOf(appState.editingGroupId);
if (indexOfEditingGroup > -1) {
groupIds = groupIds.slice(0, indexOfEditingGroup);
}
}
if (groupIds.length > 0) {
const groupId = groupIds[groupIds.length - 1];
nextAppState = {
...nextAppState,
...selectGroup(groupId, nextAppState, elements),
};
}
}
return nextAppState.selectedGroupIds;
};
export const editGroupForSelectedElement = (
appState: AppState,
element: NonDeleted<ExcalidrawElement>,
): AppState => {
return {
...appState,
editingGroupId: element.groupIds.length ? element.groupIds[0] : null,
selectedGroupIds: {},
selectedElementIds: {
[element.id]: true,
},
};
};
export const isElementInGroup = (element: ExcalidrawElement, groupId: string) =>
element.groupIds.includes(groupId);
export const getElementsInGroup = <
P extends NonDeletedExcalidrawElement | ExcalidrawElement,
>(
elements: P extends NonDeletedExcalidrawElement
? NonDeletedElementsMapOrArray
: ElementsMapOrArray,
groupId: string,
): P[] => {
const elementsInGroup: P[] = [];
for (const element of elements.values()) {
if (isElementInGroup(element, groupId)) {
elementsInGroup.push(element as P);
}
}
return elementsInGroup;
};
export const getSelectedGroupIdForElement = (
element: ExcalidrawElement,
selectedGroupIds: { [groupId: string]: boolean },
) => element.groupIds.find((groupId) => selectedGroupIds[groupId]);
export const addToGroup = (
prevGroupIds: ExcalidrawElement["groupIds"],
newGroupId: GroupId,
editingGroupId: AppState["editingGroupId"],
) => {
// insert before the editingGroupId, or push to the end.
const groupIds = [...prevGroupIds];
const positionOfEditingGroupId = editingGroupId
? groupIds.indexOf(editingGroupId)
: -1;
const positionToInsert =
positionOfEditingGroupId > -1 ? positionOfEditingGroupId : groupIds.length;
groupIds.splice(positionToInsert, 0, newGroupId);
return groupIds;
};
export const removeFromSelectedGroups = (
groupIds: ExcalidrawElement["groupIds"],
selectedGroupIds: { [groupId: string]: boolean },
) => groupIds.filter((groupId) => !selectedGroupIds[groupId]);
export const getMaximumGroups = <
T extends NonDeletedExcalidrawElement | ExcalidrawElement,
>(
elements: T[],
elementsMap: ElementsMap,
): T[][] => {
const groups: Map<String, T[]> = new Map<String, T[]>();
elements.forEach((element: T) => {
const groupId =
element.groupIds.length === 0
? element.id
: element.groupIds[element.groupIds.length - 1];
const currentGroupMembers = groups.get(groupId) || [];
// Include bound text if present when grouping
const boundTextElement = getBoundTextElement(element, elementsMap);
if (boundTextElement) {
currentGroupMembers.push(boundTextElement as T);
}
groups.set(groupId, [...currentGroupMembers, element]);
});
return Array.from(groups.values());
};
export const getNonDeletedGroupIds = (elements: ElementsMap) => {
const nonDeletedGroupIds = new Set<string>();
for (const [, element] of elements) {
// defensive check
if (element.isDeleted) {
continue;
}
// defensive fallback
for (const groupId of element.groupIds ?? []) {
nonDeletedGroupIds.add(groupId);
}
}
return nonDeletedGroupIds;
};
export const elementsAreInSameGroup = (
elements: readonly ExcalidrawElement[],
) => {
const allGroups = elements.flatMap((element) => element.groupIds);
const groupCount = new Map<string, number>();
let maxGroup = 0;
for (const group of allGroups) {
groupCount.set(group, (groupCount.get(group) ?? 0) + 1);
if (groupCount.get(group)! > maxGroup) {
maxGroup = groupCount.get(group)!;
}
}
return maxGroup === elements.length;
};
export const isInGroup = (element: ExcalidrawElement) => {
return element.groupIds.length > 0;
};
export const getNewGroupIdsForDuplication = (
groupIds: ExcalidrawElement["groupIds"],
editingGroupId: AppState["editingGroupId"],
mapper: (groupId: GroupId) => GroupId,
) => {
const copy = [...groupIds];
const positionOfEditingGroupId = editingGroupId
? groupIds.indexOf(editingGroupId)
: -1;
const endIndex =
positionOfEditingGroupId > -1 ? positionOfEditingGroupId : groupIds.length;
for (let index = 0; index < endIndex; index++) {
copy[index] = mapper(copy[index]);
}
return copy;
};
// given a list of selected elements, return the element grouped by their immediate group selected state
// in the case if only one group is selected and all elements selected are within the group, it will respect group hierarchy in accordance to their nested grouping order
export const getSelectedElementsByGroup = (
selectedElements: NonDeletedExcalidrawElement[],
elementsMap: ElementsMap,
appState: Readonly<Pick<AppState, "selectedGroupIds" | "editingGroupId">>,
): NonDeletedExcalidrawElement[][] => {
const buckets: Map<string, NonDeletedExcalidrawElement[]> = new Map();
const selectedGroupIds = getSelectedGroupIds(appState);
const isSingleSelectedGroupCase =
selectedGroupIds.length === 1 &&
selectedElements.every((element) => isSelectedViaGroup(appState, element));
selectedElements.forEach((element) => {
// skip dependent boundTextElements, they are appended after their container
if (isBoundToContainer(element)) {
return;
}
let bucketKey: string;
const selectedGroupId = getSelectedGroupIdForElement(
element,
appState.selectedGroupIds,
);
if (!selectedGroupId) {
bucketKey = `${element.id}_element`;
} else {
// if only one group is selected, grouping is based on inner hierarchy
const keyIndex = isSingleSelectedGroupCase
? element.groupIds.indexOf(selectedGroupId) - 1
: element.groupIds.indexOf(selectedGroupId);
// edge case: single selected group where element is non member of inner group
bucketKey =
keyIndex < 0
? `${element.id}_element`
: `${element.groupIds[keyIndex]}_group`;
}
const currentBucketMembers = buckets.get(bucketKey) ?? [];
const boundTextElement = getBoundTextElement(element, elementsMap);
// preserve boundtext after container ordering
buckets.set(bucketKey, [
...currentBucketMembers,
element,
...(boundTextElement ? [boundTextElement] : []),
]);
});
return [...buckets.values()];
};