This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

View File

@ -0,0 +1,68 @@
import GestureHandler from './GestureHandler';
import { TEST_MAX_IF_NOT_NAN } from './utils';
class DiscreteGestureHandler extends GestureHandler {
get isDiscrete() {
return true;
}
get shouldEnableGestureOnSetup() {
return true;
}
shouldFailUnderCustomCriteria(
{ x, y, deltaX, deltaY },
{ maxDeltaX, maxDeltaY, maxDistSq, shouldCancelWhenOutside }
) {
if (shouldCancelWhenOutside) {
if (!this.isPointInView({ x, y })) {
return true;
}
}
return (
TEST_MAX_IF_NOT_NAN(Math.abs(deltaX), maxDeltaX) ||
TEST_MAX_IF_NOT_NAN(Math.abs(deltaY), maxDeltaY) ||
TEST_MAX_IF_NOT_NAN(Math.abs(deltaY * deltaY + deltaX * deltaX), maxDistSq)
);
}
transformNativeEvent({ center: { x, y } }) {
const rect = this.view.getBoundingClientRect();
return {
absoluteX: x,
absoluteY: y,
x: x - rect.left,
y: y - rect.top,
};
}
isGestureEnabledForEvent(
{ minPointers, maxPointers, maxDist, maxDeltaX, maxDeltaY, maxDistSq, shouldCancelWhenOutside },
recognizer,
{ maxPointers: pointerLength, center, deltaX, deltaY, ...props }
) {
const validPointerCount = pointerLength >= minPointers && pointerLength <= maxPointers;
if (
this.shouldFailUnderCustomCriteria(
{ ...center, deltaX, deltaY },
{
maxDeltaX,
maxDeltaY,
maxDistSq,
shouldCancelWhenOutside,
}
) ||
// A user probably won't land a multi-pointer tap on the first tick (so we cannot just cancel each time)
// but if the gesture is running and the user adds or subtracts another pointer then it should fail.
(!validPointerCount && this.isGestureRunning)
) {
return { failed: true };
}
return { success: validPointerCount };
}
}
export default DiscreteGestureHandler;

View File

@ -0,0 +1,31 @@
import GestureHandler from './GestureHandler';
import { PixelRatio } from 'react-native';
class DraggingGestureHandler extends GestureHandler {
get shouldEnableGestureOnSetup() {
return true;
}
transformNativeEvent({
deltaX,
deltaY,
velocityX,
velocityY,
center: { x, y },
}) {
const rect = this.view.getBoundingClientRect();
const ratio = PixelRatio.get();
return {
translationX: deltaX - (this.__initialX || 0),
translationY: deltaY - (this.__initialY || 0),
absoluteX: x,
absoluteY: y,
velocityX: velocityX * ratio,
velocityY: velocityY * ratio,
x: x - rect.left,
y: y - rect.top,
};
}
}
export default DraggingGestureHandler;

View File

@ -0,0 +1,5 @@
export class GesturePropError extends Error {
constructor(name, value, expectedType) {
super(`Invalid property \`${name}: ${value}\` expected \`${expectedType}\``);
}
}

View File

@ -0,0 +1,137 @@
import Hammer from '@egjs/hammerjs';
import { Direction } from './constants';
import { GesturePropError } from './Errors';
import DraggingGestureHandler from './DraggingGestureHandler';
import { isnan } from './utils';
class FlingGestureHandler extends DraggingGestureHandler {
get name() {
return 'swipe';
}
get NativeGestureClass() {
return Hammer.Swipe;
}
onGestureActivated(event) {
this.sendEvent({
...event,
eventType: Hammer.INPUT_MOVE,
isFinal: false,
isFirst: true,
});
this.isGestureRunning = false;
this.hasGestureFailed = false;
this.sendEvent({
...event,
eventType: Hammer.INPUT_END,
isFinal: true,
});
}
onRawEvent(ev) {
super.onRawEvent(ev);
if (this.hasGestureFailed) {
return;
}
// Hammer doesn't send a `cancel` event for taps.
// Manually fail the event.
if (ev.isFinal) {
setTimeout(() => {
if (this.isGestureRunning) {
this.cancelEvent(ev);
}
});
} else if (!this.hasGestureFailed && !this.isGestureRunning) {
// Tap Gesture start event
const gesture = this.hammer.get(this.name);
if (gesture.options.enable(gesture, ev)) {
this.onStart(ev);
this.sendEvent(ev);
}
}
}
getHammerConfig() {
return {
pointers: this.config.numberOfPointers,
direction: this.getDirection(),
};
}
getTargetDirections(direction) {
const directions = [];
if (direction & Direction.RIGHT) {
directions.push(Hammer.DIRECTION_RIGHT);
}
if (direction & Direction.LEFT) {
directions.push(Hammer.DIRECTION_LEFT);
}
if (direction & Direction.UP) {
directions.push(Hammer.DIRECTION_UP);
}
if (direction & Direction.DOWN) {
directions.push(Hammer.DIRECTION_DOWN);
}
// const hammerDirection = directions.reduce((a, b) => a | b, 0);
return directions;
}
getDirection() {
const { direction } = this.getConfig();
let directions = [];
if (direction & Direction.RIGHT) {
directions.push(Hammer.DIRECTION_HORIZONTAL);
}
if (direction & Direction.LEFT) {
directions.push(Hammer.DIRECTION_HORIZONTAL);
}
if (direction & Direction.UP) {
directions.push(Hammer.DIRECTION_VERTICAL);
}
if (direction & Direction.DOWN) {
directions.push(Hammer.DIRECTION_VERTICAL);
}
directions = [...new Set(directions)];
if (directions.length === 0) return Hammer.DIRECTION_NONE;
if (directions.length === 1) return directions[0];
return Hammer.DIRECTION_ALL;
}
isGestureEnabledForEvent(
{
minPointers,
maxPointers,
numberOfPointers,
maxDist,
maxDeltaX,
maxDeltaY,
maxDistSq,
shouldCancelWhenOutside,
},
recognizer,
{ maxPointers: pointerLength, deltaX: dx, deltaY: dy, ...props }
) {
const validPointerCount = pointerLength === numberOfPointers;
if (!validPointerCount && this.isGestureRunning) {
return { failed: true };
}
return { success: validPointerCount };
}
updateGestureConfig({ numberOfPointers = 1, direction, ...props }) {
if (isnan(direction) || typeof direction !== 'number') {
throw new GesturePropError('direction', direction, 'number');
}
return super.updateGestureConfig({
numberOfPointers,
direction,
...props,
});
}
}
export default FlingGestureHandler;

