From bb151d83bce8a7107951aed445defe786bd9f7b7 Mon Sep 17 00:00:00 2001 From: Timur Khazamov Date: Thu, 2 Jan 2020 18:58:25 +0500 Subject: [PATCH] Drag to move selection (#28) --- src/index.js | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index 4497894e..bce89ba8 100644 --- a/src/index.js +++ b/src/index.js @@ -230,6 +230,23 @@ class App extends React.Component { const y = e.clientY - e.target.offsetTop; const element = newElement(this.state.elementType, x, y); + let isDraggingElements = false; + const cursorStyle = document.documentElement.style.cursor; + if (this.state.elementType === "selection") { + isDraggingElements = elements.some(el => { + if (el.isSelected) { + const minX = Math.min(el.x, el.x + el.width); + const maxX = Math.max(el.x, el.x + el.width); + const minY = Math.min(el.y, el.y + el.height); + const maxY = Math.max(el.y, el.y + el.height); + return minX <= x && x <= maxX && minY <= y && y <= maxY; + } + }); + if (isDraggingElements) { + document.documentElement.style.cursor = "move"; + } + } + if (this.state.elementType === "text") { const text = prompt("What text do you want?"); if (text === null) { @@ -263,7 +280,26 @@ class App extends React.Component { this.setState({ draggingElement: element }); } + let lastX = x; + let lastY = y; + const onMouseMove = e => { + if (isDraggingElements) { + const selectedElements = elements.filter(el => el.isSelected); + if (selectedElements.length) { + const x = e.clientX - e.target.offsetLeft; + const y = e.clientY - e.target.offsetTop; + selectedElements.forEach(element => { + element.x += x - lastX; + element.y += y - lastY; + }); + lastX = x; + lastY = y; + drawScene(); + return; + } + } + // It is very important to read this.state within each move event, // otherwise we would read a stale one! const draggingElement = this.state.draggingElement; @@ -285,15 +321,20 @@ class App extends React.Component { const onMouseUp = e => { window.removeEventListener("mousemove", onMouseMove); window.removeEventListener("mouseup", onMouseUp); + document.documentElement.style.cursor = cursorStyle; const draggingElement = this.state.draggingElement; if (draggingElement === null) { return; } if (this.state.elementType === "selection") { - // Remove actual selection element + if (isDraggingElements) { + isDraggingElements = false; + } else { + // Remove actual selection element + setSelection(draggingElement); + } elements.pop(); - setSelection(draggingElement); } else { draggingElement.isSelected = true; }