PageRenderTime 442ms CodeModel.GetById 43ms RepoModel.GetById 4ms app.codeStats 0ms

/posts/fugelsang/www/js/lib/hammer.js

https://github.com/nprapps/lookatthis
JavaScript | 2463 lines | 1376 code | 328 blank | 759 comment | 278 complexity | d33b87ac75c6f9018d3b131a7a2dd67c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  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 (

Large files files are truncated, but you can click here to view the full file