View File

@ -0,0 +1,476 @@
import Hammer from '@egjs/hammerjs';
import { findNodeHandle } from 'react-native';
import State from '../State';
import { EventMap } from './constants';
import * as NodeManager from './NodeManager';
let _gestureInstances = 0;
class GestureHandler {
isGestureRunning = false;
hasGestureFailed = false;
view = null;
config = {};
hammer = null;
pendingGestures = {};
oldState = State.UNDETERMINED;
previousState = State.UNDETERMINED;
lastSentState = null;
get id() {
return `${this.name}${this._gestureInstance}`;
}
get isDiscrete() {
return false;
}
get shouldEnableGestureOnSetup() {
throw new Error('Must override GestureHandler.shouldEnableGestureOnSetup');
}
constructor() {
this._gestureInstance = _gestureInstances++;
}
getConfig() {
return this.config;
}
onWaitingEnded(gesture) {}
removePendingGesture(id) {
delete this.pendingGestures[id];
}
addPendingGesture(gesture) {
this.pendingGestures[gesture.id] = gesture;
}
isGestureEnabledForEvent() {
return { success: true };
}
parseNativeEvent(nativeEvent) {
return nativeEvent;
}
get NativeGestureClass() {
throw new Error('Must override GestureHandler.NativeGestureClass');
}
updateHasCustomActivationCriteria(config) {
return true;
}
clearSelfAsPending = () => {
if (Array.isArray(this.config.waitFor)) {
for (const gesture of this.config.waitFor) {
gesture.removePendingGesture(this.id);
}
}
};
updateGestureConfig({ enabled = true, ...props }) {
this.clearSelfAsPending();
this.config = ensureConfig({ enabled, ...props });
this._hasCustomActivationCriteria = this.updateHasCustomActivationCriteria(
this.config
);
if (Array.isArray(this.config.waitFor)) {
for (const gesture of this.config.waitFor) {
gesture.addPendingGesture(this);
}
}
if (this.hammer) {
this.sync();
}
return this.config;
}
destroy = () => {
this.clearSelfAsPending();
if (this.hammer) {
this.hammer.stop();
this.hammer.destroy();
}
this.hammer = null;
};
isPointInView = ({ x, y }) => {
const rect = this.view.getBoundingClientRect();
const pointerInside =
x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
return pointerInside;
};
getState(type) {
return EventMap[type];
}
transformEventData(event) {
const { eventType, maxPointers: numberOfPointers } = event;
// const direction = DirectionMap[ev.direction];
const changedTouch = event.changedPointers[0];
const pointerInside = this.isPointInView({
x: changedTouch.clientX,
y: changedTouch.clientY,
});
const state = this.getState(eventType);
if (state !== this.previousState) {
this.oldState = this.previousState;
this.previousState = state;
}
return {
nativeEvent: {
numberOfPointers,
state,
pointerInside,
...this.transformNativeEvent(event),
// onHandlerStateChange only
handlerTag: this.handlerTag,
target: this.ref,
oldState: this.oldState,
},
timeStamp: Date.now(),
};
}
transformNativeEvent(event) {
return {};
}
sendEvent = nativeEvent => {
const {
onGestureHandlerStateChange: onHandlerStateChange,
onGestureHandlerEvent: onGestureEvent,
} = this.ref.props;
const event = this.transformEventData(nativeEvent);
invokeNullableMethod('onGestureEvent', onGestureEvent, event);
if (this.lastSentState !== event.nativeEvent.state) {
this.lastSentState = event.nativeEvent.state;
invokeNullableMethod('onHandlerStateChange', onHandlerStateChange, event);
}
};
cancelPendingGestures(event) {
for (const gesture of Object.values(this.pendingGestures)) {
if (gesture && gesture.isGestureRunning) {
gesture.hasGestureFailed = true;
gesture.cancelEvent(event);
}
}
}
notifyPendingGestures() {
for (const gesture of Object.values(this.pendingGestures)) {
if (gesture) {
gesture.onWaitingEnded(this);
}
}
}
onGestureEnded(event) {
this.isGestureRunning = false;
this.cancelPendingGestures(event);
}
forceInvalidate(event) {
if (this.isGestureRunning) {
this.hasGestureFailed = true;
this.cancelEvent(event);
}
}
cancelEvent(event) {
this.notifyPendingGestures();
this.sendEvent({
...event,
eventType: Hammer.INPUT_CANCEL,
isFinal: true,
});
this.onGestureEnded(event);
}
onRawEvent({ isFirst }) {
if (isFirst) {
this.hasGestureFailed = false;
}
}
setView(ref) {
if (ref == null) {
this.destroy();
this.view = null;
return;
}
this.ref = ref;
this.view = findNodeHandle(ref);
this.hammer = new Hammer.Manager(this.view);
this.oldState = State.UNDETERMINED;
this.previousState = State.UNDETERMINED;
this.lastSentState = null;
const { NativeGestureClass } = this;
const gesture = new NativeGestureClass(this.getHammerConfig());
this.hammer.add(gesture);
this.hammer.on('hammer.input', ev => {
if (!this.config.enabled) {
this.hasGestureFailed = false;
this.isGestureRunning = false;
return;
}
this.onRawEvent(ev);
// TODO: Bacon: Check against something other than null
// The isFirst value is not called when the first rotation is calculated.
if (this.initialRotation === null && ev.rotation !== 0) {
this.initialRotation = ev.rotation;
}
if (ev.isFinal) {
// in favor of a willFail otherwise the last frame of the gesture will be captured.
setTimeout(() => {
this.initialRotation = null;
this.hasGestureFailed = false;
});
}
});
this.setupEvents();
this.sync();
}
setupEvents() {
if (!this.isDiscrete) {
this.hammer.on(`${this.name}start`, event => this.onStart(event));
this.hammer.on(`${this.name}end ${this.name}cancel`, event =>
this.onGestureEnded(event)
);
}
this.hammer.on(this.name, ev => this.onGestureActivated(ev));
}
onStart({ deltaX, deltaY, rotation }) {
// Reset the state for the next gesture
this.oldState = State.UNDETERMINED;
this.previousState = State.UNDETERMINED;
this.lastSentState = null;
this.isGestureRunning = true;
this.__initialX = deltaX;
this.__initialY = deltaY;
this.initialRotation = rotation;
}
onGestureActivated(ev) {
this.sendEvent(ev);
}
onSuccess() {}
_getPendingGestures() {
if (Array.isArray(this.config.waitFor) && this.config.waitFor.length) {
// Get the list of gestures that this gesture is still waiting for.
// Use `=== false` in case a ref that isn't a gesture handler is used.
const stillWaiting = this.config.waitFor.filter(
({ hasGestureFailed }) => hasGestureFailed === false
);
return stillWaiting;
}
return [];
}
getHammerConfig() {
const pointers =
this.config.minPointers === this.config.maxPointers
? this.config.minPointers
: 0;
return {
pointers,
};
}
sync = () => {
const gesture = this.hammer.get(this.name);
if (!gesture) return;
const enable = (recognizer, inputData) => {
if (!this.config.enabled) {
this.isGestureRunning = false;
this.hasGestureFailed = false;
return false;
}
// Prevent events before the system is ready.
if (
!inputData ||
!recognizer.options ||
typeof inputData.maxPointers === 'undefined'
) {
return this.shouldEnableGestureOnSetup;
}
if (this.hasGestureFailed) {
return false;
}
if (!this.isDiscrete) {
if (this.isGestureRunning) {
return true;
}
// The built-in hammer.js "waitFor" doesn't work across multiple views.
// Only process if there are views to wait for.
this._stillWaiting = this._getPendingGestures();
// This gesture should continue waiting.
if (this._stillWaiting.length) {
// Check to see if one of the gestures you're waiting for has started.
// If it has then the gesture should fail.
for (const gesture of this._stillWaiting) {
// When the target gesture has started, this gesture must force fail.
if (!gesture.isDiscrete && gesture.isGestureRunning) {
this.hasGestureFailed = true;
this.isGestureRunning = false;
return false;
}
}
// This gesture shouldn't start until the others have finished.
return false;
}
}
// Use default behaviour
if (!this._hasCustomActivationCriteria) {
return true;
}
const deltaRotation =
this.initialRotation == null
? 0
: inputData.rotation - this.initialRotation;
const { success, failed } = this.isGestureEnabledForEvent(
this.getConfig(),
recognizer,
{
...inputData,
deltaRotation,
}
);
if (failed) {
this.simulateCancelEvent(inputData);
this.hasGestureFailed = true;
}
return success;
};
const params = this.getHammerConfig();
gesture.set({ ...params, enable });
};
simulateCancelEvent(inputData) {}
}
// Used for sending data to a callback or AnimatedEvent
function invokeNullableMethod(name, method, event) {
if (method) {
if (typeof method === 'function') {
method(event);
} else {
// For use with reanimated's AnimatedEvent
if (
'__getHandler' in method &&
typeof method.__getHandler === 'function'
) {
const handler = method.__getHandler();
invokeNullableMethod(name, handler, event);
} else {
if ('__nodeConfig' in method) {
const { argMapping } = method.__nodeConfig;
if (Array.isArray(argMapping)) {
for (const index in argMapping) {
const [key, value] = argMapping[index];
if (key in event.nativeEvent) {
const nativeValue = event.nativeEvent[key];
if (value && value.setValue) {
// Reanimated API
value.setValue(nativeValue);
} else {
// RN Animated API
method.__nodeConfig.argMapping[index] = [key, nativeValue];
}
}
}
}
}
}
}
}
}
// Validate the props
function ensureConfig(config) {
const props = { ...config };
if ('minDist' in config) {
props.minDist = config.minDist;
props.minDistSq = props.minDist * props.minDist;
}
if ('minVelocity' in config) {
props.minVelocity = config.minVelocity;
props.minVelocitySq = props.minVelocity * props.minVelocity;
}
if ('maxDist' in config) {
props.maxDist = config.maxDist;
props.maxDistSq = config.maxDist * config.maxDist;
}
if ('waitFor' in config) {
props.waitFor = asArray(config.waitFor)
.map(({ _handlerTag }) => NodeManager.getHandler(_handlerTag))
.filter(v => v);
} else {
props.waitFor = null;
}
[
'minPointers',
'maxPointers',
'minDist',
'maxDist',
'maxDistSq',
'minVelocitySq',
'minDistSq',
'minVelocity',
'failOffsetXStart',
'failOffsetYStart',
'failOffsetXEnd',
'failOffsetYEnd',
'activeOffsetXStart',
'activeOffsetXEnd',
'activeOffsetYStart',
'activeOffsetYEnd',
].forEach(prop => {
if (typeof props[prop] === 'undefined') {
props[prop] = Number.NaN;
}
});
return props;
}
function asArray(value) {
return value == null ? [] : Array.isArray(value) ? value : [value];
}
export default GestureHandler;

