Virtual whiteboard for sketching hand-drawn like diagrams
feat(editor): `w` to wrap/unwrap selection (#12264)
David Luzar704db6803c43
diff --git a/packages/element/tests/linearElementEditor.test.tsx b/packages/element/tests/linearElementEditor.test.tsxindex 9f2c8fc576..b0a23cf55b 100644--- a/packages/element/tests/linearElementEditor.test.tsx+++ b/packages/element/tests/linearElementEditor.test.tsx@@ -1669,6 +1669,8 @@ describe("Test Linear Elements", () => {contextMenu = document.querySelector(".context-menu");fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);expect(container.boundElements).toEqual([]);+ // the arrow is selected along with the freed label+ expect(h.state.selectedLinearElement).toBe(null);expect(text).toEqual(expect.objectContaining({containerId: null,diff --git a/packages/excalidraw/actions/actionBoundText.tsx b/packages/excalidraw/actions/actionBoundText.tsxindex fcdb221b5f..85f4757738 100644--- a/packages/excalidraw/actions/actionBoundText.tsx+++ b/packages/excalidraw/actions/actionBoundText.tsx@@ -4,8 +4,6 @@ import {TEXT_ALIGN,VERTICAL_ALIGN,arrayToMap,- getFontString,- getStrokeWidthByKey,isTransparent,} from "@excalidraw/common";import {@@ -34,7 +32,7 @@ import {isUsingAdaptiveRadius,} from "@excalidraw/element";-import { measureText } from "@excalidraw/element";+import { getNonDeletedElements } from "@excalidraw/element";import { syncMovedIndices } from "@excalidraw/element";@@ -42,20 +40,58 @@ import { newElement } from "@excalidraw/element";import { CaptureUpdateAction } from "@excalidraw/element";+import type { Scene } from "@excalidraw/element";+import type {ExcalidrawElement,ExcalidrawLinearElement,ExcalidrawTextContainer,ExcalidrawTextElement,+ ExcalidrawTextElementWithContainer,+ NonDeleted,+ NonDeletedExcalidrawElement,} from "@excalidraw/element/types";import type { Mutable } from "@excalidraw/common/utility-types";import type { Radians } from "@excalidraw/math";+import { getDefaultAppState } from "../appState";+import { getSelectionStateForElements } from "../components/App.selection";+import { register } from "./register";-import type { AppState } from "../types";+import type { ActionResult } from "./types";+import type { AppClassProperties, AppState } from "../types";++/**+ * Frees the container's text as it rendered: wrapped the same, at a fixed+ * width.+ */+export const unbindTextFromContainer = (+ container: ExcalidrawElement,+ boundTextElement: ExcalidrawTextElementWithContainer,+ scene: Scene,+) => {+ const { x, y } = computeBoundTextPosition(+ container,+ boundTextElement,+ scene.getNonDeletedElementsMap(),+ );+ scene.mutateElement(boundTextElement as ExcalidrawTextElement, {+ containerId: null,+ autoResize: false,+ baseFontSize: null,+ x,+ y,+ labelPosition: null,+ });+ scene.mutateElement(container, {+ boundElements: container.boundElements?.filter(+ (ele) => ele.id !== boundTextElement.id,+ ),+ });+};export const actionUnbindText = register({name: "unbindText",@@ -69,38 +105,16 @@ export const actionUnbindText = register({perform: (elements, appState, _, app) => {const selectedElements = app.scene.getSelectedElements(appState);const elementsMap = app.scene.getNonDeletedElementsMap();+ const freedTextElements: NonDeletedExcalidrawElement[] = [];selectedElements.forEach((element) => {const boundTextElement = getBoundTextElement(element, elementsMap);if (boundTextElement) {- const { width, height } = measureText(- boundTextElement.originalText,- getFontString(boundTextElement),- boundTextElement.lineHeight,- );+ freedTextElements.push(boundTextElement);const originalContainerHeight = getOriginalContainerHeightFromCache(element.id,);resetOriginalContainerCache(element.id);- const { x, y } = computeBoundTextPosition(- element,- boundTextElement,- elementsMap,- );- app.scene.mutateElement(boundTextElement as ExcalidrawTextElement, {- containerId: null,- width,- height,- text: boundTextElement.originalText,- baseFontSize: null,- x,- y,- labelPosition: null,- });- app.scene.mutateElement(element, {- boundElements: element.boundElements?.filter(- (ele) => ele.id !== boundTextElement.id,- ),- });+ unbindTextFromContainer(element, boundTextElement, app.scene);if (isStickyNoteElement(element)) {// an empty note sits at its base height; bound arrows followupdateStickyNoteLayout(element, app.scene);@@ -115,7 +129,15 @@ export const actionUnbindText = register({});return {elements,- appState,+ appState: {+ ...appState,+ // the freed texts stay selected along with their former containers+ ...getSelectionStateForElements(+ [...selectedElements, ...freedTextElements],+ getNonDeletedElements(elements),+ appState,+ ),+ },captureUpdate: CaptureUpdateAction.IMMEDIATELY,};},@@ -156,7 +178,7 @@ export const actionBindText = register({const selectedElements = app.scene.getSelectedElements(appState);let textElement: ExcalidrawTextElement;- let container: ExcalidrawTextContainer;+ let container: NonDeleted<ExcalidrawTextContainer>;if (isTextElement(selectedElements[0]) &&@@ -166,55 +188,85 @@ export const actionBindText = register({container = selectedElements[1];} else {textElement = selectedElements[1] as ExcalidrawTextElement;- container = selectedElements[0] as ExcalidrawTextContainer;+ container = selectedElements[0] as NonDeleted<ExcalidrawTextContainer>;}- // a note and its label share one ink: the text the user styled wins,- // unless it is transparent (a note's label never is)- const stickyInk = isStickyNoteElement(container)- ? isTransparent(textElement.strokeColor)- ? container.strokeColor- : textElement.strokeColor- : null;- app.scene.mutateElement(textElement, {- containerId: container.id,- verticalAlign: VERTICAL_ALIGN.MIDDLE,- textAlign: TEXT_ALIGN.CENTER,- autoResize: true,- angle: (isArrowElement(container) ? 0 : container?.angle ?? 0) as Radians,- labelPosition: isArrowElement(container)- ? DEFAULT_BOUND_TEXT_LABEL_POSITION- : null,- ...(stickyInk- ? {- baseFontSize: normalizeStickyNoteFontSize(- textElement.baseFontSize ?? textElement.fontSize,- ),- strokeColor: stickyInk,- }- : null),- });- app.scene.mutateElement(container, {- boundElements: (container.boundElements || []).concat({- type: "text",- id: textElement.id,- }),- // the footer paints with the note's ink- ...(stickyInk ? { strokeColor: stickyInk } : null),- });- const originalContainerHeight = container.height;- redrawTextBoundingBox(textElement, container, app.scene);- // overwritting the cache with original container height so- // it can be restored when unbind- updateOriginalContainerCache(container.id, originalContainerHeight);- return {- elements: pushTextAboveContainer(elements, container, textElement),- appState: { ...appState, selectedElementIds: { [container.id]: true } },- captureUpdate: CaptureUpdateAction.IMMEDIATELY,- };+ return bindTextToContainer(elements, appState, textElement, container, app);},});+/**+ * A note and its label share one ink: the text the user styled wins, unless it+ * is transparent (a note's label never is).+ */+export const getStickyNoteInk = (+ textElement: ExcalidrawTextElement,+ container: ExcalidrawElement,+) =>+ isStickyNoteElement(container)+ ? isTransparent(textElement.strokeColor)+ ? container.strokeColor+ : textElement.strokeColor+ : null;++/** binds the text to the (label-less) container, selecting the container */+export const bindTextToContainer = (+ elements: readonly ExcalidrawElement[],+ appState: Readonly<AppState>,+ textElement: ExcalidrawTextElement,+ container: NonDeleted<ExcalidrawTextContainer>,+ app: AppClassProperties,+): ActionResult => {+ const stickyInk = getStickyNoteInk(textElement, container);+ app.scene.mutateElement(textElement, {+ containerId: container.id,+ verticalAlign: VERTICAL_ALIGN.MIDDLE,+ textAlign: TEXT_ALIGN.CENTER,+ autoResize: true,+ angle: (isArrowElement(container) ? 0 : container?.angle ?? 0) as Radians,+ labelPosition: isArrowElement(container)+ ? DEFAULT_BOUND_TEXT_LABEL_POSITION+ : null,+ ...(stickyInk+ ? {+ baseFontSize: normalizeStickyNoteFontSize(+ textElement.baseFontSize ?? textElement.fontSize,+ ),+ strokeColor: stickyInk,+ }+ : null),+ });+ app.scene.mutateElement(container, {+ boundElements: (container.boundElements || []).concat({+ type: "text",+ id: textElement.id,+ }),+ // the footer paints with the note's ink+ ...(stickyInk ? { strokeColor: stickyInk } : null),+ });+ const originalContainerHeight = container.height;+ redrawTextBoundingBox(textElement, container, app.scene);+ // overwritting the cache with original container height so+ // it can be restored when unbind+ updateOriginalContainerCache(container.id, originalContainerHeight);++ const nextElements = pushTextAboveContainer(elements, container, textElement);++ return {+ elements: nextElements,+ appState: {+ ...appState,+ // with the line editor of an arrow+ ...getSelectionStateForElements(+ [container],+ getNonDeletedElements(nextElements),+ appState,+ ),+ },+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ };+};+const pushTextAboveContainer = (elements: readonly ExcalidrawElement[],container: ExcalidrawElement,@@ -235,7 +287,7 @@ const pushTextAboveContainer = (return updatedElements;};-const pushContainerBelowText = (+export const pushContainerBelowText = (elements: readonly ExcalidrawElement[],container: ExcalidrawElement,textElement: ExcalidrawTextElement,@@ -266,112 +318,120 @@ export const actionWrapTextInContainer = register({);return selectedElements.length > 0 && someTextElements;},- perform: (elements, appState, _, app) => {- const selectedElements = app.scene.getSelectedElements(appState);- let updatedElements: readonly ExcalidrawElement[] = elements.slice();- const containerIds: Mutable<AppState["selectedElementIds"]> = {};-- for (const textElement of selectedElements) {- if (isTextElement(textElement) && !isBoundToContainer(textElement)) {- const container = newElement({- type: "rectangle",- backgroundColor: appState.currentItemBackgroundColor,- boundElements: [- ...(textElement.boundElements || []),- { id: textElement.id, type: "text" },- ],- angle: textElement.angle,- fillStyle: appState.currentItemFillStyle,- strokeColor: appState.currentItemStrokeColor,- roughness: appState.currentItemRoughness,- strokeWidth: getStrokeWidthByKey(- "rectangle",- appState.currentItemStrokeWidthKey,- ),- strokeStyle: appState.currentItemStrokeStyle,- roundness:- appState.currentItemRoundness === "round"- ? {- type: isUsingAdaptiveRadius("rectangle")- ? ROUNDNESS.ADAPTIVE_RADIUS- : ROUNDNESS.PROPORTIONAL_RADIUS,- }- : null,- opacity: 100,- locked: false,- x: textElement.x - BOUND_TEXT_PADDING,- y: textElement.y - BOUND_TEXT_PADDING,- width: computeContainerDimensionForBoundText(- textElement.width,- "rectangle",- ),- height: computeContainerDimensionForBoundText(- textElement.height,- "rectangle",- ),- groupIds: textElement.groupIds,- frameId: textElement.frameId,- });-- // update bindings- if (textElement.boundElements?.length) {- const linearElementIds = textElement.boundElements- .filter((ele) => ele.type === "arrow")- .map((el) => el.id);- const linearElements = updatedElements.filter((ele) =>- linearElementIds.includes(ele.id),- ) as ExcalidrawLinearElement[];- linearElements.forEach((ele) => {- let startBinding = ele.startBinding;- let endBinding = ele.endBinding;-- if (startBinding?.elementId === textElement.id) {- startBinding = {- ...startBinding,- elementId: container.id,- };- }+ perform: (elements, appState, _, app) =>+ wrapTextsInContainers(+ elements,+ appState,+ app.scene+ .getSelectedElements(appState)+ .filter(+ (element): element is NonDeleted<ExcalidrawTextElement> =>+ isTextElement(element) && !isBoundToContainer(element),+ ),+ app,+ ),+});- if (endBinding?.elementId === textElement.id) {- endBinding = { ...endBinding, elementId: container.id };+/** wraps each (unbound) text in a new container, selecting the containers */+export const wrapTextsInContainers = (+ elements: readonly ExcalidrawElement[],+ appState: Readonly<AppState>,+ textElements: readonly ExcalidrawTextElement[],+ app: AppClassProperties,+): ActionResult => {+ let updatedElements: readonly ExcalidrawElement[] = elements.slice();+ const containerIds: Mutable<AppState["selectedElementIds"]> = {};++ for (const textElement of textElements) {+ // a default rectangle (not the current item's style), drawn in the+ // text's color+ const container = newElement({+ type: "rectangle",+ boundElements: [+ ...(textElement.boundElements || []),+ { id: textElement.id, type: "text" },+ ],+ angle: textElement.angle,+ strokeColor: textElement.strokeColor,+ roundness:+ getDefaultAppState().currentItemRoundness === "round"+ ? {+ type: isUsingAdaptiveRadius("rectangle")+ ? ROUNDNESS.ADAPTIVE_RADIUS+ : ROUNDNESS.PROPORTIONAL_RADIUS,}+ : null,+ x: textElement.x - BOUND_TEXT_PADDING,+ y: textElement.y - BOUND_TEXT_PADDING,+ width: computeContainerDimensionForBoundText(+ textElement.width,+ "rectangle",+ ),+ height: computeContainerDimensionForBoundText(+ textElement.height,+ "rectangle",+ ),+ groupIds: textElement.groupIds,+ frameId: textElement.frameId,+ });- if (startBinding || endBinding) {- app.scene.mutateElement(ele, {- startBinding,- endBinding,- });- }- });+ // update bindings+ if (textElement.boundElements?.length) {+ const linearElementIds = textElement.boundElements+ .filter((ele) => ele.type === "arrow")+ .map((el) => el.id);+ const linearElements = updatedElements.filter((ele) =>+ linearElementIds.includes(ele.id),+ ) as ExcalidrawLinearElement[];+ linearElements.forEach((ele) => {+ let startBinding = ele.startBinding;+ let endBinding = ele.endBinding;++ if (startBinding?.elementId === textElement.id) {+ startBinding = {+ ...startBinding,+ elementId: container.id,+ };}- app.scene.mutateElement(textElement, {- containerId: container.id,- verticalAlign: VERTICAL_ALIGN.MIDDLE,- boundElements: null,- textAlign: TEXT_ALIGN.CENTER,- autoResize: true,- });+ if (endBinding?.elementId === textElement.id) {+ endBinding = { ...endBinding, elementId: container.id };+ }- redrawTextBoundingBox(textElement, container, app.scene);+ if (startBinding || endBinding) {+ app.scene.mutateElement(ele, {+ startBinding,+ endBinding,+ });+ }+ });+ }- updatedElements = pushContainerBelowText(- [...updatedElements, container],- container,- textElement,- );+ app.scene.mutateElement(textElement, {+ containerId: container.id,+ verticalAlign: VERTICAL_ALIGN.MIDDLE,+ boundElements: null,+ textAlign: TEXT_ALIGN.CENTER,+ autoResize: true,+ });- containerIds[container.id] = true;- }- }+ redrawTextBoundingBox(textElement, container, app.scene);- return {- elements: updatedElements,- appState: {- ...appState,- selectedElementIds: containerIds,- },- captureUpdate: CaptureUpdateAction.IMMEDIATELY,- };- },-});+ updatedElements = pushContainerBelowText(+ [...updatedElements, container],+ container,+ textElement,+ );++ containerIds[container.id] = true;+ }++ return {+ elements: updatedElements,+ appState: {+ ...appState,+ selectedElementIds: containerIds,+ },+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ };+};diff --git a/packages/excalidraw/actions/actionFrame.ts b/packages/excalidraw/actions/actionFrame.tsindex 6ffcc5f5e8..629b5b8369 100644--- a/packages/excalidraw/actions/actionFrame.ts+++ b/packages/excalidraw/actions/actionFrame.ts@@ -1,26 +1,42 @@import { getNonDeletedElements } from "@excalidraw/element";import { mutateElement } from "@excalidraw/element";import { newFrameElement } from "@excalidraw/element";-import { isFrameLikeElement } from "@excalidraw/element";+import {+ isBoundToContainer,+ isFrameLikeElement,+ isImageElement,+} from "@excalidraw/element";import {addElementsToFrame,removeAllElementsFromFrame,} from "@excalidraw/element";import { getFrameChildren } from "@excalidraw/element";+import { fixBindingsAfterDeletion } from "@excalidraw/element";import { getElementsInGroup } from "@excalidraw/element";-import { getCommonBounds } from "@excalidraw/element";+import {+ boundsContainBounds,+ getCommonBounds,+ getElementBounds,+} from "@excalidraw/element";import { CaptureUpdateAction } from "@excalidraw/element";-import type { ExcalidrawElement } from "@excalidraw/element/types";+import type {+ ElementsMap,+ ExcalidrawElement,+ ExcalidrawFrameLikeElement,+ NonDeletedExcalidrawElement,+} from "@excalidraw/element/types";+import { getSelectionStateForElements } from "../components/App.selection";import { getSelectedElements } from "../scene";import { register } from "./register";-import type { AppClassProperties, UIAppState } from "../types";+import type { ActionResult } from "./types";+import type { AppClassProperties, AppState, UIAppState } from "../types";const isSingleFrameSelected = (appState: UIAppState,@@ -122,9 +138,147 @@ export const actionupdateFrameRendering = register({checked: (appState) => appState.frameRendering.enabled,});+const FRAME_PADDING = 16;++/**+ * The frame that wrapping the selection removes instead: the one frame the+ * selection holds (along with any of its children), or, with no frame+ * selected, the frame whose children are all selected.+ */+export const getFrameToUnwrap = (+ selectedElements: readonly ExcalidrawElement[],+ elementsMap: ElementsMap,+): ExcalidrawFrameLikeElement | null => {+ const elements = selectedElements.filter(+ (element) => !isBoundToContainer(element),+ );+ const frames = elements.filter((element) => isFrameLikeElement(element));+ if (frames.length > 1) {+ return null;+ }++ const frameId = frames[0]?.id ?? elements[0]?.frameId;+ const frame = frameId ? elementsMap.get(frameId) : null;+ if (!frame || frame.isDeleted || !isFrameLikeElement(frame)) {+ return null;+ }++ const selectedChildren = elements.filter(+ (element) => element.frameId === frame.id,+ );+ if (selectedChildren.length + frames.length !== elements.length) {+ return null;+ }+ if (frames.length) {+ return frame;+ }++ // with no frame selected, all of its children have to be+ const children = getFrameChildren(elementsMap, frame.id).filter(+ (element) => !element.isDeleted && !isBoundToContainer(element),+ );+ return children.length === selectedChildren.length ? frame : null;+};++/** removes the frame, keeping its children selected in its place */+export const unwrapFrame = (+ elements: readonly ExcalidrawElement[],+ appState: AppState,+ frame: ExcalidrawFrameLikeElement,+ app: AppClassProperties,+): ActionResult => {+ const children = getNonDeletedElements(getFrameChildren(elements, frame.id));++ removeAllElementsFromFrame(elements, frame);+ app.scene.mutateElement(frame, { isDeleted: true });+ fixBindingsAfterDeletion(elements, [frame]);++ return {+ elements,+ appState: {+ ...appState,+ ...getSelectionStateForElements(+ children,+ getNonDeletedElements(elements),+ { ...appState, editingGroupId: null },+ ),+ },+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ };+};++/** wraps the selection in a new frame — edge to edge when it's an image */+export const wrapInFrame = (+ elements: readonly ExcalidrawElement[],+ appState: AppState,+ selectedElements: NonDeletedExcalidrawElement[],+ app: AppClassProperties,+): ActionResult => {+ const elementsMap = app.scene.getNonDeletedElementsMap();++ const bounds = getCommonBounds(selectedElements, elementsMap);+ // an image framed along with what's drawn on it keeps no margin+ const padding = selectedElements.some(+ (element) =>+ isImageElement(element) &&+ boundsContainBounds(getElementBounds(element, elementsMap), bounds),+ )+ ? 0+ : FRAME_PADDING;+ const [x1, y1, x2, y2] = bounds;+ const frame = newFrameElement({+ x: x1 - padding,+ y: y1 - padding,+ width: x2 - x1 + padding * 2,+ height: y2 - y1 + padding * 2,+ });++ // for a selected partial group, we want to remove it from the remainder of the group+ if (appState.editingGroupId) {+ const elementsInGroup = getElementsInGroup(+ selectedElements,+ appState.editingGroupId,+ );++ for (const elementInGroup of elementsInGroup) {+ const index = elementInGroup.groupIds.indexOf(appState.editingGroupId);++ mutateElement(elementInGroup, elementsMap, {+ groupIds: elementInGroup.groupIds.slice(0, index),+ });+ }+ }++ const nextElements = addElementsToFrame(+ [...app.scene.getElementsIncludingDeleted(), frame],+ selectedElements,+ frame,+ );++ return {+ elements: nextElements,+ appState: {+ ...appState,+ // dropping the line editor of a framed arrow+ ...getSelectionStateForElements(+ [frame],+ getNonDeletedElements(nextElements),+ appState,+ ),+ },+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ };+};+export const actionWrapSelectionInFrame = register({name: "wrapSelectionInFrame",- label: "labels.wrapSelectionInFrame",+ label: (elements, appState, app) =>+ getFrameToUnwrap(+ app.scene.getSelectedElements(appState),+ app.scene.getNonDeletedElementsMap(),+ )+ ? "labels.removeFrame"+ : "labels.wrapSelectionInFrame",trackEvent: { category: "element" },predicate: (elements, appState, _, app) => {const selectedElements = getSelectedElements(elements, appState);@@ -136,45 +290,14 @@ export const actionWrapSelectionInFrame = register({},perform: (elements, appState, _, app) => {const selectedElements = getSelectedElements(elements, appState);- const elementsMap = app.scene.getNonDeletedElementsMap();-- const [x1, y1, x2, y2] = getCommonBounds(selectedElements, elementsMap);- const PADDING = 16;- const frame = newFrameElement({- x: x1 - PADDING,- y: y1 - PADDING,- width: x2 - x1 + PADDING * 2,- height: y2 - y1 + PADDING * 2,- });-- // for a selected partial group, we want to remove it from the remainder of the group- if (appState.editingGroupId) {- const elementsInGroup = getElementsInGroup(- selectedElements,- appState.editingGroupId,- );-- for (const elementInGroup of elementsInGroup) {- const index = elementInGroup.groupIds.indexOf(appState.editingGroupId);-- mutateElement(elementInGroup, elementsMap, {- groupIds: elementInGroup.groupIds.slice(0, index),- });- }- }-- const nextElements = addElementsToFrame(- [...app.scene.getElementsIncludingDeleted(), frame],+ // selecting all of a frame's children unwraps them instead+ const frameToUnwrap = getFrameToUnwrap(selectedElements,- frame,+ app.scene.getNonDeletedElementsMap(),);- return {- elements: nextElements,- appState: {- selectedElementIds: { [frame.id]: true },- },- captureUpdate: CaptureUpdateAction.IMMEDIATELY,- };+ return frameToUnwrap+ ? unwrapFrame(elements, appState, frameToUnwrap, app)+ : wrapInFrame(elements, appState, selectedElements, app);},});diff --git a/packages/excalidraw/actions/actionToggleWrap.ts b/packages/excalidraw/actions/actionToggleWrap.tsnew file mode 100644index 0000000000..53e4bb066c--- /dev/null+++ b/packages/excalidraw/actions/actionToggleWrap.ts@@ -0,0 +1,18 @@+import { KEYS, matchKey } from "@excalidraw/common";++import { register } from "./register";++export const actionToggleWrap = register({+ name: "toggleWrap",+ label: "labels.toggleWrap",+ trackEvent: { category: "element" },+ predicate: (elements, appState, _, app) =>+ app.scene.getSelectedElements(appState).length > 0,+ perform: (elements, appState, _, app) => app.wrap.toggle(elements, appState),+ keyTest: (event, appState, elements, app) =>+ !event[KEYS.CTRL_OR_CMD] &&+ !event.altKey &&+ !event.shiftKey &&+ matchKey(event, KEYS.W) &&+ app.scene.getSelectedElements(appState).length > 0,+});diff --git a/packages/excalidraw/actions/index.ts b/packages/excalidraw/actions/index.tsindex e72deb1766..5eed727a7f 100644--- a/packages/excalidraw/actions/index.ts+++ b/packages/excalidraw/actions/index.ts@@ -86,6 +86,7 @@ export { actionToggleShowHints } from "./actionToggleShowHints";export { actionToggleStats } from "./actionToggleStats";export { actionUnbindText, actionBindText } from "./actionBoundText";+export { actionToggleWrap } from "./actionToggleWrap";export { actionLink } from "./actionLink";export { actionToggleElementLock } from "./actionElementLock";export { actionToggleLinearEditor } from "./actionLinearEditor";diff --git a/packages/excalidraw/actions/shortcuts.ts b/packages/excalidraw/actions/shortcuts.tsindex 10bcfd64df..3f7d73b6ac 100644--- a/packages/excalidraw/actions/shortcuts.ts+++ b/packages/excalidraw/actions/shortcuts.ts@@ -48,6 +48,7 @@ export type ShortcutName =| "saveToActiveFile"| "toggleShortcuts"| "wrapSelectionInFrame"+ | "toggleWrap">| "saveScene"| "imageExport"@@ -112,6 +113,7 @@ const shortcutMap: Record<ShortcutName, string[]> = {toggleShortcuts: [getShortcutKey("?")],searchMenu: [getShortcutKey("CtrlOrCmd+F")],wrapSelectionInFrame: [],+ toggleWrap: [getShortcutKey("W")],toolLock: [getShortcutKey("Q")],};diff --git a/packages/excalidraw/actions/types.ts b/packages/excalidraw/actions/types.tsindex cd1305a7fe..1d1c94d054 100644--- a/packages/excalidraw/actions/types.ts+++ b/packages/excalidraw/actions/types.ts@@ -141,6 +141,7 @@ export type ActionName =| "linkToElement"| "cropEditor"| "wrapSelectionInFrame"+ | "toggleWrap"| "toggleShapeSwitch"| "togglePolygon";diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex deb4b3f64b..57fbd75f3b 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -394,6 +394,7 @@ import {selectGroupsForSelectedElements,} from "./App.selection";import { AppSelectionTool } from "./App.selectionTool";+import { AppWrap } from "./App.wrap";import BraveMeasureTextError from "./BraveMeasureTextError";import { ContextMenu, CONTEXT_MENU_SEPARATOR } from "./ContextMenu";import { activeEyeDropperAtom } from "./EyeDropper";@@ -684,6 +685,7 @@ class App extends React.Component<AppProps, AppState> {public wheel: AppWheel = new AppWheel(this);public selection: AppSelection = new AppSelection(this);public selectionTool: AppSelectionTool = new AppSelectionTool(this);+ public wrap: AppWrap = new AppWrap(this);bindModeHandler: ReturnType<typeof setTimeout> | null = null;diff --git a/packages/excalidraw/components/App.wrap.ts b/packages/excalidraw/components/App.wrap.tsnew file mode 100644index 0000000000..b0b3ed9c60--- /dev/null+++ b/packages/excalidraw/components/App.wrap.ts@@ -0,0 +1,395 @@+import {+ BoundElement,+ CaptureUpdateAction,+ fixBindingsAfterDeletion,+ getBoundTextElement,+ getNonDeletedElements,+ hasBoundTextElement,+ isArrowElement,+ isBoundToContainer,+ isFrameLikeElement,+ isTextBindableContainer,+ isTextElement,+ normalizeStickyNoteFontSize,+ redrawTextBoundingBox,+ updateBoundElements,+} from "@excalidraw/element";++import type {+ ExcalidrawArrowElement,+ ExcalidrawElement,+ ExcalidrawTextContainer,+ ExcalidrawTextElement,+ FixedPointBinding,+ NonDeletedExcalidrawElement,+} from "@excalidraw/element/types";++import type { Radians } from "@excalidraw/math";++import {+ bindTextToContainer,+ getStickyNoteInk,+ pushContainerBelowText,+ unbindTextFromContainer,+ wrapTextsInContainers,+} from "../actions/actionBoundText";+import {+ getFrameToUnwrap,+ unwrapFrame,+ wrapInFrame,+} from "../actions/actionFrame";++import { getSelectionStateForElements } from "./App.selection";++import type { ActionResult } from "../actions/types";+import type { AppState } from "../types";+import type App from "./App";++/** a container unwrapping removed, and how its text sat in it */+type UnwrappedContainer = {+ containerId: ExcalidrawTextContainer["id"];+ textId: ExcalidrawTextElement["id"];+ baseFontSize: ExcalidrawTextElement["baseFontSize"];+ labelPosition: ExcalidrawTextElement["labelPosition"];+ autoResize: ExcalidrawTextElement["autoResize"];+ /**+ * the freed text as it landed, to tell how far it moved since (it doesn't+ * auto-resize, so a font size change doesn't move it) and whether it was+ * resized+ */+ text: Pick<ExcalidrawTextElement, "x" | "y" | "fontSize">;+ /** the arrows bound to the container, as they were bound */+ arrows: Pick<ExcalidrawArrowElement, "id" | "startBinding" | "endBinding">[];+};++const rebind = (+ binding: FixedPointBinding | null,+ fromId: ExcalidrawElement["id"],+ toId: ExcalidrawElement["id"],+) =>+ binding?.elementId === fromId ? { ...binding, elementId: toId } : binding;++/**+ * Wraps the selection in what fits it, or unwraps it, preferring containers+ * over frames:+ *+ * 1. a text and a container without one: binds the text to the container+ * 2. texts, with any labeled containers: wraps each text in a container+ * 3. labeled containers: unwraps their texts, removing the containers+ * 4. a frame with any of its children, or all of a frame's children: removes+ * the frame+ * 5. anything else without a frame: wraps it in a frame+ *+ * The containers (3) removed come back in place of new ones while the+ * selection it left stands, so diamonds, notes and arrows survive a toggle.+ */+export class AppWrap {+ private unwrapped: {+ selectedElementIds: AppState["selectedElementIds"];+ containers: readonly UnwrappedContainer[];+ } | null = null;++ constructor(private app: App) {}++ toggle = (+ elements: readonly ExcalidrawElement[],+ appState: Readonly<AppState>,+ ): ActionResult => {+ const unwrapped =+ this.unwrapped?.selectedElementIds === appState.selectedElementIds+ ? this.unwrapped+ : null;+ this.unwrapped = null;++ const selectedElements = this.app.scene+ .getSelectedElements(appState)+ .filter((element) => !isBoundToContainer(element));+ const texts = selectedElements.filter(+ (+ element,+ ): element is NonDeletedExcalidrawElement & ExcalidrawTextElement =>+ isTextElement(element),+ );+ const labeledContainers = selectedElements.filter((element) =>+ hasBoundTextElement(element),+ );++ if (selectedElements.length === 2 && texts.length === 1) {+ const container = selectedElements.find(+ (element) => element !== texts[0],+ )!;+ if (+ isTextBindableContainer(container) &&+ !hasBoundTextElement(container)+ ) {+ return bindTextToContainer(+ elements,+ appState,+ texts[0],+ container,+ this.app,+ );+ }+ }++ if (+ texts.length &&+ texts.length + labeledContainers.length === selectedElements.length+ ) {+ const rewrapped =+ unwrapped && this.rewrap(elements, appState, unwrapped.containers);+ if (rewrapped) {+ return rewrapped;+ }++ const result = wrapTextsInContainers(elements, appState, texts, this.app);+ return (+ result && {+ ...result,+ appState: {+ ...result.appState,+ // the labeled containers stay selected, to unwrap next along+ // with the new ones+ selectedElementIds: {+ ...result.appState?.selectedElementIds,+ ...Object.fromEntries(+ labeledContainers.map((element) => [element.id, true] as const),+ ),+ },+ },+ }+ );+ }++ if (labeledContainers.length === selectedElements.length) {+ return this.unwrap(elements, appState, labeledContainers);+ }++ const frameToUnwrap = getFrameToUnwrap(+ selectedElements,+ this.app.scene.getNonDeletedElementsMap(),+ );+ if (frameToUnwrap) {+ return unwrapFrame(elements, appState, frameToUnwrap, this.app);+ }++ if (+ selectedElements.length &&+ !selectedElements.some((element) => isFrameLikeElement(element))+ ) {+ return wrapInFrame(elements, appState, selectedElements, this.app);+ }++ return false;+ };++ /** frees the containers' texts, moving the containers' arrows onto them */+ private unwrap(+ elements: readonly ExcalidrawElement[],+ appState: Readonly<AppState>,+ containers: readonly ExcalidrawElement[],+ ): ActionResult {+ const { scene } = this.app;+ const elementsMap = scene.getNonDeletedElementsMap();+ const texts: NonDeletedExcalidrawElement[] = [];+ const unwrapped: UnwrappedContainer[] = [];++ for (const container of containers) {+ const text = getBoundTextElement(container, elementsMap);+ if (!text) {+ continue;+ }+ const arrows = (container.boundElements ?? []).flatMap(({ id }) => {+ const arrow = elementsMap.get(id);+ return arrow && isArrowElement(arrow) ? [arrow] : [];+ });++ const { baseFontSize, labelPosition, autoResize } = text;+ unbindTextFromContainer(container, text, scene);+ unwrapped.push({+ containerId: container.id,+ textId: text.id,+ baseFontSize,+ labelPosition,+ autoResize,+ text: { x: text.x, y: text.y, fontSize: text.fontSize },+ arrows: arrows.map(({ id, startBinding, endBinding }) => ({+ id,+ startBinding,+ endBinding,+ })),+ });++ if (arrows.length) {+ for (const arrow of arrows) {+ scene.mutateElement(arrow, {+ startBinding: rebind(arrow.startBinding, container.id, text.id),+ endBinding: rebind(arrow.endBinding, container.id, text.id),+ });+ }+ scene.mutateElement(text, {+ boundElements: [+ ...(text.boundElements ?? []),+ ...arrows.map(({ id }) => ({ id, type: "arrow" as const })),+ ],+ });+ }+ scene.mutateElement(container, {+ isDeleted: true,+ boundElements: container.boundElements?.filter(+ ({ id }) => !arrows.some((arrow) => arrow.id === id),+ ),+ });+ updateBoundElements(text, scene);++ texts.push(text);+ }++ fixBindingsAfterDeletion(+ elements,+ containers.filter((container) => container.isDeleted),+ );++ // also drops the line editor of an unwrapped arrow+ const selection = getSelectionStateForElements(+ texts,+ getNonDeletedElements(elements),+ appState,+ );+ this.unwrapped = {+ selectedElementIds: selection.selectedElementIds,+ containers: unwrapped,+ };++ return {+ elements,+ appState: { ...appState, ...selection },+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ };+ }++ /**+ * puts the unwrapped texts back into their containers, along with the+ * containers' arrows — `null` when any of them is gone+ */+ private rewrap(+ elements: readonly ExcalidrawElement[],+ appState: Readonly<AppState>,+ unwrapped: readonly UnwrappedContainer[],+ ): ActionResult | null {+ const { scene } = this.app;+ const allElementsMap = scene.getElementsMapIncludingDeleted();++ const pairs = [];+ for (const entry of unwrapped) {+ const container = allElementsMap.get(entry.containerId);+ const text = allElementsMap.get(entry.textId);+ if (+ !container?.isDeleted ||+ !isTextBindableContainer(container) ||+ !text ||+ text.isDeleted ||+ !isTextElement(text) ||+ text.containerId+ ) {+ return null;+ }+ pairs.push({ entry, deletedContainer: container, text });+ }++ for (const { deletedContainer } of pairs) {+ scene.mutateElement(deletedContainer, { isDeleted: false });+ }+ // so that the restored containers resolve as bindings again+ scene.replaceAllElements(scene.getElementsIncludingDeleted());++ const elementsMap = scene.getNonDeletedElementsMap();+ const containers: NonDeletedExcalidrawElement[] = [];++ let nextElements: readonly ExcalidrawElement[] =+ scene.getElementsIncludingDeleted();++ for (const { entry, text } of pairs) {+ const container = elementsMap.get(entry.containerId)!;+ const isArrowContainer = isArrowElement(container);+ // the container comes back wherever its text went in the meantime,+ // except an arrow anchored to the elements it connects+ const isAnchored =+ isArrowContainer && !!(container.startBinding || container.endBinding);+ const [dx, dy] = isAnchored+ ? [0, 0]+ : [text.x - entry.text.x, text.y - entry.text.y];+ const stickyInk = getStickyNoteInk(text, container);+ scene.mutateElement(container, {+ frameId: text.frameId,+ x: container.x + dx,+ y: container.y + dy,+ ...(stickyInk ? { strokeColor: stickyInk } : null),+ ...(isArrowContainer ? null : { angle: text.angle }),+ });+ // an arrow container rejoins the elements it connects+ BoundElement.rebindAffected(elementsMap, container, (element, updates) =>+ scene.mutateElement(element, updates),+ );++ const arrowIds = new Set<ExcalidrawElement["id"]>();+ for (const { id, startBinding, endBinding } of entry.arrows) {+ const arrow = elementsMap.get(id);+ if (!arrow || !isArrowElement(arrow)) {+ continue;+ }+ const isStartOnText = arrow.startBinding?.elementId === text.id;+ const isEndOnText = arrow.endBinding?.elementId === text.id;+ if (isStartOnText || isEndOnText) {+ scene.mutateElement(arrow, {+ startBinding: isStartOnText ? startBinding : arrow.startBinding,+ endBinding: isEndOnText ? endBinding : arrow.endBinding,+ });+ arrowIds.add(id);+ }+ }++ scene.mutateElement(container, {+ boundElements: [+ ...(container.boundElements ?? []),+ { id: text.id, type: "text" as const },+ ...Array.from(arrowIds, (id) => ({ id, type: "arrow" as const })),+ ],+ });+ scene.mutateElement(text, {+ containerId: container.id,+ // a note's label keeps the size picked while it was unwrapped+ baseFontSize:+ entry.baseFontSize !== null && text.fontSize !== entry.text.fontSize+ ? normalizeStickyNoteFontSize(text.fontSize)+ : entry.baseFontSize,+ labelPosition: entry.labelPosition,+ autoResize: entry.autoResize,+ ...(stickyInk ? { strokeColor: stickyInk } : null),+ // a label carries no arrows of its own+ boundElements: null,+ ...(isArrowContainer ? { angle: 0 as Radians } : null),+ });+ redrawTextBoundingBox(text, container, scene);+ updateBoundElements(container, scene);+ // the text may have changed layers since+ nextElements = pushContainerBelowText(nextElements, container, text);++ containers.push(container);+ }++ return {+ elements: nextElements,+ appState: {+ ...appState,+ // with the line editor of a restored arrow+ ...getSelectionStateForElements(+ containers,+ getNonDeletedElements(nextElements),+ appState,+ ),+ },+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,+ };+ }+}diff --git a/packages/excalidraw/components/CommandPalette/CommandPalette.tsx b/packages/excalidraw/components/CommandPalette/CommandPalette.tsxindex d529747c81..e5a9f55a3c 100644--- a/packages/excalidraw/components/CommandPalette/CommandPalette.tsx+++ b/packages/excalidraw/components/CommandPalette/CommandPalette.tsx@@ -314,6 +314,7 @@ function CommandPaletteInner({actionManager.actions.copy,actionManager.actions.deleteSelectedElements,actionManager.actions.wrapSelectionInFrame,+ actionManager.actions.toggleWrap,actionManager.actions.copyStyles,actionManager.actions.pasteStyles,actionManager.actions.bringToFront,diff --git a/packages/excalidraw/components/HelpDialog.tsx b/packages/excalidraw/components/HelpDialog.tsxindex 4f373c2702..d61b791bbf 100644--- a/packages/excalidraw/components/HelpDialog.tsx+++ b/packages/excalidraw/components/HelpDialog.tsx@@ -485,6 +485,10 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {label={t("labels.ungroup")}shortcuts={[getShortcutKey("CtrlOrCmd+Shift+G")]}/>+ <Shortcut+ label={t("labels.toggleWrap")}+ shortcuts={[getShortcutKey("W")]}+ /><Shortcutlabel={t("labels.flipHorizontal")}shortcuts={[getShortcutKey("Shift+H")]}diff --git a/packages/excalidraw/locales/en.json b/packages/excalidraw/locales/en.jsonindex f21d507559..514c98cab4 100644--- a/packages/excalidraw/locales/en.json+++ b/packages/excalidraw/locales/en.json@@ -189,6 +189,8 @@"copyElementLink": "Copy link to object","linkToElement": "Link to object","wrapSelectionInFrame": "Wrap selection in frame",+ "removeFrame": "Remove frame",+ "toggleWrap": "Wrap or unwrap selection","tab": "Tab","shapeSwitch": "Switch shape","preferences": "Preferences",diff --git a/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snapindex 1321699b20..02d68e1e2c 100644--- a/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap+++ b/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap@@ -129,7 +129,7 @@ exports[`contextMenu element > right-clicking on a group should select whole gro},},{- "label": "labels.wrapSelectionInFrame",+ "label": [Function],"name": "wrapSelectionInFrame","perform": [Function],"predicate": [Function],@@ -4976,7 +4976,7 @@ exports[`contextMenu element > shows 'Group selection' in context menu for multi},},{- "label": "labels.wrapSelectionInFrame",+ "label": [Function],"name": "wrapSelectionInFrame","perform": [Function],"predicate": [Function],@@ -6210,7 +6210,7 @@ exports[`contextMenu element > shows 'Ungroup selection' in context menu for gro},},{- "label": "labels.wrapSelectionInFrame",+ "label": [Function],"name": "wrapSelectionInFrame","perform": [Function],"predicate": [Function],@@ -8197,7 +8197,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap},},{- "label": "labels.wrapSelectionInFrame",+ "label": [Function],"name": "wrapSelectionInFrame","perform": [Function],"predicate": [Function],@@ -9201,7 +9201,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap},},{- "label": "labels.wrapSelectionInFrame",+ "label": [Function],"name": "wrapSelectionInFrame","perform": [Function],"predicate": [Function],diff --git a/packages/excalidraw/tests/wrap.test.tsx b/packages/excalidraw/tests/wrap.test.tsxnew file mode 100644index 0000000000..23cb0276ae--- /dev/null+++ b/packages/excalidraw/tests/wrap.test.tsx@@ -0,0 +1,569 @@+import React from "react";++import { COLOR_PALETTE, KEYS, arrayToMap } from "@excalidraw/common";+import { LinearElementEditor } from "@excalidraw/element";+import { pointFrom } from "@excalidraw/math";++import type {+ ExcalidrawArrowElement,+ ExcalidrawElement,+ ExcalidrawTextElement,+ NonDeleted,+} from "@excalidraw/element/types";++import { actionWrapSelectionInFrame } from "../actions/actionFrame";+import {+ actionChangeFontSize,+ actionChangeStrokeColor,+} from "../actions/actionProperties";+import { Excalidraw } from "../index";++import { API } from "./helpers/api";+import { Keyboard, Pointer } from "./helpers/ui";+import { act, render } from "./test-utils";++const { h } = window;++const getElement = <T extends ExcalidrawElement>(id: string) =>+ h.app.scene.getElementsMapIncludingDeleted().get(id) as T;++const selectedIds = () =>+ Object.keys(h.state.selectedElementIds).filter(+ (id) => h.state.selectedElementIds[id],+ );++const pressW = () => Keyboard.keyPress(KEYS.W);++const mouse = new Pointer("mouse");++const dragBy = (element: ExcalidrawElement, dx: number, dy: number) => {+ const x = element.x + element.width / 2;+ const y = element.y + element.height / 2;+ mouse.reset();+ mouse.downAt(x, y);+ mouse.moveTo(x + dx, y + dy);+ mouse.upAt(x + dx, y + dy);+};++const createLabeled = (+ type: "rectangle" | "diamond",+ id: string,+ boundElements: ExcalidrawElement["boundElements"] = [+ { type: "text", id: `${id}-label` },+ ],+) => {+ const container = API.createElement({+ type,+ id,+ y: 0,+ width: 200,+ height: 100,+ boundElements,+ });+ const label = API.createElement({+ type: "text",+ id: `${id}-label`,+ x: 50,+ y: 40,+ text: id,+ containerId: id,+ frameId: container.frameId,+ textAlign: "center",+ verticalAlign: "middle",+ });+ return [container, label] as const;+};++describe("wrap (w)", () => {+ beforeEach(async () => {+ await render(<Excalidraw handleKeyboardGlobally={true} />);+ });++ afterEach(async () => {+ await act(async () => {});+ });++ it("binds a text to the selected container", () => {+ const rectangle = API.createElement({ type: "rectangle", id: "rect" });+ const text = API.createElement({ type: "text", id: "text", x: 300 });+ API.setElements([rectangle, text]);+ API.setSelectedElements([rectangle, text]);++ pressW();++ expect(getElement<ExcalidrawTextElement>("text").containerId).toBe("rect");+ expect(selectedIds()).toEqual(["rect"]);+ });++ it("binds a text to the selected arrow, selecting the arrow to edit", () => {+ const arrow = API.createElement({ type: "arrow", id: "arrow" });+ const text = API.createElement({ type: "text", id: "text", x: 300 });+ API.setElements([arrow, text]);+ API.setSelectedElements([arrow, text]);++ pressW();++ expect(getElement<ExcalidrawTextElement>("text").containerId).toBe("arrow");+ expect(h.state.selectedLinearElement?.elementId).toBe("arrow");+ });++ it("wraps a text in a default rectangle of the text's color", () => {+ const text = API.createElement({+ type: "text",+ id: "text",+ strokeColor: COLOR_PALETTE.blue[4],+ });+ API.setElements([text]);+ API.setSelectedElements([text]);+ act(() => {+ h.setState({+ currentItemStrokeColor: COLOR_PALETTE.red[4],+ currentItemBackgroundColor: COLOR_PALETTE.yellow[1],+ currentItemStrokeStyle: "dashed",+ });+ });++ pressW();++ const containerId = getElement<ExcalidrawTextElement>("text").containerId!;+ expect(getElement(containerId)).toMatchObject({+ strokeColor: COLOR_PALETTE.blue[4],+ backgroundColor: "transparent",+ strokeStyle: "solid",+ });+ });++ it("wraps texts, keeping labeled containers selected to unwrap next", () => {+ const [rectangle, label] = createLabeled("rectangle", "rect");+ const text = API.createElement({ type: "text", id: "text", x: 300 });+ API.setElements([rectangle, label, text]);+ API.setSelectedElements([rectangle, text]);++ pressW();++ const containerId = getElement<ExcalidrawTextElement>("text").containerId!;+ expect(containerId).toBeTruthy();+ expect(selectedIds().sort()).toEqual([containerId, "rect"].sort());++ pressW();++ expect(getElement("rect").isDeleted).toBe(true);+ expect(getElement(containerId).isDeleted).toBe(true);+ expect(getElement<ExcalidrawTextElement>("rect-label").containerId).toBe(+ null,+ );+ expect(getElement<ExcalidrawTextElement>("text").containerId).toBe(null);+ expect(selectedIds().sort()).toEqual(["rect-label", "text"]);+ });++ it("unwraps a text as it rendered, at a fixed width", () => {+ const rectangle = API.createElement({+ type: "rectangle",+ id: "rect",+ width: 120,+ height: 100,+ });+ const text = API.createElement({+ type: "text",+ id: "text",+ x: 300,+ text: "a label long enough to wrap",+ });+ API.setElements([rectangle, text]);+ API.setSelectedElements([rectangle, text]);+ pressW();+ const label = getElement<ExcalidrawTextElement>("text");+ const { width, text: wrapped } = label;+ expect(wrapped).toContain("\n");++ API.setSelectedElements([getElement("rect")]);+ pressW();++ expect(getElement<ExcalidrawTextElement>("text")).toMatchObject({+ containerId: null,+ autoResize: false,+ width,+ text: wrapped,+ });++ pressW();++ expect(getElement<ExcalidrawTextElement>("text")).toMatchObject({+ containerId: "rect",+ autoResize: true,+ });+ });++ it("brings back the unwrapped containers, arrows included", () => {+ const [diamond, label] = createLabeled("diamond", "diamond", [+ { type: "text", id: "diamond-label" },+ { type: "arrow", id: "arrow" },+ ]);+ const arrow = API.createElement({+ type: "arrow",+ id: "arrow",+ x: 100,+ y: 400,+ width: 0,+ height: -300,+ points: [pointFrom(0, 0), pointFrom(0, -300)],+ endBinding: { elementId: "diamond", fixedPoint: [0.5, 1], mode: "orbit" },+ });+ API.setElements([diamond, label, arrow]);+ API.setSelectedElements([diamond]);++ pressW();++ expect(getElement("diamond").isDeleted).toBe(true);+ expect(+ getElement<ExcalidrawArrowElement>("arrow").endBinding?.elementId,+ ).toBe("diamond-label");+ expect(getElement("diamond-label").boundElements).toEqual([+ { type: "arrow", id: "arrow" },+ ]);+ expect(selectedIds()).toEqual(["diamond-label"]);++ pressW();++ expect(getElement("diamond").isDeleted).toBe(false);+ expect(getElement<ExcalidrawTextElement>("diamond-label").containerId).toBe(+ "diamond",+ );+ expect(getElement<ExcalidrawArrowElement>("arrow").endBinding).toEqual({+ elementId: "diamond",+ fixedPoint: [0.5, 1],+ mode: "orbit",+ });+ expect(getElement("diamond").boundElements).toEqual([+ { type: "text", id: "diamond-label" },+ { type: "arrow", id: "arrow" },+ ]);+ expect(getElement("diamond-label").boundElements).toBe(null);+ expect(selectedIds()).toEqual(["diamond"]);+ });++ it("brings back an unwrapped arrow", () => {+ const [arrow, label] = API.createLabeledArrow();+ API.setElements([arrow, label]);+ API.setSelectedElements([arrow]);++ pressW();++ expect(getElement(arrow.id).isDeleted).toBe(true);+ expect(selectedIds()).toEqual([label.id]);++ pressW();++ expect(getElement(arrow.id).isDeleted).toBe(false);+ expect(getElement<ExcalidrawTextElement>(label.id).containerId).toBe(+ arrow.id,+ );+ expect(selectedIds()).toEqual([arrow.id]);+ });++ it("drops the point editor of an unwrapped arrow", () => {+ const [arrow, label] = API.createLabeledArrow();+ API.setElements([arrow, label]);+ API.setSelectedElements([arrow]);+ act(() => {+ h.setState({+ selectedLinearElement: {+ ...new LinearElementEditor(+ arrow as NonDeleted<ExcalidrawArrowElement>,+ arrayToMap(h.elements),+ ),+ isEditing: true,+ },+ });+ });++ pressW();++ expect(h.state.selectedLinearElement).toBe(null);+ });++ it("brings a note back with the label's font size and color", () => {+ const note = API.createElement({ type: "stickynote", id: "note" });+ const text = API.createElement({+ type: "text",+ id: "text",+ text: "note",+ fontSize: 20,+ });+ API.setElements([note, text]);+ API.setSelectedElements([note, text]);+ pressW();+ expect(getElement<ExcalidrawTextElement>("text").baseFontSize).toBe(20);++ API.setSelectedElements([getElement("note")]);+ pressW();+ act(() => {+ h.app.actionManager.executeAction(actionChangeFontSize, "ui", 36);+ h.app.actionManager.executeAction(actionChangeStrokeColor, "ui", {+ color: COLOR_PALETTE.red[4],+ });+ });+ pressW();++ expect(getElement<ExcalidrawTextElement>("text")).toMatchObject({+ containerId: "note",+ baseFontSize: 36,+ strokeColor: COLOR_PALETTE.red[4],+ });+ expect(getElement("note").strokeColor).toBe(COLOR_PALETTE.red[4]);+ });++ it("wraps in a new container once the selection changed", () => {+ const [diamond, label] = createLabeled("diamond", "diamond");+ API.setElements([diamond, label]);+ API.setSelectedElements([diamond]);++ pressW();+ API.setSelectedElements([]);+ API.setSelectedElements([getElement(label.id)]);+ pressW();++ expect(getElement("diamond").isDeleted).toBe(true);+ const container = getElement(+ getElement<ExcalidrawTextElement>(label.id).containerId!,+ );+ expect(container.type).toBe("rectangle");+ });++ it("brings the container back where its text was moved", () => {+ const [diamond, label] = createLabeled("diamond", "diamond");+ API.setElements([diamond, label]);+ API.setSelectedElements([diamond]);++ pressW();+ dragBy(getElement(label.id), 100, 50);+ pressW();++ expect(getElement("diamond")).toMatchObject({+ isDeleted: false,+ x: 100,+ y: 50,+ });+ expect(getElement<ExcalidrawTextElement>(label.id).containerId).toBe(+ "diamond",+ );+ });++ it("doesn't count resizing the text as moving it", () => {+ const [rectangle, label] = createLabeled("rectangle", "rect");+ API.setElements([rectangle, label]);+ API.setSelectedElements([rectangle]);++ pressW();+ act(() => {+ h.app.actionManager.executeAction(actionChangeFontSize, "ui", 36);+ });+ dragBy(getElement(label.id), 100, 50);+ pressW();++ expect(getElement("rect").x).toBeCloseTo(100);+ expect(getElement("rect").y).toBeCloseTo(50);+ });++ it("brings the container back into the frame its text was moved to", () => {+ const [diamond, label] = createLabeled("diamond", "diamond");+ const frame = API.createElement({+ type: "frame",+ id: "frame",+ x: 400,+ y: -100,+ width: 400,+ height: 400,+ });+ API.setElements([frame, diamond, label]);+ API.setSelectedElements([diamond]);++ pressW();+ dragBy(getElement(label.id), 500, 0);+ expect(getElement(label.id).frameId).toBe("frame");+ pressW();++ expect(getElement("diamond").frameId).toBe("frame");+ const ids = h.elements.map((element) => element.id);+ expect(ids.indexOf("diamond")).toBe(ids.indexOf(label.id) - 1);+ });++ it("leaves an arrow connecting elements in place", () => {+ const rectangle = API.createElement({+ type: "rectangle",+ id: "rect",+ x: 300,+ width: 100,+ height: 100,+ boundElements: [{ type: "arrow", id: "arrow" }],+ });+ const arrow = API.createElement({+ type: "arrow",+ id: "arrow",+ y: 50,+ width: 295,+ height: 0,+ points: [pointFrom(0, 0), pointFrom(295, 0)],+ endBinding: { elementId: "rect", fixedPoint: [0, 0.5], mode: "orbit" },+ boundElements: [{ type: "text", id: "label" }],+ });+ const label = API.createElement({+ type: "text",+ id: "label",+ x: 120,+ y: 40,+ text: "label",+ containerId: "arrow",+ });+ API.setElements([rectangle, arrow, label]);+ API.setSelectedElements([arrow]);++ pressW();+ dragBy(getElement("label"), 100, 200);+ pressW();++ expect(getElement("arrow")).toMatchObject({ isDeleted: false, x: 0 });+ expect(getElement<ExcalidrawTextElement>("label").containerId).toBe(+ "arrow",+ );+ expect(getElement("rect").boundElements).toEqual([+ { type: "arrow", id: "arrow" },+ ]);+ });++ describe("frames", () => {+ const createFrameWithChildren = () => {+ const frame = API.createElement({+ type: "frame",+ id: "frame",+ width: 500,+ height: 500,+ });+ const children = ["a", "b"].map((id, index) =>+ API.createElement({+ type: "rectangle",+ id,+ x: 50 + index * 200,+ y: 50,+ frameId: "frame",+ }),+ );+ API.setElements([...children, frame]);+ return { frame, children };+ };++ it("removes a selected frame along with its children", () => {+ const { frame, children } = createFrameWithChildren();+ API.setSelectedElements([frame, ...children]);++ pressW();++ expect(getElement("frame").isDeleted).toBe(true);+ expect(children.map((child) => getElement(child.id).frameId)).toEqual([+ null,+ null,+ ]);+ expect(selectedIds().sort()).toEqual(["a", "b"]);+ });++ it("removes the frame when all its children are selected", () => {+ const { children } = createFrameWithChildren();+ API.setSelectedElements(children);++ API.executeAction(actionWrapSelectionInFrame);++ expect(getElement("frame").isDeleted).toBe(true);+ expect(getElement("a").frameId).toBe(null);+ expect(selectedIds().sort()).toEqual(["a", "b"]);+ });++ it("moves some of a frame's children into a new frame", () => {+ const { children } = createFrameWithChildren();+ API.setSelectedElements([children[0]]);++ pressW();++ expect(getElement("frame").isDeleted).toBe(false);+ const newFrameId = getElement("a").frameId;+ expect(newFrameId).not.toBe("frame");+ expect(getElement(newFrameId!).type).toBe("frame");+ expect(getElement("b").frameId).toBe("frame");+ });++ it("drops the point editor of an arrow it frames", () => {+ const arrow = API.createElement({ type: "arrow" });+ API.setElements([arrow]);+ API.setSelectedElements([arrow]);+ act(() => {+ h.setState({+ selectedLinearElement: new LinearElementEditor(+ arrow,+ arrayToMap(h.elements),+ ),+ });+ });++ pressW();++ expect(getElement(arrow.id).frameId).toBeTruthy();+ expect(h.state.selectedLinearElement).toBe(null);+ });++ it("leaves several frames be", () => {+ const frames = [0, 600].map((x, index) =>+ API.createElement({ type: "frame", id: `frame${index}`, x }),+ );+ API.setElements(frames);+ API.setSelectedElements(frames);++ pressW();++ expect(h.elements.filter((element) => !element.isDeleted)).toEqual(+ frames,+ );+ });++ it("wraps shapes with padding, and an image edge to edge", () => {+ const rectangle = API.createElement({+ type: "rectangle",+ x: 100,+ y: 100,+ width: 100,+ height: 100,+ });+ API.setElements([rectangle]);+ API.setSelectedElements([rectangle]);++ pressW();++ const frame = getElement(rectangle.id).frameId!;+ expect(getElement(frame)).toMatchObject({ x: 84, y: 84, width: 132 });++ const image = API.createElement({+ type: "image",+ x: 400,+ y: 100,+ width: 300,+ height: 200,+ });+ const mark = API.createElement({+ type: "rectangle",+ x: 450,+ y: 150,+ width: 50,+ height: 50,+ });+ API.setElements([...h.elements, image, mark]);+ API.setSelectedElements([image, mark]);++ pressW();++ expect(getElement(getElement(image.id).frameId!)).toMatchObject({+ x: 400,+ y: 100,+ width: 300,+ height: 200,+ });+ });+ });+});diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.tsindex e18a3e61f4..7c81c832c2 100644--- a/packages/excalidraw/types.ts+++ b/packages/excalidraw/types.ts@@ -1226,6 +1226,7 @@ export type AppClassProperties = {toolDrag: App["toolDrag"];activeResizeHandle: App["activeResizeHandle"];selectionTool: App["selectionTool"];+ wrap: App["wrap"];modifiers: App["modifiers"];isToolLocked: App["isToolLocked"];getEffectiveGridSize: App["getEffectiveGridSize"];diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsxindex 76e8fc281b..852c2aa7a4 100644--- a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx+++ b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx@@ -2040,6 +2040,10 @@ describe("textWysiwyg", () => {expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(null,);+ expect(h.state.selectedElementIds).toEqual({+ [rectangle.id]: true,+ [text.id]: true,+ });});it("shouldn't bind to container if container has bound text", async () => {