diff --git a/src/actions/tappable/tappable.js b/src/actions/tappable/tappable.js index eea2339..dc983f8 100644 --- a/src/actions/tappable/tappable.js +++ b/src/actions/tappable/tappable.js @@ -1,12 +1,16 @@ import { createDispatcher } from '../../utils/event' import { get } from '../../utils/object' +import { getDistance } from '../../utils/math' import { addFocusinEventListener, removeFocusinEventListener, addFocusoutEventListener, removeFocusoutEventListener, } from './event' -import { TAP_DURATION_MS } from '../../units' +import { + TAP_DURATION_MS, + TAP_MOVEMENT_PX, +} from '../../units' /** * tappable events are for touchable devices only @@ -16,15 +20,37 @@ export function tappable(node, options) { const dispatch = get(options, 'dispatch', createDispatcher(node)) let tapStartedAt = 0 + let tapStartPos = { x: 0, y: 0 } - function handleTapstart() { + function getIsValidTap({ + tapEndedAt, + tapEndedPos + }) { + const tapTime = tapEndedAt - tapStartedAt + const tapDist = getDistance(tapStartPos, tapEndedPos) + return ( + tapTime <= TAP_DURATION_MS && + tapDist <= TAP_MOVEMENT_PX + ) + } + + function handleTapstart(event) { tapStartedAt = Date.now() + + const touch = event.touches[0] + tapStartPos = { x: touch.clientX, y: touch.clientY } + addFocusoutEventListener(node, handleTapend) } - function handleTapend() { + function handleTapend(event) { removeFocusoutEventListener(node, handleTapend) - if (Date.now() - tapStartedAt <= TAP_DURATION_MS) { + + const touch = event.changedTouches[0] + if (getIsValidTap({ + tapEndedAt: Date.now(), + tapEndedPos: { x: touch.clientX, y: touch.clientY } + })) { dispatch('tapped') } } diff --git a/src/units.js b/src/units.js index b20316b..ea5606d 100644 --- a/src/units.js +++ b/src/units.js @@ -1,3 +1,5 @@ export const TAP_DURATION_MS = 110 +export const TAP_MOVEMENT_PX = 9 // max movement during the tap, keep it small + export const SWIPE_MIN_DURATION_MS = 111 export const SWIPE_MIN_DISTANCE_PX = 20 diff --git a/src/utils/math.js b/src/utils/math.js new file mode 100644 index 0000000..09bea67 --- /dev/null +++ b/src/utils/math.js @@ -0,0 +1,6 @@ +export const getDistance = (p1, p2) => { + const x = p2.x - p1.x; + const y = p2.y - p1.y; + + return Math.sqrt((x * x) + (y * y)); +} \ No newline at end of file