hammer.js 67 KB

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