Virtual whiteboard for sketching hand-drawn like diagrams
feat(editor): alt-drag the text being edited to duplicate it (#12219)
David Luzared10ac7dca7e
diff --git a/packages/element/tests/duplicate.test.tsx b/packages/element/tests/duplicate.test.tsxindex 5c0fd9a0fd..98b28fe392 100644--- a/packages/element/tests/duplicate.test.tsx+++ b/packages/element/tests/duplicate.test.tsx@@ -2,6 +2,7 @@ import { pointFrom } from "@excalidraw/math";import {FONT_FAMILY,+ KEYS,ORIG_ID,ROUNDNESS,isPrimitive,@@ -1184,3 +1185,113 @@ describe("duplicating list items", () => {]);});});++describe("alt-dragging the text being edited", () => {+ beforeEach(async () => {+ await render(<Excalidraw handleKeyboardGlobally={true} />);+ });++ /** alt-presses the text editor, which hands the press over to the canvas */+ const altPressTextEditor = async (x: number, y: number) => {+ const editor = await getTextEditor();+ // (the editor takes pointer downs from the next frame on)+ await act(() => new Promise((resolve) => requestAnimationFrame(resolve)));++ mouse.restorePosition(x, y);+ fireEvent.pointerDown(editor, {+ clientX: x,+ clientY: y,+ pointerType: "mouse",+ pointerId: 1,+ button: 0,+ altKey: true,+ });+ expect(h.state.editingTextElement).toBe(null);+ };++ it.each([+ ["foo", "foo", "foo"],+ // a list item's text only, as when alt-dragged on the canvas+ ["1. foo", "2. foo", "foo"],+ ])(+ "duplicates %j, editing the duplicate %j with %j selected",+ async (text, duplicateText, selectedText) => {+ const element = API.createElement({ type: "text", text });+ API.setElements([element]);+ API.setSelectedElements([element]);+ Keyboard.keyPress(KEYS.ENTER);+ await altPressTextEditor(element.x + 5, element.y + 5);++ Keyboard.withModifierKeys({ alt: true }, () => {+ mouse.moveTo(element.x + 5, element.y + 50);+ mouse.up();+ });++ const duplicate = getCloneByOrigId(element.id);+ expect(duplicate).toMatchObject({ originalText: duplicateText });+ const duplicateEditor = await getTextEditor();+ expect(h.state.editingTextElement?.id).toBe(duplicate.id);+ await waitFor(() =>+ expect(+ duplicateEditor.value.slice(+ duplicateEditor.selectionStart,+ duplicateEditor.selectionEnd,+ ),+ ).toBe(selectedText),+ );+ },+ );++ // the editor reaches past the text's bounds, over its resize handles+ it("duplicates the text when pressed past its bounds", async () => {+ const element = API.createElement({+ type: "text",+ text: "foo\nbar\nbaz\nqux\nquux",+ });+ API.setElements([element]);+ API.setSelectedElements([element]);+ Keyboard.keyPress(KEYS.ENTER);+ // (as laid out by the editor)+ const { x, y, width, height, fontSize } = h+ .elements[0] as ExcalidrawTextElement;+ await altPressTextEditor(x + 5, y + height + 3);++ Keyboard.withModifierKeys({ alt: true }, () => {+ mouse.moveTo(x + 5, y + height + 100);+ mouse.up();+ });++ assertElements(h.elements, [+ { id: element.id, x, y, width, height, fontSize },+ { id: getCloneByOrigId(element.id).id, width, height, fontSize },+ ]);+ });++ // the label is over the arrow's midpoint handle+ it("duplicates a labeled arrow when pressed on its label", async () => {+ const [arrow, label] = API.createLabeledArrow();+ API.setElements([arrow, label]);+ const { x, y, width, height, points } = arrow as ExcalidrawLinearElement;+ mouse.clickAt(x + width / 4, y + height / 4);+ // (its editor keeps what the last press grabbed)+ mouse.clickAt(x + width / 2, y + height / 2);+ expect(+ h.state.selectedLinearElement?.initialState.segmentMidpoint.value,+ ).not.toBe(null);+ Keyboard.keyPress(KEYS.ENTER);+ expect(h.state.editingTextElement?.id).toBe(label.id);+ await altPressTextEditor(x + width / 2, y + height / 2);++ Keyboard.withModifierKeys({ alt: true }, () => {+ mouse.moveTo(x + width / 2, y + height + 100);+ mouse.up();+ });++ assertElements(h.elements, [+ { id: arrow.id, x, y, points },+ { id: label.id },+ { id: getCloneByOrigId(arrow.id).id, points },+ { id: getCloneByOrigId(label.id).id },+ ]);+ });+});diff --git a/packages/element/tests/linearElementEditor.test.tsx b/packages/element/tests/linearElementEditor.test.tsxindex a0940ce359..aed3e4a78e 100644--- a/packages/element/tests/linearElementEditor.test.tsx+++ b/packages/element/tests/linearElementEditor.test.tsx@@ -426,6 +426,40 @@ describe("Test Linear Elements", () => {await getTextEditor();});+ it("updates the hovered handles together (midpoint, then endpoint)", () => {+ createTwoPointerLinearElement("arrow");+ mouse.moveTo(midpoint[0], midpoint[1]);+ expect(+ h.state.selectedLinearElement?.segmentMidPointHoveredCoords,+ ).not.toBe(null);++ mouse.moveTo(p2[0], p2[1]);+ expect(h.state.selectedLinearElement).toMatchObject({+ hoverPointIndex: 1,+ segmentMidPointHoveredCoords: null,+ });+ });++ it("doesn't highlight the arrow's midpoint while its label is edited", async () => {+ createTwoPointerLinearElement("arrow");+ mouse.moveTo(midpoint[0], midpoint[1]);+ expect(+ h.state.selectedLinearElement?.segmentMidPointHoveredCoords,+ ).not.toBe(null);++ mouse.doubleClickAt(midpoint[0], midpoint[1]);+ await getTextEditor();+ expect(h.state.selectedLinearElement?.segmentMidPointHoveredCoords).toBe(+ null,+ );++ // (beside the editor)+ mouse.moveTo(midpoint[0] + 8, midpoint[1]);+ expect(h.state.selectedLinearElement?.segmentMidPointHoveredCoords).toBe(+ null,+ );+ });+it.each([["start", null],["start", "triangle"],diff --git a/packages/excalidraw/components/App.duplicate.ts b/packages/excalidraw/components/App.duplicate.tsindex e6af94981d..00cce96c54 100644--- a/packages/excalidraw/components/App.duplicate.ts+++ b/packages/excalidraw/components/App.duplicate.ts@@ -18,7 +18,9 @@ import {getCommonBounds,getSelectionStateForElements,isBindableElement,+ isLinearElement,isTextElement,+ LinearElementEditor,newElementWith,reconcileDuplicatedElements,syncMovedIndices,@@ -26,7 +28,10 @@ import {} from "@excalidraw/element";import type { ListMarkerAdvance } from "@excalidraw/element";-import type { ExcalidrawElement } from "@excalidraw/element/types";+import type {+ ExcalidrawElement,+ ExcalidrawTextElement,+} from "@excalidraw/element/types";import type { PointerDownState } from "../types";@@ -110,51 +115,133 @@ export class AppDuplicate {});};+ /**+ * The text whose editing an alt-press on it ended, while the press is+ * handed over to the canvas (see `handOverTextEditorPress()`).+ */+ handedOverTextId: ExcalidrawTextElement["id"] | null = null;++ /**+ * An alt-press on the text being edited, once it ended the editing, is+ * handed over to the canvas, for the text to be alt-dragged (duplicated) as+ * on the canvas — its duplicate is then edited on drop.+ */+ handOverTextEditorPress = (+ event: PointerEvent,+ textElementId: ExcalidrawTextElement["id"],+ ) => {+ this.handedOverTextId = textElementId;+ try {+ this.app.interactiveCanvas?.dispatchEvent(+ new this.app.ownerWindow.PointerEvent(event.type, event),+ );+ } finally {+ this.handedOverTextId = null;+ }+ };++ /**+ * The pointer down a handed-over press is replayed as (see+ * `handOverTextEditorPress()`) moves what was edited — the text, or its+ * container — and nothing beneath the editor, which reaches past the text:+ * no resize handle, nor an arrow's point, midpoint or label.+ *+ * @returns `false` if the pointer down isn't a handed-over press+ */+ hitEditedElement = (pointerDownState: PointerDownState): boolean => {+ const { editedTextId } = pointerDownState.hit;+ const elementsMap = this.app.scene.getNonDeletedElementsMap();+ const text = editedTextId && this.app.scene.getElement(editedTextId);+ // (the text is gone if emptied)+ const element =+ text && isTextElement(text)+ ? elementsMap.get(text.containerId ?? text.id)+ : null;+ if (!element) {+ return false;+ }++ pointerDownState.hit.element = element;+ pointerDownState.hit.allHitElements = [element];++ // a fresh arrow editor, as the last press' (on a point, the midpoint or+ // the label) would drive the drag+ if (this.app.state.selectedLinearElement) {+ this.app.setState({+ selectedLinearElement: isLinearElement(element)+ ? new LinearElementEditor(element, elementsMap)+ : null,+ });+ }++ return true;+ };+/*** On alt-drag drop: the list markers advanced along with the drag go back,* for the drag to be committed as is, and forth again once it is, as* a separate undo step (before the browser gets to paint either).*- * A single list item with text after its marker is then edited, with that- * text selected (`1. |foo|`), as it's likely to differ from the original's.+ * A duplicate is then edited (once the drop is committed): a single list+ * item with text after its marker, with that text selected (`1. |foo|`),+ * as it's likely to differ from the original's — or else the duplicate of+ * the text the drag ended the editing of, with all of it selected.*/- commitDraggedListMarkers = (- advances: readonly ListMarkerAdvance[],+ commitDraggedDuplicates = (+ { hit }: PointerDownState,{- editListItem,+ editText,}: {/** `false` if the drag didn't end with a genuine pointerup */- editListItem: boolean;+ editText: boolean;},) => {- applyListMarkerAdvances(advances, "prev", this.app.scene);-- this.afterCommit(() => {- applyListMarkerAdvances(advances, "next", this.app.scene);-- const [advance] = advances;- if (- editListItem &&- advances.length === 1 &&- advance.contentStart < advance.nextOriginalText.length- ) {- // once the marker is committed+ const advances = hit.advancedListMarkers;+ const [advance] = advances;+ const listItem =+ advances.length === 1 &&+ advance.contentStart < advance.nextOriginalText.length+ ? advance+ : null;+ const textToEditId = !editText+ ? null+ : listItem+ ? listItem.elementId+ : hit.editedTextId;++ const editTextOnceCommitted = () => {+ if (textToEditId) {this.afterCommit(() => {- this.editListItemText(advance);+ this.editDuplicatedText(textToEditId, listItem);return false;});}+ };++ if (!advances.length) {+ editTextOnceCommitted();+ return;+ }+ applyListMarkerAdvances(advances, "prev", this.app.scene);++ this.afterCommit(() => {+ applyListMarkerAdvances(advances, "next", this.app.scene);+ editTextOnceCommitted();return true;});};- private editListItemText(advance: ListMarkerAdvance) {- const element = this.app.scene.getNonDeletedElement(advance.elementId);+ private editDuplicatedText(+ elementId: ExcalidrawTextElement["id"],+ /** to select the item's text only */+ listItem: ListMarkerAdvance | null,+ ) {+ const element = this.app.scene.getNonDeletedElement(elementId);if (!element ||!isTextElement(element) ||- element.originalText !== advance.nextOriginalText ||+ (listItem && element.originalText !== listItem.nextOriginalText) ||// another interaction has startedthis.dependencies.getPointerCount() > 0) {@@ -167,7 +254,7 @@ export class AppDuplicate {insertAtParentCenter: false,textElement: element,initialSelection: {- start: advance.contentStart,+ start: listItem?.contentStart ?? 0,end: element.originalText.length,},});@@ -346,6 +433,7 @@ export class AppDuplicate {// host vetoed the duplication, so we keep dragging the originalsif (!duplicatedElements.length) {+ pointerDownState.hit.editedTextId = null;return;}@@ -368,6 +456,14 @@ export class AppDuplicate {const clonedElement = cloneId && duplicateElementsMap.get(cloneId);pointerDownState.hit.element = clonedElement || null;}+ // swap the edited text with its duplicate+ if (pointerDownState.hit.editedTextId) {+ const cloneId = origIdToDuplicateId.get(+ pointerDownState.hit.editedTextId,+ );+ pointerDownState.hit.editedTextId =+ (cloneId && duplicateElementsMap.get(cloneId)?.id) || null;+ }// swap hit elements with the duplicated onespointerDownState.hit.allHitElements =pointerDownState.hit.allHitElements.reduce(@@ -402,7 +498,7 @@ export class AppDuplicate {this.app.scene.replaceAllElements(elementsWithIndices);// visible from the start of the drag, captured on drop (see- // `commitDraggedListMarkers()`)+ // `commitDraggedDuplicates()`)pointerDownState.hit.advancedListMarkers = advanceDuplicatedListMarkers(duplicatedElements,this.app.scene,diff --git a/packages/excalidraw/components/App.text.ts b/packages/excalidraw/components/App.text.tsindex a9eaf9fe06..2c5d679436 100644--- a/packages/excalidraw/components/App.text.ts+++ b/packages/excalidraw/components/App.text.ts@@ -371,6 +371,18 @@ export class AppText {});// deselect all other elements when inserting textthis.app.deselectElements();+ // (the linear element editor stays up, to come back to on submit — but+ // without the hover affordances, which are for the selection)+ if (this.app.state.selectedLinearElement) {+ this.app.setState({+ selectedLinearElement: {+ ...this.app.state.selectedLinearElement,+ hoverPointIndex: -1,+ segmentMidPointHoveredCoords: null,+ hoveredFocusPointBinding: null,+ },+ });+ }// do an initial update to re-initialize element position since we were// modifying element's x/y for sake of editor (case: syncing to remote)diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex d770f1ccea..ca4da03c1c 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -7407,7 +7407,8 @@ class App extends React.Component<AppProps, AppState> {elementsMap,);- if (!element) {+ // (editing text deselects the element)+ if (!element || this.state.editingTextElement) {return;}if (this.state.selectedLinearElement) {@@ -7462,15 +7463,16 @@ class App extends React.Component<AppProps, AppState> {this.cursor.set(CURSOR_TYPE.MOVE);}+ // (updating the previous state, as these updates are batched)if (this.state.selectedLinearElement.hoverPointIndex !== hoverPointIndex) {- this.setState({- selectedLinearElement: {- ...this.state.selectedLinearElement,+ this.setState((prevState) => ({+ selectedLinearElement: prevState.selectedLinearElement && {+ ...prevState.selectedLinearElement,hoverPointIndex,},- });+ }));}if (@@ -7479,12 +7481,12 @@ class App extends React.Component<AppProps, AppState> {segmentMidPointHoveredCoords,)) {- this.setState({- selectedLinearElement: {- ...this.state.selectedLinearElement,+ this.setState((prevState) => ({+ selectedLinearElement: prevState.selectedLinearElement && {+ ...prevState.selectedLinearElement,segmentMidPointHoveredCoords,},- });+ }));}// Check for focus point hover@@ -7504,13 +7506,13 @@ class App extends React.Component<AppProps, AppState> {this.state.selectedLinearElement.hoveredFocusPointBinding !==hoveredFocusPointBinding) {- this.setState({- selectedLinearElement: {- ...this.state.selectedLinearElement,+ this.setState((prevState) => ({+ selectedLinearElement: prevState.selectedLinearElement && {+ ...prevState.selectedLinearElement,isDragging: false,hoveredFocusPointBinding,},- });+ }));}// Set cursor to pointer when hovering over a focus point@@ -8275,6 +8277,7 @@ class App extends React.Component<AppProps, AppState> {wasAddedToSelection: false,hasBeenDuplicated: false,advancedListMarkers: [],+ editedTextId: this.duplicate.handedOverTextId,arrowLabel: false,hasHitCommonBoundingBoxOfSelectedElements:this.isHittingCommonBoundingBoxOfSelectedElements(@@ -8360,6 +8363,10 @@ class App extends React.Component<AppProps, AppState> {pointerDownState: PointerDownState,): boolean => {if (isSelectionLikeTool(this.state.activeTool.type)) {+ if (this.duplicate.hitEditedElement(pointerDownState)) {+ return false;+ }+const elements = this.scene.getNonDeletedElements();const elementsMap = this.scene.getNonDeletedElementsMap();const selectedElements = this.scene.getSelectedElements(this.state);@@ -10361,13 +10368,12 @@ class App extends React.Component<AppProps, AppState> {this.textTool.handlePointerUp(childEvent, pointerDownState);- if (pointerDownState.hit.advancedListMarkers.length) {- this.duplicate.commitDraggedListMarkers(- pointerDownState.hit.advancedListMarkers,+ if (pointerDownState.hit.hasBeenDuplicated) {+ this.duplicate.commitDraggedDuplicates(pointerDownState, {// not for a replay by the missing-pointerup cleanup (a// pointercancel, or the next interaction's pointerdown)- { editListItem: childEvent.type === "pointerup" },- );+ editText: childEvent.type === "pointerup",+ });}// an armed bucket fill commits only on a GENUINE pointer up. Thediff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.tsindex a9cf94570e..e7a999787f 100644--- a/packages/excalidraw/types.ts+++ b/packages/excalidraw/types.ts@@ -1290,6 +1290,10 @@ export type PointerDownState = Readonly<{// The list markers advanced by duplicating the selected element(s)// (alt-drag)advancedListMarkers: readonly ListMarkerAdvance[];+ // The text whose editing the pointer down ended (alt-pressing it in the+ // text editor), swapped with its duplicate when duplicated, which is+ // then edited on drop+ editedTextId: ExcalidrawTextElement["id"] | null;// Whether the pointer is hitting the common bounding box of selected// elements, which is useful for discriminating between selecitng// the entire selection vs a specific elementdiff --git a/packages/excalidraw/wysiwyg/textWysiwyg.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.tsxindex b9a8863ece..682864ab3e 100644--- a/packages/excalidraw/wysiwyg/textWysiwyg.tsx+++ b/packages/excalidraw/wysiwyg/textWysiwyg.tsx@@ -1145,7 +1145,7 @@ export const textWysiwyg = ({};// prevent blur when changing properties from the menu- const onPointerDown = (event: MouseEvent) => {+ const onPointerDown = (event: PointerEvent) => {const target = event?.target;// panning canvas@@ -1160,6 +1160,25 @@ export const textWysiwyg = ({return;}+ // alt+drag on the text being edited duplicates it, as on the canvas:+ // finish the edit keeping the text selected, then hand the press to the+ // canvas (the editor is gone by then, so the canvas receives the drag)+ if (+ event.altKey &&+ !event[KEYS.CTRL_OR_CMD] &&+ event.button === POINTER_BUTTON.MAIN &&+ target === editable &&+ (app.state.activeTool.type === "selection" ||+ app.state.activeTool.type === "lasso")+ ) {+ event.preventDefault();+ event.stopPropagation();+ submittedViaKeyboard = true;+ handleSubmit();+ app.duplicate.handOverTextEditorPress(event, element.id);+ return;+ }+const isPropertiesTrigger =target instanceof ownerWindow.HTMLElement &&target.classList.contains("properties-trigger");