View File

@ -0,0 +1,33 @@
import GestureHandler from './GestureHandler';
/**
* The base class for **Rotation** and **Pinch** gesture handlers.
*/
class IndiscreteGestureHandler extends GestureHandler {
get shouldEnableGestureOnSetup() {
return false;
}
updateGestureConfig({ minPointers = 2, maxPointers = 2, ...props }) {
return super.updateGestureConfig({
minPointers,
maxPointers,
...props,
});
}
isGestureEnabledForEvent(
{ minPointers, maxPointers },
recognizer,
{ maxPointers: pointerLength }
) {
if (pointerLength > maxPointers) {
return { failed: true };
}
const validPointerCount = pointerLength >= minPointers;
return {
success: validPointerCount,
};
}
}
export default IndiscreteGestureHandler;

View File

@ -0,0 +1,50 @@
import Hammer from '@egjs/hammerjs';
import State from '../State';
import PressGestureHandler from './PressGestureHandler';
import { isnan, isValidNumber } from './utils';
class LongPressGestureHandler extends PressGestureHandler {
get minDurationMs() {
return isnan(this.config.minDurationMs) ? 251 : this.config.minDurationMs;
}
get maxDist() {
return isnan(this.config.maxDist) ? 9 : this.config.maxDist;
}
updateHasCustomActivationCriteria({ maxDistSq }) {
return !isValidNumber(maxDistSq);
}
getConfig() {
if (!this._hasCustomActivationCriteria) {
// Default config
// If no params have been defined then this config should emulate the native gesture as closely as possible.
return {
shouldCancelWhenOutside: true,
maxDistSq: 10,
};
}
return this.config;
}
getHammerConfig() {
return {
...super.getHammerConfig(),
// threshold: this.maxDist,
time: this.minDurationMs,
};
}
getState(type) {
return {
[Hammer.INPUT_START]: State.ACTIVE,
[Hammer.INPUT_MOVE]: State.ACTIVE,
[Hammer.INPUT_END]: State.END,
[Hammer.INPUT_CANCEL]: State.FAILED,
}[type];
}
}
export default LongPressGestureHandler;

