hammer.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456
  1. define(function(require, exports, module) {
  2. /*! Hammer.JS - v2.0.4 - 2014-09-28
  3. * http://hammerjs.github.io/
  4. *
  5. * Copyright (c) 2014 Jorik Tangelder;
  6. * Licensed under the MIT license */
  7. 'use strict';
  8. var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o'];
  9. var TEST_ELEMENT = document.createElement('div');
  10. var TYPE_FUNCTION = 'function';
  11. var round = Math.round;
  12. var abs = Math.abs;
  13. var now = Date.now;
  14. /**
  15. * set a timeout with a given scope
  16. * @param {Function} fn
  17. * @param {Number} timeout
  18. * @param {Object} context
  19. * @returns {number}
  20. */
  21. function setTimeoutContext(fn, timeout, context) {
  22. return setTimeout(bindFn(fn, context), timeout);
  23. }
  24. /**
  25. * if the argument is an array, we want to execute the fn on each entry
  26. * if it aint an array we don't want to do a thing.
  27. * this is used by all the methods that accept a single and array argument.
  28. * @param {*|Array} arg
  29. * @param {String} fn
  30. * @param {Object} [context]
  31. * @returns {Boolean}
  32. */
  33. function invokeArrayArg(arg, fn, context) {
  34. if (Array.isArray(arg)) {
  35. each(arg, context[fn], context);
  36. return true;
  37. }
  38. return false;
  39. }
  40. /**
  41. * walk objects and arrays
  42. * @param {Object} obj
  43. * @param {Function} iterator
  44. * @param {Object} context
  45. */
  46. function each(obj, iterator, context) {
  47. var i;
  48. if (!obj) {
  49. return;
  50. }
  51. if (obj.forEach) {
  52. obj.forEach(iterator, context);
  53. } else if (obj.length !== undefined) {
  54. i = 0;
  55. while (i < obj.length) {
  56. iterator.call(context, obj[i], i, obj);
  57. i++;
  58. }
  59. } else {
  60. for (i in obj) {
  61. obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
  62. }
  63. }
  64. }
  65. /**
  66. * extend object.
  67. * means that properties in dest will be overwritten by the ones in src.
  68. * @param {Object} dest
  69. * @param {Object} src
  70. * @param {Boolean} [merge]
  71. * @returns {Object} dest
  72. */
  73. function extend(dest, src, merge) {
  74. var keys = Object.keys(src);
  75. var i = 0;
  76. while (i < keys.length) {
  77. if (!merge || (merge && dest[keys[i]] === undefined)) {
  78. dest[keys[i]] = src[keys[i]];
  79. }
  80. i++;
  81. }
  82. return dest;
  83. }
  84. /**
  85. * merge the values from src in the dest.
  86. * means that properties that exist in dest will not be overwritten by src
  87. * @param {Object} dest
  88. * @param {Object} src
  89. * @returns {Object} dest
  90. */
  91. function merge(dest, src) {
  92. return extend(dest, src, true);
  93. }
  94. /**
  95. * simple class inheritance
  96. * @param {Function} child
  97. * @param {Function} base
  98. * @param {Object} [properties]
  99. */
  100. function inherit(child, base, properties) {
  101. var baseP = base.prototype,
  102. childP;
  103. childP = child.prototype = Object.create(baseP);
  104. childP.constructor = child;
  105. childP._super = baseP;
  106. if (properties) {
  107. extend(childP, properties);
  108. }
  109. }
  110. /**
  111. * simple function bind
  112. * @param {Function} fn
  113. * @param {Object} context
  114. * @returns {Function}
  115. */
  116. function bindFn(fn, context) {
  117. return function boundFn() {
  118. return fn.apply(context, arguments);
  119. };
  120. }
  121. /**
  122. * let a boolean value also be a function that must return a boolean
  123. * this first item in args will be used as the context
  124. * @param {Boolean|Function} val
  125. * @param {Array} [args]
  126. * @returns {Boolean}
  127. */
  128. function boolOrFn(val, args) {
  129. if (typeof val == TYPE_FUNCTION) {
  130. return val.apply(args ? args[0] || undefined : undefined, args);
  131. }
  132. return val;
  133. }
  134. /**
  135. * use the val2 when val1 is undefined
  136. * @param {*} val1
  137. * @param {*} val2
  138. * @returns {*}
  139. */
  140. function ifUndefined(val1, val2) {
  141. return (val1 === undefined) ? val2 : val1;
  142. }
  143. /**
  144. * addEventListener with multiple events at once
  145. * @param {EventTarget} target
  146. * @param {String} types
  147. * @param {Function} handler
  148. */
  149. function addEventListeners(target, types, handler) {
  150. each(splitStr(types), function(type) {
  151. target.addEventListener(type, handler, false);
  152. });
  153. }
  154. /**
  155. * removeEventListener with multiple events at once
  156. * @param {EventTarget} target
  157. * @param {String} types
  158. * @param {Function} handler
  159. */
  160. function removeEventListeners(target, types, handler) {
  161. each(splitStr(types), function(type) {
  162. target.removeEventListener(type, handler, false);
  163. });
  164. }
  165. /**
  166. * find if a node is in the given parent
  167. * @method hasParent
  168. * @param {HTMLElement} node
  169. * @param {HTMLElement} parent
  170. * @return {Boolean} found
  171. */
  172. function hasParent(node, parent) {
  173. while (node) {
  174. if (node == parent) {
  175. return true;
  176. }
  177. node = node.parentNode;
  178. }
  179. return false;
  180. }
  181. /**
  182. * small indexOf wrapper
  183. * @param {String} str
  184. * @param {String} find
  185. * @returns {Boolean} found
  186. */
  187. function inStr(str, find) {
  188. return str.indexOf(find) > -1;
  189. }
  190. /**
  191. * split string on whitespace
  192. * @param {String} str
  193. * @returns {Array} words
  194. */
  195. function splitStr(str) {
  196. return str.trim().split(/\s+/g);
  197. }
  198. /**
  199. * find if a array contains the object using indexOf or a simple polyFill
  200. * @param {Array} src
  201. * @param {String} find
  202. * @param {String} [findByKey]
  203. * @return {Boolean|Number} false when not found, or the index
  204. */
  205. function inArray(src, find, findByKey) {
  206. if (src.indexOf && !findByKey) {
  207. return src.indexOf(find);
  208. } else {
  209. var i = 0;
  210. while (i < src.length) {
  211. if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
  212. return i;
  213. }
  214. i++;
  215. }
  216. return -1;
  217. }
  218. }
  219. /**
  220. * convert array-like objects to real arrays
  221. * @param {Object} obj
  222. * @returns {Array}
  223. */
  224. function toArray(obj) {
  225. return Array.prototype.slice.call(obj, 0);
  226. }
  227. /**
  228. * unique array with objects based on a key (like 'id') or just by the array's value
  229. * @param {Array} src [{id:1},{id:2},{id:1}]
  230. * @param {String} [key]
  231. * @param {Boolean} [sort=False]
  232. * @returns {Array} [{id:1},{id:2}]
  233. */
  234. function uniqueArray(src, key, sort) {
  235. var results = [];
  236. var values = [];
  237. var i = 0;
  238. while (i < src.length) {
  239. var val = key ? src[i][key] : src[i];
  240. if (inArray(values, val) < 0) {
  241. results.push(src[i]);
  242. }
  243. values[i] = val;
  244. i++;
  245. }
  246. if (sort) {
  247. if (!key) {
  248. results = results.sort();
  249. } else {
  250. results = results.sort(function sortUniqueArray(a, b) {
  251. return a[key] > b[key];
  252. });
  253. }
  254. }
  255. return results;
  256. }
  257. /**
  258. * get the prefixed property
  259. * @param {Object} obj
  260. * @param {String} property
  261. * @returns {String|Undefined} prefixed
  262. */
  263. function prefixed(obj, property) {
  264. var prefix, prop;
  265. var camelProp = property[0].toUpperCase() + property.slice(1);
  266. var i = 0;
  267. while (i < VENDOR_PREFIXES.length) {
  268. prefix = VENDOR_PREFIXES[i];
  269. prop = (prefix) ? prefix + camelProp : property;
  270. if (prop in obj) {
  271. return prop;
  272. }
  273. i++;
  274. }
  275. return undefined;
  276. }
  277. /**
  278. * get a unique id
  279. * @returns {number} uniqueId
  280. */
  281. var _uniqueId = 1;
  282. function uniqueId() {
  283. return _uniqueId++;
  284. }
  285. /**
  286. * get the window object of an element
  287. * @param {HTMLElement} element
  288. * @returns {DocumentView|Window}
  289. */
  290. function getWindowForElement(element) {
  291. var doc = element.ownerDocument;
  292. return (doc.defaultView || doc.parentWindow);
  293. }
  294. var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  295. var SUPPORT_TOUCH = ('ontouchstart' in window);
  296. var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
  297. var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
  298. var INPUT_TYPE_TOUCH = 'touch';
  299. var INPUT_TYPE_PEN = 'pen';
  300. var INPUT_TYPE_MOUSE = 'mouse';
  301. var INPUT_TYPE_KINECT = 'kinect';
  302. var COMPUTE_INTERVAL = 25;
  303. var INPUT_START = 1;
  304. var INPUT_MOVE = 2;
  305. var INPUT_END = 4;
  306. var INPUT_CANCEL = 8;
  307. var DIRECTION_NONE = 1;
  308. var DIRECTION_LEFT = 2;
  309. var DIRECTION_RIGHT = 4;
  310. var DIRECTION_UP = 8;
  311. var DIRECTION_DOWN = 16;
  312. var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
  313. var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
  314. var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
  315. var PROPS_XY = ['x', 'y'];
  316. var PROPS_CLIENT_XY = ['clientX', 'clientY'];
  317. /**
  318. * create new input type manager
  319. * @param {Manager} manager
  320. * @param {Function} callback
  321. * @returns {Input}
  322. * @constructor
  323. */
  324. function Input(manager, callback) {
  325. var self = this;
  326. this.manager = manager;
  327. this.callback = callback;
  328. this.element = manager.element;
  329. this.target = manager.options.inputTarget;
  330. // smaller wrapper around the handler, for the scope and the enabled state of the manager,
  331. // so when disabled the input events are completely bypassed.
  332. this.domHandler = function(ev) {
  333. if (boolOrFn(manager.options.enable, [manager])) {
  334. self.handler(ev);
  335. }
  336. };
  337. this.init();
  338. }
  339. Input.prototype = {
  340. /**
  341. * should handle the inputEvent data and trigger the callback
  342. * @virtual
  343. */
  344. handler: function() { },
  345. /**
  346. * bind the events
  347. */
  348. init: function() {
  349. this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
  350. this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
  351. this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  352. },
  353. /**
  354. * unbind the events
  355. */
  356. destroy: function() {
  357. this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
  358. this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
  359. this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  360. }
  361. };
  362. /**
  363. * create new input type manager
  364. * called by the Manager constructor
  365. * @param {Hammer} manager
  366. * @returns {Input}
  367. */
  368. function createInputInstance(manager) {
  369. var Type;
  370. var inputClass = manager.options.inputClass;
  371. if (inputClass) {
  372. Type = inputClass;
  373. } else if (SUPPORT_POINTER_EVENTS) {
  374. Type = PointerEventInput;
  375. } else if (SUPPORT_ONLY_TOUCH) {
  376. Type = TouchInput;
  377. } else if (!SUPPORT_TOUCH) {
  378. Type = MouseInput;
  379. } else {
  380. Type = TouchMouseInput;
  381. }
  382. return new (Type)(manager, inputHandler);
  383. }
  384. /**
  385. * handle input events
  386. * @param {Manager} manager
  387. * @param {String} eventType
  388. * @param {Object} input
  389. */
  390. function inputHandler(manager, eventType, input) {
  391. var pointersLen = input.pointers.length;
  392. var changedPointersLen = input.changedPointers.length;
  393. var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
  394. var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
  395. input.isFirst = !!isFirst;
  396. input.isFinal = !!isFinal;
  397. if (isFirst) {
  398. manager.session = {};
  399. }
  400. // source event is the normalized value of the domEvents
  401. // like 'touchstart, mouseup, pointerdown'
  402. input.eventType = eventType;
  403. // compute scale, rotation etc
  404. computeInputData(manager, input);
  405. // emit secret event
  406. manager.emit('hammer.input', input);
  407. manager.recognize(input);
  408. manager.session.prevInput = input;
  409. }
  410. /**
  411. * extend the data with some usable properties like scale, rotate, velocity etc
  412. * @param {Object} manager
  413. * @param {Object} input
  414. */
  415. function computeInputData(manager, input) {
  416. var session = manager.session;
  417. var pointers = input.pointers;
  418. var pointersLength = pointers.length;
  419. // store the first input to calculate the distance and direction
  420. if (!session.firstInput) {
  421. session.firstInput = simpleCloneInputData(input);
  422. }
  423. // to compute scale and rotation we need to store the multiple touches
  424. if (pointersLength > 1 && !session.firstMultiple) {
  425. session.firstMultiple = simpleCloneInputData(input);
  426. } else if (pointersLength === 1) {
  427. session.firstMultiple = false;
  428. }
  429. var firstInput = session.firstInput;
  430. var firstMultiple = session.firstMultiple;
  431. var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
  432. var center = input.center = getCenter(pointers);
  433. input.timeStamp = now();
  434. input.deltaTime = input.timeStamp - firstInput.timeStamp;
  435. input.angle = getAngle(offsetCenter, center);
  436. input.distance = getDistance(offsetCenter, center);
  437. computeDeltaXY(session, input);
  438. input.offsetDirection = getDirection(input.deltaX, input.deltaY);
  439. input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
  440. input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
  441. computeIntervalInputData(session, input);
  442. // find the correct target
  443. var target = manager.element;
  444. if (hasParent(input.srcEvent.target, target)) {
  445. target = input.srcEvent.target;
  446. }
  447. input.target = target;
  448. }
  449. function computeDeltaXY(session, input) {
  450. var center = input.center;
  451. var offset = session.offsetDelta || {};
  452. var prevDelta = session.prevDelta || {};
  453. var prevInput = session.prevInput || {};
  454. if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
  455. prevDelta = session.prevDelta = {
  456. x: prevInput.deltaX || 0,
  457. y: prevInput.deltaY || 0
  458. };
  459. offset = session.offsetDelta = {
  460. x: center.x,
  461. y: center.y
  462. };
  463. }
  464. input.deltaX = prevDelta.x + (center.x - offset.x);
  465. input.deltaY = prevDelta.y + (center.y - offset.y);
  466. }
  467. /**
  468. * velocity is calculated every x ms
  469. * @param {Object} session
  470. * @param {Object} input
  471. */
  472. function computeIntervalInputData(session, input) {
  473. var last = session.lastInterval || input,
  474. deltaTime = input.timeStamp - last.timeStamp,
  475. velocity, velocityX, velocityY, direction;
  476. if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
  477. var deltaX = last.deltaX - input.deltaX;
  478. var deltaY = last.deltaY - input.deltaY;
  479. var v = getVelocity(deltaTime, deltaX, deltaY);
  480. velocityX = v.x;
  481. velocityY = v.y;
  482. velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
  483. direction = getDirection(deltaX, deltaY);
  484. session.lastInterval = input;
  485. } else {
  486. // use latest velocity info if it doesn't overtake a minimum period
  487. velocity = last.velocity;
  488. velocityX = last.velocityX;
  489. velocityY = last.velocityY;
  490. direction = last.direction;
  491. }
  492. input.velocity = velocity;
  493. input.velocityX = velocityX;
  494. input.velocityY = velocityY;
  495. input.direction = direction;
  496. }
  497. /**
  498. * create a simple clone from the input used for storage of firstInput and firstMultiple
  499. * @param {Object} input
  500. * @returns {Object} clonedInputData
  501. */
  502. function simpleCloneInputData(input) {
  503. // make a simple copy of the pointers because we will get a reference if we don't
  504. // we only need clientXY for the calculations
  505. var pointers = [];
  506. var i = 0;
  507. while (i < input.pointers.length) {
  508. pointers[i] = {
  509. clientX: round(input.pointers[i].clientX),
  510. clientY: round(input.pointers[i].clientY)
  511. };
  512. i++;
  513. }
  514. return {
  515. timeStamp: now(),
  516. pointers: pointers,
  517. center: getCenter(pointers),
  518. deltaX: input.deltaX,
  519. deltaY: input.deltaY
  520. };
  521. }
  522. /**
  523. * get the center of all the pointers
  524. * @param {Array} pointers
  525. * @return {Object} center contains `x` and `y` properties
  526. */
  527. function getCenter(pointers) {
  528. var pointersLength = pointers.length;
  529. // no need to loop when only one touch
  530. if (pointersLength === 1) {
  531. return {
  532. x: round(pointers[0].clientX),
  533. y: round(pointers[0].clientY)
  534. };
  535. }
  536. var x = 0, y = 0, i = 0;
  537. while (i < pointersLength) {
  538. x += pointers[i].clientX;
  539. y += pointers[i].clientY;
  540. i++;
  541. }
  542. return {
  543. x: round(x / pointersLength),
  544. y: round(y / pointersLength)
  545. };
  546. }
  547. /**
  548. * calculate the velocity between two points. unit is in px per ms.
  549. * @param {Number} deltaTime
  550. * @param {Number} x
  551. * @param {Number} y
  552. * @return {Object} velocity `x` and `y`
  553. */
  554. function getVelocity(deltaTime, x, y) {
  555. return {
  556. x: x / deltaTime || 0,
  557. y: y / deltaTime || 0
  558. };
  559. }
  560. /**
  561. * get the direction between two points
  562. * @param {Number} x
  563. * @param {Number} y
  564. * @return {Number} direction
  565. */
  566. function getDirection(x, y) {
  567. if (x === y) {
  568. return DIRECTION_NONE;
  569. }
  570. if (abs(x) >= abs(y)) {
  571. return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  572. }
  573. return y > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  574. }
  575. /**
  576. * calculate the absolute distance between two points
  577. * @param {Object} p1 {x, y}
  578. * @param {Object} p2 {x, y}
  579. * @param {Array} [props] containing x and y keys
  580. * @return {Number} distance
  581. */
  582. function getDistance(p1, p2, props) {
  583. if (!props) {
  584. props = PROPS_XY;
  585. }
  586. var x = p2[props[0]] - p1[props[0]],
  587. y = p2[props[1]] - p1[props[1]];
  588. return Math.sqrt((x * x) + (y * y));
  589. }
  590. /**
  591. * calculate the angle between two coordinates
  592. * @param {Object} p1
  593. * @param {Object} p2
  594. * @param {Array} [props] containing x and y keys
  595. * @return {Number} angle
  596. */
  597. function getAngle(p1, p2, props) {
  598. if (!props) {
  599. props = PROPS_XY;
  600. }
  601. var x = p2[props[0]] - p1[props[0]],
  602. y = p2[props[1]] - p1[props[1]];
  603. return Math.atan2(y, x) * 180 / Math.PI;
  604. }
  605. /**
  606. * calculate the rotation degrees between two pointersets
  607. * @param {Array} start array of pointers
  608. * @param {Array} end array of pointers
  609. * @return {Number} rotation
  610. */
  611. function getRotation(start, end) {
  612. return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY);
  613. }
  614. /**
  615. * calculate the scale factor between two pointersets
  616. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  617. * @param {Array} start array of pointers
  618. * @param {Array} end array of pointers
  619. * @return {Number} scale
  620. */
  621. function getScale(start, end) {
  622. return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
  623. }
  624. var MOUSE_INPUT_MAP = {
  625. mousedown: INPUT_START,
  626. mousemove: INPUT_MOVE,
  627. mouseup: INPUT_END
  628. };
  629. var MOUSE_ELEMENT_EVENTS = 'mousedown';
  630. var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
  631. /**
  632. * Mouse events input
  633. * @constructor
  634. * @extends Input
  635. */
  636. function MouseInput() {
  637. this.evEl = MOUSE_ELEMENT_EVENTS;
  638. this.evWin = MOUSE_WINDOW_EVENTS;
  639. this.allow = true; // used by Input.TouchMouse to disable mouse events
  640. this.pressed = false; // mousedown state
  641. Input.apply(this, arguments);
  642. }
  643. inherit(MouseInput, Input, {
  644. /**
  645. * handle mouse events
  646. * @param {Object} ev
  647. */
  648. handler: function MEhandler(ev) {
  649. var eventType = MOUSE_INPUT_MAP[ev.type];
  650. // on start we want to have the left mouse button down
  651. if (eventType & INPUT_START && ev.button === 0) {
  652. this.pressed = true;
  653. }
  654. if (eventType & INPUT_MOVE && ev.which !== 1) {
  655. eventType = INPUT_END;
  656. }
  657. // mouse must be down, and mouse events are allowed (see the TouchMouse input)
  658. if (!this.pressed || !this.allow) {
  659. return;
  660. }
  661. if (eventType & INPUT_END) {
  662. this.pressed = false;
  663. }
  664. this.callback(this.manager, eventType, {
  665. pointers: [ev],
  666. changedPointers: [ev],
  667. pointerType: INPUT_TYPE_MOUSE,
  668. srcEvent: ev
  669. });
  670. }
  671. });
  672. var POINTER_INPUT_MAP = {
  673. pointerdown: INPUT_START,
  674. pointermove: INPUT_MOVE,
  675. pointerup: INPUT_END,
  676. pointercancel: INPUT_CANCEL,
  677. pointerout: INPUT_CANCEL
  678. };
  679. // in IE10 the pointer types is defined as an enum
  680. var IE10_POINTER_TYPE_ENUM = {
  681. 2: INPUT_TYPE_TOUCH,
  682. 3: INPUT_TYPE_PEN,
  683. 4: INPUT_TYPE_MOUSE,
  684. 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
  685. };
  686. var POINTER_ELEMENT_EVENTS = 'pointerdown';
  687. var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
  688. // IE10 has prefixed support, and case-sensitive
  689. if (window.MSPointerEvent) {
  690. POINTER_ELEMENT_EVENTS = 'MSPointerDown';
  691. POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
  692. }
  693. /**
  694. * Pointer events input
  695. * @constructor
  696. * @extends Input
  697. */
  698. function PointerEventInput() {
  699. this.evEl = POINTER_ELEMENT_EVENTS;
  700. this.evWin = POINTER_WINDOW_EVENTS;
  701. Input.apply(this, arguments);
  702. this.store = (this.manager.session.pointerEvents = []);
  703. }
  704. inherit(PointerEventInput, Input, {
  705. /**
  706. * handle mouse events
  707. * @param {Object} ev
  708. */
  709. handler: function PEhandler(ev) {
  710. var store = this.store;
  711. var removePointer = false;
  712. var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
  713. var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
  714. var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
  715. var isTouch = (pointerType == INPUT_TYPE_TOUCH);
  716. // get index of the event in the store
  717. var storeIndex = inArray(store, ev.pointerId, 'pointerId');
  718. // start and mouse must be down
  719. if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
  720. if (storeIndex < 0) {
  721. store.push(ev);
  722. storeIndex = store.length - 1;
  723. }
  724. } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
  725. removePointer = true;
  726. }
  727. // it not found, so the pointer hasn't been down (so it's probably a hover)
  728. if (storeIndex < 0) {
  729. return;
  730. }
  731. // update the event in the store
  732. store[storeIndex] = ev;
  733. this.callback(this.manager, eventType, {
  734. pointers: store,
  735. changedPointers: [ev],
  736. pointerType: pointerType,
  737. srcEvent: ev
  738. });
  739. if (removePointer) {
  740. // remove from the store
  741. store.splice(storeIndex, 1);
  742. }
  743. }
  744. });
  745. var SINGLE_TOUCH_INPUT_MAP = {
  746. touchstart: INPUT_START,
  747. touchmove: INPUT_MOVE,
  748. touchend: INPUT_END,
  749. touchcancel: INPUT_CANCEL
  750. };
  751. var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
  752. var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
  753. /**
  754. * Touch events input
  755. * @constructor
  756. * @extends Input
  757. */
  758. function SingleTouchInput() {
  759. this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
  760. this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
  761. this.started = false;
  762. Input.apply(this, arguments);
  763. }
  764. inherit(SingleTouchInput, Input, {
  765. handler: function TEhandler(ev) {
  766. var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
  767. // should we handle the touch events?
  768. if (type === INPUT_START) {
  769. this.started = true;
  770. }
  771. if (!this.started) {
  772. return;
  773. }
  774. var touches = normalizeSingleTouches.call(this, ev, type);
  775. // when done, reset the started state
  776. if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
  777. this.started = false;
  778. }
  779. this.callback(this.manager, type, {
  780. pointers: touches[0],
  781. changedPointers: touches[1],
  782. pointerType: INPUT_TYPE_TOUCH,
  783. srcEvent: ev
  784. });
  785. }
  786. });
  787. /**
  788. * @this {TouchInput}
  789. * @param {Object} ev
  790. * @param {Number} type flag
  791. * @returns {undefined|Array} [all, changed]
  792. */
  793. function normalizeSingleTouches(ev, type) {
  794. var all = toArray(ev.touches);
  795. var changed = toArray(ev.changedTouches);
  796. if (type & (INPUT_END | INPUT_CANCEL)) {
  797. all = uniqueArray(all.concat(changed), 'identifier', true);
  798. }
  799. return [all, changed];
  800. }
  801. var TOUCH_INPUT_MAP = {
  802. touchstart: INPUT_START,
  803. touchmove: INPUT_MOVE,
  804. touchend: INPUT_END,
  805. touchcancel: INPUT_CANCEL
  806. };
  807. var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
  808. /**
  809. * Multi-user touch events input
  810. * @constructor
  811. * @extends Input
  812. */
  813. function TouchInput() {
  814. this.evTarget = TOUCH_TARGET_EVENTS;
  815. this.targetIds = {};
  816. Input.apply(this, arguments);
  817. }
  818. inherit(TouchInput, Input, {
  819. handler: function MTEhandler(ev) {
  820. var type = TOUCH_INPUT_MAP[ev.type];
  821. var touches = getTouches.call(this, ev, type);
  822. if (!touches) {
  823. return;
  824. }
  825. this.callback(this.manager, type, {
  826. pointers: touches[0],
  827. changedPointers: touches[1],
  828. pointerType: INPUT_TYPE_TOUCH,
  829. srcEvent: ev
  830. });
  831. }
  832. });
  833. /**
  834. * @this {TouchInput}
  835. * @param {Object} ev
  836. * @param {Number} type flag
  837. * @returns {undefined|Array} [all, changed]
  838. */
  839. function getTouches(ev, type) {
  840. var allTouches = toArray(ev.touches);
  841. var targetIds = this.targetIds;
  842. // when there is only one touch, the process can be simplified
  843. if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
  844. targetIds[allTouches[0].identifier] = true;
  845. return [allTouches, allTouches];
  846. }
  847. var i,
  848. targetTouches,
  849. changedTouches = toArray(ev.changedTouches),
  850. changedTargetTouches = [],
  851. target = this.target;
  852. // get target touches from touches
  853. targetTouches = allTouches.filter(function(touch) {
  854. return hasParent(touch.target, target);
  855. });
  856. // collect touches
  857. if (type === INPUT_START) {
  858. i = 0;
  859. while (i < targetTouches.length) {
  860. targetIds[targetTouches[i].identifier] = true;
  861. i++;
  862. }
  863. }
  864. // filter changed touches to only contain touches that exist in the collected target ids
  865. i = 0;
  866. while (i < changedTouches.length) {
  867. if (targetIds[changedTouches[i].identifier]) {
  868. changedTargetTouches.push(changedTouches[i]);
  869. }
  870. // cleanup removed touches
  871. if (type & (INPUT_END | INPUT_CANCEL)) {
  872. delete targetIds[changedTouches[i].identifier];
  873. }
  874. i++;
  875. }
  876. if (!changedTargetTouches.length) {
  877. return;
  878. }
  879. return [
  880. // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
  881. uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
  882. changedTargetTouches
  883. ];
  884. }
  885. /**
  886. * Combined touch and mouse input
  887. *
  888. * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
  889. * This because touch devices also emit mouse events while doing a touch.
  890. *
  891. * @constructor
  892. * @extends Input
  893. */
  894. function TouchMouseInput() {
  895. Input.apply(this, arguments);
  896. var handler = bindFn(this.handler, this);
  897. this.touch = new TouchInput(this.manager, handler);
  898. this.mouse = new MouseInput(this.manager, handler);
  899. }
  900. inherit(TouchMouseInput, Input, {
  901. /**
  902. * handle mouse and touch events
  903. * @param {Hammer} manager
  904. * @param {String} inputEvent
  905. * @param {Object} inputData
  906. */
  907. handler: function TMEhandler(manager, inputEvent, inputData) {
  908. var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
  909. isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
  910. // when we're in a touch event, so block all upcoming mouse events
  911. // most mobile browser also emit mouseevents, right after touchstart
  912. if (isTouch) {
  913. this.mouse.allow = false;
  914. } else if (isMouse && !this.mouse.allow) {
  915. return;
  916. }
  917. // reset the allowMouse when we're done
  918. if (inputEvent & (INPUT_END | INPUT_CANCEL)) {
  919. this.mouse.allow = true;
  920. }
  921. this.callback(manager, inputEvent, inputData);
  922. },
  923. /**
  924. * remove the event listeners
  925. */
  926. destroy: function destroy() {
  927. this.touch.destroy();
  928. this.mouse.destroy();
  929. }
  930. });
  931. var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
  932. var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
  933. // magical touchAction value
  934. var TOUCH_ACTION_COMPUTE = 'compute';
  935. var TOUCH_ACTION_AUTO = 'auto';
  936. var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
  937. var TOUCH_ACTION_NONE = 'none';
  938. var TOUCH_ACTION_PAN_X = 'pan-x';
  939. var TOUCH_ACTION_PAN_Y = 'pan-y';
  940. /**
  941. * Touch Action
  942. * sets the touchAction property or uses the js alternative
  943. * @param {Manager} manager
  944. * @param {String} value
  945. * @constructor
  946. */
  947. function TouchAction(manager, value) {
  948. this.manager = manager;
  949. this.set(value);
  950. }
  951. TouchAction.prototype = {
  952. /**
  953. * set the touchAction value on the element or enable the polyfill
  954. * @param {String} value
  955. */
  956. set: function(value) {
  957. // find out the touch-action by the event handlers
  958. if (value == TOUCH_ACTION_COMPUTE) {
  959. value = this.compute();
  960. }
  961. if (NATIVE_TOUCH_ACTION) {
  962. this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
  963. }
  964. this.actions = value.toLowerCase().trim();
  965. },
  966. /**
  967. * just re-set the touchAction value
  968. */
  969. update: function() {
  970. this.set(this.manager.options.touchAction);
  971. },
  972. /**
  973. * compute the value for the touchAction property based on the recognizer's settings
  974. * @returns {String} value
  975. */
  976. compute: function() {
  977. var actions = [];
  978. each(this.manager.recognizers, function(recognizer) {
  979. if (boolOrFn(recognizer.options.enable, [recognizer])) {
  980. actions = actions.concat(recognizer.getTouchAction());
  981. }
  982. });
  983. return cleanTouchActions(actions.join(' '));
  984. },
  985. /**
  986. * this method is called on each input cycle and provides the preventing of the browser behavior
  987. * @param {Object} input
  988. */
  989. preventDefaults: function(input) {
  990. // not needed with native support for the touchAction property
  991. if (NATIVE_TOUCH_ACTION) {
  992. return;
  993. }
  994. var srcEvent = input.srcEvent;
  995. var direction = input.offsetDirection;
  996. // if the touch action did prevented once this session
  997. if (this.manager.session.prevented) {
  998. srcEvent.preventDefault();
  999. return;
  1000. }
  1001. var actions = this.actions;
  1002. var hasNone = inStr(actions, TOUCH_ACTION_NONE);
  1003. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  1004. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  1005. if (hasNone ||
  1006. (hasPanY && direction & DIRECTION_HORIZONTAL) ||
  1007. (hasPanX && direction & DIRECTION_VERTICAL)) {
  1008. return this.preventSrc(srcEvent);
  1009. }
  1010. },
  1011. /**
  1012. * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
  1013. * @param {Object} srcEvent
  1014. */
  1015. preventSrc: function(srcEvent) {
  1016. this.manager.session.prevented = true;
  1017. srcEvent.preventDefault();
  1018. }
  1019. };
  1020. /**
  1021. * when the touchActions are collected they are not a valid value, so we need to clean things up. *
  1022. * @param {String} actions
  1023. * @returns {*}
  1024. */
  1025. function cleanTouchActions(actions) {
  1026. // none
  1027. if (inStr(actions, TOUCH_ACTION_NONE)) {
  1028. return TOUCH_ACTION_NONE;
  1029. }
  1030. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  1031. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  1032. // pan-x and pan-y can be combined
  1033. if (hasPanX && hasPanY) {
  1034. return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y;
  1035. }
  1036. // pan-x OR pan-y
  1037. if (hasPanX || hasPanY) {
  1038. return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
  1039. }
  1040. // manipulation
  1041. if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
  1042. return TOUCH_ACTION_MANIPULATION;
  1043. }
  1044. return TOUCH_ACTION_AUTO;
  1045. }
  1046. /**
  1047. * Recognizer flow explained; *
  1048. * All recognizers have the initial state of POSSIBLE when a input session starts.
  1049. * The definition of a input session is from the first input until the last input, with all it's movement in it. *
  1050. * Example session for mouse-input: mousedown -> mousemove -> mouseup
  1051. *
  1052. * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
  1053. * which determines with state it should be.
  1054. *
  1055. * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
  1056. * POSSIBLE to give it another change on the next cycle.
  1057. *
  1058. * Possible
  1059. * |
  1060. * +-----+---------------+
  1061. * | |
  1062. * +-----+-----+ |
  1063. * | | |
  1064. * Failed Cancelled |
  1065. * +-------+------+
  1066. * | |
  1067. * Recognized Began
  1068. * |
  1069. * Changed
  1070. * |
  1071. * Ended/Recognized
  1072. */
  1073. var STATE_POSSIBLE = 1;
  1074. var STATE_BEGAN = 2;
  1075. var STATE_CHANGED = 4;
  1076. var STATE_ENDED = 8;
  1077. var STATE_RECOGNIZED = STATE_ENDED;
  1078. var STATE_CANCELLED = 16;
  1079. var STATE_FAILED = 32;
  1080. /**
  1081. * Recognizer
  1082. * Every recognizer needs to extend from this class.
  1083. * @constructor
  1084. * @param {Object} options
  1085. */
  1086. function Recognizer(options) {
  1087. this.id = uniqueId();
  1088. this.manager = null;
  1089. this.options = merge(options || {}, this.defaults);
  1090. // default is enable true
  1091. this.options.enable = ifUndefined(this.options.enable, true);
  1092. this.state = STATE_POSSIBLE;
  1093. this.simultaneous = {};
  1094. this.requireFail = [];
  1095. }
  1096. Recognizer.prototype = {
  1097. /**
  1098. * @virtual
  1099. * @type {Object}
  1100. */
  1101. defaults: {},
  1102. /**
  1103. * set options
  1104. * @param {Object} options
  1105. * @return {Recognizer}
  1106. */
  1107. set: function(options) {
  1108. extend(this.options, options);
  1109. // also update the touchAction, in case something changed about the directions/enabled state
  1110. this.manager && this.manager.touchAction.update();
  1111. return this;
  1112. },
  1113. /**
  1114. * recognize simultaneous with an other recognizer.
  1115. * @param {Recognizer} otherRecognizer
  1116. * @returns {Recognizer} this
  1117. */
  1118. recognizeWith: function(otherRecognizer) {
  1119. if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
  1120. return this;
  1121. }
  1122. var simultaneous = this.simultaneous;
  1123. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  1124. if (!simultaneous[otherRecognizer.id]) {
  1125. simultaneous[otherRecognizer.id] = otherRecognizer;
  1126. otherRecognizer.recognizeWith(this);
  1127. }
  1128. return this;
  1129. },
  1130. /**
  1131. * drop the simultaneous link. it doesnt remove the link on the other recognizer.
  1132. * @param {Recognizer} otherRecognizer
  1133. * @returns {Recognizer} this
  1134. */
  1135. dropRecognizeWith: function(otherRecognizer) {
  1136. if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
  1137. return this;
  1138. }
  1139. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  1140. delete this.simultaneous[otherRecognizer.id];
  1141. return this;
  1142. },
  1143. /**
  1144. * recognizer can only run when an other is failing
  1145. * @param {Recognizer} otherRecognizer
  1146. * @returns {Recognizer} this
  1147. */
  1148. requireFailure: function(otherRecognizer) {
  1149. if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
  1150. return this;
  1151. }
  1152. var requireFail = this.requireFail;
  1153. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  1154. if (inArray(requireFail, otherRecognizer) === -1) {
  1155. requireFail.push(otherRecognizer);
  1156. otherRecognizer.requireFailure(this);
  1157. }
  1158. return this;
  1159. },
  1160. /**
  1161. * drop the requireFailure link. it does not remove the link on the other recognizer.
  1162. * @param {Recognizer} otherRecognizer
  1163. * @returns {Recognizer} this
  1164. */
  1165. dropRequireFailure: function(otherRecognizer) {
  1166. if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
  1167. return this;
  1168. }
  1169. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  1170. var index = inArray(this.requireFail, otherRecognizer);
  1171. if (index > -1) {
  1172. this.requireFail.splice(index, 1);
  1173. }
  1174. return this;
  1175. },
  1176. /**
  1177. * has require failures boolean
  1178. * @returns {boolean}
  1179. */
  1180. hasRequireFailures: function() {
  1181. return this.requireFail.length > 0;
  1182. },
  1183. /**
  1184. * if the recognizer can recognize simultaneous with an other recognizer
  1185. * @param {Recognizer} otherRecognizer
  1186. * @returns {Boolean}
  1187. */
  1188. canRecognizeWith: function(otherRecognizer) {
  1189. return !!this.simultaneous[otherRecognizer.id];
  1190. },
  1191. /**
  1192. * You should use `tryEmit` instead of `emit` directly to check
  1193. * that all the needed recognizers has failed before emitting.
  1194. * @param {Object} input
  1195. */
  1196. emit: function(input) {
  1197. var self = this;
  1198. var state = this.state;
  1199. function emit(withState) {
  1200. self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input);
  1201. }
  1202. // 'panstart' and 'panmove'
  1203. if (state < STATE_ENDED) {
  1204. emit(true);
  1205. }
  1206. emit(); // simple 'eventName' events
  1207. // panend and pancancel
  1208. if (state >= STATE_ENDED) {
  1209. emit(true);
  1210. }
  1211. },
  1212. /**
  1213. * Check that all the require failure recognizers has failed,
  1214. * if true, it emits a gesture event,
  1215. * otherwise, setup the state to FAILED.
  1216. * @param {Object} input
  1217. */
  1218. tryEmit: function(input) {
  1219. if (this.canEmit()) {
  1220. return this.emit(input);
  1221. }
  1222. // it's failing anyway
  1223. this.state = STATE_FAILED;
  1224. },
  1225. /**
  1226. * can we emit?
  1227. * @returns {boolean}
  1228. */
  1229. canEmit: function() {
  1230. var i = 0;
  1231. while (i < this.requireFail.length) {
  1232. if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
  1233. return false;
  1234. }
  1235. i++;
  1236. }
  1237. return true;
  1238. },
  1239. /**
  1240. * update the recognizer
  1241. * @param {Object} inputData
  1242. */
  1243. recognize: function(inputData) {
  1244. // make a new copy of the inputData
  1245. // so we can change the inputData without messing up the other recognizers
  1246. var inputDataClone = extend({}, inputData);
  1247. // is is enabled and allow recognizing?
  1248. if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
  1249. this.reset();
  1250. this.state = STATE_FAILED;
  1251. return;
  1252. }
  1253. // reset when we've reached the end
  1254. if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
  1255. this.state = STATE_POSSIBLE;
  1256. }
  1257. this.state = this.process(inputDataClone);
  1258. // the recognizer has recognized a gesture
  1259. // so trigger an event
  1260. if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
  1261. this.tryEmit(inputDataClone);
  1262. }
  1263. },
  1264. /**
  1265. * return the state of the recognizer
  1266. * the actual recognizing happens in this method
  1267. * @virtual
  1268. * @param {Object} inputData
  1269. * @returns {Const} STATE
  1270. */
  1271. process: function(inputData) { }, // jshint ignore:line
  1272. /**
  1273. * return the preferred touch-action
  1274. * @virtual
  1275. * @returns {Array}
  1276. */
  1277. getTouchAction: function() { },
  1278. /**
  1279. * called when the gesture isn't allowed to recognize
  1280. * like when another is being recognized or it is disabled
  1281. * @virtual
  1282. */
  1283. reset: function() { }
  1284. };
  1285. /**
  1286. * get a usable string, used as event postfix
  1287. * @param {Const} state
  1288. * @returns {String} state
  1289. */
  1290. function stateStr(state) {
  1291. if (state & STATE_CANCELLED) {
  1292. return 'cancel';
  1293. } else if (state & STATE_ENDED) {
  1294. return 'end';
  1295. } else if (state & STATE_CHANGED) {
  1296. return 'move';
  1297. } else if (state & STATE_BEGAN) {
  1298. return 'start';
  1299. }
  1300. return '';
  1301. }
  1302. /**
  1303. * direction cons to string
  1304. * @param {Const} direction
  1305. * @returns {String}
  1306. */
  1307. function directionStr(direction) {
  1308. if (direction == DIRECTION_DOWN) {
  1309. return 'down';
  1310. } else if (direction == DIRECTION_UP) {
  1311. return 'up';
  1312. } else if (direction == DIRECTION_LEFT) {
  1313. return 'left';
  1314. } else if (direction == DIRECTION_RIGHT) {
  1315. return 'right';
  1316. }
  1317. return '';
  1318. }
  1319. /**
  1320. * get a recognizer by name if it is bound to a manager
  1321. * @param {Recognizer|String} otherRecognizer
  1322. * @param {Recognizer} recognizer
  1323. * @returns {Recognizer}
  1324. */
  1325. function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
  1326. var manager = recognizer.manager;
  1327. if (manager) {
  1328. return manager.get(otherRecognizer);
  1329. }
  1330. return otherRecognizer;
  1331. }
  1332. /**
  1333. * This recognizer is just used as a base for the simple attribute recognizers.
  1334. * @constructor
  1335. * @extends Recognizer
  1336. */
  1337. function AttrRecognizer() {
  1338. Recognizer.apply(this, arguments);
  1339. }
  1340. inherit(AttrRecognizer, Recognizer, {
  1341. /**
  1342. * @namespace
  1343. * @memberof AttrRecognizer
  1344. */
  1345. defaults: {
  1346. /**
  1347. * @type {Number}
  1348. * @default 1
  1349. */
  1350. pointers: 1
  1351. },
  1352. /**
  1353. * Used to check if it the recognizer receives valid input, like input.distance > 10.
  1354. * @memberof AttrRecognizer
  1355. * @param {Object} input
  1356. * @returns {Boolean} recognized
  1357. */
  1358. attrTest: function(input) {
  1359. var optionPointers = this.options.pointers;
  1360. return optionPointers === 0 || input.pointers.length === optionPointers;
  1361. },
  1362. /**
  1363. * Process the input and return the state for the recognizer
  1364. * @memberof AttrRecognizer
  1365. * @param {Object} input
  1366. * @returns {*} State
  1367. */
  1368. process: function(input) {
  1369. var state = this.state;
  1370. var eventType = input.eventType;
  1371. var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
  1372. var isValid = this.attrTest(input);
  1373. // on cancel input and we've recognized before, return STATE_CANCELLED
  1374. if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
  1375. return state | STATE_CANCELLED;
  1376. } else if (isRecognized || isValid) {
  1377. if (eventType & INPUT_END) {
  1378. return state | STATE_ENDED;
  1379. } else if (!(state & STATE_BEGAN)) {
  1380. return STATE_BEGAN;
  1381. }
  1382. return state | STATE_CHANGED;
  1383. }
  1384. return STATE_FAILED;
  1385. }
  1386. });
  1387. /**
  1388. * Pan
  1389. * Recognized when the pointer is down and moved in the allowed direction.
  1390. * @constructor
  1391. * @extends AttrRecognizer
  1392. */
  1393. function PanRecognizer() {
  1394. AttrRecognizer.apply(this, arguments);
  1395. this.pX = null;
  1396. this.pY = null;
  1397. }
  1398. inherit(PanRecognizer, AttrRecognizer, {
  1399. /**
  1400. * @namespace
  1401. * @memberof PanRecognizer
  1402. */
  1403. defaults: {
  1404. event: 'pan',
  1405. threshold: 10,
  1406. pointers: 1,
  1407. direction: DIRECTION_ALL
  1408. },
  1409. getTouchAction: function() {
  1410. var direction = this.options.direction;
  1411. var actions = [];
  1412. if (direction & DIRECTION_HORIZONTAL) {
  1413. actions.push(TOUCH_ACTION_PAN_Y);
  1414. }
  1415. if (direction & DIRECTION_VERTICAL) {
  1416. actions.push(TOUCH_ACTION_PAN_X);
  1417. }
  1418. return actions;
  1419. },
  1420. directionTest: function(input) {
  1421. var options = this.options;
  1422. var hasMoved = true;
  1423. var distance = input.distance;
  1424. var direction = input.direction;
  1425. var x = input.deltaX;
  1426. var y = input.deltaY;
  1427. // lock to axis?
  1428. if (!(direction & options.direction)) {
  1429. if (options.direction & DIRECTION_HORIZONTAL) {
  1430. direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
  1431. hasMoved = x != this.pX;
  1432. distance = Math.abs(input.deltaX);
  1433. } else {
  1434. direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
  1435. hasMoved = y != this.pY;
  1436. distance = Math.abs(input.deltaY);
  1437. }
  1438. }
  1439. input.direction = direction;
  1440. return hasMoved && distance > options.threshold && direction & options.direction;
  1441. },
  1442. attrTest: function(input) {
  1443. return AttrRecognizer.prototype.attrTest.call(this, input) &&
  1444. (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
  1445. },
  1446. emit: function(input) {
  1447. this.pX = input.deltaX;
  1448. this.pY = input.deltaY;
  1449. var direction = directionStr(input.direction);
  1450. if (direction) {
  1451. this.manager.emit(this.options.event + direction, input);
  1452. }
  1453. this._super.emit.call(this, input);
  1454. },
  1455. reset:function(){
  1456. }
  1457. });
  1458. /**
  1459. * Pinch
  1460. * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
  1461. * @constructor
  1462. * @extends AttrRecognizer
  1463. */
  1464. function PinchRecognizer() {
  1465. AttrRecognizer.apply(this, arguments);
  1466. }
  1467. inherit(PinchRecognizer, AttrRecognizer, {
  1468. /**
  1469. * @namespace
  1470. * @memberof PinchRecognizer
  1471. */
  1472. defaults: {
  1473. event: 'pinch',
  1474. threshold: 0,
  1475. pointers: 2
  1476. },
  1477. getTouchAction: function() {
  1478. return [TOUCH_ACTION_NONE];
  1479. },
  1480. attrTest: function(input) {
  1481. return this._super.attrTest.call(this, input) &&
  1482. (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
  1483. },
  1484. emit: function(input) {
  1485. this._super.emit.call(this, input);
  1486. if (input.scale !== 1) {
  1487. var inOut = input.scale < 1 ? 'in' : 'out';
  1488. this.manager.emit(this.options.event + inOut, input);
  1489. }
  1490. }
  1491. });
  1492. /**
  1493. * Press
  1494. * Recognized when the pointer is down for x ms without any movement.
  1495. * @constructor
  1496. * @extends Recognizer
  1497. */
  1498. function PressRecognizer() {
  1499. Recognizer.apply(this, arguments);
  1500. this._timer = null;
  1501. this._input = null;
  1502. }
  1503. inherit(PressRecognizer, Recognizer, {
  1504. /**
  1505. * @namespace
  1506. * @memberof PressRecognizer
  1507. */
  1508. defaults: {
  1509. event: 'press',
  1510. pointers: 1,
  1511. time: 500, // minimal time of the pointer to be pressed
  1512. threshold: 5 // a minimal movement is ok, but keep it low
  1513. },
  1514. getTouchAction: function() {
  1515. return [TOUCH_ACTION_AUTO];
  1516. },
  1517. process: function(input) {
  1518. var options = this.options;
  1519. var validPointers = input.pointers.length === options.pointers;
  1520. var validMovement = input.distance < options.threshold;
  1521. var validTime = input.deltaTime > options.time;
  1522. this._input = input;
  1523. // we only allow little movement
  1524. // and we've reached an end event, so a tap is possible
  1525. if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
  1526. this.reset();
  1527. } else if (input.eventType & INPUT_START) {
  1528. this.reset();
  1529. this._timer = setTimeoutContext(function() {
  1530. this.state = STATE_RECOGNIZED;
  1531. this.tryEmit();
  1532. }, options.time, this);
  1533. } else if (input.eventType & INPUT_END) {
  1534. return STATE_RECOGNIZED;
  1535. }
  1536. return STATE_FAILED;
  1537. },
  1538. reset: function() {
  1539. clearTimeout(this._timer);
  1540. },
  1541. emit: function(input) {
  1542. if (this.state !== STATE_RECOGNIZED) {
  1543. return;
  1544. }
  1545. if (input && (input.eventType & INPUT_END)) {
  1546. this.manager.emit(this.options.event + 'up', input);
  1547. } else {
  1548. this._input.timeStamp = now();
  1549. this.manager.emit(this.options.event, this._input);
  1550. }
  1551. }
  1552. });
  1553. /**
  1554. * Rotate
  1555. * Recognized when two or more pointer are moving in a circular motion.
  1556. * @constructor
  1557. * @extends AttrRecognizer
  1558. */
  1559. function RotateRecognizer() {
  1560. AttrRecognizer.apply(this, arguments);
  1561. }
  1562. inherit(RotateRecognizer, AttrRecognizer, {
  1563. /**
  1564. * @namespace
  1565. * @memberof RotateRecognizer
  1566. */
  1567. defaults: {
  1568. event: 'rotate',
  1569. threshold: 0,
  1570. pointers: 2
  1571. },
  1572. getTouchAction: function() {
  1573. return [TOUCH_ACTION_NONE];
  1574. },
  1575. attrTest: function(input) {
  1576. return this._super.attrTest.call(this, input) &&
  1577. (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
  1578. }
  1579. });
  1580. /**
  1581. * Swipe
  1582. * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
  1583. * @constructor
  1584. * @extends AttrRecognizer
  1585. */
  1586. function SwipeRecognizer() {
  1587. AttrRecognizer.apply(this, arguments);
  1588. }
  1589. inherit(SwipeRecognizer, AttrRecognizer, {
  1590. /**
  1591. * @namespace
  1592. * @memberof SwipeRecognizer
  1593. */
  1594. defaults: {
  1595. event: 'swipe',
  1596. threshold: 10,
  1597. velocity: 0.65,
  1598. direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
  1599. pointers: 1
  1600. },
  1601. getTouchAction: function() {
  1602. return PanRecognizer.prototype.getTouchAction.call(this);
  1603. },
  1604. attrTest: function(input) {
  1605. var direction = this.options.direction;
  1606. var velocity;
  1607. if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
  1608. velocity = input.velocity;
  1609. } else if (direction & DIRECTION_HORIZONTAL) {
  1610. velocity = input.velocityX;
  1611. } else if (direction & DIRECTION_VERTICAL) {
  1612. velocity = input.velocityY;
  1613. }
  1614. return this._super.attrTest.call(this, input) &&
  1615. direction & input.direction &&
  1616. input.distance > this.options.threshold &&
  1617. abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
  1618. },
  1619. emit: function(input) {
  1620. var direction = directionStr(input.direction);
  1621. if (direction) {
  1622. this.manager.emit(this.options.event + direction, input);
  1623. }
  1624. this.manager.emit(this.options.event, input);
  1625. }
  1626. });
  1627. /**
  1628. * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
  1629. * between the given interval and position. The delay option can be used to recognize multi-taps without firing
  1630. * a single tap.
  1631. *
  1632. * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
  1633. * multi-taps being recognized.
  1634. * @constructor
  1635. * @extends Recognizer
  1636. */
  1637. function TapRecognizer() {
  1638. Recognizer.apply(this, arguments);
  1639. // previous time and center,
  1640. // used for tap counting
  1641. this.pTime = false;
  1642. this.pCenter = false;
  1643. this._timer = null;
  1644. this._input = null;
  1645. this.count = 0;
  1646. }
  1647. inherit(TapRecognizer, Recognizer, {
  1648. /**
  1649. * @namespace
  1650. * @memberof PinchRecognizer
  1651. */
  1652. defaults: {
  1653. event: 'tap',
  1654. pointers: 1,
  1655. taps: 1,
  1656. interval: 300, // max time between the multi-tap taps
  1657. time: 250, // max time of the pointer to be down (like finger on the screen)
  1658. threshold: 10, // a minimal movement is ok, but keep it low
  1659. posThreshold: 10 // a multi-tap can be a bit off the initial position
  1660. },
  1661. getTouchAction: function() {
  1662. return [TOUCH_ACTION_MANIPULATION];
  1663. },
  1664. process: function(input) {
  1665. var options = this.options;
  1666. var validPointers = input.pointers.length === options.pointers;
  1667. var validMovement = input.distance < options.threshold;
  1668. var validTouchTime = input.deltaTime < options.time;
  1669. this.reset();
  1670. if ((input.eventType & INPUT_START) && (this.count === 0)) {
  1671. return this.failTimeout();
  1672. }
  1673. // we only allow little movement
  1674. // and we've reached an end event, so a tap is possible
  1675. if (validMovement && validTouchTime && validPointers) {
  1676. if (input.eventType != INPUT_END) {
  1677. return this.failTimeout();
  1678. }
  1679. var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
  1680. var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
  1681. this.pTime = input.timeStamp;
  1682. this.pCenter = input.center;
  1683. if (!validMultiTap || !validInterval) {
  1684. this.count = 1;
  1685. } else {
  1686. this.count += 1;
  1687. }
  1688. this._input = input;
  1689. // if tap count matches we have recognized it,
  1690. // else it has began recognizing...
  1691. var tapCount = this.count % options.taps;
  1692. if (tapCount === 0) {
  1693. // no failing requirements, immediately trigger the tap event
  1694. // or wait as long as the multitap interval to trigger
  1695. if (!this.hasRequireFailures()) {
  1696. return STATE_RECOGNIZED;
  1697. } else {
  1698. this._timer = setTimeoutContext(function() {
  1699. this.state = STATE_RECOGNIZED;
  1700. this.tryEmit();
  1701. }, options.interval, this);
  1702. return STATE_BEGAN;
  1703. }
  1704. }
  1705. }
  1706. return STATE_FAILED;
  1707. },
  1708. failTimeout: function() {
  1709. this._timer = setTimeoutContext(function() {
  1710. this.state = STATE_FAILED;
  1711. }, this.options.interval, this);
  1712. return STATE_FAILED;
  1713. },
  1714. reset: function() {
  1715. clearTimeout(this._timer);
  1716. },
  1717. emit: function() {
  1718. if (this.state == STATE_RECOGNIZED ) {
  1719. this._input.tapCount = this.count;
  1720. this.manager.emit(this.options.event, this._input);
  1721. }
  1722. }
  1723. });
  1724. /**
  1725. * Simple way to create an manager with a default set of recognizers.
  1726. * @param {HTMLElement} element
  1727. * @param {Object} [options]
  1728. * @constructor
  1729. */
  1730. function Hammer(element, options) {
  1731. options = options || {};
  1732. options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
  1733. return new Manager(element, options);
  1734. }
  1735. /**
  1736. * @const {string}
  1737. */
  1738. Hammer.VERSION = '2.0.4';
  1739. /**
  1740. * default settings
  1741. * @namespace
  1742. */
  1743. Hammer.defaults = {
  1744. /**
  1745. * set if DOM events are being triggered.
  1746. * But this is slower and unused by simple implementations, so disabled by default.
  1747. * @type {Boolean}
  1748. * @default false
  1749. */
  1750. domEvents: false,
  1751. /**
  1752. * The value for the touchAction property/fallback.
  1753. * When set to `compute` it will magically set the correct value based on the added recognizers.
  1754. * @type {String}
  1755. * @default compute
  1756. */
  1757. touchAction: TOUCH_ACTION_COMPUTE,
  1758. /**
  1759. * @type {Boolean}
  1760. * @default true
  1761. */
  1762. enable: true,
  1763. /**
  1764. * EXPERIMENTAL FEATURE -- can be removed/changed
  1765. * Change the parent input target element.
  1766. * If Null, then it is being set the to main element.
  1767. * @type {Null|EventTarget}
  1768. * @default null
  1769. */
  1770. inputTarget: null,
  1771. /**
  1772. * force an input class
  1773. * @type {Null|Function}
  1774. * @default null
  1775. */
  1776. inputClass: null,
  1777. /**
  1778. * Default recognizer setup when calling `Hammer()`
  1779. * When creating a new Manager these will be skipped.
  1780. * @type {Array}
  1781. */
  1782. preset: [
  1783. // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
  1784. [RotateRecognizer, { enable: false }],
  1785. [PinchRecognizer, { enable: false }, ['rotate']],
  1786. [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }],
  1787. [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']],
  1788. [TapRecognizer],
  1789. [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']],
  1790. [PressRecognizer]
  1791. ],
  1792. /**
  1793. * Some CSS properties can be used to improve the working of Hammer.
  1794. * Add them to this method and they will be set when creating a new Manager.
  1795. * @namespace
  1796. */
  1797. cssProps: {
  1798. /**
  1799. * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
  1800. * @type {String}
  1801. * @default 'none'
  1802. */
  1803. userSelect: 'none',
  1804. /**
  1805. * Disable the Windows Phone grippers when pressing an element.
  1806. * @type {String}
  1807. * @default 'none'
  1808. */
  1809. touchSelect: 'none',
  1810. /**
  1811. * Disables the default callout shown when you touch and hold a touch target.
  1812. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  1813. * a callout containing information about the link. This property allows you to disable that callout.
  1814. * @type {String}
  1815. * @default 'none'
  1816. */
  1817. touchCallout: 'none',
  1818. /**
  1819. * Specifies whether zooming is enabled. Used by IE10>
  1820. * @type {String}
  1821. * @default 'none'
  1822. */
  1823. contentZooming: 'none',
  1824. /**
  1825. * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
  1826. * @type {String}
  1827. * @default 'none'
  1828. */
  1829. userDrag: 'none',
  1830. /**
  1831. * Overrides the highlight color shown when the user taps a link or a JavaScript
  1832. * clickable element in iOS. This property obeys the alpha value, if specified.
  1833. * @type {String}
  1834. * @default 'rgba(0,0,0,0)'
  1835. */
  1836. tapHighlightColor: 'rgba(0,0,0,0)'
  1837. }
  1838. };
  1839. var STOP = 1;
  1840. var FORCED_STOP = 2;
  1841. /**
  1842. * Manager
  1843. * @param {HTMLElement} element
  1844. * @param {Object} [options]
  1845. * @constructor
  1846. */
  1847. function Manager(element, options) {
  1848. options = options || {};
  1849. this.options = merge(options, Hammer.defaults);
  1850. this.options.inputTarget = this.options.inputTarget || element;
  1851. this.handlers = {};
  1852. this.session = {};
  1853. this.recognizers = [];
  1854. this.element = element;
  1855. this.input = createInputInstance(this);
  1856. this.touchAction = new TouchAction(this, this.options.touchAction);
  1857. toggleCssProps(this, true);
  1858. each(options.recognizers, function(item) {
  1859. var recognizer = this.add(new (item[0])(item[1]));
  1860. item[2] && recognizer.recognizeWith(item[2]);
  1861. item[3] && recognizer.requireFailure(item[3]);
  1862. }, this);
  1863. }
  1864. Manager.prototype = {
  1865. /**
  1866. * set options
  1867. * @param {Object} options
  1868. * @returns {Manager}
  1869. */
  1870. set: function(options) {
  1871. extend(this.options, options);
  1872. // Options that need a little more setup
  1873. if (options.touchAction) {
  1874. this.touchAction.update();
  1875. }
  1876. if (options.inputTarget) {
  1877. // Clean up existing event listeners and reinitialize
  1878. this.input.destroy();
  1879. this.input.target = options.inputTarget;
  1880. this.input.init();
  1881. }
  1882. return this;
  1883. },
  1884. /**
  1885. * stop recognizing for this session.
  1886. * This session will be discarded, when a new [input]start event is fired.
  1887. * When forced, the recognizer cycle is stopped immediately.
  1888. * @param {Boolean} [force]
  1889. */
  1890. stop: function(force) {
  1891. this.session.stopped = force ? FORCED_STOP : STOP;
  1892. },
  1893. /**
  1894. * run the recognizers!
  1895. * called by the inputHandler function on every movement of the pointers (touches)
  1896. * it walks through all the recognizers and tries to detect the gesture that is being made
  1897. * @param {Object} inputData
  1898. */
  1899. recognize: function(inputData) {
  1900. var session = this.session;
  1901. if (session.stopped) {
  1902. return;
  1903. }
  1904. // run the touch-action polyfill
  1905. this.touchAction.preventDefaults(inputData);
  1906. var recognizer;
  1907. var recognizers = this.recognizers;
  1908. // this holds the recognizer that is being recognized.
  1909. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
  1910. // if no recognizer is detecting a thing, it is set to `null`
  1911. var curRecognizer = session.curRecognizer;
  1912. // reset when the last recognizer is recognized
  1913. // or when we're in a new session
  1914. if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
  1915. curRecognizer = session.curRecognizer = null;
  1916. }
  1917. var i = 0;
  1918. while (i < recognizers.length) {
  1919. recognizer = recognizers[i];
  1920. // find out if we are allowed try to recognize the input for this one.
  1921. // 1. allow if the session is NOT forced stopped (see the .stop() method)
  1922. // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
  1923. // that is being recognized.
  1924. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
  1925. // this can be setup with the `recognizeWith()` method on the recognizer.
  1926. if (session.stopped !== FORCED_STOP && ( // 1
  1927. !curRecognizer || recognizer == curRecognizer || // 2
  1928. recognizer.canRecognizeWith(curRecognizer))) { // 3
  1929. recognizer.recognize(inputData);
  1930. } else {
  1931. recognizer.reset();
  1932. }
  1933. // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
  1934. // current active recognizer. but only if we don't already have an active recognizer
  1935. if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
  1936. curRecognizer = session.curRecognizer = recognizer;
  1937. }
  1938. i++;
  1939. }
  1940. },
  1941. /**
  1942. * get a recognizer by its event name.
  1943. * @param {Recognizer|String} recognizer
  1944. * @returns {Recognizer|Null}
  1945. */
  1946. get: function(recognizer) {
  1947. if (recognizer instanceof Recognizer) {
  1948. return recognizer;
  1949. }
  1950. var recognizers = this.recognizers;
  1951. for (var i = 0; i < recognizers.length; i++) {
  1952. if (recognizers[i].options.event == recognizer) {
  1953. return recognizers[i];
  1954. }
  1955. }
  1956. return null;
  1957. },
  1958. /**
  1959. * add a recognizer to the manager
  1960. * existing recognizers with the same event name will be removed
  1961. * @param {Recognizer} recognizer
  1962. * @returns {Recognizer|Manager}
  1963. */
  1964. add: function(recognizer) {
  1965. if (invokeArrayArg(recognizer, 'add', this)) {
  1966. return this;
  1967. }
  1968. // remove existing
  1969. var existing = this.get(recognizer.options.event);
  1970. if (existing) {
  1971. this.remove(existing);
  1972. }
  1973. this.recognizers.push(recognizer);
  1974. recognizer.manager = this;
  1975. this.touchAction.update();
  1976. return recognizer;
  1977. },
  1978. /**
  1979. * remove a recognizer by name or instance
  1980. * @param {Recognizer|String} recognizer
  1981. * @returns {Manager}
  1982. */
  1983. remove: function(recognizer) {
  1984. if (invokeArrayArg(recognizer, 'remove', this)) {
  1985. return this;
  1986. }
  1987. var recognizers = this.recognizers;
  1988. recognizer = this.get(recognizer);
  1989. recognizers.splice(inArray(recognizers, recognizer), 1);
  1990. this.touchAction.update();
  1991. return this;
  1992. },
  1993. /**
  1994. * bind event
  1995. * @param {String} events
  1996. * @param {Function} handler
  1997. * @returns {EventEmitter} this
  1998. */
  1999. on: function(events, handler) {
  2000. var handlers = this.handlers;
  2001. each(splitStr(events), function(event) {
  2002. handlers[event] = handlers[event] || [];
  2003. handlers[event].push(handler);
  2004. });
  2005. return this;
  2006. },
  2007. /**
  2008. * unbind event, leave emit blank to remove all handlers
  2009. * @param {String} events
  2010. * @param {Function} [handler]
  2011. * @returns {EventEmitter} this
  2012. */
  2013. off: function(events, handler) {
  2014. var handlers = this.handlers;
  2015. each(splitStr(events), function(event) {
  2016. if (!handler) {
  2017. delete handlers[event];
  2018. } else {
  2019. handlers[event].splice(inArray(handlers[event], handler), 1);
  2020. }
  2021. });
  2022. return this;
  2023. },
  2024. /**
  2025. * emit event to the listeners
  2026. * @param {String} event
  2027. * @param {Object} data
  2028. */
  2029. emit: function(event, data) {
  2030. // we also want to trigger dom events
  2031. if (this.options.domEvents) {
  2032. triggerDomEvent(event, data);
  2033. }
  2034. // no handlers, so skip it all
  2035. var handlers = this.handlers[event] && this.handlers[event].slice();
  2036. if (!handlers || !handlers.length) {
  2037. return;
  2038. }
  2039. data.type = event;
  2040. data.preventDefault = function() {
  2041. data.srcEvent.preventDefault();
  2042. };
  2043. var i = 0;
  2044. while (i < handlers.length) {
  2045. handlers[i](data);
  2046. i++;
  2047. }
  2048. },
  2049. /**
  2050. * destroy the manager and unbinds all events
  2051. * it doesn't unbind dom events, that is the user own responsibility
  2052. */
  2053. destroy: function() {
  2054. this.element && toggleCssProps(this, false);
  2055. this.handlers = {};
  2056. this.session = {};
  2057. this.input.destroy();
  2058. this.element = null;
  2059. }
  2060. };
  2061. /**
  2062. * add/remove the css properties as defined in manager.options.cssProps
  2063. * @param {Manager} manager
  2064. * @param {Boolean} add
  2065. */
  2066. function toggleCssProps(manager, add) {
  2067. var element = manager.element;
  2068. each(manager.options.cssProps, function(value, name) {
  2069. element.style[prefixed(element.style, name)] = add ? value : '';
  2070. });
  2071. }
  2072. /**
  2073. * trigger dom event
  2074. * @param {String} event
  2075. * @param {Object} data
  2076. */
  2077. function triggerDomEvent(event, data) {
  2078. var gestureEvent = document.createEvent('Event');
  2079. gestureEvent.initEvent(event, true, true);
  2080. gestureEvent.gesture = data;
  2081. data.target.dispatchEvent(gestureEvent);
  2082. }
  2083. extend(Hammer, {
  2084. INPUT_START: INPUT_START,
  2085. INPUT_MOVE: INPUT_MOVE,
  2086. INPUT_END: INPUT_END,
  2087. INPUT_CANCEL: INPUT_CANCEL,
  2088. STATE_POSSIBLE: STATE_POSSIBLE,
  2089. STATE_BEGAN: STATE_BEGAN,
  2090. STATE_CHANGED: STATE_CHANGED,
  2091. STATE_ENDED: STATE_ENDED,
  2092. STATE_RECOGNIZED: STATE_RECOGNIZED,
  2093. STATE_CANCELLED: STATE_CANCELLED,
  2094. STATE_FAILED: STATE_FAILED,
  2095. DIRECTION_NONE: DIRECTION_NONE,
  2096. DIRECTION_LEFT: DIRECTION_LEFT,
  2097. DIRECTION_RIGHT: DIRECTION_RIGHT,
  2098. DIRECTION_UP: DIRECTION_UP,
  2099. DIRECTION_DOWN: DIRECTION_DOWN,
  2100. DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
  2101. DIRECTION_VERTICAL: DIRECTION_VERTICAL,
  2102. DIRECTION_ALL: DIRECTION_ALL,
  2103. Manager: Manager,
  2104. Input: Input,
  2105. TouchAction: TouchAction,
  2106. TouchInput: TouchInput,
  2107. MouseInput: MouseInput,
  2108. PointerEventInput: PointerEventInput,
  2109. TouchMouseInput: TouchMouseInput,
  2110. SingleTouchInput: SingleTouchInput,
  2111. Recognizer: Recognizer,
  2112. AttrRecognizer: AttrRecognizer,
  2113. Tap: TapRecognizer,
  2114. Pan: PanRecognizer,
  2115. Swipe: SwipeRecognizer,
  2116. Pinch: PinchRecognizer,
  2117. Rotate: RotateRecognizer,
  2118. Press: PressRecognizer,
  2119. on: addEventListeners,
  2120. off: removeEventListeners,
  2121. each: each,
  2122. merge: merge,
  2123. extend: extend,
  2124. inherit: inherit,
  2125. bindFn: bindFn,
  2126. prefixed: prefixed
  2127. });
  2128. if (typeof module == 'object' && module.exports) {
  2129. module.exports = Hammer;
  2130. }
  2131. /** ignored by jsdoc **/
  2132. else {
  2133. return Hammer;
  2134. }
  2135. });