#49 : Validate tap event
This commit is contained in:
@@ -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')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
6
src/utils/math.js
Normal file
6
src/utils/math.js
Normal file
@@ -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));
|
||||
}
|
||||
Reference in New Issue
Block a user