Skip to content

Commit

Permalink
feat(close modals on esc and click outside)
Browse files Browse the repository at this point in the history
  • Loading branch information
sixtedemaupeou committed Jun 12, 2018
1 parent cd7972e commit 9623728
Showing 1 changed file with 39 additions and 8 deletions.
@@ -1,6 +1,9 @@
import React, { PureComponent } from 'react'
import { compose } from 'redux'
import { connect } from 'react-redux'
import ReactDOM from 'react-dom'
import { equals } from 'ramda'

import { actions, selectors } from 'data'

const mapDispatchToProps = (dispatch) => ({
Expand All @@ -18,21 +21,49 @@ const enhance = connect(mapStateToProps, mapDispatchToProps)

export default (type) => (Component) => enhance(
class Modal extends PureComponent {
constructor (props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.onKeyPressed = this.onKeyPressed.bind(this)
}

handleClick (e) {
const modalContainer = ReactDOM.findDOMNode(this.node)
if (modalContainer && equals(modalContainer.children[0], e.target)) {
this.props.close()
}
}

onKeyPressed (evt) {
const event = evt || window.event
if (event.keyCode === 27) {
this.props.close()
}
}

render () {
const { modals, ...rest } = this.props
const filtered = modals.filter(m => m.type === type)
const setRef = (node) => {
if (node) {
this.node = node
node.focus()
}
}

return filtered.length ? (
<div>
{filtered.map((modal, i) => (
<Component
key={`${type}:${i}`}
position={modals.indexOf(modal) + 1}
total={modals.length}
{...modal.options}
{...modal.props}
{...rest}
/>
<div key={`${type}:${i}`} onKeyDown={this.onKeyPressed}
onMouseDown={this.handleClick} ref={setRef} tabIndex='0'>
<Component ref={this.node}
position={modals.indexOf(modal) + 1}
total={modals.length}
{...modal.options}
{...modal.props}
{...rest}
/>
</div>
))}
</div>
) : null
Expand Down

0 comments on commit 9623728

Please sign in to comment.