Util Hammer
Util Hammer
8 - 2016-04-22
* [Link]
*
* Copyright (c) 2016 Jorik Tangelder;
* Licensed under the MIT license */
'use strict';
var $ = require('jquery');
var UI = require('./core');
/**
* set a timeout with a given scope
* @param {Function} fn
* @param {Number} timeout
* @param {Object} context
* @returns {number}
*/
function setTimeoutContext(fn, timeout, context) {
return setTimeout(bindFn(fn, context), timeout);
}
/**
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if ([Link](arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
/**
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if ([Link]) {
[Link](iterator, context);
} else if ([Link] !== undefined) {
i = 0;
while (i < [Link]) {
[Link](context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
[Link](i) && [Link](context, obj[i], i, obj);
}
}
}
/**
* wrap a method with a deprecation warning and stack trace
* @param {Function} method
* @param {String} name
* @param {String} message
* @returns {Function} A new function wrapping the supplied method.
*/
function deprecate(method, name, message) {
var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \
n';
return function() {
var e = new Error('get-stack-trace');
var stack = e && [Link] ? [Link](/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
.replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack
Trace';
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} target
* @param {...Object} objects_to_assign
* @returns {Object} target
*/
var assign;
if (typeof [Link] !== 'function') {
assign = function assign(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge=false]
* @returns {Object} dest
*/
var extend = deprecate(function extend(dest, src, merge) {
var keys = [Link](src);
var i = 0;
while (i < [Link]) {
if (!merge || (merge && dest[keys[i]] === undefined)) {
dest[keys[i]] = src[keys[i]];
}
i++;
}
return dest;
}, 'extend', 'Use `assign`.');
/**
* merge the values from src in the dest.
* means that properties that exist in dest will not be overwritten by src
* @param {Object} dest
* @param {Object} src
* @returns {Object} dest
*/
var merge = deprecate(function merge(dest, src) {
return extend(dest, src, true);
}, 'merge', 'Use `assign`.');
/**
* simple class inheritance
* @param {Function} child
* @param {Function} base
* @param {Object} [properties]
*/
function inherit(child, base, properties) {
var baseP = [Link],
childP;
/**
* simple function bind
* @param {Function} fn
* @param {Object} context
* @returns {Function}
*/
function bindFn(fn, context) {
return function boundFn() {
return [Link](context, arguments);
};
}
/**
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return [Link](args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* use the val2 when val1 is undefined
* @param {*} val1
* @param {*} val2
* @returns {*}
*/
function ifUndefined(val1, val2) {
return (val1 === undefined) ? val2 : val1;
}
/**
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
[Link](type, handler, false);
});
}
/**
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
[Link](type, handler, false);
});
}
/**
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node == parent) {
return true;
}
node = [Link];
}
return false;
}
/**
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return [Link](find) > -1;
}
/**
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return [Link]().split(/\s+/g);
}
/**
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if ([Link] && !findByKey) {
return [Link](find);
} else {
var i = 0;
while (i < [Link]) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] ===
find)) {
return i;
}
i++;
}
return -1;
}
}
/**
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return [Link](obj, 0);
}
/**
* unique array with objects based on a key (like 'id') or just by the array's
value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
if (sort) {
if (!key) {
results = [Link]();
} else {
results = [Link](function sortUniqueArray(a, b) {
return a[key] > b[key];
});
}
}
return results;
}
/**
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix, prop;
var camelProp = property[0].toUpperCase() + [Link](1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = (prefix) ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/**
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = [Link] || element;
return ([Link] || [Link] || window);
}
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
/**
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
function Input(manager, callback) {
var self = this;
[Link] = manager;
[Link] = callback;
[Link] = [Link];
[Link] = [Link];
// smaller wrapper around the handler, for the scope and the enabled state of the
manager,
// so when disabled the input events are completely bypassed.
[Link] = function(ev) {
if (boolOrFn([Link], [manager])) {
[Link](ev);
}
};
[Link]();
[Link] = {
/**
* should handle the inputEvent data and trigger the callback
* @virtual
*/
handler: function() { },
/**
* bind the events
*/
init: function() {
[Link] && addEventListeners([Link], [Link], [Link]);
[Link] && addEventListeners([Link], [Link],
[Link]);
[Link] && addEventListeners(getWindowForElement([Link]), [Link],
[Link]);
},
/**
* unbind the events
*/
destroy: function() {
[Link] && removeEventListeners([Link], [Link], [Link]);
[Link] && removeEventListeners([Link], [Link],
[Link]);
[Link] && removeEventListeners(getWindowForElement([Link]),
[Link], [Link]);
}
};
/**
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type;
var inputClass = [Link];
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new (Type)(manager, inputHandler);
}
/**
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = [Link];
var changedPointersLen = [Link];
var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen ===
0));
var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen -
changedPointersLen === 0));
[Link] = !!isFirst;
[Link] = !!isFinal;
if (isFirst) {
[Link] = {};
}
[Link](input);
[Link] = input;
}
/**
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = [Link];
var pointers = [Link];
var pointersLength = [Link];
computeDeltaXY(session, input);
[Link] = getDirection([Link], [Link]);
computeIntervalInputData(session, input);
offset = [Link] = {
x: center.x,
y: center.y
};
}
/**
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = [Link] || input,
deltaTime = [Link] - [Link],
velocity, velocityX, velocityY, direction;
[Link] = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = [Link];
velocityX = [Link];
velocityY = [Link];
direction = [Link];
}
[Link] = velocity;
[Link] = velocityX;
[Link] = velocityY;
[Link] = direction;
}
/**
* create a simple clone from the input used for storage of firstInput and
firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < [Link]) {
pointers[i] = {
clientX: round([Link][i].clientX),
clientY: round([Link][i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: [Link],
deltaY: [Link]
};
}
/**
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = [Link];
var x = 0, y = 0, i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
/**
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
/**
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / [Link];
}
/**
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0],
PROPS_CLIENT_XY);
}
/**
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched
out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0],
start[1], PROPS_CLIENT_XY);
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
/**
* Mouse events input
* @constructor
* @extends Input
*/
function MouseInput() {
[Link] = MOUSE_ELEMENT_EVENTS;
[Link] = MOUSE_WINDOW_EVENTS;
[Link](this, arguments);
}
inherit(MouseInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function MEhandler(ev) {
var eventType = MOUSE_INPUT_MAP[[Link]];
[Link]([Link], eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
}
});
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
};
/**
* Pointer events input
* @constructor
* @extends Input
*/
function PointerEventInput() {
[Link] = POINTER_ELEMENT_EVENTS;
[Link] = POINTER_WINDOW_EVENTS;
[Link](this, arguments);
inherit(PointerEventInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function PEhandler(ev) {
var store = [Link];
var removePointer = false;
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
[Link]([Link], eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
[Link](storeIndex, 1);
}
}
});
var SINGLE_TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
/**
* Touch events input
* @constructor
* @extends Input
*/
function SingleTouchInput() {
[Link] = SINGLE_TOUCH_TARGET_EVENTS;
[Link] = SINGLE_TOUCH_WINDOW_EVENTS;
[Link] = false;
[Link](this, arguments);
}
inherit(SingleTouchInput, Input, {
handler: function TEhandler(ev) {
var type = SINGLE_TOUCH_INPUT_MAP[[Link]];
if (![Link]) {
return;
}
[Link]([Link], type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function normalizeSingleTouches(ev, type) {
var all = toArray([Link]);
var changed = toArray([Link]);
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
/**
* Multi-user touch events input
* @constructor
* @extends Input
*/
function TouchInput() {
[Link] = TOUCH_TARGET_EVENTS;
[Link] = {};
[Link](this, arguments);
}
inherit(TouchInput, Input, {
handler: function MTEhandler(ev) {
var type = TOUCH_INPUT_MAP[[Link]];
var touches = [Link](this, ev, type);
if (!touches) {
return;
}
[Link]([Link], type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function getTouches(ev, type) {
var allTouches = toArray([Link]);
var targetIds = [Link];
var i,
targetTouches,
changedTouches = toArray([Link]),
changedTargetTouches = [],
target = [Link];
// collect touches
if (type === INPUT_START) {
i = 0;
while (i < [Link]) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
}
// filter changed touches to only contain touches that exist in the collected
target ids
i = 0;
while (i < [Link]) {
if (targetIds[changedTouches[i].identifier]) {
[Link](changedTouches[i]);
}
if (![Link]) {
return;
}
return [
// merge targetTouches with changedTargetTouches so it contains ALL touches,
including 'end' and 'cancel'
uniqueArray([Link](changedTargetTouches), 'identifier', true),
changedTargetTouches
];
}
/**
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are
allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
function TouchMouseInput() {
[Link](this, arguments);
[Link] = null;
[Link] = [];
}
inherit(TouchMouseInput, Input, {
/**
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
handler: function TMEhandler(manager, inputEvent, inputData) {
var isTouch = ([Link] == INPUT_TYPE_TOUCH),
isMouse = ([Link] == INPUT_TYPE_MOUSE);
/**
* remove the event listeners
*/
destroy: function destroy() {
[Link]();
[Link]();
}
});
function setLastTouch(eventData) {
var touch = [Link][0];
function isSyntheticEvent(eventData) {
var x = [Link], y = [Link];
for (var i = 0; i < [Link]; i++) {
var t = [Link][i];
var dx = [Link](x - t.x), dy = [Link](y - t.y);
if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
return true;
}
}
return false;
}
/**
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
function TouchAction(manager, value) {
[Link] = manager;
[Link](value);
}
[Link] = {
/**
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
set: function(value) {
// find out the touch-action by the event handlers
if (value == TOUCH_ACTION_COMPUTE) {
value = [Link]();
}
/**
* just re-set the touchAction value
*/
update: function() {
[Link]([Link]);
},
/**
* compute the value for the touchAction property based on the recognizer's
settings
* @returns {String} value
*/
compute: function() {
var actions = [];
each([Link], function(recognizer) {
if (boolOrFn([Link], [recognizer])) {
actions = [Link]([Link]());
}
});
return cleanTouchActions([Link](' '));
},
/**
* this method is called on each input cycle and provides the preventing of the
browser behavior
* @param {Object} input
*/
preventDefaults: function(input) {
var srcEvent = [Link];
var direction = [Link];
if (hasNone) {
//do not prevent defaults if this is a tap gesture
if (hasNone ||
(hasPanY && direction & DIRECTION_HORIZONTAL) ||
(hasPanX && direction & DIRECTION_VERTICAL)) {
return [Link](srcEvent);
}
},
/**
* call preventDefault to prevent the browser's default behavior (scrolling in
most cases)
* @param {Object} srcEvent
*/
preventSrc: function(srcEvent) {
[Link] = true;
[Link]();
}
};
/**
* when the touchActions are collected they are not a valid value, so we need to
clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
// pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
}
// manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
function getTouchActionProps() {
if (!NATIVE_TOUCH_ACTION) {
return false;
}
var touchMap = {};
var cssSupports = [Link] && [Link];
['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y',
'none'].forEach(function(val) {
/**
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input,
with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see [Link]) the .recognize() method is
executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED),
it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
function Recognizer(options) {
[Link] = assign({}, [Link], options || {});
[Link] = uniqueId();
[Link] = null;
[Link] = STATE_POSSIBLE;
[Link] = {};
[Link] = [];
}
[Link] = {
/**
* @virtual
* @type {Object}
*/
defaults: {},
/**
* set options
* @param {Object} options
* @return {Recognizer}
*/
set: function(options) {
assign([Link], options);
/**
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
recognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
/**
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRecognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
/**
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
requireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
/**
* drop the requireFailure link. it does not remove the link on the other
recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRequireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
/**
* has require failures boolean
* @returns {boolean}
*/
hasRequireFailures: function() {
return [Link] > 0;
},
/**
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
canRecognizeWith: function(otherRecognizer) {
return !![Link][[Link]];
},
/**
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
emit: function(input) {
var self = this;
var state = [Link];
function emit(event) {
[Link](event, input);
}
/**
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
tryEmit: function(input) {
if ([Link]()) {
return [Link](input);
}
// it's failing anyway
[Link] = STATE_FAILED;
},
/**
* can we emit?
* @returns {boolean}
*/
canEmit: function() {
var i = 0;
while (i < [Link]) {
if (!([Link][i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
},
/**
* update the recognizer
* @param {Object} inputData
*/
recognize: function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign({}, inputData);
[Link] = [Link](inputDataClone);
/**
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
getTouchAction: function() { },
/**
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
reset: function() { }
};
/**
* get a usable string, used as event postfix
* @param {Const} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* direction cons to string
* @param {Const} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = [Link];
if (manager) {
return [Link](otherRecognizer);
}
return otherRecognizer;
}
/**
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
function AttrRecognizer() {
[Link](this, arguments);
}
inherit(AttrRecognizer, Recognizer, {
/**
* @namespace
* @memberof AttrRecognizer
*/
defaults: {
/**
* @type {Number}
* @default 1
*/
pointers: 1
},
/**
* Used to check if it the recognizer receives valid input, like [Link] >
10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
attrTest: function(input) {
var optionPointers = [Link];
return optionPointers === 0 || [Link] === optionPointers;
},
/**
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
process: function(input) {
var state = [Link];
var eventType = [Link];
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = [Link](input);
/**
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function PanRecognizer() {
[Link](this, arguments);
[Link] = null;
[Link] = null;
}
inherit(PanRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PanRecognizer
*/
defaults: {
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
},
getTouchAction: function() {
var direction = [Link];
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
[Link](TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
[Link](TOUCH_ACTION_PAN_X);
}
return actions;
},
directionTest: function(input) {
var options = [Link];
var hasMoved = true;
var distance = [Link];
var direction = [Link];
var x = [Link];
var y = [Link];
// lock to axis?
if (!(direction & [Link])) {
if ([Link] & DIRECTION_HORIZONTAL) {
direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT :
DIRECTION_RIGHT;
hasMoved = x != [Link];
distance = [Link]([Link]);
} else {
direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP :
DIRECTION_DOWN;
hasMoved = y != [Link];
distance = [Link]([Link]);
}
}
[Link] = direction;
return hasMoved && distance > [Link] && direction &
[Link];
},
attrTest: function(input) {
return [Link](this, input) &&
([Link] & STATE_BEGAN || (!([Link] & STATE_BEGAN) &&
[Link](input)));
},
emit: function(input) {
[Link] = [Link];
[Link] = [Link];
if (direction) {
[Link] = [Link] + direction;
}
this._super.[Link](this, input);
}
});
/**
* Pinch
* Recognized when two or more pointers are moving toward (zoom-in) or away from
each other (zoom-out).
* @constructor
* @extends AttrRecognizer
*/
function PinchRecognizer() {
[Link](this, arguments);
}
inherit(PinchRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'pinch',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.[Link](this, input) &&
([Link]([Link] - 1) > [Link] || [Link] &
STATE_BEGAN);
},
emit: function(input) {
if ([Link] !== 1) {
var inOut = [Link] < 1 ? 'in' : 'out';
[Link] = [Link] + inOut;
}
this._super.[Link](this, input);
}
});
/**
* Press
* Recognized when the pointer is down for x ms without any movement.
* @constructor
* @extends Recognizer
*/
function PressRecognizer() {
[Link](this, arguments);
this._timer = null;
this._input = null;
}
inherit(PressRecognizer, Recognizer, {
/**
* @namespace
* @memberof PressRecognizer
*/
defaults: {
event: 'press',
pointers: 1,
time: 251, // minimal time of the pointer to be pressed
threshold: 9 // a minimal movement is ok, but keep it low
},
getTouchAction: function() {
return [TOUCH_ACTION_AUTO];
},
process: function(input) {
var options = [Link];
var validPointers = [Link] === [Link];
var validMovement = [Link] < [Link];
var validTime = [Link] > [Link];
this._input = input;
reset: function() {
clearTimeout(this._timer);
},
emit: function(input) {
if ([Link] !== STATE_RECOGNIZED) {
return;
}
/**
* Rotate
* Recognized when two or more pointer are moving in a circular motion.
* @constructor
* @extends AttrRecognizer
*/
function RotateRecognizer() {
[Link](this, arguments);
}
inherit(RotateRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof RotateRecognizer
*/
defaults: {
event: 'rotate',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.[Link](this, input) &&
([Link]([Link]) > [Link] || [Link] &
STATE_BEGAN);
}
});
/**
* Swipe
* Recognized when the pointer is moving fast (velocity), with enough distance in
the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function SwipeRecognizer() {
[Link](this, arguments);
}
inherit(SwipeRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof SwipeRecognizer
*/
defaults: {
event: 'swipe',
threshold: 10,
velocity: 0.3,
direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
pointers: 1
},
getTouchAction: function() {
return [Link](this);
},
attrTest: function(input) {
var direction = [Link];
var velocity;
emit: function(input) {
var direction = directionStr([Link]);
if (direction) {
[Link]([Link] + direction, input);
}
[Link]([Link], input);
}
});
/**
* A tap is ecognized when the pointer is doing a small tap/click. Multiple taps
are recognized if they occur
* between the given interval and position. The delay option can be used to
recognize multi-taps without firing
* a single tap.
*
* The eventData from the emitted event contains the property `tapCount`, which
contains the amount of
* multi-taps being recognized.
* @constructor
* @extends Recognizer
*/
function TapRecognizer() {
[Link](this, arguments);
this._timer = null;
this._input = null;
[Link] = 0;
}
inherit(TapRecognizer, Recognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'tap',
pointers: 1,
taps: 1,
interval: 300, // max time between the multi-tap taps
time: 250, // max time of the pointer to be down (like finger on the screen)
threshold: 9, // a minimal movement is ok, but keep it low
posThreshold: 10 // a multi-tap can be a bit off the initial position
},
getTouchAction: function() {
return [TOUCH_ACTION_MANIPULATION];
},
process: function(input) {
var options = [Link];
[Link]();
[Link] = [Link];
[Link] = [Link];
if (!validMultiTap || !validInterval) {
[Link] = 1;
} else {
[Link] += 1;
}
this._input = input;
failTimeout: function() {
this._timer = setTimeoutContext(function() {
[Link] = STATE_FAILED;
}, [Link], this);
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function() {
if ([Link] == STATE_RECOGNIZED) {
this._input.tapCount = [Link];
[Link]([Link], this._input);
}
}
});
/**
* Simple way to create a manager with a default set of recognizers.
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Hammer(element, options) {
options = options || {};
[Link] = ifUndefined([Link], [Link]);
return new Manager(element, options);
}
/**
* @const {string}
*/
[Link] = '2.0.7';
/**
* default settings
* @namespace
*/
[Link] = {
/**
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by
default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the
added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @type {Boolean}
* @default true
*/
enable: true,
/**
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* @type {Array}
*/
preset: [
// RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
[RotateRecognizer, {enable: false}],
[PinchRecognizer, {enable: false}, ['rotate']],
[SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
[PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
[TapRecognizer],
[TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
[PressRecognizer]
],
/**
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* Disables text selection to improve the dragging gesture. Mainly for desktop
browsers.
* @type {String}
* @default 'none'
*/
userSelect: 'none',
/**
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: 'none',
/**
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari
displays
* a callout containing information about the link. This property allows you to
disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: 'none',
/**
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: 'none',
/**
* Specifies that an entire element should be draggable instead of its
contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: 'none',
/**
* Overrides the highlight color shown when the user taps a link or a
JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: 'rgba(0,0,0,0)'
}
};
var STOP = 1;
var FORCED_STOP = 2;
/**
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Manager(element, options) {
[Link] = assign({}, [Link], options || {});
[Link] = {};
[Link] = {};
[Link] = [];
[Link] = {};
[Link] = element;
[Link] = createInputInstance(this);
[Link] = new TouchAction(this, [Link]);
toggleCssProps(this, true);
each([Link], function(item) {
var recognizer = [Link](new (item[0])(item[1]));
item[2] && [Link](item[2]);
item[3] && [Link](item[3]);
}, this);
}
[Link] = {
/**
* set options
* @param {Object} options
* @returns {Manager}
*/
set: function(options) {
assign([Link], options);
/**
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
stop: function(force) {
[Link] = force ? FORCED_STOP : STOP;
},
/**
* run the recognizers!
* called by the inputHandler function on every movement of the pointers
(touches)
* it walks through all the recognizers and tries to detect the gesture that is
being made
* @param {Object} inputData
*/
recognize: function(inputData) {
var session = [Link];
if ([Link]) {
return;
}
var recognizer;
var recognizers = [Link];
var i = 0;
while (i < [Link]) {
recognizer = recognizers[i];
// find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or
the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the
current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the
recognizer.
if ([Link] !== FORCED_STOP && ( // 1
!curRecognizer || recognizer == curRecognizer || // 2
[Link](curRecognizer))) { // 3
[Link](inputData);
} else {
[Link]();
}
/**
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
get: function(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
// remove existing
var existing = [Link]([Link]);
if (existing) {
[Link](existing);
}
[Link](recognizer);
[Link] = this;
[Link]();
return recognizer;
},
/**
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
remove: function(recognizer) {
if (invokeArrayArg(recognizer, 'remove', this)) {
return this;
}
recognizer = [Link](recognizer);
return this;
},
/**
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
on: function(events, handler) {
if (events === undefined) {
return;
}
if (handler === undefined) {
return;
}
/**
* unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
off: function(events, handler) {
if (events === undefined) {
return;
}
/**
* emit event to the listeners
* @param {String} event
* @param {Object} data
*/
emit: function(event, data) {
// we also want to trigger dom events
if ([Link]) {
triggerDomEvent(event, data);
}
[Link] = event;
[Link] = function() {
[Link]();
};
var i = 0;
while (i < [Link]) {
handlers[i](data);
i++;
}
},
/**
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
destroy: function() {
[Link] && toggleCssProps(this, false);
[Link] = {};
[Link] = {};
[Link]();
[Link] = null;
}
};
/**
* add/remove the css properties as defined in [Link]
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = [Link];
if (![Link]) {
return;
}
var prop;
each([Link], function(value, name) {
prop = prefixed([Link], name);
if (add) {
[Link][prop] = [Link][prop];
[Link][prop] = value;
} else {
[Link][prop] = [Link][prop] || '';
}
});
if (!add) {
[Link] = {};
}
}
/**
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = [Link]('Event');
[Link](event, true, true);
[Link] = data;
[Link](gestureEvent);
}
assign(Hammer, {
INPUT_START: INPUT_START,
INPUT_MOVE: INPUT_MOVE,
INPUT_END: INPUT_END,
INPUT_CANCEL: INPUT_CANCEL,
STATE_POSSIBLE: STATE_POSSIBLE,
STATE_BEGAN: STATE_BEGAN,
STATE_CHANGED: STATE_CHANGED,
STATE_ENDED: STATE_ENDED,
STATE_RECOGNIZED: STATE_RECOGNIZED,
STATE_CANCELLED: STATE_CANCELLED,
STATE_FAILED: STATE_FAILED,
DIRECTION_NONE: DIRECTION_NONE,
DIRECTION_LEFT: DIRECTION_LEFT,
DIRECTION_RIGHT: DIRECTION_RIGHT,
DIRECTION_UP: DIRECTION_UP,
DIRECTION_DOWN: DIRECTION_DOWN,
DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
DIRECTION_VERTICAL: DIRECTION_VERTICAL,
DIRECTION_ALL: DIRECTION_ALL,
Manager: Manager,
Input: Input,
TouchAction: TouchAction,
TouchInput: TouchInput,
MouseInput: MouseInput,
PointerEventInput: PointerEventInput,
TouchMouseInput: TouchMouseInput,
SingleTouchInput: SingleTouchInput,
Recognizer: Recognizer,
AttrRecognizer: AttrRecognizer,
Tap: TapRecognizer,
Pan: PanRecognizer,
Swipe: SwipeRecognizer,
Pinch: PinchRecognizer,
Rotate: RotateRecognizer,
Press: PressRecognizer,
on: addEventListeners,
off: removeEventListeners,
each: each,
merge: merge,
extend: extend,
assign: assign,
inherit: inherit,
bindFn: bindFn,
prefixed: prefixed
});
// [Link]
// This jQuery plugin is just a small wrapper around the Hammer() class.
// It also extends the [Link] method by triggering jQuery events.
// $(element).hammer(options).bind("pan", myPanHandler);
// The Hammer instance is stored at $[Link]("hammer").
// [Link]
(function($, Hammer) {
function hammerify(el, options) {
var $el = $(el);
if (!$[Link]('hammer')) {
$[Link]('hammer', new Hammer($el[0], options));
}
}
$.[Link] = function(options) {
return [Link](function() {
hammerify(this, options);
});
};