vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2463 lines
66 KiB

  1. /*! Hammer.JS - v2.0.4 - 2014-09-28
  2. * http://hammerjs.github.io/
  3. *
  4. * Copyright (c) 2014 Jorik Tangelder;
  5. * Licensed under the MIT license */
  6. (function(window, document, exportName, undefined) {
  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. });
  1456. /**
  1457. * Pinch
  1458. * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
  1459. * @constructor
  1460. * @extends AttrRecognizer
  1461. */
  1462. function PinchRecognizer() {
  1463. AttrRecognizer.apply(this, arguments);
  1464. }
  1465. inherit(PinchRecognizer, AttrRecognizer, {
  1466. /**
  1467. * @namespace
  1468. * @memberof PinchRecognizer
  1469. */
  1470. defaults: {
  1471. event: 'pinch',
  1472. threshold: 0,
  1473. pointers: 2
  1474. },
  1475. getTouchAction: function() {
  1476. return [TOUCH_ACTION_NONE];
  1477. },
  1478. attrTest: function(input) {
  1479. return this._super.attrTest.call(this, input) &&
  1480. (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
  1481. },
  1482. emit: function(input) {
  1483. this._super.emit.call(this, input);
  1484. if (input.scale !== 1) {
  1485. var inOut = input.scale < 1 ? 'in' : 'out';
  1486. this.manager.emit(this.options.event + inOut, input);
  1487. }
  1488. }
  1489. });
  1490. /**
  1491. * Press
  1492. * Recognized when the pointer is down for x ms without any movement.
  1493. * @constructor
  1494. * @extends Recognizer
  1495. */
  1496. function PressRecognizer() {
  1497. Recognizer.apply(this, arguments);
  1498. this._timer = null;
  1499. this._input = null;
  1500. }
  1501. inherit(PressRecognizer, Recognizer, {
  1502. /**
  1503. * @namespace
  1504. * @memberof PressRecognizer
  1505. */
  1506. defaults: {
  1507. event: 'press',
  1508. pointers: 1,
  1509. time: 500, // minimal time of the pointer to be pressed
  1510. threshold: 5 // a minimal movement is ok, but keep it low
  1511. },
  1512. getTouchAction: function() {
  1513. return [TOUCH_ACTION_AUTO];
  1514. },
  1515. process: function(input) {
  1516. var options = this.options;
  1517. var validPointers = input.pointers.length === options.pointers;
  1518. var validMovement = input.distance < options.threshold;
  1519. var validTime = input.deltaTime > options.time;
  1520. this._input = input;
  1521. // we only allow little movement
  1522. // and we've reached an end event, so a tap is possible
  1523. if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
  1524. this.reset();
  1525. } else if (input.eventType & INPUT_START) {
  1526. this.reset();
  1527. this._timer = setTimeoutContext(function() {
  1528. this.state = STATE_RECOGNIZED;
  1529. this.tryEmit();
  1530. }, options.time, this);
  1531. } else if (input.eventType & INPUT_END) {
  1532. return STATE_RECOGNIZED;
  1533. }
  1534. return STATE_FAILED;
  1535. },
  1536. reset: function() {
  1537. clearTimeout(this._timer);
  1538. },
  1539. emit: function(input) {
  1540. if (this.state !== STATE_RECOGNIZED) {
  1541. return;
  1542. }
  1543. if (input && (input.eventType & INPUT_END)) {
  1544. this.manager.emit(this.options.event + 'up', input);
  1545. } else {
  1546. this._input.timeStamp = now();
  1547. this.manager.emit(this.options.event, this._input);
  1548. }
  1549. }
  1550. });
  1551. /**
  1552. * Rotate
  1553. * Recognized when two or more pointer are moving in a circular motion.
  1554. * @constructor
  1555. * @extends AttrRecognizer
  1556. */
  1557. function RotateRecognizer() {
  1558. AttrRecognizer.apply(this, arguments);
  1559. }
  1560. inherit(RotateRecognizer, AttrRecognizer, {
  1561. /**
  1562. * @namespace
  1563. * @memberof RotateRecognizer
  1564. */
  1565. defaults: {
  1566. event: 'rotate',
  1567. threshold: 0,
  1568. pointers: 2
  1569. },
  1570. getTouchAction: function() {
  1571. return [TOUCH_ACTION_NONE];
  1572. },
  1573. attrTest: function(input) {
  1574. return this._super.attrTest.call(this, input) &&
  1575. (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
  1576. }
  1577. });
  1578. /**
  1579. * Swipe
  1580. * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
  1581. * @constructor
  1582. * @extends AttrRecognizer
  1583. */
  1584. function SwipeRecognizer() {
  1585. AttrRecognizer.apply(this, arguments);
  1586. }
  1587. inherit(SwipeRecognizer, AttrRecognizer, {
  1588. /**
  1589. * @namespace
  1590. * @memberof SwipeRecognizer
  1591. */
  1592. defaults: {
  1593. event: 'swipe',
  1594. threshold: 10,
  1595. velocity: 0.65,
  1596. direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
  1597. pointers: 1
  1598. },
  1599. getTouchAction: function() {
  1600. return PanRecognizer.prototype.getTouchAction.call(this);
  1601. },
  1602. attrTest: function(input) {
  1603. var direction = this.options.direction;
  1604. var velocity;
  1605. if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
  1606. velocity = input.velocity;
  1607. } else if (direction & DIRECTION_HORIZONTAL) {
  1608. velocity = input.velocityX;
  1609. } else if (direction & DIRECTION_VERTICAL) {
  1610. velocity = input.velocityY;
  1611. }
  1612. return this._super.attrTest.call(this, input) &&
  1613. direction & input.direction &&
  1614. input.distance > this.options.threshold &&
  1615. abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
  1616. },
  1617. emit: function(input) {
  1618. var direction = directionStr(input.direction);
  1619. if (direction) {
  1620. this.manager.emit(this.options.event + direction, input);
  1621. }
  1622. this.manager.emit(this.options.event, input);
  1623. }
  1624. });
  1625. /**
  1626. * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
  1627. * between the given interval and position. The delay option can be used to recognize multi-taps without firing
  1628. * a single tap.
  1629. *
  1630. * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
  1631. * multi-taps being recognized.
  1632. * @constructor
  1633. * @extends Recognizer
  1634. */
  1635. function TapRecognizer() {
  1636. Recognizer.apply(this, arguments);
  1637. // previous time and center,
  1638. // used for tap counting
  1639. this.pTime = false;
  1640. this.pCenter = false;
  1641. this._timer = null;
  1642. this._input = null;
  1643. this.count = 0;
  1644. }
  1645. inherit(TapRecognizer, Recognizer, {
  1646. /**
  1647. * @namespace
  1648. * @memberof PinchRecognizer
  1649. */
  1650. defaults: {
  1651. event: 'tap',
  1652. pointers: 1,
  1653. taps: 1,
  1654. interval: 300, // max time between the multi-tap taps
  1655. time: 250, // max time of the pointer to be down (like finger on the screen)
  1656. threshold: 2, // a minimal movement is ok, but keep it low
  1657. posThreshold: 10 // a multi-tap can be a bit off the initial position
  1658. },
  1659. getTouchAction: function() {
  1660. return [TOUCH_ACTION_MANIPULATION];
  1661. },
  1662. process: function(input) {
  1663. var options = this.options;
  1664. var validPointers = input.pointers.length === options.pointers;
  1665. var validMovement = input.distance < options.threshold;
  1666. var validTouchTime = input.deltaTime < options.time;
  1667. this.reset();
  1668. if ((input.eventType & INPUT_START) && (this.count === 0)) {
  1669. return this.failTimeout();
  1670. }
  1671. // we only allow little movement
  1672. // and we've reached an end event, so a tap is possible
  1673. if (validMovement && validTouchTime && validPointers) {
  1674. if (input.eventType != INPUT_END) {
  1675. return this.failTimeout();
  1676. }
  1677. var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
  1678. var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
  1679. this.pTime = input.timeStamp;
  1680. this.pCenter = input.center;
  1681. if (!validMultiTap || !validInterval) {
  1682. this.count = 1;
  1683. } else {
  1684. this.count += 1;
  1685. }
  1686. this._input = input;
  1687. // if tap count matches we have recognized it,
  1688. // else it has began recognizing...
  1689. var tapCount = this.count % options.taps;
  1690. if (tapCount === 0) {
  1691. // no failing requirements, immediately trigger the tap event
  1692. // or wait as long as the multitap interval to trigger
  1693. if (!this.hasRequireFailures()) {
  1694. return STATE_RECOGNIZED;
  1695. } else {
  1696. this._timer = setTimeoutContext(function() {
  1697. this.state = STATE_RECOGNIZED;
  1698. this.tryEmit();
  1699. }, options.interval, this);
  1700. return STATE_BEGAN;
  1701. }
  1702. }
  1703. }
  1704. return STATE_FAILED;
  1705. },
  1706. failTimeout: function() {
  1707. this._timer = setTimeoutContext(function() {
  1708. this.state = STATE_FAILED;
  1709. }, this.options.interval, this);
  1710. return STATE_FAILED;
  1711. },
  1712. reset: function() {
  1713. clearTimeout(this._timer);
  1714. },
  1715. emit: function() {
  1716. if (this.state == STATE_RECOGNIZED ) {
  1717. this._input.tapCount = this.count;
  1718. this.manager.emit(this.options.event, this._input);
  1719. }
  1720. }
  1721. });
  1722. /**
  1723. * Simple way to create an manager with a default set of recognizers.
  1724. * @param {HTMLElement} element
  1725. * @param {Object} [options]
  1726. * @constructor
  1727. */
  1728. function Hammer(element, options) {
  1729. options = options || {};
  1730. options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
  1731. return new Manager(element, options);
  1732. }
  1733. /**
  1734. * @const {string}
  1735. */
  1736. Hammer.VERSION = '2.0.4';
  1737. /**
  1738. * default settings
  1739. * @namespace
  1740. */
  1741. Hammer.defaults = {
  1742. /**
  1743. * set if DOM events are being triggered.
  1744. * But this is slower and unused by simple implementations, so disabled by default.
  1745. * @type {Boolean}
  1746. * @default false
  1747. */
  1748. domEvents: false,
  1749. /**
  1750. * The value for the touchAction property/fallback.
  1751. * When set to `compute` it will magically set the correct value based on the added recognizers.
  1752. * @type {String}
  1753. * @default compute
  1754. */
  1755. touchAction: TOUCH_ACTION_COMPUTE,
  1756. /**
  1757. * @type {Boolean}
  1758. * @default true
  1759. */
  1760. enable: true,
  1761. /**
  1762. * EXPERIMENTAL FEATURE -- can be removed/changed
  1763. * Change the parent input target element.
  1764. * If Null, then it is being set the to main element.
  1765. * @type {Null|EventTarget}
  1766. * @default null
  1767. */
  1768. inputTarget: null,
  1769. /**
  1770. * force an input class
  1771. * @type {Null|Function}
  1772. * @default null
  1773. */
  1774. inputClass: null,
  1775. /**
  1776. * Default recognizer setup when calling `Hammer()`
  1777. * When creating a new Manager these will be skipped.
  1778. * @type {Array}
  1779. */
  1780. preset: [
  1781. // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
  1782. [RotateRecognizer, { enable: false }],
  1783. [PinchRecognizer, { enable: false }, ['rotate']],
  1784. [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }],
  1785. [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']],
  1786. [TapRecognizer],
  1787. [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']],
  1788. [PressRecognizer]
  1789. ],
  1790. /**
  1791. * Some CSS properties can be used to improve the working of Hammer.
  1792. * Add them to this method and they will be set when creating a new Manager.
  1793. * @namespace
  1794. */
  1795. cssProps: {
  1796. /**
  1797. * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
  1798. * @type {String}
  1799. * @default 'none'
  1800. */
  1801. userSelect: 'none',
  1802. /**
  1803. * Disable the Windows Phone grippers when pressing an element.
  1804. * @type {String}
  1805. * @default 'none'
  1806. */
  1807. touchSelect: 'none',
  1808. /**
  1809. * Disables the default callout shown when you touch and hold a touch target.
  1810. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  1811. * a callout containing information about the link. This property allows you to disable that callout.
  1812. * @type {String}
  1813. * @default 'none'
  1814. */
  1815. touchCallout: 'none',
  1816. /**
  1817. * Specifies whether zooming is enabled. Used by IE10>
  1818. * @type {String}
  1819. * @default 'none'
  1820. */
  1821. contentZooming: 'none',
  1822. /**
  1823. * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
  1824. * @type {String}
  1825. * @default 'none'
  1826. */
  1827. userDrag: 'none',
  1828. /**
  1829. * Overrides the highlight color shown when the user taps a link or a JavaScript
  1830. * clickable element in iOS. This property obeys the alpha value, if specified.
  1831. * @type {String}
  1832. * @default 'rgba(0,0,0,0)'
  1833. */
  1834. tapHighlightColor: 'rgba(0,0,0,0)'
  1835. }
  1836. };
  1837. var STOP = 1;
  1838. var FORCED_STOP = 2;
  1839. /**
  1840. * Manager
  1841. * @param {HTMLElement} element
  1842. * @param {Object} [options]
  1843. * @constructor
  1844. */
  1845. function Manager(element, options) {
  1846. options = options || {};
  1847. this.options = merge(options, Hammer.defaults);
  1848. this.options.inputTarget = this.options.inputTarget || element;
  1849. this.handlers = {};
  1850. this.session = {};
  1851. this.recognizers = [];
  1852. this.element = element;
  1853. this.input = createInputInstance(this);
  1854. this.touchAction = new TouchAction(this, this.options.touchAction);
  1855. toggleCssProps(this, true);
  1856. each(options.recognizers, function(item) {
  1857. var recognizer = this.add(new (item[0])(item[1]));
  1858. item[2] && recognizer.recognizeWith(item[2]);
  1859. item[3] && recognizer.requireFailure(item[3]);
  1860. }, this);
  1861. }
  1862. Manager.prototype = {
  1863. /**
  1864. * set options
  1865. * @param {Object} options
  1866. * @returns {Manager}
  1867. */
  1868. set: function(options) {
  1869. extend(this.options, options);
  1870. // Options that need a little more setup
  1871. if (options.touchAction) {
  1872. this.touchAction.update();
  1873. }
  1874. if (options.inputTarget) {
  1875. // Clean up existing event listeners and reinitialize
  1876. this.input.destroy();
  1877. this.input.target = options.inputTarget;
  1878. this.input.init();
  1879. }
  1880. return this;
  1881. },
  1882. /**
  1883. * stop recognizing for this session.
  1884. * This session will be discarded, when a new [input]start event is fired.
  1885. * When forced, the recognizer cycle is stopped immediately.
  1886. * @param {Boolean} [force]
  1887. */
  1888. stop: function(force) {
  1889. this.session.stopped = force ? FORCED_STOP : STOP;
  1890. },
  1891. /**
  1892. * run the recognizers!
  1893. * called by the inputHandler function on every movement of the pointers (touches)
  1894. * it walks through all the recognizers and tries to detect the gesture that is being made
  1895. * @param {Object} inputData
  1896. */
  1897. recognize: function(inputData) {
  1898. var session = this.session;
  1899. if (session.stopped) {
  1900. return;
  1901. }
  1902. // run the touch-action polyfill
  1903. this.touchAction.preventDefaults(inputData);
  1904. var recognizer;
  1905. var recognizers = this.recognizers;
  1906. // this holds the recognizer that is being recognized.
  1907. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
  1908. // if no recognizer is detecting a thing, it is set to `null`
  1909. var curRecognizer = session.curRecognizer;
  1910. // reset when the last recognizer is recognized
  1911. // or when we're in a new session
  1912. if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
  1913. curRecognizer = session.curRecognizer = null;
  1914. }
  1915. var i = 0;
  1916. while (i < recognizers.length) {
  1917. recognizer = recognizers[i];
  1918. // find out if we are allowed try to recognize the input for this one.
  1919. // 1. allow if the session is NOT forced stopped (see the .stop() method)
  1920. // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
  1921. // that is being recognized.
  1922. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
  1923. // this can be setup with the `recognizeWith()` method on the recognizer.
  1924. if (session.stopped !== FORCED_STOP && ( // 1
  1925. !curRecognizer || recognizer == curRecognizer || // 2
  1926. recognizer.canRecognizeWith(curRecognizer))) { // 3
  1927. recognizer.recognize(inputData);
  1928. } else {
  1929. recognizer.reset();
  1930. }
  1931. // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
  1932. // current active recognizer. but only if we don't already have an active recognizer
  1933. if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
  1934. curRecognizer = session.curRecognizer = recognizer;
  1935. }
  1936. i++;
  1937. }
  1938. },
  1939. /**
  1940. * get a recognizer by its event name.
  1941. * @param {Recognizer|String} recognizer
  1942. * @returns {Recognizer|Null}
  1943. */
  1944. get: function(recognizer) {
  1945. if (recognizer instanceof Recognizer) {
  1946. return recognizer;
  1947. }
  1948. var recognizers = this.recognizers;
  1949. for (var i = 0; i < recognizers.length; i++) {
  1950. if (recognizers[i].options.event == recognizer) {
  1951. return recognizers[i];
  1952. }
  1953. }
  1954. return null;
  1955. },
  1956. /**
  1957. * add a recognizer to the manager
  1958. * existing recognizers with the same event name will be removed
  1959. * @param {Recognizer} recognizer
  1960. * @returns {Recognizer|Manager}
  1961. */
  1962. add: function(recognizer) {
  1963. if (invokeArrayArg(recognizer, 'add', this)) {
  1964. return this;
  1965. }
  1966. // remove existing
  1967. var existing = this.get(recognizer.options.event);
  1968. if (existing) {
  1969. this.remove(existing);
  1970. }
  1971. this.recognizers.push(recognizer);
  1972. recognizer.manager = this;
  1973. this.touchAction.update();
  1974. return recognizer;
  1975. },
  1976. /**
  1977. * remove a recognizer by name or instance
  1978. * @param {Recognizer|String} recognizer
  1979. * @returns {Manager}
  1980. */
  1981. remove: function(recognizer) {
  1982. if (invokeArrayArg(recognizer, 'remove', this)) {
  1983. return this;
  1984. }
  1985. var recognizers = this.recognizers;
  1986. recognizer = this.get(recognizer);
  1987. recognizers.splice(inArray(recognizers, recognizer), 1);
  1988. this.touchAction.update();
  1989. return this;
  1990. },
  1991. /**
  1992. * bind event
  1993. * @param {String} events
  1994. * @param {Function} handler
  1995. * @returns {EventEmitter} this
  1996. */
  1997. on: function(events, handler) {
  1998. var handlers = this.handlers;
  1999. each(splitStr(events), function(event) {
  2000. handlers[event] = handlers[event] || [];
  2001. handlers[event].push(handler);
  2002. });
  2003. return this;
  2004. },
  2005. /**
  2006. * unbind event, leave emit blank to remove all handlers
  2007. * @param {String} events
  2008. * @param {Function} [handler]
  2009. * @returns {EventEmitter} this
  2010. */
  2011. off: function(events, handler) {
  2012. var handlers = this.handlers;
  2013. each(splitStr(events), function(event) {
  2014. if (!handler) {
  2015. delete handlers[event];
  2016. } else {
  2017. handlers[event].splice(inArray(handlers[event], handler), 1);
  2018. }
  2019. });
  2020. return this;
  2021. },
  2022. /**
  2023. * emit event to the listeners
  2024. * @param {String} event
  2025. * @param {Object} data
  2026. */
  2027. emit: function(event, data) {
  2028. // we also want to trigger dom events
  2029. if (this.options.domEvents) {
  2030. triggerDomEvent(event, data);
  2031. }
  2032. // no handlers, so skip it all
  2033. var handlers = this.handlers[event] && this.handlers[event].slice();
  2034. if (!handlers || !handlers.length) {
  2035. return;
  2036. }
  2037. data.type = event;
  2038. data.preventDefault = function() {
  2039. data.srcEvent.preventDefault();
  2040. };
  2041. var i = 0;
  2042. while (i < handlers.length) {
  2043. handlers[i](data);
  2044. i++;
  2045. }
  2046. },
  2047. /**
  2048. * destroy the manager and unbinds all events
  2049. * it doesn't unbind dom events, that is the user own responsibility
  2050. */
  2051. destroy: function() {
  2052. this.element && toggleCssProps(this, false);
  2053. this.handlers = {};
  2054. this.session = {};
  2055. this.input.destroy();
  2056. this.element = null;
  2057. }
  2058. };
  2059. /**
  2060. * add/remove the css properties as defined in manager.options.cssProps
  2061. * @param {Manager} manager
  2062. * @param {Boolean} add
  2063. */
  2064. function toggleCssProps(manager, add) {
  2065. var element = manager.element;
  2066. each(manager.options.cssProps, function(value, name) {
  2067. element.style[prefixed(element.style, name)] = add ? value : '';
  2068. });
  2069. }
  2070. /**
  2071. * trigger dom event
  2072. * @param {String} event
  2073. * @param {Object} data
  2074. */
  2075. function triggerDomEvent(event, data) {
  2076. var gestureEvent = document.createEvent('Event');
  2077. gestureEvent.initEvent(event, true, true);
  2078. gestureEvent.gesture = data;
  2079. data.target.dispatchEvent(gestureEvent);
  2080. }
  2081. extend(Hammer, {
  2082. INPUT_START: INPUT_START,
  2083. INPUT_MOVE: INPUT_MOVE,
  2084. INPUT_END: INPUT_END,
  2085. INPUT_CANCEL: INPUT_CANCEL,
  2086. STATE_POSSIBLE: STATE_POSSIBLE,
  2087. STATE_BEGAN: STATE_BEGAN,
  2088. STATE_CHANGED: STATE_CHANGED,
  2089. STATE_ENDED: STATE_ENDED,
  2090. STATE_RECOGNIZED: STATE_RECOGNIZED,
  2091. STATE_CANCELLED: STATE_CANCELLED,
  2092. STATE_FAILED: STATE_FAILED,
  2093. DIRECTION_NONE: DIRECTION_NONE,
  2094. DIRECTION_LEFT: DIRECTION_LEFT,
  2095. DIRECTION_RIGHT: DIRECTION_RIGHT,
  2096. DIRECTION_UP: DIRECTION_UP,
  2097. DIRECTION_DOWN: DIRECTION_DOWN,
  2098. DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
  2099. DIRECTION_VERTICAL: DIRECTION_VERTICAL,
  2100. DIRECTION_ALL: DIRECTION_ALL,
  2101. Manager: Manager,
  2102. Input: Input,
  2103. TouchAction: TouchAction,
  2104. TouchInput: TouchInput,
  2105. MouseInput: MouseInput,
  2106. PointerEventInput: PointerEventInput,
  2107. TouchMouseInput: TouchMouseInput,
  2108. SingleTouchInput: SingleTouchInput,
  2109. Recognizer: Recognizer,
  2110. AttrRecognizer: AttrRecognizer,
  2111. Tap: TapRecognizer,
  2112. Pan: PanRecognizer,
  2113. Swipe: SwipeRecognizer,
  2114. Pinch: PinchRecognizer,
  2115. Rotate: RotateRecognizer,
  2116. Press: PressRecognizer,
  2117. on: addEventListeners,
  2118. off: removeEventListeners,
  2119. each: each,
  2120. merge: merge,
  2121. extend: extend,
  2122. inherit: inherit,
  2123. bindFn: bindFn,
  2124. prefixed: prefixed
  2125. });
  2126. if (typeof define == TYPE_FUNCTION && define.amd) {
  2127. define(function() {
  2128. return Hammer;
  2129. });
  2130. } else if (typeof module != 'undefined' && module.exports) {
  2131. module.exports = Hammer;
  2132. } else {
  2133. window[exportName] = Hammer;
  2134. }
  2135. })(window, document, 'Hammer');