Constrain draggable window to browser window

This commit is contained in:
Jordan Eldredge 2016-08-05 22:04:33 -07:00
parent 08a91c4b35
commit ac5bd91109

View file

@ -1,4 +1,5 @@
import {cloneElement, Children, Component} from 'react';
import {clamp} from '../utils';
// Many of the ideas of how to build this as a React componant were stolen
// from: https://github.com/mzabriskie/react-draggable Thanks! @mzabriskie
@ -24,6 +25,8 @@ class DraggableWindow extends Component {
left: parseInt(this.body.offsetLeft || 0, 10),
top: parseInt(this.body.offsetTop || 0, 10)
};
const width = this.body.offsetWidth;
const height = this.body.offsetHeight;
// Get starting mouse position
const mouseStart = {
@ -39,13 +42,20 @@ class DraggableWindow extends Component {
top: moveEvent.clientY - mouseStart.top
};
let left = winStart.left + diff.left;
let top = winStart.top + diff.top;
// Constrain window to within the browser window
left = clamp(left, 0, window.innerWidth - width);
top = clamp(top, 0, window.innerHeight - height);
// These margins were only useful for centering the div, now we
// don't need them
this.setState({
marginLeft: '0px',
marginTop: '0px',
left: `${winStart.left + diff.left}px`,
top: `${winStart.top + diff.top}px`,
left: `${left}px`,
top: `${top}px`,
position: 'absolute'
});
};