insomnia/app/ui/components/base/Dropdown.js

97 lines
2.0 KiB
JavaScript
Raw Normal View History

import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
2016-03-21 05:47:49 +00:00
class Dropdown extends Component {
2016-07-22 16:14:27 +00:00
constructor (props) {
2016-06-20 06:05:40 +00:00
super(props);
2016-03-22 05:01:58 +00:00
this.state = {
open: false,
dropUp: false
2016-03-22 05:01:58 +00:00
};
2016-03-21 05:47:49 +00:00
}
2016-03-21 06:36:39 +00:00
2016-07-22 16:14:27 +00:00
_handleClick () {
this.toggle();
2016-03-21 05:47:49 +00:00
}
_addKeyListener () {
this._bodyKeydownHandler = e => {
if (!this.state.open) {
return;
}
// Catch all key presses if we're open
e.stopPropagation();
// Pressed escape?
if (e.keyCode === 27) {
e.preventDefault();
this.hide();
}
};
document.body.addEventListener('keydown', this._bodyKeydownHandler);
}
_removeKeyListener () {
document.body.removeEventListener('keydown', this._bodyKeydownHandler);
}
2016-07-22 16:14:27 +00:00
hide () {
this.setState({open: false});
this._removeKeyListener();
}
2016-07-22 16:14:27 +00:00
show () {
const bodyHeight = document.body.getBoundingClientRect().height;
const dropdownTop = ReactDOM.findDOMNode(this).getBoundingClientRect().top;
2016-07-22 16:14:27 +00:00
const dropUp = dropdownTop > bodyHeight * 0.65;
this.setState({open: true, dropUp});
this._addKeyListener();
}
2016-07-22 16:14:27 +00:00
toggle () {
if (this.state.open) {
this.hide();
} else {
this.show();
}
}
componentWillUnmount () {
this._removeKeyListener();
}
2016-07-22 16:14:27 +00:00
render () {
const {right, className, outline} = this.props;
const {dropUp, open} = this.state;
const classes = classnames(
2016-05-01 19:56:30 +00:00
'dropdown',
className,
{'dropdown--open': open},
{'dropdown--outlined': outline},
{'dropdown--up': dropUp},
{'dropdown--right': right}
2016-05-01 19:56:30 +00:00
);
2016-03-22 05:01:58 +00:00
2016-03-21 05:47:49 +00:00
return (
2016-07-22 16:14:27 +00:00
<div className={classes}
2016-09-07 22:21:10 +00:00
onClick={this._handleClick.bind(this)}
onMouseDown={e => e.preventDefault()}>
2016-03-21 05:47:49 +00:00
{this.props.children}
2016-06-20 06:05:40 +00:00
<div className="dropdown__backdrop"></div>
</div>
2016-03-21 05:47:49 +00:00
)
}
}
2016-03-21 06:36:39 +00:00
Dropdown.propTypes = {
right: PropTypes.bool,
outline: PropTypes.bool
2016-03-21 06:36:39 +00:00
};
2016-03-21 05:47:49 +00:00
export default Dropdown;