From d4507855a47c7d8a7fb7600829ad4a77fb2dcf77 Mon Sep 17 00:00:00 2001 From: moklick Date: Wed, 24 Jul 2019 10:57:31 +0200 Subject: [PATCH] feat(selection): add container bounds --- src/Selection/index.js | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/Selection/index.js b/src/Selection/index.js index 10dd8945..d31e58f1 100644 --- a/src/Selection/index.js +++ b/src/Selection/index.js @@ -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));