-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathPointTarget.js
81 lines (62 loc) · 1.71 KB
/
PointTarget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import React from 'react'
import PropTypes from 'prop-types'
const touchX = (event) =>
event.touches[0].clientX
const touchY = (event) =>
event.touches[0].clientY
class PointTarget extends React.Component {
static defaultProps = {
tolerance: 10
}
handleClick = () => {
if (!this.usingTouch && this.props.onPoint)
this.props.onPoint()
}
handleTouchStart = (event) => {
this.usingTouch = true
if (this.touchStarted)
return
this.touchStarted = true
this.touchMoved = false
this.startX = touchX(event)
this.startY = touchY(event)
}
handleTouchMove = (event) => {
if (!this.touchMoved) {
const { tolerance } = this.props
this.touchMoved = Math.abs(this.startX - touchX(event)) > tolerance ||
Math.abs(this.startY - touchY(event)) > tolerance
}
}
handleTouchCancel = () => {
this.touchStarted = this.touchMoved = false
this.startX = this.startY = 0
}
handleTouchEnd = () => {
this.touchStarted = false
if (!this.touchMoved && this.props.onPoint)
this.props.onPoint()
}
componentWillMount() {
this.usingTouch = false
}
render() {
const { children } = this.props
const element = children ? React.Children.only(children) : <button/>
return React.cloneElement(element, {
onClick: this.handleClick,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove,
onTouchCancel: this.handleTouchCancel,
onTouchEnd: this.handleTouchEnd
})
}
}
if (__DEV__) {
PointTarget.propTypes = {
children: PropTypes.node,
tolerance: PropTypes.number,
onPoint: PropTypes.func
}
}
export default PointTarget