insomnia/app/components/base/Modal.js

90 lines
1.6 KiB
JavaScript
Raw Normal View History

import React, {Component, PropTypes} from 'react';
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 {
2016-07-07 20:10:55 +00:00
constructor (props) {
super(props);
this.state = {
open: false
2016-07-14 22:48:56 +00:00
};
}
2016-07-07 20:10:55 +00:00
_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
2016-07-07 20:10:55 +00:00
show () {
this.setState({open: true});
2016-07-07 20:10:55 +00:00
Mousetrap.bindGlobal('esc', () => {
this.hide();
});
}
2016-07-07 20:10:55 +00:00
toggle () {
if (this.state.open) {
this.hide();
} else {
this.show();
2016-04-09 19:24:33 +00:00
}
}
2016-07-07 20:10:55 +00:00
hide () {
this.setState({open: false});
2016-04-07 03:09:14 +00:00
}
2016-07-07 20:10:55 +00:00
render () {
const {tall, className} = this.props;
const {open} = this.state;
2016-04-07 03:09:14 +00:00
2016-07-07 20:10:55 +00:00
const classes = classnames(
'modal',
className,
{'modal--open': open},
{'modal--fixed-height': tall}
2016-07-14 22:48:56 +00:00
);
2016-04-07 03:09:14 +00:00
return (
<div
2016-07-07 20:10:55 +00:00
className={classes}
onClick={this._handleClick.bind(this)}>
2016-07-07 20:10:55 +00:00
<div className="modal__content">
2016-07-14 22:48:56 +00:00
<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;