View File

@ -0,0 +1,38 @@
import DiscreteGestureHandler from './DiscreteGestureHandler';
import * as NodeManager from './NodeManager';
import PressGestureHandler from './PressGestureHandler';
import { TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils';
class NativeViewGestureHandler extends PressGestureHandler {
onRawEvent(ev) {
super.onRawEvent(ev);
if (!ev.isFinal) {
// if (this.ref instanceof ScrollView) {
if (TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ({ x: ev.deltaX, y: ev.deltaY }), 10)) {
if (this.config.disallowInterruption) {
const gestures = Object.values(NodeManager.getNodes()).filter(gesture => {
const { handlerTag, view, isGestureRunning } = gesture;
return (
// Check if this gesture isn't self
handlerTag !== this.handlerTag &&
// Ensure the gesture needs to be cancelled
isGestureRunning &&
// ScrollView can cancel discrete gestures like taps and presses
gesture instanceof DiscreteGestureHandler &&
// Ensure a view exists and is a child of the current view
view &&
this.view.contains(view)
);
});
// Cancel all of the gestures that passed the filter
for (const gesture of gestures) {
// TODO: Bacon: Send some cached event.
gesture.forceInvalidate(ev);
}
}
}
}
}
}
export default NativeViewGestureHandler;

View File

