Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

fix(editor): reach text containers below transparent ones (#12210)

David Luzar1919728724a1
diff --git a/packages/element/src/collision.ts b/packages/element/src/collision.ts
index 83a8eeaef2..cb1f13f675 100644
--- a/packages/element/src/collision.ts
+++ b/packages/element/src/collision.ts
@@ -346,10 +346,11 @@ type BindingCandidate = {
};
/**
- * Whether the element hides what is behind it from binding. Images count as
- * opaque, and frames once they support a background.
+ * Whether the element hides what is behind it from binding — an arrow's or a
+ * text label's. Images count as opaque, and frames once they support a
+ * background.
*/
-const isOpaqueForBinding = (element: ExcalidrawElement) =>
+export const isOpaqueForBinding = (element: ExcalidrawElement) =>
isImageElement(element) ||
(hasBackground(element.type) && !isTransparent(element.backgroundColor));
diff --git a/packages/excalidraw/components/App.text.ts b/packages/excalidraw/components/App.text.ts
index ee18ea2384..f54666246e 100644
--- a/packages/excalidraw/components/App.text.ts
+++ b/packages/excalidraw/components/App.text.ts
@@ -31,6 +31,7 @@ import {
isArrowElement,
isFrameLikeElement,
isNonDeletedElement,
+ isOpaqueForBinding,
isStickyNoteElement,
isTextBindableContainer,
isTextElement,
@@ -502,44 +503,77 @@ export class AppText {
/**
* The text container at a position — an arrow hit on its path, any other
* container hit anywhere in its bounds (frames are skipped so a container
- * inside one can be hit). Purely positional: the selection plays no part.
+ * inside one can be hit, and a frame's children are only hit inside it,
+ * where they are drawn). Purely positional: the selection plays no part.
+ *
+ * Only what hides the rest ends the search — a filled element or an image
+ * (as for arrow binding), or an arrow — so containers below a transparent
+ * one stay in reach whatever their z-order. Of the containers found, the
+ * innermost one centered on the position wins, since that is where its
+ * label would go (an arrow counting as innermost: it is pointed at, not just
+ * enclosing); failing that, the top-most.
*/
getTextBindableContainerAtPosition(x: number, y: number) {
const elements = this.app.scene.getNonDeletedElements();
- let hitElement = null;
+ const elementsMap = this.app.scene.getNonDeletedElementsMap();
+ // top-most first, each with the area it is ranked by
+ const hits: {
+ container: NonDeleted<ExcalidrawTextContainer>;
+ area: number;
+ }[] = [];
// We need to do hit testing from front (end of the array) to back (beginning of the array)
for (let index = elements.length - 1; index >= 0; --index) {
- if (elements[index].isDeleted) {
+ const element = elements[index];
+ // to allow binding to containers within frames,
+ // ignore frames in hit testing
+ if (
+ isFrameLikeElement(element) ||
+ this.app.isClippedByFrameAt(x, y, element)
+ ) {
continue;
}
- const [x1, y1, x2, y2] = getElementAbsoluteCoords(
- elements[index],
- this.app.scene.getNonDeletedElementsMap(),
- );
+ const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
+ const isArrow = isArrowElement(element);
if (
- isArrowElement(elements[index]) &&
- hitElementItself({
- point: pointFrom(x, y),
- element: elements[index],
- elementsMap: this.app.scene.getNonDeletedElementsMap(),
- threshold: this.app.getElementHitThreshold(elements[index]),
- })
+ isArrow
+ ? // an arrow has no inside to hit
+ !hitElementItself({
+ point: pointFrom(x, y),
+ element,
+ elementsMap,
+ threshold: this.app.getElementHitThreshold(element),
+ })
+ : !(x1 < x && x < x2 && y1 < y && y < y2)
) {
- hitElement = elements[index];
- break;
- } else if (x1 < x && x < x2 && y1 < y && y < y2) {
- // to allow binding to containers within frames,
- // ignore frames in hit testing
- if (isFrameLikeElement(elements[index])) {
- continue;
- }
-
- hitElement = elements[index];
+ continue;
+ }
+ if (isTextBindableContainer(element, false)) {
+ hits.push({
+ container: element,
+ area: isArrow ? 0 : (x2 - x1) * (y2 - y1),
+ });
+ }
+ if (isArrow || isOpaqueForBinding(element)) {
break;
}
}
- return isTextBindableContainer(hitElement, false) ? hitElement : null;
+ const innermostCentered = hits
+ .filter(({ container }) =>
+ this.getTextWysiwygSnappedToCenterPosition(
+ x,
+ y,
+ this.app.state,
+ container,
+ ),
+ )
+ .reduce<typeof hits[number] | null>(
+ (innermost, hit) =>
+ !innermost || hit.area < innermost.area ? hit : innermost,
+ null,
+ );
+
+ return (innermostCentered ?? hits[0])?.container ?? null;
}
/**
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index aa846b0844..a26fe3f083 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -6023,8 +6023,6 @@ class App extends React.Component<AppProps, AppState> {
): NonDeleted<ExcalidrawElement>[] {
const iframeLikes: Ordered<NonDeleted<ExcalidrawIframeLikeElement>>[] = [];
- const elementsMap = this.scene.getNonDeletedElementsMap();
-
const elements = (
opts?.includeBoundTextElement && opts?.includeLockedElements
? this.scene.getNonDeletedElements()
@@ -6038,25 +6036,7 @@ class App extends React.Component<AppProps, AppState> {
)
)
.filter((el) => this.hitElement(x, y, el))
- .filter((element) => {
- // hitting a frame's element from outside the frame is not considered a hit
- const containingFrame = getContainingFrame(element, elementsMap);
- if (containingFrame && !isNonDeletedElement(containingFrame)) {
- console.error("[NONDELETED][INVARIANT] Containing frame is deleted");
- }
- return containingFrame &&
- this.state.frameRendering.enabled &&
- this.state.frameRendering.clip &&
- // iframe-like elements are rendered as DOM overlays and are not
- // visually clipped by their containing frames
- !isIframeLikeElement(element)
- ? isCursorInFrame(
- { x, y },
- containingFrame as NonDeleted<ExcalidrawFrameLikeElement>,
- elementsMap,
- )
- : true;
- })
+ .filter((element) => !this.isClippedByFrameAt(x, y, element))
.filter((el) => {
// The parameter elements comes ordered from lower z-index to higher.
// We want to preserve that order on the returned array.
@@ -6073,6 +6053,31 @@ class App extends React.Component<AppProps, AppState> {
return elements;
}
+ /**
+ * Whether the element's frame clips it away at the position — hitting a
+ * frame's element from outside the frame is not considered a hit.
+ */
+ isClippedByFrameAt(x: number, y: number, element: ExcalidrawElement) {
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+ const containingFrame = getContainingFrame(element, elementsMap);
+ if (containingFrame && !isNonDeletedElement(containingFrame)) {
+ console.error("[NONDELETED][INVARIANT] Containing frame is deleted");
+ }
+ return (
+ !!containingFrame &&
+ this.state.frameRendering.enabled &&
+ this.state.frameRendering.clip &&
+ // iframe-like elements are rendered as DOM overlays and are not
+ // visually clipped by their containing frames
+ !isIframeLikeElement(element) &&
+ !isCursorInFrame(
+ { x, y },
+ containingFrame as NonDeleted<ExcalidrawFrameLikeElement>,
+ elementsMap,
+ )
+ );
+ }
+
getElementHitThreshold(element: ExcalidrawElement) {
return Math.max(
element.strokeWidth / 2 + 0.1,
diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx
index 10c527f54c..c9a73bad79 100644
--- a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx
+++ b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx
@@ -5,6 +5,7 @@ import { pointFrom } from "@excalidraw/math";
import {
getLineHeightInPx,
getOriginalContainerHeightFromCache,
+ isTextElement,
newElementWith,
} from "@excalidraw/element";
@@ -1471,6 +1472,169 @@ describe("textWysiwyg", () => {
expect(text.frameId).toBe(frame.id);
});
+ it.each(["text tool click", "double-click"] as const)(
+ "should bind text to a shape nested in a transparent one above it on a %s at its center",
+ async (via) => {
+ const inner = API.createElement({
+ type: "rectangle",
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 100,
+ });
+ // on top, with the same center
+ const outer = API.createElement({
+ type: "rectangle",
+ x: 50,
+ y: 50,
+ width: 300,
+ height: 200,
+ });
+ API.setElements([inner, outer]);
+
+ if (via === "text tool click") {
+ UI.clickTool("text");
+ mouse.moveTo(200, 150);
+ expect(h.state.textToolHover).toEqual({
+ type: "container",
+ elementId: inner.id,
+ });
+ mouse.clickAt(200, 150);
+ } else {
+ mouse.doubleClickAt(200, 150);
+ }
+ const editor = await getTextEditor();
+ updateTextEditor(editor, "Label");
+ Keyboard.exitTextEditor(editor);
+
+ const text = h.elements.find(isTextElement)!;
+ expect(text.containerId).toBe(inner.id);
+ expect(outer.boundElements).toBe(null);
+ },
+ );
+
+ it("should not reach a shape below a filled one at its center", () => {
+ const inner = API.createElement({
+ type: "rectangle",
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 100,
+ });
+ const outer = API.createElement({
+ type: "rectangle",
+ x: 50,
+ y: 50,
+ width: 300,
+ height: 200,
+ backgroundColor: "#ffc9c9",
+ fillStyle: "solid",
+ });
+ API.setElements([inner, outer]);
+
+ UI.clickTool("text");
+ mouse.moveTo(200, 150);
+ expect(h.state.textToolHover).toEqual({
+ type: "container",
+ elementId: outer.id,
+ });
+ });
+
+ it("should not let an arrow below a shape take its label off the arrow's path", () => {
+ // midpoint (200, 200), off the path at the shape's center
+ const arrow = API.createElement({
+ type: "arrow",
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 200,
+ points: [pointFrom(0, 0), pointFrom(200, 200)],
+ });
+ const shape = API.createElement({
+ type: "rectangle",
+ x: 65,
+ y: 35,
+ width: 300,
+ height: 300,
+ });
+ API.setElements([arrow, shape]);
+
+ UI.clickTool("text");
+ mouse.moveTo(215, 185);
+ expect(h.state.textToolHover).toEqual({
+ type: "container",
+ elementId: shape.id,
+ });
+ });
+
+ it("should not bind to a frame child's clipped-off part", () => {
+ const frame = API.createElement({
+ type: "frame",
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 200,
+ });
+ // centered outside the frame, where it is clipped
+ const child = API.createElement({
+ type: "rectangle",
+ x: 160,
+ y: 60,
+ width: 100,
+ height: 80,
+ frameId: frame.id,
+ });
+ const shape = API.createElement({
+ type: "rectangle",
+ x: 110,
+ y: 0,
+ width: 200,
+ height: 200,
+ });
+ API.setElements([child, frame, shape]);
+
+ UI.clickTool("text");
+ mouse.moveTo(210, 100);
+ expect(h.state.textToolHover).toEqual({
+ type: "container",
+ elementId: shape.id,
+ });
+ });
+
+ it("should label an arrow below a transparent shape when clicking its midpoint", async () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ x: 100,
+ y: 200,
+ width: 150,
+ height: 0,
+ points: [pointFrom(0, 0), pointFrom(150, 0)],
+ });
+ const shape = API.createElement({
+ type: "rectangle",
+ x: 50,
+ y: 50,
+ width: 300,
+ height: 200,
+ });
+ API.setElements([arrow, shape]);
+
+ UI.clickTool("text");
+ mouse.moveTo(175, 200);
+ expect(h.state.textToolHover).toEqual({
+ type: "arrow",
+ elementId: arrow.id,
+ anchor: "label",
+ });
+ mouse.clickAt(175, 200);
+ const editor = await getTextEditor();
+ updateTextEditor(editor, "Label");
+ Keyboard.exitTextEditor(editor);
+
+ const text = h.elements.find(isTextElement)!;
+ expect(text.containerId).toBe(arrow.id);
+ });
+
it("should set the text element angle to same as container angle when binding to rotated container", async () => {
const rectangle = API.createElement({
type: "rectangle",