Drag to move selection (#28)
This commit is contained in:
parent
44ff545219
commit
bb151d83bc
43
src/index.js
43
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") {
|
||||
if (isDraggingElements) {
|
||||
isDraggingElements = false;
|
||||
} else {
|
||||
// Remove actual selection element
|
||||
elements.pop();
|
||||
setSelection(draggingElement);
|
||||
}
|
||||
elements.pop();
|
||||
} else {
|
||||
draggingElement.isSelected = true;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user