@ -0,0 +1,24 @@
let gestures = {};
export function getHandler(tag) {
if (tag in gestures) return gestures[tag];
throw new Error('No handler for tag ' + tag);
}
export function createGestureHandler(handlerTag, handler) {
if (handlerTag in gestures) {
throw new Error('Handler with tag ' + handlerTag + ' already exists');
}
gestures[handlerTag] = handler;
gestures[handlerTag].handlerTag = handlerTag;
}
export function dropGestureHandler(handlerTag) {
getHandler(handlerTag).destroy();
delete gestures[handlerTag];
}
export function getNodes() {
return { ...gestures };
}

View File

@ -0,0 +1,241 @@
import Hammer from '@egjs/hammerjs';
import {
MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD,
MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD,
} from './constants';
import DraggingGestureHandler from './DraggingGestureHandler';
import { isValidNumber, isnan, TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils';
import State from '../State';
class PanGestureHandler extends DraggingGestureHandler {
get name() {
return 'pan';
}
get NativeGestureClass() {
return Hammer.Pan;
}
getHammerConfig() {
return {
...super.getHammerConfig(),
direction: this.getDirection(),
};
}
getState(type) {
const nextState = super.getState(type);
// Ensure that the first state sent is `BEGAN` and not `ACTIVE`
if (
this.previousState === State.UNDETERMINED &&
nextState === State.ACTIVE
) {
return State.BEGAN;
}
return nextState;
}
getDirection() {
const config = this.getConfig();
const {
activeOffsetXStart,
activeOffsetXEnd,
activeOffsetYStart,
activeOffsetYEnd,
minDist,
} = config;
let directions = [];
let horizontalDirections = [];
if (!isnan(minDist)) {
return Hammer.DIRECTION_ALL;
}
if (!isnan(activeOffsetXStart))
horizontalDirections.push(Hammer.DIRECTION_LEFT);
if (!isnan(activeOffsetXEnd))
horizontalDirections.push(Hammer.DIRECTION_RIGHT);
if (horizontalDirections.length === 2)
horizontalDirections = [Hammer.DIRECTION_HORIZONTAL];
directions = directions.concat(horizontalDirections);
let verticalDirections = [];
if (!isnan(activeOffsetYStart))
verticalDirections.push(Hammer.DIRECTION_UP);
if (!isnan(activeOffsetYEnd))
verticalDirections.push(Hammer.DIRECTION_DOWN);
if (verticalDirections.length === 2)
verticalDirections = [Hammer.DIRECTION_VERTICAL];
directions = directions.concat(verticalDirections);
if (!directions.length) {
return Hammer.DIRECTION_NONE;
}
if (
directions[0] === Hammer.DIRECTION_HORIZONTAL &&
directions[1] === Hammer.DIRECTION_VERTICAL
) {
return Hammer.DIRECTION_ALL;
}
if (horizontalDirections.length && verticalDirections.length) {
return Hammer.DIRECTION_ALL;
}
return directions[0];
}
getConfig() {
if (!this._hasCustomActivationCriteria) {
// Default config
// If no params have been defined then this config should emulate the native gesture as closely as possible.
return {
minDistSq: 10,
};
}
return this.config;
}
shouldFailUnderCustomCriteria({ deltaX, deltaY }, criteria) {
return (
(!isnan(criteria.failOffsetXStart) &&
deltaX < criteria.failOffsetXStart) ||
(!isnan(criteria.failOffsetXEnd) && deltaX > criteria.failOffsetXEnd) ||
(!isnan(criteria.failOffsetYStart) &&
deltaY < criteria.failOffsetYStart) ||
(!isnan(criteria.failOffsetYEnd) && deltaY > criteria.failOffsetYEnd)
);
}
shouldActivateUnderCustomCriteria({ deltaX, deltaY, velocity }, criteria) {
return (
(!isnan(criteria.activeOffsetXStart) &&
deltaX < criteria.activeOffsetXStart) ||
(!isnan(criteria.activeOffsetXEnd) &&
deltaX > criteria.activeOffsetXEnd) ||
(!isnan(criteria.activeOffsetYStart) &&
deltaY < criteria.activeOffsetYStart) ||
(!isnan(criteria.activeOffsetYEnd) &&
deltaY > criteria.activeOffsetYEnd) ||
TEST_MIN_IF_NOT_NAN(
VEC_LEN_SQ({ x: deltaX, y: deltaY }),
criteria.minDistSq
) ||
TEST_MIN_IF_NOT_NAN(velocity.x, criteria.minVelocityX) ||
TEST_MIN_IF_NOT_NAN(velocity.y, criteria.minVelocityY) ||
TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ(velocity), criteria.minVelocitySq)
);
}
shouldMultiFingerPanFail({ pointerLength, scale, deltaRotation }) {
if (pointerLength <= 1) {
return false;
}
// Test if the pan had too much pinching or rotating.
const deltaScale = Math.abs(scale - 1);
const absDeltaRotation = Math.abs(deltaRotation);
if (deltaScale > MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD) {
// > If the threshold doesn't seem right.
// You can log the value which it failed at here:
return true;
}
if (absDeltaRotation > MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD) {
// > If the threshold doesn't seem right.
// You can log the value which it failed at here:
return true;
}
return false;
}
updateHasCustomActivationCriteria(criteria) {
return (
isValidNumber(criteria.minDistSq) ||
isValidNumber(criteria.minVelocityX) ||
isValidNumber(criteria.minVelocityY) ||
isValidNumber(criteria.minVelocitySq) ||
isValidNumber(criteria.activeOffsetXStart) ||
isValidNumber(criteria.activeOffsetXEnd) ||
isValidNumber(criteria.activeOffsetYStart) ||
isValidNumber(criteria.activeOffsetYEnd)
);
}
isGestureEnabledForEvent(props, recognizer, inputData) {
if (this.shouldFailUnderCustomCriteria(inputData, props)) {
return { failed: true };
}
const velocity = { x: inputData.velocityX, y: inputData.velocityY };
if (
this._hasCustomActivationCriteria &&
this.shouldActivateUnderCustomCriteria(
{ deltaX: inputData.deltaX, deltaY: inputData.deltaY, velocity },
props
)
) {
if (
this.shouldMultiFingerPanFail({
pointerLength: inputData.maxPointers,
scale: inputData.scale,
deltaRotation: inputData.deltaRotation,
})
) {
return {
failed: true,
};
}
return { success: true };
}
return { success: false };
}
}
function validateConfig(config = {}) {
const isNum = v => isnan(v) || typeof v === 'number';
const isBool = v => typeof v === 'boolean';
const valid = {
enabled: isBool,
minDistSq: isNum,
minVelocityX: isNum,
minVelocityY: isNum,
// TODO: Bacon: remove `minVelocity`
minVelocity: isNum,
minVelocitySq: isNum,
activeOffsetXStart: isNum,
activeOffsetXEnd: isNum,
failOffsetXStart: isNum,
failOffsetXEnd: isNum,
activeOffsetYStart: isNum,
activeOffsetYEnd: isNum,
failOffsetYStart: isNum,
failOffsetYEnd: isNum,
hasCustomActivationCriteria: isBool,
minPointers: isNum,
maxPointers: isNum,
};
const keys = Object.keys(valid);
let invalidKeys = [];
for (const key of Object.keys(config)) {
if (keys.includes(key)) {
if (valid[key](config[key])) {
console.warn('Invalid type: ' + key + ': ' + config[key]);
}
} else {
invalidKeys.push(key);
}
}
if (invalidKeys.length) {
throw new Error('Invalid config props found: ' + invalidKeys.join(', '));
}
return config;
}
export default PanGestureHandler;

