apeman-react-touchable
Version:
apeman react package for touchable component.
60 lines (54 loc) • 1.38 kB
JSX
/**
* Higher order component with outside touch
* @function withOutside
* @param {function} Component - A component constructor
* @returns {function} - Wrapped component
*/
import { wrap } from 'breact'
import React, { PropTypes as types } from 'react'
import ReactDOM from 'react-dom'
import { get } from 'bwindow'
import newHammer from './helpers/new_hammer'
/** @lends withOutside */
function withOutside (Component, handleOutSide) {
return wrap(Component, {
propTypes: {
onOutside: types.func
},
componentDidMount () {
const s = this
let body = get('document.body')
let hammer = newHammer(body)
hammer.on('tap', s.handleTapForOutside)
s.hammer = hammer
},
componentWillUnmount () {
const s = this
let { hammer } = s
hammer.off('tap', s.handleTapForOutside)
hammer.destroy()
hammer.stop()
hammer.destroy()
},
handleTapForOutside (e) {
const s = this
let { props } = s
let {
onOutside = () => undefined
} = props
let node = ReactDOM.findDOMNode(s)
if (!node) {
return
}
let contained = node.contains(e.target)
if (!contained) {
onOutside(e)
if (handleOutSide) {
handleOutSide(e, { element: s })
}
}
}
})
}
export default withOutside