Skip to content

Commit

Permalink
feat(selection): add container bounds
Browse files Browse the repository at this point in the history
  • Loading branch information
moklick committed Jul 24, 2019
1 parent 31c1f56 commit d450785
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions src/Selection/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,30 @@ 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);
const { dispatch, state } = useContext(GraphContext);

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
}));

Expand All @@ -35,19 +46,21 @@ 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;
}

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));
Expand Down

0 comments on commit d450785

Please sign in to comment.