View File

@ -0,0 +1,24 @@
import Hammer from '@egjs/hammerjs';
import IndiscreteGestureHandler from './IndiscreteGestureHandler';
class PinchGestureHandler extends IndiscreteGestureHandler {
get name() {
return 'pinch';
}
get NativeGestureClass() {
return Hammer.Pinch;
}
transformNativeEvent({ scale, velocity, center }) {
return {
focalX: center.x,
focalY: center.y,
velocity,
scale,
};
}
}
export default PinchGestureHandler;

View File

@ -0,0 +1,150 @@
import Hammer from '@egjs/hammerjs';
import State from '../State';
import {
CONTENT_TOUCHES_DELAY,
CONTENT_TOUCHES_QUICK_TAP_END_DELAY,
} from './constants';
import DiscreteGestureHandler from './DiscreteGestureHandler';
import { fireAfterInterval, isValidNumber, isnan } from './utils';
class PressGestureHandler extends DiscreteGestureHandler {
get name() {
return 'press';
}
get minDurationMs() {
return isnan(this.config.minDurationMs) ? 5 : this.config.minDurationMs;
}
get maxDist() {
return isnan(this.config.maxDist) ? 9 : this.config.maxDist;
}
get NativeGestureClass() {
return Hammer.Press;
}
shouldDelayTouches = true;
simulateCancelEvent(inputData) {
// Long press never starts so we can't rely on the running event boolean.
this.hasGestureFailed = true;
this.cancelEvent(inputData);
}
updateHasCustomActivationCriteria({ shouldCancelWhenOutside, maxDistSq }) {
return shouldCancelWhenOutside || !isValidNumber(maxDistSq);
}
getState(type) {
return {
[Hammer.INPUT_START]: State.BEGAN,
[Hammer.INPUT_MOVE]: State.ACTIVE,
[Hammer.INPUT_END]: State.END,
[Hammer.INPUT_CANCEL]: State.CANCELLED,
}[type];
}
getConfig() {
if (!this._hasCustomActivationCriteria) {
// Default config
// If no params have been defined then this config should emulate the native gesture as closely as possible.
return {
shouldCancelWhenOutside: true,
maxDistSq: 10,
};
}
return this.config;
}
getHammerConfig() {
return {
...super.getHammerConfig(),
// threshold: this.maxDist,
time: this.minDurationMs,
};
}
onGestureActivated(ev) {
this.onGestureStart(ev);
}
shouldDelayTouchForEvent({ pointerType }) {
// Don't disable event for mouse input
return this.shouldDelayTouches && pointerType === 'touch';
}
onGestureStart(ev) {
this.isGestureRunning = true;
clearTimeout(this.visualFeedbackTimer);
this.initialEvent = ev;
this.visualFeedbackTimer = fireAfterInterval(() => {
this.sendGestureStartedEvent(this.initialEvent);
this.initialEvent = null;
}, this.shouldDelayTouchForEvent(ev) && CONTENT_TOUCHES_DELAY);
}
sendGestureStartedEvent(ev) {
clearTimeout(this.visualFeedbackTimer);
this.visualFeedbackTimer = null;
this.sendEvent({
...ev,
eventType: Hammer.INPUT_MOVE,
isFirst: true,
});
}
forceInvalidate(event) {
super.forceInvalidate(event);
clearTimeout(this.visualFeedbackTimer);
this.visualFeedbackTimer = null;
this.initialEvent = null;
}
onRawEvent(ev) {
super.onRawEvent(ev);
if (ev.isFinal && this.isGestureRunning) {
let timeout;
if (this.visualFeedbackTimer) {
// Aesthetic timing for a quick tap.
// We haven't activated the tap right away to emulate iOS `delaysContentTouches`
// Now we must send the initial activation event and wait a set amount of time before firing the end event.
timeout = CONTENT_TOUCHES_QUICK_TAP_END_DELAY;
this.sendGestureStartedEvent(this.initialEvent);
this.initialEvent = null;
}
fireAfterInterval(() => {
this.sendEvent({
...ev,
eventType: Hammer.INPUT_END,
isFinal: true,
});
this.onGestureEnded();
}, timeout);
}
}
updateGestureConfig({
shouldActivateOnStart = false,
disallowInterruption = false,
shouldCancelWhenOutside = true,
minDurationMs = Number.NaN,
maxDist = Number.NaN,
minPointers = 1,
maxPointers = 1,
...props
}) {
return super.updateGestureConfig({
shouldActivateOnStart,
disallowInterruption,
shouldCancelWhenOutside,
minDurationMs,
maxDist,
minPointers,
maxPointers,
...props,
});
}
}
export default PressGestureHandler;

