Virtual whiteboard for sketching hand-drawn like diagrams
fix(editor): respect boxSelectionMode ('contain' vs 'overlap') in lasso tool (#11862)
Jayeshc5a50d223feb
diff --git a/packages/excalidraw/lasso/index.ts b/packages/excalidraw/lasso/index.tsindex e07a684a94..d624ce6d42 100644--- a/packages/excalidraw/lasso/index.ts+++ b/packages/excalidraw/lasso/index.ts@@ -6,17 +6,11 @@ import {import { getElementLineSegments } from "@excalidraw/element";import { LinearElementEditor } from "@excalidraw/element";-import {- isFrameLikeElement,- isLinearElement,- isTextElement,-} from "@excalidraw/element";+import { isFrameLikeElement, isLinearElement } from "@excalidraw/element";import { getFrameChildren } from "@excalidraw/element";import { selectGroupsForSelectedElements } from "@excalidraw/element";-import { getContainerElement } from "@excalidraw/element";-import { arrayToMap, easeOut, isShallowEqual } from "@excalidraw/common";import type {@@ -100,21 +94,6 @@ export class LassoTrail extends AnimatedTrail {}}- for (const [id] of Object.entries(nextSelectedElementIds)) {- const element = this.app.scene.getNonDeletedElement(id);-- if (element && isTextElement(element)) {- const container = getContainerElement(- element,- this.app.scene.getNonDeletedElementsMap(),- );- if (container) {- nextSelectedElementIds[container.id] = true;- delete nextSelectedElementIds[element.id];- }- }- }-// remove all children of selected framesfor (const [id] of Object.entries(nextSelectedElementIds)) {const element = this.app.scene.getNonDeletedElement(id);@@ -202,6 +181,7 @@ export class LassoTrail extends AnimatedTrail {intersectedElements: this.intersectedElements,enclosedElements: this.enclosedElements,simplifyDistance: 5 / this.app.state.zoom.value,+ mode: this.app.state.boxSelectionMode,});this.selectElementsFromIds(selectedElementIds);diff --git a/packages/excalidraw/lasso/utils.ts b/packages/excalidraw/lasso/utils.tsindex f7eb7cba55..f09c401db0 100644--- a/packages/excalidraw/lasso/utils.ts+++ b/packages/excalidraw/lasso/utils.ts@@ -3,22 +3,37 @@ import { simplify } from "points-on-curve";import {polygonFromPoints,lineSegment,+ pointFrom,+ pointOnLineSegment,polygonIncludesPointNonZero,+ PRECISION,} from "@excalidraw/math";import { type Bounds } from "@excalidraw/common";import {+ boundsContainBounds,computeBoundTextPosition,doBoundsIntersect,+ elementOverlapsWithFrame,getBoundTextElement,+ getContainingFrame,getElementBounds,intersectElementWithLineSegment,+ isBoundToContainer,+ pointInsideBoundsInclusive,} from "@excalidraw/element";-import type { ElementsSegmentsMap, GlobalPoint } from "@excalidraw/math/types";+import type {+ ElementsSegmentsMap,+ GlobalPoint,+ LineSegment,+ Polygon,+} from "@excalidraw/math/types";import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types";+import type { BoxSelectionMode } from "../types";+export const getLassoSelectedElementIds = (input: {lassoPath: GlobalPoint[];elements: readonly ExcalidrawElement[];@@ -27,6 +42,7 @@ export const getLassoSelectedElementIds = (input: {intersectedElements: Set<ExcalidrawElement["id"]>;enclosedElements: Set<ExcalidrawElement["id"]>;simplifyDistance?: number;+ mode?: BoxSelectionMode;}): {selectedElementIds: string[];} => {@@ -38,13 +54,17 @@ export const getLassoSelectedElementIds = (input: {intersectedElements,enclosedElements,simplifyDistance,+ mode = "contain",} = input;// simplify the path to reduce the number of pointslet path: GlobalPoint[] = lassoPath;if (simplifyDistance) {path = simplify(lassoPath, simplifyDistance) as GlobalPoint[];}- const unlockedElements = elements.filter((el) => !el.locked);+ // bound text is never selected on its own, it's covered by its container+ const selectableElements = elements.filter(+ (el) => !el.locked && !isBoundToContainer(el),+ );// as the path might not enclose a shape anymore, clear before checkingenclosedElements.clear();intersectedElements.clear();@@ -59,58 +79,285 @@ export const getLassoSelectedElementIds = (input: {},[Infinity, Infinity, -Infinity, -Infinity],) as Bounds;- for (const element of unlockedElements) {+ const lassoPolygon = polygonFromPoints(path);+ const containBounds: Bounds = [+ lassoBounds[0] - PRECISION,+ lassoBounds[1] - PRECISION,+ lassoBounds[2] + PRECISION,+ lassoBounds[3] + PRECISION,+ ];++ for (const element of selectableElements) {+ // Only the visible (frame-clipped) portion of an element is relevant for+ // selection, so everything outside of its frame is disregarded below+ const bounds = getElementBounds(element, elementsMap);+ const clipBounds = getFrameClipBounds(element, bounds, elementsMap);+// First check if the lasso segment intersects the element's axis-aligned// bounding box as it is much faster than checking intersection against// the element's shape- const elementBounds = getElementBounds(element, elementsMap);+ const elementBounds = clipToBounds(bounds, clipBounds);if (doBoundsIntersect(lassoBounds, elementBounds) &&!intersectedElements.has(element.id) &&!enclosedElements.has(element.id)) {- const enclosed = enclosureTest(path, element, elementsSegments);- if (enclosed) {- enclosedElements.add(element.id);- } else {- const intersects = intersectionTest(path, element, elementsMap);- if (intersects) {- intersectedElements.add(element.id);+ if (+ mode === "contain" &&+ !boundsContainBounds(containBounds, elementBounds)+ ) {+ continue;+ }++ const segments = getSelectionSegments(+ element,+ elementsMap,+ elementsSegments,+ clipBounds,+ );+ const enclosed = enclosureTest(+ lassoPolygon,+ segments,+ elementBounds,+ mode,+ );+ if (mode === "contain") {+ if (+ enclosed &&+ !intersectionTest(path, element, elementsMap, clipBounds)+ ) {+ enclosedElements.add(element.id);}+ } else if (enclosed) {+ enclosedElements.add(element.id);+ } else if (intersectionTest(path, element, elementsMap, clipBounds)) {+ intersectedElements.add(element.id);}}}- const results = [...intersectedElements, ...enclosedElements];+ const results =+ mode === "contain"+ ? excludeIncompleteGroups([...enclosedElements], elementsMap)+ : [...intersectedElements, ...enclosedElements];return {selectedElementIds: results,};};-const enclosureTest = (- lassoPath: GlobalPoint[],+/**+ * The bounds an element is clipped to by the frame containing it, or `null`+ * when the element isn't clipped at all.+ */+const getFrameClipBounds = (element: ExcalidrawElement,+ elementBounds: Bounds,+ elementsMap: ElementsMap,+): Bounds | null => {+ const frame = getContainingFrame(element, elementsMap);++ if (!frame) {+ return null;+ }++ const frameBounds = getElementBounds(frame, elementsMap);++ // nothing is clipped away from an element fitting inside its frame+ if (boundsContainBounds(frameBounds, elementBounds)) {+ return null;+ }++ return elementOverlapsWithFrame(element, frame, elementsMap)+ ? frameBounds+ : null;+};++const clipToBounds = (bounds: Bounds, clipBounds: Bounds | null): Bounds =>+ clipBounds+ ? [+ Math.max(bounds[0], clipBounds[0]),+ Math.max(bounds[1], clipBounds[1]),+ Math.min(bounds[2], clipBounds[2]),+ Math.min(bounds[3], clipBounds[3]),+ ]+ : bounds;++/**+ * The segments taking part in the selection tests: the element's own outline+ * together with its label's, clipped to the element's containing frame.+ */+const getSelectionSegments = (+ element: ExcalidrawElement,+ elementsMap: ElementsMap,elementsSegments: ElementsSegmentsMap,-): boolean => {- const lassoPolygon = polygonFromPoints(lassoPath);- const segments = elementsSegments.get(element.id);- if (!segments) {- return false;+ clipBounds: Bounds | null,+): LineSegment<GlobalPoint>[] => {+ const elementSegments = elementsSegments.get(element.id) ?? [];+ const boundTextElement = getBoundTextElement(element, elementsMap);+ const boundTextSegments = boundTextElement+ ? elementsSegments.get(boundTextElement.id)+ : null;++ const segments = boundTextSegments?.length+ ? [...elementSegments, ...boundTextSegments]+ : elementSegments;++ return clipBounds ? clipSegmentsToBounds(segments, clipBounds) : segments;+};++const clipSegmentsToBounds = (+ segments: LineSegment<GlobalPoint>[],+ bounds: Bounds,+): LineSegment<GlobalPoint>[] => {+ const [minX, minY, maxX, maxY] = bounds;+ const clipped: LineSegment<GlobalPoint>[] = [];++ for (const [[x1, y1], [x2, y2]] of segments) {+ const dx = x2 - x1;+ const dy = y2 - y1;+ let t0 = 0;+ let t1 = 1;+ let inside = true;++ // clip the segment against each of the four edges in turn, narrowing down+ // the [t0, t1] portion of it which lies inside the bounds+ for (const [p, q] of [+ [-dx, x1 - minX],+ [dx, maxX - x1],+ [-dy, y1 - minY],+ [dy, maxY - y1],+ ]) {+ if (p === 0) {+ // parallel to this edge: either entirely inside or entirely outside+ if (q < 0) {+ inside = false;+ break;+ }+ continue;+ }++ const t = q / p;+ if (p < 0) {+ if (t > t1) {+ inside = false;+ break;+ }+ t0 = Math.max(t0, t);+ } else {+ if (t < t0) {+ inside = false;+ break;+ }+ t1 = Math.min(t1, t);+ }+ }++ if (inside) {+ clipped.push(+ lineSegment(+ pointFrom<GlobalPoint>(x1 + t0 * dx, y1 + t0 * dy),+ pointFrom<GlobalPoint>(x1 + t1 * dx, y1 + t1 * dy),+ ),+ );+ }}- return segments.some((segment) => {- return segment.some((point) =>- polygonIncludesPointNonZero(point, lassoPolygon),- );+ return clipped;+};++/**+ * In "contain" mode a group is only selected if every one of its members is,+ * mirroring marquee selection.+ *+ * NOTE: currently we only support top-level group handling since we don't+ * support box selecting while editing the group/subgroup+ */+const excludeIncompleteGroups = (+ selectedElementIds: ExcalidrawElement["id"][],+ elementsMap: ElementsMap,+): ExcalidrawElement["id"][] => {+ if (!selectedElementIds.some((id) => elementsMap.get(id)?.groupIds.length)) {+ return selectedElementIds;+ }++ const groups = new Map<string, ExcalidrawElement["id"][]>();++ for (const element of elementsMap.values()) {+ const groupId = element.groupIds.at(-1);++ // ignored elements such as bound text and locked elements must not+ // affect group selection+ if (!groupId || element.locked || isBoundToContainer(element)) {+ continue;+ }++ const group = groups.get(groupId);+ if (group) {+ group.push(element.id);+ } else {+ groups.set(groupId, [element.id]);+ }+ }++ if (!groups.size) {+ return selectedElementIds;+ }++ const selected = new Set(selectedElementIds);++ return selectedElementIds.filter((id) => {+ const groupId = elementsMap.get(id)?.groupIds.at(-1);+ const group = groupId ? groups.get(groupId) : null;++ return !group || group.every((memberId) => selected.has(memberId));});};+const enclosureTest = (+ lassoPolygon: Polygon<GlobalPoint>,+ segments: LineSegment<GlobalPoint>[],+ elementBounds: Bounds,+ mode: BoxSelectionMode,+): boolean => {+ const quantifier = mode === "contain" ? "every" : "some";++ const includesPoint = (point: GlobalPoint) =>+ polygonIncludesPointNonZero(point, lassoPolygon) ||+ (mode === "contain" && isPointOnPolygon(point, lassoPolygon));++ // NOTE: elements without an outline (e.g. a single point freedraw dot) are+ // tested by the corners of their bounding box instead+ if (segments.length === 0) {+ return boundsCorners(elementBounds)[quantifier](includesPoint);+ }++ return segments[quantifier]((segment) => segment[quantifier](includesPoint));+};++const boundsCorners = ([minX, minY, maxX, maxY]: Bounds): GlobalPoint[] => [+ pointFrom(minX, minY),+ pointFrom(maxX, minY),+ pointFrom(maxX, maxY),+ pointFrom(minX, maxY),+];++const isPointOnPolygon = (+ point: GlobalPoint,+ polygon: Polygon<GlobalPoint>,+): boolean =>+ polygon.some(+ (vertex, index) =>+ index > 0 &&+ pointOnLineSegment(point, lineSegment(polygon[index - 1], vertex)),+ );+const intersectionTest = (lassoPath: GlobalPoint[],element: ExcalidrawElement,elementsMap: ElementsMap,+ clipBounds: Bounds | null,): boolean => {const lassoSegments = lassoPath.slice(1)@@ -119,25 +366,35 @@ const intersectionTest = (const boundTextElement = getBoundTextElement(element, elementsMap);+ // hits on the part of the element clipped away by its frame are invisible,+ // hence they do not count as an intersection+ const intersects = (+ target: ExcalidrawElement,+ lassoSegment: LineSegment<GlobalPoint>,+ ) => {+ const hits = intersectElementWithLineSegment(+ target,+ elementsMap,+ lassoSegment,+ 0,+ !clipBounds,+ );++ return clipBounds+ ? hits.some((hit) => pointInsideBoundsInclusive(hit, clipBounds))+ : hits.length > 0;+ };+return lassoSegments.some((lassoSegment) =>- intersectElementWithLineSegment(- element,- elementsMap,- lassoSegment,- 0,- true,- ).length > 0 ||+ intersects(element, lassoSegment) ||(!!boundTextElement &&- intersectElementWithLineSegment(+ intersects({...boundTextElement,...computeBoundTextPosition(element, boundTextElement, elementsMap),},- elementsMap,lassoSegment,- 0,- true,- ).length > 0),+ )),);};diff --git a/packages/excalidraw/tests/lasso.test.tsx b/packages/excalidraw/tests/lasso.test.tsxindex f9a9d12d27..dec39f271d 100644--- a/packages/excalidraw/tests/lasso.test.tsx+++ b/packages/excalidraw/tests/lasso.test.tsx@@ -32,6 +32,8 @@ import { getSelectedElements } from "../scene";import { getLassoSelectedElementIds } from "../lasso/utils";+import { API } from "./helpers/api";+import { act, render } from "./test-utils";const { h } = window;@@ -74,6 +76,7 @@ const updatePath = (startPoint: GlobalPoint, points: LocalPoint[]) => {elementsSegments,intersectedElements: new Set(),enclosedElements: new Set(),+ mode: h.state.boxSelectionMode,});act(() =>@@ -365,6 +368,7 @@ describe("Basic lasso selection tests", () => {act(() => {h.elements = elements;h.app.setActiveTool({ type: "lasso" });+ h.app.setState({ boxSelectionMode: "overlap" });});});@@ -1047,6 +1051,7 @@ describe("Special cases", () => {})) as ExcalidrawElement[];h.elements = elements;+ h.app.setState({ boxSelectionMode: "overlap" });});const startPoint = pointFrom<GlobalPoint>(-352, -64);@@ -1766,6 +1771,7 @@ describe("Special cases", () => {})) as ExcalidrawElement[];h.elements = elements;+ h.app.setState({ boxSelectionMode: "overlap" });});const startPoint = pointFrom<GlobalPoint>(117, 463);@@ -1801,4 +1807,413 @@ describe("Special cases", () => {expect(selectedElements.length).toBe(16);expect(h.app.state.selectedGroupIds["-9NzH7Fa5JaHu4ArEFpa_"]).toBe(true);});++ it("respects boxSelectionMode ('contain' vs 'overlap') during lasso selection", () => {+ const rect1 = API.createElement({+ type: "rectangle",+ id: "rect1",+ x: 100,+ y: 100,+ width: 50,+ height: 50,+ });++ const rect2 = API.createElement({+ type: "rectangle",+ id: "rect2",+ x: 300,+ y: 300,+ width: 50,+ height: 50,+ });++ h.elements = [rect1, rect2];++ // Lasso path enclosing rect1 fully, and intersecting rect2 partially+ const startPoint = pointFrom<GlobalPoint>(80, 80);+ const lassoPoints = [+ [0, 0],+ [100, 0],+ [240, 240],+ [240, 320],+ [0, 320],+ [0, 0],+ ] as LocalPoint[];++ // 1) Test 'overlap' mode -> should select both rect1 (enclosed) and rect2 (intersected)+ act(() => h.app.setState({ boxSelectionMode: "overlap" }));+ updatePath(startPoint, lassoPoints);+ let selected = getSelectedElements(h.elements, h.state);+ expect(selected.map((el) => el.id)).toContain("rect1");+ expect(selected.map((el) => el.id)).toContain("rect2");++ // 2) Test 'contain' mode -> should select ONLY rect1 (enclosed), not rect2 (only intersected)+ act(() => h.app.setState({ boxSelectionMode: "contain" }));+ updatePath(startPoint, lassoPoints);+ selected = getSelectedElements(h.elements, h.state);+ expect(selected.map((el) => el.id)).toContain("rect1");+ expect(selected.map((el) => el.id)).not.toContain("rect2");+ });+});++describe("Box selection mode (through the lasso tool)", () => {+ const drawLasso = (points: GlobalPoint[]) => {+ act(() => {+ h.app.lassoTrail.startPath(points[0][0], points[0][1]);+ points+ .slice(1)+ .forEach(([x, y]) => h.app.lassoTrail.addPointToPath(x, y));+ h.app.lassoTrail.endPath();+ });+ };++ const selectedIds = () => Object.keys(h.state.selectedElementIds).sort();++ describe("lasso enclosing one element and cutting through another", () => {+ // NOTE: the lasso wraps around `enclosed`, while its right edge (x = 320) cuts+ // through `crossed` (x = 300 to 350)+ const LASSO: GlobalPoint[] = (+ [+ [80, 80],+ [320, 80],+ [320, 220],+ [80, 220],+ [80, 80],+ ] as [number, number][]+ ).map(([x, y]) => pointFrom<GlobalPoint>(x, y));++ beforeEach(() => {+ act(() => {+ h.elements = [+ API.createElement({+ type: "rectangle",+ id: "enclosed",+ x: 100,+ y: 100,+ width: 50,+ height: 50,+ }),+ API.createElement({+ type: "rectangle",+ id: "crossed",+ x: 300,+ y: 100,+ width: 50,+ height: 50,+ }),+ ];+ });+ });++ it("selects only enclosed elements with the default mode ('contain')", () => {+ expect(h.state.boxSelectionMode).toBe("contain");++ drawLasso(LASSO);++ expect(selectedIds()).toEqual(["enclosed"]);+ });++ it("selects intersected elements as well in 'overlap' mode", () => {+ act(() => h.app.setState({ boxSelectionMode: "overlap" }));++ drawLasso(LASSO);++ expect(selectedIds()).toEqual(["crossed", "enclosed"]);+ });+ });++ it("does not treat an element as contained when the lasso cuts through it", () => {+ act(() => {+ h.elements = [+ API.createElement({+ type: "rectangle",+ id: "rect",+ x: 100,+ y: 100,+ width: 50,+ height: 50,+ }),+ ];+ });++ // NOTE: the lasso surrounding the rectangle, but with a spike poking through+ // its top edge into its interior: all four corners are inside the lasso+ // polygon, yet the rectangle is not fully contained+ const LASSO: GlobalPoint[] = (+ [+ [80, 80],+ [120, 80],+ [120, 125],+ [130, 125],+ [130, 80],+ [170, 80],+ [170, 170],+ [80, 170],+ [80, 80],+ ] as [number, number][]+ ).map(([x, y]) => pointFrom<GlobalPoint>(x, y));++ drawLasso(LASSO);++ expect(h.state.boxSelectionMode).toBe("contain");+ expect(selectedIds()).toEqual([]);++ // NOTE: the very same lasso still selects it in "overlap" mode+ act(() => h.app.setState({ boxSelectionMode: "overlap" }));++ drawLasso(LASSO);++ expect(selectedIds()).toEqual(["rect"]);+ });++ it("does not select a container whose label alone is enclosed", () => {+ act(() => {+ h.elements = [+ API.createElement({+ type: "rectangle",+ id: "container",+ x: 100,+ y: 100,+ width: 200,+ height: 100,+ boundElements: [{ type: "text", id: "label" }],+ }),+ API.createElement({+ type: "text",+ id: "label",+ x: 140,+ y: 130,+ width: 80,+ height: 25,+ containerId: "container",+ }),+ ];+ });++ // NOTE: the lasso wraps around the label only, staying well inside the+ // container it is bound to+ const LASSO: GlobalPoint[] = (+ [+ [130, 120],+ [230, 120],+ [230, 165],+ [130, 165],+ [130, 120],+ ] as [number, number][]+ ).map(([x, y]) => pointFrom<GlobalPoint>(x, y));++ expect(h.state.boxSelectionMode).toBe("contain");++ drawLasso(LASSO);++ expect(selectedIds()).toEqual([]);++ // NOTE: reaching the label is enough to select the container in "overlap"+ act(() => h.app.setState({ boxSelectionMode: "overlap" }));++ drawLasso(LASSO);++ expect(selectedIds()).toEqual(["container"]);+ });++ describe("lasso enclosing a single member of a group", () => {+ const LASSO: GlobalPoint[] = (+ [+ [80, 80],+ [200, 80],+ [200, 200],+ [80, 200],+ [80, 80],+ ] as [number, number][]+ ).map(([x, y]) => pointFrom<GlobalPoint>(x, y));++ beforeEach(() => {+ act(() => {+ h.elements = [+ API.createElement({+ type: "rectangle",+ id: "member1",+ x: 100,+ y: 100,+ width: 50,+ height: 50,+ groupIds: ["group"],+ }),+ API.createElement({+ type: "rectangle",+ id: "member2",+ x: 300,+ y: 100,+ width: 50,+ height: 50,+ groupIds: ["group"],+ }),+ ];+ });+ });++ it("selects nothing in 'contain' mode, as the group isn't complete", () => {+ expect(h.state.boxSelectionMode).toBe("contain");++ drawLasso(LASSO);++ expect(selectedIds()).toEqual([]);+ });++ it("selects the whole group in 'overlap' mode", () => {+ act(() => h.app.setState({ boxSelectionMode: "overlap" }));++ drawLasso(LASSO);++ expect(selectedIds()).toEqual(["member1", "member2"]);+ });++ it("selects the whole group once all its members are enclosed", () => {+ expect(h.state.boxSelectionMode).toBe("contain");++ drawLasso(+ (+ [+ [80, 80],+ [400, 80],+ [400, 200],+ [80, 200],+ [80, 80],+ ] as [number, number][]+ ).map(([x, y]) => pointFrom<GlobalPoint>(x, y)),+ );++ expect(selectedIds()).toEqual(["member1", "member2"]);+ });+ });++ it("contains an element whose frame-clipped part is enclosed", () => {+ act(() => {+ h.elements = [+ API.createElement({+ type: "frame",+ id: "frame",+ x: 0,+ y: 0,+ width: 200,+ height: 200,+ }),+ // NOTE: overflows the frame to the right, so only the x = 150 to 200+ // part of it is visible+ API.createElement({+ type: "rectangle",+ id: "overflowing",+ x: 150,+ y: 50,+ width: 100,+ height: 50,+ frameId: "frame",+ }),+ ];+ });++ // NOTE: wraps the visible part of the rectangle, while its right edge cuts+ // through the clipped-away part of it+ const LASSO: GlobalPoint[] = (+ [+ [140, 40],+ [210, 40],+ [210, 110],+ [140, 110],+ [140, 40],+ ] as [number, number][]+ ).map(([x, y]) => pointFrom<GlobalPoint>(x, y));++ expect(h.state.boxSelectionMode).toBe("contain");++ drawLasso(LASSO);++ expect(selectedIds()).toEqual(["overflowing"]);+ });++ it("contains elements without an outline, such as a freedraw dot", () => {+ act(() => {+ h.elements = [+ API.createElement({+ type: "freedraw",+ id: "dot",+ x: 100,+ y: 100,+ width: 0,+ height: 0,+ points: [pointFrom<LocalPoint>(0, 0)],+ }),+ ];+ });++ const LASSO: GlobalPoint[] = (+ [+ [80, 80],+ [120, 80],+ [120, 120],+ [80, 120],+ [80, 80],+ ] as [number, number][]+ ).map(([x, y]) => pointFrom<GlobalPoint>(x, y));++ expect(h.state.boxSelectionMode).toBe("contain");++ drawLasso(LASSO);++ expect(selectedIds()).toEqual(["dot"]);+ });++ it("contains elements whose outline lies exactly on the lasso path", () => {+ act(() => {+ h.elements = [+ API.createElement({+ type: "rectangle",+ id: "rect",+ x: 100,+ y: 100,+ width: 50,+ height: 50,+ }),+ ];+ });++ // NOTE: a lasso running exactly along one edge of the rectangle, from each+ // of the four sides in turn. Which side it is may not decide the outcome.+ const LASSOS = {+ right: [+ [80, 80],+ [150, 80],+ [150, 200],+ [80, 200],+ ],+ left: [+ [100, 80],+ [200, 80],+ [200, 200],+ [100, 200],+ ],+ top: [+ [80, 100],+ [200, 100],+ [200, 200],+ [80, 200],+ ],+ bottom: [+ [80, 50],+ [200, 50],+ [200, 150],+ [80, 150],+ ],+ } as Record<string, [number, number][]>;++ expect(h.state.boxSelectionMode).toBe("contain");++ for (const [side, lasso] of Object.entries(LASSOS)) {+ drawLasso(+ [...lasso, lasso[0]].map(([x, y]) => pointFrom<GlobalPoint>(x, y)),+ );++ expect([side, selectedIds()]).toEqual([side, ["rect"]]);+ }+ });});diff --git a/packages/excalidraw/tests/selection.test.tsx b/packages/excalidraw/tests/selection.test.tsxindex 6447c10909..e3b6b34f93 100644--- a/packages/excalidraw/tests/selection.test.tsx+++ b/packages/excalidraw/tests/selection.test.tsx@@ -182,14 +182,17 @@ describe("lasso reselection", () => {h.app.setActiveTool({ type: "lasso" });});+ // NOTE: the lasso starts inside the common bounds of the selection, and+ // encloses rectA only (the default box selection mode being "contain")Keyboard.withModifierKeys({ ctrl: true, alt: true }, () => {mouse.downAt(110, 50);- mouse.moveTo(50, -20);+ mouse.moveTo(110, -50);expect(h.app.lassoTrail.hasCurrentTrail).toBe(true);- mouse.moveTo(-20, 50);- mouse.moveTo(50, 120);+ mouse.moveTo(-50, -50);+ mouse.moveTo(-50, 150);+ mouse.moveTo(110, 150);mouse.moveTo(110, 50);mouse.up();});