insomnia/app/components/base/Modal.js

108 lines
2.2 KiB
JavaScript
Raw Normal View History

import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
2016-04-07 03:09:14 +00:00
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
if (target === ReactDOM.findDOMNode(this)) {
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});
if (this.props.dontFocus) {
return;
}
setTimeout(() => {
this._node.focus();
});
}
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
}
componentDidMount () {
// In order for this to work, there needs to be tabIndex of -1 on the modal container
ReactDOM.findDOMNode(this).addEventListener('keydown', e => {
if (this.state.open && e.keyCode === 27) {
e.preventDefault();
e.stopPropagation();
// Pressed escape
this.hide();
}
});
}
2016-07-07 20:10:55 +00:00
render () {
const {tall, top, wide, className} = this.props;
2016-07-07 20:10:55 +00:00
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},
2016-07-20 18:35:08 +00:00
{'modal--fixed-height': tall},
{'modal--fixed-top': top},
{'modal--wide': wide}
2016-07-14 22:48:56 +00:00
);
2016-04-07 03:09:14 +00:00
return (
<div ref={n => this._node = n} tabIndex="-1" 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-07-20 18:35:08 +00:00
tall: PropTypes.bool,
top: PropTypes.bool,
wide: PropTypes.bool,
dontFocus: PropTypes.bool
2016-04-07 03:09:14 +00:00
};
2016-04-15 05:23:54 +00:00
export default Modal;