View File

@ -0,0 +1,24 @@
import Hammer from '@egjs/hammerjs';
import { DEG_RAD } from './constants';
import IndiscreteGestureHandler from './IndiscreteGestureHandler';
class RotationGestureHandler extends IndiscreteGestureHandler {
get name() {
return 'rotate';
}
get NativeGestureClass() {
return Hammer.Rotate;
}
transformNativeEvent({ rotation, velocity, center }) {
return {
rotation: (rotation - this.initialRotation) * DEG_RAD,
anchorX: center.x,
anchorY: center.y,
velocity,
};
}
}
export default RotationGestureHandler;

View File

@ -0,0 +1,160 @@
import Hammer from '@egjs/hammerjs';
import DiscreteGestureHandler from './DiscreteGestureHandler';
import { isnan } from './utils';
class TapGestureHandler extends DiscreteGestureHandler {
get name() {
return 'tap';
}
get NativeGestureClass() {
return Hammer.Tap;
}
get maxDelayMs() {
return isnan(this.config.maxDelayMs) ? 300 : this.config.maxDelayMs;
}
simulateCancelEvent(inputData) {
if (this.isGestureRunning) {
this.cancelEvent(inputData);
}
}
onGestureActivated(ev) {
if (this.isGestureRunning) {
this.onSuccessfulTap(ev);
}
}
onSuccessfulTap = ev => {
if (this._getPendingGestures().length) {
this._shouldFireEndEvent = ev;
return;
}
if (ev.eventType === Hammer.INPUT_END) {
this.sendEvent({ ...ev, eventType: Hammer.INPUT_MOVE });
}
// When handler gets activated it will turn into State.END immediately.
this.sendEvent({ ...ev, isFinal: true });
this.onGestureEnded(ev);
};
onRawEvent(ev) {
super.onRawEvent(ev);
// Attempt to create a touch-down event by checking if a valid tap hasn't started yet, then validating the input.
if (
!this.hasGestureFailed &&
!this.isGestureRunning &&
// Prevent multi-pointer events from misfiring.
!ev.isFinal
) {
// Tap Gesture start event
const gesture = this.hammer.get(this.name);
if (gesture.options.enable(gesture, ev)) {
clearTimeout(this._multiTapTimer);
this.onStart(ev);
this.sendEvent(ev);
}
}
if (ev.isFinal && ev.maxPointers > 1) {
setTimeout(() => {
// Handle case where one finger presses slightly
// after the first finger on a multi-tap event
if (this.isGestureRunning) {
this.cancelEvent(ev);
}
});
}
if (this.hasGestureFailed) {
return;
}
// Hammer doesn't send a `cancel` event for taps.
// Manually fail the event.
if (ev.isFinal) {
// Handle case where one finger presses slightly
// after the first finger on a multi-tap event
if (ev.maxPointers > 1) {
setTimeout(() => {
if (this.isGestureRunning) {
this.cancelEvent(ev);
}
});
}
// Clear last timer
clearTimeout(this._timer);
// Create time out for multi-taps.
this._timer = setTimeout(() => {
this.hasGestureFailed = true;
this.cancelEvent(ev);
}, this.maxDelayMs);
} else if (!this.hasGestureFailed && !this.isGestureRunning) {
// Tap Gesture start event
const gesture = this.hammer.get(this.name);
if (gesture.options.enable(gesture, ev)) {
clearTimeout(this._multiTapTimer);
this.onStart(ev);
this.sendEvent(ev);
}
}
}
getHammerConfig() {
return {
...super.getHammerConfig(),
event: this.name,
taps: isnan(this.config.numberOfTaps) ? 1 : this.config.numberOfTaps,
interval: this.maxDelayMs,
time:
isnan(this.config.maxDurationMs) || this.config.maxDurationMs == null
? 250
: this.config.maxDurationMs,
};
}
updateGestureConfig({
shouldCancelWhenOutside = true,
maxDeltaX = Number.NaN,
maxDeltaY = Number.NaN,
numberOfTaps = 1,
minDurationMs = 525,
maxDelayMs = Number.NaN,
maxDurationMs = Number.NaN,
maxDist = 2,
minPointers = 1,
maxPointers = 1,
...props
}) {
return super.updateGestureConfig({
shouldCancelWhenOutside,
numberOfTaps,
maxDeltaX,
maxDeltaY,
minDurationMs,
maxDelayMs,
maxDist,
minPointers,
maxPointers,
...props,
});
}
onGestureEnded(...props) {
clearTimeout(this._timer);
super.onGestureEnded(...props);
}
onWaitingEnded(gesture) {
if (this._shouldFireEndEvent) {
this.onSuccessfulTap(this._shouldFireEndEvent);
this._shouldFireEndEvent = null;
}
}
}
export default TapGestureHandler;

