feat(selection): add container bounds

This commit is contained in:
moklick
2019-07-24 10:57:31 +02:00
parent 31c1f562fb
commit d4507855a4
+23 -10
View File
@@ -14,6 +14,15 @@ const initialRect = {
fixed: false 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 () => { export default () => {
const selectionPane = useRef(null); const selectionPane = useRef(null);
const [rect, setRect] = useState(initialRect); const [rect, setRect] = useState(initialRect);
@@ -21,12 +30,14 @@ export default () => {
useEffect(() => { useEffect(() => {
function onMouseDown(evt) { function onMouseDown(evt) {
const mousePos = getMousePosition(evt);
setRect((r) => ({ setRect((r) => ({
...r, ...r,
startX: evt.clientX, startX: mousePos.x,
startY: evt.clientY, startY: mousePos.y,
x: evt.clientX, x: mousePos.x,
y: evt.clientY, y: mousePos.y,
draw: true draw: true
})); }));
@@ -35,8 +46,10 @@ export default () => {
function onMouseMove(evt) { function onMouseMove(evt) {
setRect((r) => { setRect((r) => {
const negativeX = evt.clientX < r.startX; const mousePos = getMousePosition(evt);
const negativeY = evt.clientY < r.startY;
const negativeX = mousePos.x < r.startX;
const negativeY = mousePos.y < r.startY;
if (!r.draw) { if (!r.draw) {
return r; return r;
@@ -44,10 +57,10 @@ export default () => {
const nextRect = { const nextRect = {
...r, ...r,
x: negativeX ? evt.clientX : r.x, x: negativeX ? mousePos.x : r.x,
y: negativeY ? evt.clientY : r.y, y: negativeY ? mousePos.y : r.y,
width: negativeX ? r.startX - evt.clientX : evt.clientX - r.startX, width: negativeX ? r.startX - mousePos.x : mousePos.x - r.startX,
height: negativeY ? r.startY - evt.clientY : evt.clientY - r.startY, height: negativeY ? r.startY - mousePos.y : mousePos.y - r.startY,
}; };
dispatch(updateSelection(nextRect)); dispatch(updateSelection(nextRect));