@baleada/listenable-gestures
Version:
A collection of gesture recognizers that are compatible with Baleada Logic's Listenable class.
86 lines (76 loc) • 2.46 kB
JavaScript
import { emit, toEmitted, storeStartMetadata, storeMoveMetadata, isDefined } from '../util';
/*
* swipe is defined as a single touch that:
* - starts at a given point
* - travels a distance greater than 0px (or a minimum distance of your choice)
* - travels at a velocity of greater than 0px/ms (or a minimum velocity of your choice)
* - does not cancel
* - ends
*/
var defaultOptions = {
minDistance: 0,
minVelocity: 0
};
export default function swipe() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var onStart = options.onStart,
onMove = options.onMove,
onCancel = options.onCancel,
onEnd = options.onEnd,
minDistance = isDefined(options.minDistance) ? options.minDistance : defaultOptions.minDistance,
minVelocity = isDefined(options.minVelocity) ? options.minVelocity : defaultOptions.minVelocity;
function touchstart(handlerApi) {
var event = handlerApi.event,
setMetadata = handlerApi.setMetadata;
setMetadata({
path: 'touchTotal',
value: event.touches.length
});
storeStartMetadata(event, handlerApi, 'touch');
emit(onStart, toEmitted(handlerApi));
}
function touchmove(handlerApi) {
var event = handlerApi.event,
getMetadata = handlerApi.getMetadata,
denied = handlerApi.denied;
if (getMetadata().touchTotal === 1) {
storeMoveMetadata(event, handlerApi, 'touch');
} else {
denied();
}
emit(onMove, toEmitted(handlerApi));
}
function touchcancel(handlerApi) {
var denied = handlerApi.denied;
denied();
emit(onCancel, toEmitted(handlerApi));
}
function touchend(handlerApi) {
var event = handlerApi.event,
getMetadata = handlerApi.getMetadata,
setMetadata = handlerApi.setMetadata;
setMetadata({
path: 'touchTotal',
value: getMetadata().touchTotal - 1
});
storeMoveMetadata(event, handlerApi, 'touchend');
recognize(handlerApi);
emit(onEnd, toEmitted(handlerApi));
}
function recognize(_ref) {
var getMetadata = _ref.getMetadata,
recognized = _ref.recognized,
denied = _ref.denied;
if (getMetadata().distance.fromStart >= minDistance && getMetadata().velocity >= minVelocity) {
recognized();
} else {
denied();
}
}
return {
touchstart: touchstart,
touchmove: touchmove,
touchcancel: touchcancel,
touchend: touchend
};
}