View File

@ -0,0 +1,48 @@
import Hammer from '@egjs/hammerjs';
import State from '../State';
export const CONTENT_TOUCHES_DELAY = 240;
export const CONTENT_TOUCHES_QUICK_TAP_END_DELAY = 50;
export const MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = 0.1;
export const MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = 7;
export const DEG_RAD = Math.PI / 180;
// Map Hammer values to RNGH
export const EventMap = {
[Hammer.INPUT_START]: State.BEGAN,
[Hammer.INPUT_MOVE]: State.ACTIVE,
[Hammer.INPUT_END]: State.END,
[Hammer.INPUT_CANCEL]: State.FAILED,
};
export const Direction = {
RIGHT: 1,
LEFT: 2,
UP: 4,
DOWN: 8,
};
export const DirectionMap = {
[Hammer.DIRECTION_RIGHT]: Direction.RIGHT,
[Hammer.DIRECTION_LEFT]: Direction.LEFT,
[Hammer.DIRECTION_UP]: Direction.UP,
[Hammer.DIRECTION_DOWN]: Direction.DOWN,
};
export const HammerInputNames = {
[Hammer.INPUT_START]: 'START',
[Hammer.INPUT_MOVE]: 'MOVE',
[Hammer.INPUT_END]: 'END',
[Hammer.INPUT_CANCEL]: 'CANCEL',
};
export const HammerDirectionNames = {
[Hammer.DIRECTION_HORIZONTAL]: 'HORIZONTAL',
[Hammer.DIRECTION_UP]: 'UP',
[Hammer.DIRECTION_DOWN]: 'DOWN',
[Hammer.DIRECTION_VERTICAL]: 'VERTICAL',
[Hammer.DIRECTION_NONE]: 'NONE',
[Hammer.DIRECTION_ALL]: 'ALL',
[Hammer.DIRECTION_RIGHT]: 'RIGHT',
[Hammer.DIRECTION_LEFT]: 'LEFT',
};

18
node_modules/react-native-gesture-handler/web/utils.js generated vendored Normal file
View File

@ -0,0 +1,18 @@
export const isnan = v => Number.isNaN(v);
export const isValidNumber = v => typeof v === 'number' && !Number.isNaN(v);
export const TEST_MIN_IF_NOT_NAN = (value, limit) =>
!isnan(limit) &&
((limit < 0 && value <= limit) || (limit >= 0 && value >= limit));
export const VEC_LEN_SQ = ({ x = 0, y = 0 } = {}) => x * x + y * y;
export const TEST_MAX_IF_NOT_NAN = (value, max) =>
!isnan(max) && ((max < 0 && value < max) || (max >= 0 && value > max));
export function fireAfterInterval(method, interval) {
if (!interval) {
method();
return null;
}
return setTimeout(() => method(), interval);
}