feat(selection): add container bounds

This commit is contained in:
moklick
2019-07-24 10:57:31 +02:00
parent 31c1f562fb
commit d4507855a4

View File

@@ -14,6 +14,15 @@ const initialRect = {
fixed: false
};
function getMousePosition(evt) {
const containerBounds = document.querySelector('.react-graph').getBoundingClientRect();
return {
x: evt.clientX - containerBounds.left,
y: evt.clientY - containerBounds.top,
}
}
export default () => {
const selectionPane = useRef(null);
const [rect, setRect] = useState(initialRect);
@@ -21,12 +30,14 @@ export default () => {
useEffect(() => {
function onMouseDown(evt) {
const mousePos = getMousePosition(evt);
setRect((r) => ({
...r,
startX: evt.clientX,
startY: evt.clientY,
x: evt.clientX,
y: evt.clientY,
startX: mousePos.x,
startY: mousePos.y,
x: mousePos.x,
y: mousePos.y,
draw: true
}));
@@ -35,8 +46,10 @@ export default () => {
function onMouseMove(evt) {
setRect((r) => {
const negativeX = evt.clientX < r.startX;
const negativeY = evt.clientY < r.startY;
const mousePos = getMousePosition(evt);
const negativeX = mousePos.x < r.startX;
const negativeY = mousePos.y < r.startY;
if (!r.draw) {
return r;
@@ -44,10 +57,10 @@ export default () => {
const nextRect = {
...r,
x: negativeX ? evt.clientX : r.x,
y: negativeY ? evt.clientY : r.y,
width: negativeX ? r.startX - evt.clientX : evt.clientX - r.startX,
height: negativeY ? r.startY - evt.clientY : evt.clientY - r.startY,
x: negativeX ? mousePos.x : r.x,
y: negativeY ? mousePos.y : r.y,
width: negativeX ? r.startX - mousePos.x : mousePos.x - r.startX,
height: negativeY ? r.startY - mousePos.y : mousePos.y - r.startY,
};
dispatch(updateSelection(nextRect));