insomnia/app/components/base/Modal.js

95 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-04-15 05:23:54 +00:00
import React, {Component, PropTypes} from 'react'
import ReactDOM from 'react-dom'
2016-04-15 05:23:54 +00:00
import classnames from 'classnames'
2016-04-07 03:09:14 +00:00
import Mousetrap from '../../lib/mousetrap'
2016-04-07 03:09:14 +00:00
class Modal extends Component {
constructor(props) {
super(props);
this.state = {
open: false
}
}
_handleClick(e) {
2016-04-07 03:09:14 +00:00
// Did we click a close button. Let's check a few parent nodes up as well
// because some buttons might have nested elements. Maybe there is a better
// way to check this?
let target = e.target;
let shouldHide = false;
2016-04-08 04:05:08 +00:00
2016-04-07 03:27:45 +00:00
if (target === this.refs.modal) {
shouldHide = true;
2016-04-07 03:27:45 +00:00
}
2016-04-07 03:09:14 +00:00
for (let i = 0; i < 5; i++) {
if (target.hasAttribute('data-close-modal')) {
shouldHide = true;
2016-04-07 03:09:14 +00:00
break;
}
target = target.parentNode;
}
2016-04-08 04:05:08 +00:00
if (shouldHide) {
this.hide();
2016-04-07 03:27:45 +00:00
}
}
2016-04-08 04:05:08 +00:00
show() {
this.setState({open: true});
this.focus();
Mousetrap.bind('esc', () => {
this.hide();
});
}
toggle() {
if (this.state.open) {
this.hide();
} else {
this.show();
2016-04-09 19:24:33 +00:00
}
}
hide() {
this.setState({open: false});
// Focus the app when the modal closes
// TODO: Is this the best thing to do here? Maybe we should focus the last thing
document.getElementById('wrapper').focus();
// Unbind keys
Mousetrap.unbind('esc');
2016-04-07 03:09:14 +00:00
}
focus() {
const node = ReactDOM.findDOMNode(this);
node && node.focus();
2016-04-10 02:58:48 +00:00
}
2016-04-07 03:09:14 +00:00
render() {
2016-04-07 03:09:14 +00:00
return (
<div
tabIndex="-1"
className={classnames('modal', this.props.className, {'modal--open': this.state.open})}
onClick={this._handleClick.bind(this)}>
2016-06-20 06:05:40 +00:00
<div className={classnames('modal__content', {tall: this.props.tall})}>
<div className="modal__backdrop" onClick={() => this.hide()}></div>
2016-04-07 03:09:14 +00:00
{this.props.children}
</div>
</div>
2016-04-07 03:09:14 +00:00
)
}
}
Modal.propTypes = {
2016-04-10 02:58:48 +00:00
tall: PropTypes.bool
2016-04-07 03:09:14 +00:00
};
2016-04-15 05:23:54 +00:00
export default Modal;