Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

gesture-detector.js 54KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. /*
  2. * Gesture detector library that forked from github.com/EightMedia/hammer.js.
  3. */
  4. 'use strict';
  5. import _Object$keys from 'babel-runtime/core-js/object/keys';
  6. import util from './util';
  7. var Event, Utils, Detection, PointerEvent;
  8. /**
  9. * @object ons.GestureDetector
  10. * @category gesture
  11. * @description
  12. * [en]Utility class for gesture detection.[/en]
  13. * [ja]ジェスチャを検知するためのユーティリティクラスです。[/ja]
  14. */
  15. /**
  16. * @method constructor
  17. * @signature constructor(element[, options])
  18. * @description
  19. * [en]Create a new GestureDetector instance.[/en]
  20. * [ja]GestureDetectorのインスタンスを生成します。[/ja]
  21. * @param {Element} element
  22. * [en]Name of the event.[/en]
  23. * [ja]ジェスチャを検知するDOM要素を指定します。[/ja]
  24. * @param {Object} [options]
  25. * [en]Options object.[/en]
  26. * [ja]オプションを指定します。[/ja]
  27. * @return {ons.GestureDetector.Instance}
  28. */
  29. var GestureDetector = function GestureDetector(element, options) {
  30. return new GestureDetector.Instance(element, options || {});
  31. };
  32. /**
  33. * default settings.
  34. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled
  35. * by setting it's name (like `swipe`) to false.
  36. * You can set the defaults for all instances by changing this object before creating an instance.
  37. * @example
  38. * ````
  39. * GestureDetector.defaults.drag = false;
  40. * GestureDetector.defaults.behavior.touchAction = 'pan-y';
  41. * delete GestureDetector.defaults.behavior.userSelect;
  42. * ````
  43. * @property defaults
  44. * @type {Object}
  45. */
  46. GestureDetector.defaults = {
  47. behavior: {
  48. // userSelect: 'none', // Also disables selection in `input` children
  49. touchAction: 'pan-y',
  50. touchCallout: 'none',
  51. contentZooming: 'none',
  52. userDrag: 'none',
  53. tapHighlightColor: 'rgba(0,0,0,0)'
  54. }
  55. };
  56. /**
  57. * GestureDetector document where the base events are added at
  58. * @property DOCUMENT
  59. * @type {HTMLElement}
  60. * @default window.document
  61. */
  62. GestureDetector.DOCUMENT = document;
  63. /**
  64. * detect support for pointer events
  65. * @property HAS_POINTEREVENTS
  66. * @type {Boolean}
  67. */
  68. GestureDetector.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
  69. /**
  70. * detect support for touch events
  71. * @property HAS_TOUCHEVENTS
  72. * @type {Boolean}
  73. */
  74. GestureDetector.HAS_TOUCHEVENTS = 'ontouchstart' in window;
  75. /**
  76. * detect mobile browsers
  77. * @property IS_MOBILE
  78. * @type {Boolean}
  79. */
  80. GestureDetector.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent);
  81. /**
  82. * detect if we want to support mouseevents at all
  83. * @property NO_MOUSEEVENTS
  84. * @type {Boolean}
  85. */
  86. GestureDetector.NO_MOUSEEVENTS = GestureDetector.HAS_TOUCHEVENTS && GestureDetector.IS_MOBILE || GestureDetector.HAS_POINTEREVENTS;
  87. /**
  88. * interval in which GestureDetector recalculates current velocity/direction/angle in ms
  89. * @property CALCULATE_INTERVAL
  90. * @type {Number}
  91. * @default 25
  92. */
  93. GestureDetector.CALCULATE_INTERVAL = 25;
  94. /**
  95. * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup`
  96. * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`)
  97. * @property EVENT_TYPES
  98. * @private
  99. * @writeOnce
  100. * @type {Object}
  101. */
  102. var EVENT_TYPES = {};
  103. /**
  104. * direction strings, for safe comparisons
  105. * @property DIRECTION_DOWN|LEFT|UP|RIGHT
  106. * @final
  107. * @type {String}
  108. * @default 'down' 'left' 'up' 'right'
  109. */
  110. var DIRECTION_DOWN = GestureDetector.DIRECTION_DOWN = 'down';
  111. var DIRECTION_LEFT = GestureDetector.DIRECTION_LEFT = 'left';
  112. var DIRECTION_UP = GestureDetector.DIRECTION_UP = 'up';
  113. var DIRECTION_RIGHT = GestureDetector.DIRECTION_RIGHT = 'right';
  114. /**
  115. * pointertype strings, for safe comparisons
  116. * @property POINTER_MOUSE|TOUCH|PEN
  117. * @final
  118. * @type {String}
  119. * @default 'mouse' 'touch' 'pen'
  120. */
  121. var POINTER_MOUSE = GestureDetector.POINTER_MOUSE = 'mouse';
  122. var POINTER_TOUCH = GestureDetector.POINTER_TOUCH = 'touch';
  123. var POINTER_PEN = GestureDetector.POINTER_PEN = 'pen';
  124. /**
  125. * eventtypes
  126. * @property EVENT_START|MOVE|END|RELEASE|TOUCH
  127. * @final
  128. * @type {String}
  129. * @default 'start' 'change' 'move' 'end' 'release' 'touch'
  130. */
  131. var EVENT_START = GestureDetector.EVENT_START = 'start';
  132. var EVENT_MOVE = GestureDetector.EVENT_MOVE = 'move';
  133. var EVENT_END = GestureDetector.EVENT_END = 'end';
  134. var EVENT_RELEASE = GestureDetector.EVENT_RELEASE = 'release';
  135. var EVENT_TOUCH = GestureDetector.EVENT_TOUCH = 'touch';
  136. /**
  137. * if the window events are set...
  138. * @property READY
  139. * @writeOnce
  140. * @type {Boolean}
  141. * @default false
  142. */
  143. GestureDetector.READY = false;
  144. /**
  145. * plugins namespace
  146. * @property plugins
  147. * @type {Object}
  148. */
  149. GestureDetector.plugins = GestureDetector.plugins || {};
  150. /**
  151. * gestures namespace
  152. * see `/gestures` for the definitions
  153. * @property gestures
  154. * @type {Object}
  155. */
  156. GestureDetector.gestures = GestureDetector.gestures || {};
  157. /**
  158. * setup events to detect gestures on the document
  159. * this function is called when creating an new instance
  160. * @private
  161. */
  162. function setup(opts) {
  163. if (GestureDetector.READY) {
  164. return;
  165. }
  166. // find what eventtypes we add listeners to
  167. Event.determineEventTypes();
  168. // Register all gestures inside GestureDetector.gestures
  169. Utils.each(GestureDetector.gestures, function (gesture) {
  170. Detection.register(gesture);
  171. });
  172. // Add touch events on the document
  173. Event.onTouch(GestureDetector.DOCUMENT, EVENT_MOVE, Detection.detect, opts);
  174. Event.onTouch(GestureDetector.DOCUMENT, EVENT_END, Detection.detect, opts);
  175. // GestureDetector is ready...!
  176. GestureDetector.READY = true;
  177. }
  178. /**
  179. * @module GestureDetector
  180. *
  181. * @class Utils
  182. * @static
  183. */
  184. Utils = GestureDetector.utils = {
  185. /**
  186. * extend method, could also be used for cloning when `dest` is an empty object.
  187. * changes the dest object
  188. * @param {Object} dest
  189. * @param {Object} src
  190. * @param {Boolean} [merge=false] do a merge
  191. * @return {Object} dest
  192. */
  193. extend: function extend(dest, src, merge) {
  194. for (var key in src) {
  195. if (src.hasOwnProperty(key) && (dest[key] === undefined || !merge)) {
  196. dest[key] = src[key];
  197. }
  198. }
  199. return dest;
  200. },
  201. /**
  202. * simple addEventListener wrapper
  203. * @param {HTMLElement} element
  204. * @param {String} type
  205. * @param {Function} handler
  206. */
  207. on: function on(element, type, handler, opt) {
  208. util.addEventListener(element, type, handler, opt, true);
  209. },
  210. /**
  211. * simple removeEventListener wrapper
  212. * @param {HTMLElement} element
  213. * @param {String} type
  214. * @param {Function} handler
  215. */
  216. off: function off(element, type, handler, opt) {
  217. util.removeEventListener(element, type, handler, opt, true);
  218. },
  219. /**
  220. * forEach over arrays and objects
  221. * @param {Object|Array} obj
  222. * @param {Function} iterator
  223. * @param {any} iterator.item
  224. * @param {Number} iterator.index
  225. * @param {Object|Array} iterator.obj the source object
  226. * @param {Object} context value to use as `this` in the iterator
  227. */
  228. each: function each(obj, iterator, context) {
  229. var i, len;
  230. // native forEach on arrays
  231. if ('forEach' in obj) {
  232. obj.forEach(iterator, context);
  233. // arrays
  234. } else if (obj.length !== undefined) {
  235. for (i = 0, len = obj.length; i < len; i++) {
  236. if (iterator.call(context, obj[i], i, obj) === false) {
  237. return;
  238. }
  239. }
  240. // objects
  241. } else {
  242. for (i in obj) {
  243. if (obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) {
  244. return;
  245. }
  246. }
  247. }
  248. },
  249. /**
  250. * find if a string contains the string using indexOf
  251. * @param {String} src
  252. * @param {String} find
  253. * @return {Boolean} found
  254. */
  255. inStr: function inStr(src, find) {
  256. return src.indexOf(find) > -1;
  257. },
  258. /**
  259. * find if a array contains the object using indexOf or a simple polyfill
  260. * @param {String} src
  261. * @param {String} find
  262. * @return {Boolean|Number} false when not found, or the index
  263. */
  264. inArray: function inArray(src, find, deep) {
  265. if (deep) {
  266. for (var i = 0, len = src.length; i < len; i++) {
  267. // Array.findIndex
  268. if (_Object$keys(find).every(function (key) {
  269. return src[i][key] === find[key];
  270. })) {
  271. return i;
  272. }
  273. }
  274. return -1;
  275. }
  276. if (src.indexOf) {
  277. return src.indexOf(find);
  278. } else {
  279. for (var i = 0, len = src.length; i < len; i++) {
  280. if (src[i] === find) {
  281. return i;
  282. }
  283. }
  284. return -1;
  285. }
  286. },
  287. /**
  288. * convert an array-like object (`arguments`, `touchlist`) to an array
  289. * @param {Object} obj
  290. * @return {Array}
  291. */
  292. toArray: function toArray(obj) {
  293. return Array.prototype.slice.call(obj, 0);
  294. },
  295. /**
  296. * find if a node is in the given parent
  297. * @param {HTMLElement} node
  298. * @param {HTMLElement} parent
  299. * @return {Boolean} found
  300. */
  301. hasParent: function hasParent(node, parent) {
  302. while (node) {
  303. if (node == parent) {
  304. return true;
  305. }
  306. node = node.parentNode;
  307. }
  308. return false;
  309. },
  310. /**
  311. * get the center of all the touches
  312. * @param {Array} touches
  313. * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties
  314. */
  315. getCenter: function getCenter(touches) {
  316. var pageX = [],
  317. pageY = [],
  318. clientX = [],
  319. clientY = [],
  320. min = Math.min,
  321. max = Math.max;
  322. // no need to loop when only one touch
  323. if (touches.length === 1) {
  324. return {
  325. pageX: touches[0].pageX,
  326. pageY: touches[0].pageY,
  327. clientX: touches[0].clientX,
  328. clientY: touches[0].clientY
  329. };
  330. }
  331. Utils.each(touches, function (touch) {
  332. pageX.push(touch.pageX);
  333. pageY.push(touch.pageY);
  334. clientX.push(touch.clientX);
  335. clientY.push(touch.clientY);
  336. });
  337. return {
  338. pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2,
  339. pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2,
  340. clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2,
  341. clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2
  342. };
  343. },
  344. /**
  345. * calculate the velocity between two points. unit is in px per ms.
  346. * @param {Number} deltaTime
  347. * @param {Number} deltaX
  348. * @param {Number} deltaY
  349. * @return {Object} velocity `x` and `y`
  350. */
  351. getVelocity: function getVelocity(deltaTime, deltaX, deltaY) {
  352. return {
  353. x: Math.abs(deltaX / deltaTime) || 0,
  354. y: Math.abs(deltaY / deltaTime) || 0
  355. };
  356. },
  357. /**
  358. * calculate the angle between two coordinates
  359. * @param {Touch} touch1
  360. * @param {Touch} touch2
  361. * @return {Number} angle
  362. */
  363. getAngle: function getAngle(touch1, touch2) {
  364. var x = touch2.clientX - touch1.clientX,
  365. y = touch2.clientY - touch1.clientY;
  366. return Math.atan2(y, x) * 180 / Math.PI;
  367. },
  368. /**
  369. * do a small comparison to get the direction between two touches.
  370. * @param {Touch} touch1
  371. * @param {Touch} touch2
  372. * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN`
  373. */
  374. getDirection: function getDirection(touch1, touch2) {
  375. var x = Math.abs(touch1.clientX - touch2.clientX),
  376. y = Math.abs(touch1.clientY - touch2.clientY);
  377. if (x >= y) {
  378. return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  379. }
  380. return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  381. },
  382. /**
  383. * calculate the distance between two touches
  384. * @param {Touch}touch1
  385. * @param {Touch} touch2
  386. * @return {Number} distance
  387. */
  388. getDistance: function getDistance(touch1, touch2) {
  389. var x = touch2.clientX - touch1.clientX,
  390. y = touch2.clientY - touch1.clientY;
  391. return Math.sqrt(x * x + y * y);
  392. },
  393. /**
  394. * calculate the scale factor between two touchLists
  395. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  396. * @param {Array} start array of touches
  397. * @param {Array} end array of touches
  398. * @return {Number} scale
  399. */
  400. getScale: function getScale(start, end) {
  401. // need two fingers...
  402. if (start.length >= 2 && end.length >= 2) {
  403. return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]);
  404. }
  405. return 1;
  406. },
  407. /**
  408. * calculate the rotation degrees between two touchLists
  409. * @param {Array} start array of touches
  410. * @param {Array} end array of touches
  411. * @return {Number} rotation
  412. */
  413. getRotation: function getRotation(start, end) {
  414. // need two fingers
  415. if (start.length >= 2 && end.length >= 2) {
  416. return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]);
  417. }
  418. return 0;
  419. },
  420. /**
  421. * find out if the direction is vertical *
  422. * @param {String} direction matches `DIRECTION_UP|DOWN`
  423. * @return {Boolean} is_vertical
  424. */
  425. isVertical: function isVertical(direction) {
  426. return direction == DIRECTION_UP || direction == DIRECTION_DOWN;
  427. },
  428. /**
  429. * set css properties with their prefixes
  430. * @param {HTMLElement} element
  431. * @param {String} prop
  432. * @param {String} value
  433. * @param {Boolean} [toggle=true]
  434. * @return {Boolean}
  435. */
  436. setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) {
  437. var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms'];
  438. prop = Utils.toCamelCase(prop);
  439. for (var i = 0; i < prefixes.length; i++) {
  440. var p = prop;
  441. // prefixes
  442. if (prefixes[i]) {
  443. p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1);
  444. }
  445. // test the style
  446. if (p in element.style) {
  447. element.style[p] = (toggle === null || toggle) && value || '';
  448. break;
  449. }
  450. }
  451. },
  452. /**
  453. * toggle browser default behavior by setting css properties.
  454. * `userSelect='none'` also sets `element.onselectstart` to false
  455. * `userDrag='none'` also sets `element.ondragstart` to false
  456. *
  457. * @param {HtmlElement} element
  458. * @param {Object} props
  459. * @param {Boolean} [toggle=true]
  460. */
  461. toggleBehavior: function toggleBehavior(element, props, toggle) {
  462. if (!props || !element || !element.style) {
  463. return;
  464. }
  465. // set the css properties
  466. Utils.each(props, function (value, prop) {
  467. Utils.setPrefixedCss(element, prop, value, toggle);
  468. });
  469. var falseFn = toggle && function () {
  470. return false;
  471. };
  472. // also the disable onselectstart
  473. if (props.userSelect == 'none') {
  474. element.onselectstart = falseFn;
  475. }
  476. // and disable ondragstart
  477. if (props.userDrag == 'none') {
  478. element.ondragstart = falseFn;
  479. }
  480. },
  481. /**
  482. * convert a string with underscores to camelCase
  483. * so prevent_default becomes preventDefault
  484. * @param {String} str
  485. * @return {String} camelCaseStr
  486. */
  487. toCamelCase: function toCamelCase(str) {
  488. return str.replace(/[_-]([a-z])/g, function (s) {
  489. return s[1].toUpperCase();
  490. });
  491. }
  492. };
  493. /**
  494. * @module GestureDetector
  495. */
  496. /**
  497. * @class Event
  498. * @static
  499. */
  500. Event = GestureDetector.event = {
  501. /**
  502. * when touch events have been fired, this is true
  503. * this is used to stop mouse events
  504. * @property prevent_mouseevents
  505. * @private
  506. * @type {Boolean}
  507. */
  508. preventMouseEvents: false,
  509. /**
  510. * if EVENT_START has been fired
  511. * @property started
  512. * @private
  513. * @type {Boolean}
  514. */
  515. started: false,
  516. /**
  517. * when the mouse is hold down, this is true
  518. * @property should_detect
  519. * @private
  520. * @type {Boolean}
  521. */
  522. shouldDetect: false,
  523. /**
  524. * simple event binder with a hook and support for multiple types
  525. * @param {HTMLElement} element
  526. * @param {String} type
  527. * @param {Function} handler
  528. * @param {Object} [opt]
  529. * @param {Function} [hook]
  530. * @param {Object} hook.type
  531. */
  532. on: function on(element, type, handler, opt, hook) {
  533. var types = type.split(' ');
  534. Utils.each(types, function (type) {
  535. Utils.on(element, type, handler, opt);
  536. hook && hook(type);
  537. });
  538. },
  539. /**
  540. * simple event unbinder with a hook and support for multiple types
  541. * @param {HTMLElement} element
  542. * @param {String} type
  543. * @param {Function} handler
  544. * @param {Object} [opt]
  545. * @param {Function} [hook]
  546. * @param {Object} hook.type
  547. */
  548. off: function off(element, type, handler, opt, hook) {
  549. var types = type.split(' ');
  550. Utils.each(types, function (type) {
  551. Utils.off(element, type, handler, opt);
  552. hook && hook(type);
  553. });
  554. },
  555. /**
  556. * the core touch event handler.
  557. * this finds out if we should to detect gestures
  558. * @param {HTMLElement} element
  559. * @param {String} eventType matches `EVENT_START|MOVE|END`
  560. * @param {Function} handler
  561. * @return onTouchHandler {Function} the core event handler
  562. */
  563. onTouch: function onTouch(element, eventType, handler, opt) {
  564. var self = this;
  565. var onTouchHandler = function onTouchHandler(ev) {
  566. var srcType = ev.type.toLowerCase(),
  567. isPointer = GestureDetector.HAS_POINTEREVENTS,
  568. isMouse = Utils.inStr(srcType, 'mouse'),
  569. triggerType;
  570. // if we are in a mouseevent, but there has been a touchevent triggered in this session
  571. // we want to do nothing. simply break out of the event.
  572. if (isMouse && self.preventMouseEvents) {
  573. return;
  574. // mousebutton must be down
  575. } else if (isMouse && eventType == EVENT_START && ev.button === 0) {
  576. self.preventMouseEvents = false;
  577. self.shouldDetect = true;
  578. } else if (isPointer && eventType == EVENT_START) {
  579. self.shouldDetect = ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev);
  580. // just a valid start event, but no mouse
  581. } else if (!isMouse && eventType == EVENT_START) {
  582. self.preventMouseEvents = true;
  583. self.shouldDetect = true;
  584. }
  585. // update the pointer event before entering the detection
  586. if (isPointer && eventType != EVENT_END) {
  587. PointerEvent.updatePointer(eventType, ev);
  588. }
  589. // we are in a touch/down state, so allowed detection of gestures
  590. if (self.shouldDetect) {
  591. triggerType = self.doDetect.call(self, ev, eventType, element, handler);
  592. }
  593. // ...and we are done with the detection
  594. // so reset everything to start each detection totally fresh
  595. if (triggerType == EVENT_END) {
  596. self.preventMouseEvents = false;
  597. self.shouldDetect = false;
  598. PointerEvent.reset();
  599. // update the pointerevent object after the detection
  600. }
  601. if (isPointer && eventType == EVENT_END) {
  602. PointerEvent.updatePointer(eventType, ev);
  603. }
  604. };
  605. this.on(element, EVENT_TYPES[eventType], onTouchHandler, opt);
  606. return onTouchHandler;
  607. },
  608. /**
  609. * the core detection method
  610. * this finds out what GestureDetector-touch-events to trigger
  611. * @param {Object} ev
  612. * @param {String} eventType matches `EVENT_START|MOVE|END`
  613. * @param {HTMLElement} element
  614. * @param {Function} handler
  615. * @return {String} triggerType matches `EVENT_START|MOVE|END`
  616. */
  617. doDetect: function doDetect(ev, eventType, element, handler) {
  618. var touchList = this.getTouchList(ev, eventType);
  619. var touchListLength = touchList.length;
  620. var triggerType = eventType;
  621. var triggerChange = touchList.trigger; // used by fakeMultitouch plugin
  622. var changedLength = touchListLength;
  623. // at each touchstart-like event we want also want to trigger a TOUCH event...
  624. if (eventType == EVENT_START) {
  625. triggerChange = EVENT_TOUCH;
  626. // ...the same for a touchend-like event
  627. } else if (eventType == EVENT_END) {
  628. triggerChange = EVENT_RELEASE;
  629. // keep track of how many touches have been removed
  630. changedLength = touchList.length - (ev.changedTouches ? ev.changedTouches.length : 1);
  631. }
  632. // after there are still touches on the screen,
  633. // we just want to trigger a MOVE event. so change the START or END to a MOVE
  634. // but only after detection has been started, the first time we actually want a START
  635. if (changedLength > 0 && this.started) {
  636. triggerType = EVENT_MOVE;
  637. }
  638. // detection has been started, we keep track of this, see above
  639. this.started = true;
  640. // generate some event data, some basic information
  641. var evData = this.collectEventData(element, triggerType, touchList, ev);
  642. // trigger the triggerType event before the change (TOUCH, RELEASE) events
  643. // but the END event should be at last
  644. if (eventType != EVENT_END) {
  645. handler.call(Detection, evData);
  646. }
  647. // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed
  648. if (triggerChange) {
  649. evData.changedLength = changedLength;
  650. evData.eventType = triggerChange;
  651. handler.call(Detection, evData);
  652. evData.eventType = triggerType;
  653. delete evData.changedLength;
  654. }
  655. // trigger the END event
  656. if (triggerType == EVENT_END) {
  657. handler.call(Detection, evData);
  658. // ...and we are done with the detection
  659. // so reset everything to start each detection totally fresh
  660. this.started = false;
  661. }
  662. return triggerType;
  663. },
  664. /**
  665. * we have different events for each device/browser
  666. * determine what we need and set them in the EVENT_TYPES constant
  667. * the `onTouch` method is bind to these properties.
  668. * @return {Object} events
  669. */
  670. determineEventTypes: function determineEventTypes() {
  671. var types;
  672. if (GestureDetector.HAS_POINTEREVENTS) {
  673. if (window.PointerEvent) {
  674. types = ['pointerdown', 'pointermove', 'pointerup pointercancel lostpointercapture'];
  675. } else {
  676. types = ['MSPointerDown', 'MSPointerMove', 'MSPointerUp MSPointerCancel MSLostPointerCapture'];
  677. }
  678. } else if (GestureDetector.NO_MOUSEEVENTS) {
  679. types = ['touchstart', 'touchmove', 'touchend touchcancel'];
  680. } else {
  681. types = ['touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup'];
  682. }
  683. EVENT_TYPES[EVENT_START] = types[0];
  684. EVENT_TYPES[EVENT_MOVE] = types[1];
  685. EVENT_TYPES[EVENT_END] = types[2];
  686. return EVENT_TYPES;
  687. },
  688. /**
  689. * create touchList depending on the event
  690. * @param {Object} ev
  691. * @param {String} eventType
  692. * @return {Array} touches
  693. */
  694. getTouchList: function getTouchList(ev, eventType) {
  695. // get the fake pointerEvent touchlist
  696. if (GestureDetector.HAS_POINTEREVENTS) {
  697. return PointerEvent.getTouchList();
  698. }
  699. // get the touchlist
  700. if (ev.touches) {
  701. if (eventType == EVENT_MOVE) {
  702. return ev.touches;
  703. }
  704. var identifiers = [];
  705. var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches));
  706. var touchList = [];
  707. Utils.each(concat, function (touch) {
  708. if (Utils.inArray(identifiers, touch.identifier) === -1) {
  709. touchList.push(touch);
  710. }
  711. identifiers.push(touch.identifier);
  712. });
  713. return touchList;
  714. }
  715. // make fake touchList from mouse position
  716. ev.identifier = 1;
  717. return [ev];
  718. },
  719. /**
  720. * collect basic event data
  721. * @param {HTMLElement} element
  722. * @param {String} eventType matches `EVENT_START|MOVE|END`
  723. * @param {Array} touches
  724. * @param {Object} ev
  725. * @return {Object} ev
  726. */
  727. collectEventData: function collectEventData(element, eventType, touches, ev) {
  728. // find out pointerType
  729. var pointerType = POINTER_TOUCH;
  730. if (Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) {
  731. pointerType = POINTER_MOUSE;
  732. } else if (PointerEvent.matchType(POINTER_PEN, ev)) {
  733. pointerType = POINTER_PEN;
  734. }
  735. return {
  736. center: Utils.getCenter(touches),
  737. timeStamp: Date.now(),
  738. target: ev.target,
  739. touches: touches,
  740. eventType: eventType,
  741. pointerType: pointerType,
  742. srcEvent: ev,
  743. /**
  744. * prevent the browser default actions
  745. * mostly used to disable scrolling of the browser
  746. */
  747. preventDefault: function preventDefault() {
  748. var srcEvent = this.srcEvent;
  749. srcEvent.preventManipulation && srcEvent.preventManipulation();
  750. srcEvent.preventDefault && srcEvent.preventDefault();
  751. },
  752. /**
  753. * stop bubbling the event up to its parents
  754. */
  755. stopPropagation: function stopPropagation() {
  756. this.srcEvent.stopPropagation();
  757. },
  758. /**
  759. * immediately stop gesture detection
  760. * might be useful after a swipe was detected
  761. * @return {*}
  762. */
  763. stopDetect: function stopDetect() {
  764. return Detection.stopDetect();
  765. }
  766. };
  767. }
  768. };
  769. /**
  770. * @module GestureDetector
  771. *
  772. * @class PointerEvent
  773. * @static
  774. */
  775. PointerEvent = GestureDetector.PointerEvent = {
  776. /**
  777. * holds all pointers, by `identifier`
  778. * @property pointers
  779. * @type {Object}
  780. */
  781. pointers: {},
  782. /**
  783. * get the pointers as an array
  784. * @return {Array} touchlist
  785. */
  786. getTouchList: function getTouchList() {
  787. var touchlist = [];
  788. // we can use forEach since pointerEvents only is in IE10
  789. Utils.each(this.pointers, function (pointer) {
  790. touchlist.push(pointer);
  791. });
  792. return touchlist;
  793. },
  794. /**
  795. * update the position of a pointer
  796. * @param {String} eventType matches `EVENT_START|MOVE|END`
  797. * @param {Object} pointerEvent
  798. */
  799. updatePointer: function updatePointer(eventType, pointerEvent) {
  800. if (eventType == EVENT_END || eventType != EVENT_END && pointerEvent.buttons !== 1) {
  801. delete this.pointers[pointerEvent.pointerId];
  802. } else {
  803. pointerEvent.identifier = pointerEvent.pointerId;
  804. this.pointers[pointerEvent.pointerId] = pointerEvent;
  805. }
  806. },
  807. /**
  808. * check if ev matches pointertype
  809. * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN`
  810. * @param {PointerEvent} ev
  811. */
  812. matchType: function matchType(pointerType, ev) {
  813. if (!ev.pointerType) {
  814. return false;
  815. }
  816. var pt = ev.pointerType,
  817. types = {};
  818. types[POINTER_MOUSE] = pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE);
  819. types[POINTER_TOUCH] = pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH);
  820. types[POINTER_PEN] = pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN);
  821. return types[pointerType];
  822. },
  823. /**
  824. * reset the stored pointers
  825. */
  826. reset: function resetList() {
  827. this.pointers = {};
  828. }
  829. };
  830. /**
  831. * @module GestureDetector
  832. *
  833. * @class Detection
  834. * @static
  835. */
  836. Detection = GestureDetector.detection = {
  837. // contains all registered GestureDetector.gestures in the correct order
  838. gestures: [],
  839. // data of the current GestureDetector.gesture detection session
  840. current: null,
  841. // the previous GestureDetector.gesture session data
  842. // is a full clone of the previous gesture.current object
  843. previous: null,
  844. // when this becomes true, no gestures are fired
  845. stopped: false,
  846. /**
  847. * start GestureDetector.gesture detection
  848. * @param {GestureDetector.Instance} inst
  849. * @param {Object} eventData
  850. */
  851. startDetect: function startDetect(inst, eventData) {
  852. // already busy with a GestureDetector.gesture detection on an element
  853. if (this.current) {
  854. return;
  855. }
  856. this.stopped = false;
  857. // holds current session
  858. this.current = {
  859. inst: inst, // reference to GestureDetectorInstance we're working for
  860. startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc
  861. lastEvent: false, // last eventData
  862. lastCalcEvent: false, // last eventData for calculations.
  863. futureCalcEvent: false, // last eventData for calculations.
  864. lastCalcData: {}, // last lastCalcData
  865. name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  866. };
  867. this.detect(eventData);
  868. },
  869. /**
  870. * GestureDetector.gesture detection
  871. * @param {Object} eventData
  872. * @return {any}
  873. */
  874. detect: function detect(eventData) {
  875. if (!this.current || this.stopped) {
  876. return;
  877. }
  878. // extend event data with calculations about scale, distance etc
  879. eventData = this.extendEventData(eventData);
  880. // GestureDetector instance and instance options
  881. var inst = this.current.inst,
  882. instOptions = inst.options;
  883. // call GestureDetector.gesture handlers
  884. Utils.each(this.gestures, function triggerGesture(gesture) {
  885. // only when the instance options have enabled this gesture
  886. if (!this.stopped && inst.enabled && instOptions[gesture.name]) {
  887. gesture.handler.call(gesture, eventData, inst);
  888. }
  889. }, this);
  890. // store as previous event event
  891. if (this.current) {
  892. this.current.lastEvent = eventData;
  893. }
  894. if (eventData.eventType == EVENT_END) {
  895. this.stopDetect();
  896. }
  897. return eventData; // eslint-disable-line consistent-return
  898. },
  899. /**
  900. * clear the GestureDetector.gesture vars
  901. * this is called on endDetect, but can also be used when a final GestureDetector.gesture has been detected
  902. * to stop other GestureDetector.gestures from being fired
  903. */
  904. stopDetect: function stopDetect() {
  905. // clone current data to the store as the previous gesture
  906. // used for the double tap gesture, since this is an other gesture detect session
  907. this.previous = Utils.extend({}, this.current);
  908. // reset the current
  909. this.current = null;
  910. this.stopped = true;
  911. },
  912. /**
  913. * calculate velocity, angle and direction
  914. * @param {Object} ev
  915. * @param {Object} center
  916. * @param {Number} deltaTime
  917. * @param {Number} deltaX
  918. * @param {Number} deltaY
  919. */
  920. getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) {
  921. var cur = this.current,
  922. recalc = false,
  923. calcEv = cur.lastCalcEvent,
  924. calcData = cur.lastCalcData;
  925. if (calcEv && ev.timeStamp - calcEv.timeStamp > GestureDetector.CALCULATE_INTERVAL) {
  926. center = calcEv.center;
  927. deltaTime = ev.timeStamp - calcEv.timeStamp;
  928. deltaX = ev.center.clientX - calcEv.center.clientX;
  929. deltaY = ev.center.clientY - calcEv.center.clientY;
  930. recalc = true;
  931. }
  932. if (ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  933. cur.futureCalcEvent = ev;
  934. }
  935. if (!cur.lastCalcEvent || recalc) {
  936. calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY);
  937. calcData.angle = Utils.getAngle(center, ev.center);
  938. calcData.direction = Utils.getDirection(center, ev.center);
  939. cur.lastCalcEvent = cur.futureCalcEvent || ev;
  940. cur.futureCalcEvent = ev;
  941. }
  942. ev.velocityX = calcData.velocity.x;
  943. ev.velocityY = calcData.velocity.y;
  944. ev.interimAngle = calcData.angle;
  945. ev.interimDirection = calcData.direction;
  946. },
  947. /**
  948. * extend eventData for GestureDetector.gestures
  949. * @param {Object} ev
  950. * @return {Object} ev
  951. */
  952. extendEventData: function extendEventData(ev) {
  953. var cur = this.current,
  954. startEv = cur.startEvent,
  955. lastEv = cur.lastEvent || startEv;
  956. // update the start touchlist to calculate the scale/rotation
  957. if (ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
  958. startEv.touches = [];
  959. Utils.each(ev.touches, function (touch) {
  960. startEv.touches.push({
  961. clientX: touch.clientX,
  962. clientY: touch.clientY
  963. });
  964. });
  965. }
  966. var deltaTime = ev.timeStamp - startEv.timeStamp,
  967. deltaX = ev.center.clientX - startEv.center.clientX,
  968. deltaY = ev.center.clientY - startEv.center.clientY;
  969. this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY);
  970. Utils.extend(ev, {
  971. startEvent: startEv,
  972. deltaTime: deltaTime,
  973. deltaX: deltaX,
  974. deltaY: deltaY,
  975. distance: Utils.getDistance(startEv.center, ev.center),
  976. angle: Utils.getAngle(startEv.center, ev.center),
  977. direction: Utils.getDirection(startEv.center, ev.center),
  978. scale: Utils.getScale(startEv.touches, ev.touches),
  979. rotation: Utils.getRotation(startEv.touches, ev.touches)
  980. });
  981. return ev;
  982. },
  983. /**
  984. * register new gesture
  985. * @param {Object} gesture object, see `gestures/` for documentation
  986. * @return {Array} gestures
  987. */
  988. register: function register(gesture) {
  989. // add an enable gesture options if there is no given
  990. var options = gesture.defaults || {};
  991. if (options[gesture.name] === undefined) {
  992. options[gesture.name] = true;
  993. }
  994. // extend GestureDetector default options with the GestureDetector.gesture options
  995. Utils.extend(GestureDetector.defaults, options, true);
  996. // set its index
  997. gesture.index = gesture.index || 1000;
  998. // add GestureDetector.gesture to the list
  999. this.gestures.push(gesture);
  1000. // sort the list by index
  1001. this.gestures.sort(function (a, b) {
  1002. if (a.index < b.index) {
  1003. return -1;
  1004. }
  1005. if (a.index > b.index) {
  1006. return 1;
  1007. }
  1008. return 0;
  1009. });
  1010. return this.gestures;
  1011. }
  1012. };
  1013. /**
  1014. * @module GestureDetector
  1015. */
  1016. /**
  1017. * create new GestureDetector instance
  1018. * all methods should return the instance itself, so it is chainable.
  1019. *
  1020. * @class Instance
  1021. * @constructor
  1022. * @param {HTMLElement} element
  1023. * @param {Object} [options={}] options are merged with `GestureDetector.defaults`
  1024. * @return {GestureDetector.Instance}
  1025. */
  1026. GestureDetector.Instance = function (element, options) {
  1027. var self = this;
  1028. var listenerOptions = options && options.passive ? { passive: true } : undefined;
  1029. // setup GestureDetectorJS window events and register all gestures
  1030. // this also sets up the default options
  1031. setup(listenerOptions);
  1032. /**
  1033. * @property element
  1034. * @type {HTMLElement}
  1035. */
  1036. this.element = element;
  1037. /**
  1038. * @property enabled
  1039. * @type {Boolean}
  1040. * @protected
  1041. */
  1042. this.enabled = true;
  1043. /**
  1044. * options, merged with the defaults
  1045. * options with an _ are converted to camelCase
  1046. * @property options
  1047. * @type {Object}
  1048. */
  1049. Utils.each(options, function (value, name) {
  1050. delete options[name];
  1051. options[Utils.toCamelCase(name)] = value;
  1052. });
  1053. this.options = Utils.extend(Utils.extend({}, GestureDetector.defaults), options || {});
  1054. this.options.listenerOptions = listenerOptions;
  1055. // add some css to the element to prevent the browser from doing its native behavior
  1056. if (this.options.behavior) {
  1057. Utils.toggleBehavior(this.element, this.options.behavior, true);
  1058. }
  1059. /**
  1060. * event start handler on the element to start the detection
  1061. * @property eventStartHandler
  1062. * @type {Object}
  1063. */
  1064. this.eventStartHandler = Event.onTouch(element, EVENT_START, function (ev) {
  1065. if (self.enabled && ev.eventType == EVENT_START) {
  1066. Detection.startDetect(self, ev);
  1067. } else if (ev.eventType == EVENT_TOUCH) {
  1068. Detection.detect(ev);
  1069. }
  1070. }, listenerOptions);
  1071. /**
  1072. * keep a list of user event handlers which needs to be removed when calling 'dispose'
  1073. * @property eventHandlers
  1074. * @type {Array}
  1075. */
  1076. this.eventHandlers = [];
  1077. };
  1078. GestureDetector.Instance.prototype = {
  1079. /**
  1080. * @method on
  1081. * @signature on(gestures, handler)
  1082. * @description
  1083. * [en]Adds an event handler for a gesture. Available gestures are: drag, dragleft, dragright, dragup, dragdown, hold, release, swipe, swipeleft, swiperight, swipeup, swipedown, tap, doubletap, touch, transform, pinch, pinchin, pinchout and rotate. [/en]
  1084. * [ja]ジェスチャに対するイベントハンドラを追加します。指定できるジェスチャ名は、drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate です。[/ja]
  1085. * @param {String} gestures
  1086. * [en]A space separated list of gestures.[/en]
  1087. * [ja]検知するジェスチャ名を指定します。スペースで複数指定することができます。[/ja]
  1088. * @param {Function} handler
  1089. * [en]An event handling function.[/en]
  1090. * [ja]イベントハンドラとなる関数オブジェクトを指定します。[/ja]
  1091. */
  1092. on: function onEvent(gestures, handler, opt) {
  1093. var self = this;
  1094. Event.on(self.element, gestures, handler, util.extend({}, self.options.listenerOptions, opt), function (type) {
  1095. self.eventHandlers.push({ gesture: type, handler: handler });
  1096. });
  1097. return self;
  1098. },
  1099. /**
  1100. * @method off
  1101. * @signature off(gestures, handler)
  1102. * @description
  1103. * [en]Remove an event listener.[/en]
  1104. * [ja]イベントリスナーを削除します。[/ja]
  1105. * @param {String} gestures
  1106. * [en]A space separated list of gestures.[/en]
  1107. * [ja]ジェスチャ名を指定します。スペースで複数指定することができます。[/ja]
  1108. * @param {Function} handler
  1109. * [en]An event handling function.[/en]
  1110. * [ja]イベントハンドラとなる関数オブジェクトを指定します。[/ja]
  1111. */
  1112. off: function offEvent(gestures, handler, opt) {
  1113. var self = this;
  1114. Event.off(self.element, gestures, handler, util.extend({}, self.options.listenerOptions, opt), function (type) {
  1115. var index = Utils.inArray(self.eventHandlers, { gesture: type, handler: handler }, true);
  1116. if (index >= 0) {
  1117. self.eventHandlers.splice(index, 1);
  1118. }
  1119. });
  1120. return self;
  1121. },
  1122. /**
  1123. * trigger gesture event
  1124. * @method trigger
  1125. * @signature trigger(gesture, eventData)
  1126. * @param {String} gesture
  1127. * @param {Object} [eventData]
  1128. */
  1129. trigger: function triggerEvent(gesture, eventData) {
  1130. // optional
  1131. if (!eventData) {
  1132. eventData = {};
  1133. }
  1134. // create DOM event
  1135. var event = GestureDetector.DOCUMENT.createEvent('Event');
  1136. event.initEvent(gesture, true, true);
  1137. event.gesture = eventData;
  1138. // trigger on the target if it is in the instance element,
  1139. // this is for event delegation tricks
  1140. var element = this.element;
  1141. if (Utils.hasParent(eventData.target, element)) {
  1142. element = eventData.target;
  1143. }
  1144. element.dispatchEvent(event);
  1145. return this;
  1146. },
  1147. /**
  1148. * @method enable
  1149. * @signature enable(state)
  1150. * @description
  1151. * [en]Enable or disable gesture detection.[/en]
  1152. * [ja]ジェスチャ検知を有効化/無効化します。[/ja]
  1153. * @param {Boolean} state
  1154. * [en]Specify if it should be enabled or not.[/en]
  1155. * [ja]有効にするかどうかを指定します。[/ja]
  1156. */
  1157. enable: function enable(state) {
  1158. this.enabled = state;
  1159. return this;
  1160. },
  1161. /**
  1162. * @method dispose
  1163. * @signature dispose()
  1164. * @description
  1165. * [en]Remove and destroy all event handlers for this instance.[/en]
  1166. * [ja]このインスタンスでのジェスチャの検知や、イベントハンドラを全て解除して廃棄します。[/ja]
  1167. */
  1168. dispose: function dispose() {
  1169. var i, eh;
  1170. // undo all changes made by stop_browser_behavior
  1171. Utils.toggleBehavior(this.element, this.options.behavior, false);
  1172. // unbind all custom event handlers
  1173. for (i = -1; eh = this.eventHandlers[++i];) {
  1174. // eslint-disable-line no-cond-assign
  1175. Utils.off(this.element, eh.gesture, eh.handler);
  1176. }
  1177. this.eventHandlers = [];
  1178. // unbind the start event listener
  1179. Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler);
  1180. return null;
  1181. }
  1182. };
  1183. /**
  1184. * @module gestures
  1185. */
  1186. /**
  1187. * Move with x fingers (default 1) around on the page.
  1188. * Preventing the default browser behavior is a good way to improve feel and working.
  1189. * ````
  1190. * GestureDetectortime.on("drag", function(ev) {
  1191. * console.log(ev);
  1192. * ev.gesture.preventDefault();
  1193. * });
  1194. * ````
  1195. *
  1196. * @class Drag
  1197. * @static
  1198. */
  1199. /**
  1200. * @event drag
  1201. * @param {Object} ev
  1202. */
  1203. /**
  1204. * @event dragstart
  1205. * @param {Object} ev
  1206. */
  1207. /**
  1208. * @event dragend
  1209. * @param {Object} ev
  1210. */
  1211. /**
  1212. * @event drapleft
  1213. * @param {Object} ev
  1214. */
  1215. /**
  1216. * @event dragright
  1217. * @param {Object} ev
  1218. */
  1219. /**
  1220. * @event dragup
  1221. * @param {Object} ev
  1222. */
  1223. /**
  1224. * @event dragdown
  1225. * @param {Object} ev
  1226. */
  1227. /**
  1228. * @param {String} name
  1229. */
  1230. (function (name) {
  1231. var triggered = false;
  1232. function dragGesture(ev, inst) {
  1233. var cur = Detection.current;
  1234. // max touches
  1235. if (inst.options.dragMaxTouches > 0 && ev.touches.length > inst.options.dragMaxTouches) {
  1236. return;
  1237. }
  1238. switch (ev.eventType) {
  1239. case EVENT_START:
  1240. triggered = false;
  1241. break;
  1242. case EVENT_MOVE:
  1243. // when the distance we moved is too small we skip this gesture
  1244. // or we can be already in dragging
  1245. if (ev.distance < inst.options.dragMinDistance && cur.name != name) {
  1246. return;
  1247. }
  1248. var startCenter = cur.startEvent.center;
  1249. // we are dragging!
  1250. if (cur.name != name) {
  1251. cur.name = name;
  1252. if (inst.options.dragDistanceCorrection && ev.distance > 0) {
  1253. // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center.
  1254. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0.
  1255. // It might be useful to save the original start point somewhere
  1256. var factor = Math.abs(inst.options.dragMinDistance / ev.distance);
  1257. startCenter.pageX += ev.deltaX * factor;
  1258. startCenter.pageY += ev.deltaY * factor;
  1259. startCenter.clientX += ev.deltaX * factor;
  1260. startCenter.clientY += ev.deltaY * factor;
  1261. // recalculate event data using new start point
  1262. ev = Detection.extendEventData(ev);
  1263. }
  1264. }
  1265. // lock drag to axis?
  1266. if (cur.lastEvent.dragLockToAxis || inst.options.dragLockToAxis && inst.options.dragLockMinDistance <= ev.distance) {
  1267. ev.dragLockToAxis = true;
  1268. }
  1269. // keep direction on the axis that the drag gesture started on
  1270. var lastDirection = cur.lastEvent.direction;
  1271. if (ev.dragLockToAxis && lastDirection !== ev.direction) {
  1272. if (Utils.isVertical(lastDirection)) {
  1273. ev.direction = ev.deltaY < 0 ? DIRECTION_UP : DIRECTION_DOWN;
  1274. } else {
  1275. ev.direction = ev.deltaX < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  1276. }
  1277. }
  1278. // first time, trigger dragstart event
  1279. if (!triggered) {
  1280. inst.trigger(name + 'start', ev);
  1281. triggered = true;
  1282. }
  1283. // trigger events
  1284. inst.trigger(name, ev);
  1285. inst.trigger(name + ev.direction, ev);
  1286. var isVertical = Utils.isVertical(ev.direction);
  1287. // block the browser events
  1288. if (inst.options.dragBlockVertical && isVertical || inst.options.dragBlockHorizontal && !isVertical) {
  1289. ev.preventDefault();
  1290. }
  1291. break;
  1292. case EVENT_RELEASE:
  1293. if (triggered && ev.changedLength <= inst.options.dragMaxTouches) {
  1294. inst.trigger(name + 'end', ev);
  1295. triggered = false;
  1296. }
  1297. break;
  1298. case EVENT_END:
  1299. triggered = false;
  1300. break;
  1301. }
  1302. }
  1303. GestureDetector.gestures.Drag = {
  1304. name: name,
  1305. index: 50,
  1306. handler: dragGesture,
  1307. defaults: {
  1308. /**
  1309. * minimal movement that have to be made before the drag event gets triggered
  1310. * @property dragMinDistance
  1311. * @type {Number}
  1312. * @default 10
  1313. */
  1314. dragMinDistance: 10,
  1315. /**
  1316. * Set dragDistanceCorrection to true to make the starting point of the drag
  1317. * be calculated from where the drag was triggered, not from where the touch started.
  1318. * Useful to avoid a jerk-starting drag, which can make fine-adjustments
  1319. * through dragging difficult, and be visually unappealing.
  1320. * @property dragDistanceCorrection
  1321. * @type {Boolean}
  1322. * @default true
  1323. */
  1324. dragDistanceCorrection: true,
  1325. /**
  1326. * set 0 for unlimited, but this can conflict with transform
  1327. * @property dragMaxTouches
  1328. * @type {Number}
  1329. * @default 1
  1330. */
  1331. dragMaxTouches: 1,
  1332. /**
  1333. * prevent default browser behavior when dragging occurs
  1334. * be careful with it, it makes the element a blocking element
  1335. * when you are using the drag gesture, it is a good practice to set this true
  1336. * @property dragBlockHorizontal
  1337. * @type {Boolean}
  1338. * @default false
  1339. */
  1340. dragBlockHorizontal: false,
  1341. /**
  1342. * same as `dragBlockHorizontal`, but for vertical movement
  1343. * @property dragBlockVertical
  1344. * @type {Boolean}
  1345. * @default false
  1346. */
  1347. dragBlockVertical: false,
  1348. /**
  1349. * dragLockToAxis keeps the drag gesture on the axis that it started on,
  1350. * It disallows vertical directions if the initial direction was horizontal, and vice versa.
  1351. * @property dragLockToAxis
  1352. * @type {Boolean}
  1353. * @default false
  1354. */
  1355. dragLockToAxis: false,
  1356. /**
  1357. * drag lock only kicks in when distance > dragLockMinDistance
  1358. * This way, locking occurs only when the distance has become large enough to reliably determine the direction
  1359. * @property dragLockMinDistance
  1360. * @type {Number}
  1361. * @default 25
  1362. */
  1363. dragLockMinDistance: 25
  1364. }
  1365. };
  1366. })('drag');
  1367. /**
  1368. * @module gestures
  1369. */
  1370. /**
  1371. * trigger a simple gesture event, so you can do anything in your handler.
  1372. * only usable if you know what your doing...
  1373. *
  1374. * @class Gesture
  1375. * @static
  1376. */
  1377. /**
  1378. * @event gesture
  1379. * @param {Object} ev
  1380. */
  1381. GestureDetector.gestures.Gesture = {
  1382. name: 'gesture',
  1383. index: 1337,
  1384. handler: function releaseGesture(ev, inst) {
  1385. inst.trigger(this.name, ev);
  1386. }
  1387. };
  1388. /**
  1389. * @module gestures
  1390. */
  1391. /**
  1392. * Touch stays at the same place for x time
  1393. *
  1394. * @class Hold
  1395. * @static
  1396. */
  1397. /**
  1398. * @event hold
  1399. * @param {Object} ev
  1400. */
  1401. /**
  1402. * @param {String} name
  1403. */
  1404. (function (name) {
  1405. var timer;
  1406. function holdGesture(ev, inst) {
  1407. var options = inst.options,
  1408. current = Detection.current;
  1409. switch (ev.eventType) {
  1410. case EVENT_START:
  1411. clearTimeout(timer);
  1412. // set the gesture so we can check in the timeout if it still is
  1413. current.name = name;
  1414. // set timer and if after the timeout it still is hold,
  1415. // we trigger the hold event
  1416. timer = setTimeout(function () {
  1417. if (current && current.name == name) {
  1418. inst.trigger(name, ev);
  1419. }
  1420. }, options.holdTimeout);
  1421. break;
  1422. case EVENT_MOVE:
  1423. if (ev.distance > options.holdThreshold) {
  1424. clearTimeout(timer);
  1425. }
  1426. break;
  1427. case EVENT_RELEASE:
  1428. clearTimeout(timer);
  1429. break;
  1430. }
  1431. }
  1432. GestureDetector.gestures.Hold = {
  1433. name: name,
  1434. index: 10,
  1435. defaults: {
  1436. /**
  1437. * @property holdTimeout
  1438. * @type {Number}
  1439. * @default 500
  1440. */
  1441. holdTimeout: 500,
  1442. /**
  1443. * movement allowed while holding
  1444. * @property holdThreshold
  1445. * @type {Number}
  1446. * @default 2
  1447. */
  1448. holdThreshold: 2
  1449. },
  1450. handler: holdGesture
  1451. };
  1452. })('hold');
  1453. /**
  1454. * @module gestures
  1455. */
  1456. /**
  1457. * when a touch is being released from the page
  1458. *
  1459. * @class Release
  1460. * @static
  1461. */
  1462. /**
  1463. * @event release
  1464. * @param {Object} ev
  1465. */
  1466. GestureDetector.gestures.Release = {
  1467. name: 'release',
  1468. index: Infinity,
  1469. handler: function releaseGesture(ev, inst) {
  1470. if (ev.eventType == EVENT_RELEASE) {
  1471. inst.trigger(this.name, ev);
  1472. }
  1473. }
  1474. };
  1475. /**
  1476. * @module gestures
  1477. */
  1478. /**
  1479. * triggers swipe events when the end velocity is above the threshold
  1480. * for best usage, set `preventDefault` (on the drag gesture) to `true`
  1481. * ````
  1482. * GestureDetectortime.on("dragleft swipeleft", function(ev) {
  1483. * console.log(ev);
  1484. * ev.gesture.preventDefault();
  1485. * });
  1486. * ````
  1487. *
  1488. * @class Swipe
  1489. * @static
  1490. */
  1491. /**
  1492. * @event swipe
  1493. * @param {Object} ev
  1494. */
  1495. /**
  1496. * @event swipeleft
  1497. * @param {Object} ev
  1498. */
  1499. /**
  1500. * @event swiperight
  1501. * @param {Object} ev
  1502. */
  1503. /**
  1504. * @event swipeup
  1505. * @param {Object} ev
  1506. */
  1507. /**
  1508. * @event swipedown
  1509. * @param {Object} ev
  1510. */
  1511. GestureDetector.gestures.Swipe = {
  1512. name: 'swipe',
  1513. index: 40,
  1514. defaults: {
  1515. /**
  1516. * @property swipeMinTouches
  1517. * @type {Number}
  1518. * @default 1
  1519. */
  1520. swipeMinTouches: 1,
  1521. /**
  1522. * @property swipeMaxTouches
  1523. * @type {Number}
  1524. * @default 1
  1525. */
  1526. swipeMaxTouches: 1,
  1527. /**
  1528. * horizontal swipe velocity
  1529. * @property swipeVelocityX
  1530. * @type {Number}
  1531. * @default 0.6
  1532. */
  1533. swipeVelocityX: 0.6,
  1534. /**
  1535. * vertical swipe velocity
  1536. * @property swipeVelocityY
  1537. * @type {Number}
  1538. * @default 0.6
  1539. */
  1540. swipeVelocityY: 0.6
  1541. },
  1542. handler: function swipeGesture(ev, inst) {
  1543. if (ev.eventType == EVENT_RELEASE) {
  1544. var touches = ev.touches.length,
  1545. options = inst.options;
  1546. // max touches
  1547. if (touches < options.swipeMinTouches || touches > options.swipeMaxTouches) {
  1548. return;
  1549. }
  1550. // when the distance we moved is too small we skip this gesture
  1551. // or we can be already in dragging
  1552. if (ev.velocityX > options.swipeVelocityX || ev.velocityY > options.swipeVelocityY) {
  1553. // trigger swipe events
  1554. inst.trigger(this.name, ev);
  1555. inst.trigger(this.name + ev.direction, ev);
  1556. }
  1557. }
  1558. }
  1559. };
  1560. /**
  1561. * @module gestures
  1562. */
  1563. /**
  1564. * Single tap and a double tap on a place
  1565. *
  1566. * @class Tap
  1567. * @static
  1568. */
  1569. /**
  1570. * @event tap
  1571. * @param {Object} ev
  1572. */
  1573. /**
  1574. * @event doubletap
  1575. * @param {Object} ev
  1576. */
  1577. /**
  1578. * @param {String} name
  1579. */
  1580. (function (name) {
  1581. var hasMoved = false;
  1582. function tapGesture(ev, inst) {
  1583. var options = inst.options,
  1584. current = Detection.current,
  1585. prev = Detection.previous,
  1586. sincePrev,
  1587. didDoubleTap;
  1588. switch (ev.eventType) {
  1589. case EVENT_START:
  1590. hasMoved = false;
  1591. break;
  1592. case EVENT_MOVE:
  1593. hasMoved = hasMoved || ev.distance > options.tapMaxDistance;
  1594. break;
  1595. case EVENT_END:
  1596. if (!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) {
  1597. // previous gesture, for the double tap since these are two different gesture detections
  1598. sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp;
  1599. didDoubleTap = false;
  1600. // check if double tap
  1601. if (prev && prev.name == name && sincePrev && sincePrev < options.doubleTapInterval && ev.distance < options.doubleTapDistance) {
  1602. inst.trigger('doubletap', ev);
  1603. didDoubleTap = true;
  1604. }
  1605. // do a single tap
  1606. if (!didDoubleTap || options.tapAlways) {
  1607. current.name = name;
  1608. inst.trigger(current.name, ev);
  1609. }
  1610. }
  1611. break;
  1612. }
  1613. }
  1614. GestureDetector.gestures.Tap = {
  1615. name: name,
  1616. index: 100,
  1617. handler: tapGesture,
  1618. defaults: {
  1619. /**
  1620. * max time of a tap, this is for the slow tappers
  1621. * @property tapMaxTime
  1622. * @type {Number}
  1623. * @default 250
  1624. */
  1625. tapMaxTime: 250,
  1626. /**
  1627. * max distance of movement of a tap, this is for the slow tappers
  1628. * @property tapMaxDistance
  1629. * @type {Number}
  1630. * @default 10
  1631. */
  1632. tapMaxDistance: 10,
  1633. /**
  1634. * always trigger the `tap` event, even while double-tapping
  1635. * @property tapAlways
  1636. * @type {Boolean}
  1637. * @default true
  1638. */
  1639. tapAlways: true,
  1640. /**
  1641. * max distance between two taps
  1642. * @property doubleTapDistance
  1643. * @type {Number}
  1644. * @default 20
  1645. */
  1646. doubleTapDistance: 20,
  1647. /**
  1648. * max time between two taps
  1649. * @property doubleTapInterval
  1650. * @type {Number}
  1651. * @default 300
  1652. */
  1653. doubleTapInterval: 300
  1654. }
  1655. };
  1656. })('tap');
  1657. /**
  1658. * @module gestures
  1659. */
  1660. /**
  1661. * when a touch is being touched at the page
  1662. *
  1663. * @class Touch
  1664. * @static
  1665. */
  1666. /**
  1667. * @event touch
  1668. * @param {Object} ev
  1669. */
  1670. GestureDetector.gestures.Touch = {
  1671. name: 'touch',
  1672. index: -Infinity,
  1673. defaults: {
  1674. /**
  1675. * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page,
  1676. * but it improves gestures like transforming and dragging.
  1677. * be careful with using this, it can be very annoying for users to be stuck on the page
  1678. * @property preventDefault
  1679. * @type {Boolean}
  1680. * @default false
  1681. */
  1682. preventDefault: false,
  1683. /**
  1684. * disable mouse events, so only touch (or pen!) input triggers events
  1685. * @property preventMouse
  1686. * @type {Boolean}
  1687. * @default false
  1688. */
  1689. preventMouse: false
  1690. },
  1691. handler: function touchGesture(ev, inst) {
  1692. if (inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) {
  1693. ev.stopDetect();
  1694. return;
  1695. }
  1696. if (inst.options.preventDefault) {
  1697. ev.preventDefault();
  1698. }
  1699. if (ev.eventType == EVENT_TOUCH) {
  1700. inst.trigger('touch', ev);
  1701. }
  1702. }
  1703. };
  1704. /**
  1705. * @module gestures
  1706. */
  1707. /**
  1708. * User want to scale or rotate with 2 fingers
  1709. * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the
  1710. * `preventDefault` option.
  1711. *
  1712. * @class Transform
  1713. * @static
  1714. */
  1715. /**
  1716. * @event transform
  1717. * @param {Object} ev
  1718. */
  1719. /**
  1720. * @event transformstart
  1721. * @param {Object} ev
  1722. */
  1723. /**
  1724. * @event transformend
  1725. * @param {Object} ev
  1726. */
  1727. /**
  1728. * @event pinchin
  1729. * @param {Object} ev
  1730. */
  1731. /**
  1732. * @event pinchout
  1733. * @param {Object} ev
  1734. */
  1735. /**
  1736. * @event rotate
  1737. * @param {Object} ev
  1738. */
  1739. /**
  1740. * @param {String} name
  1741. */
  1742. (function (name) {
  1743. var triggered = false;
  1744. function transformGesture(ev, inst) {
  1745. switch (ev.eventType) {
  1746. case EVENT_START:
  1747. triggered = false;
  1748. break;
  1749. case EVENT_MOVE:
  1750. // at least multitouch
  1751. if (ev.touches.length < 2) {
  1752. return;
  1753. }
  1754. var scaleThreshold = Math.abs(1 - ev.scale);
  1755. var rotationThreshold = Math.abs(ev.rotation);
  1756. // when the distance we moved is too small we skip this gesture
  1757. // or we can be already in dragging
  1758. if (scaleThreshold < inst.options.transformMinScale && rotationThreshold < inst.options.transformMinRotation) {
  1759. return;
  1760. }
  1761. // we are transforming!
  1762. Detection.current.name = name;
  1763. // first time, trigger dragstart event
  1764. if (!triggered) {
  1765. inst.trigger(name + 'start', ev);
  1766. triggered = true;
  1767. }
  1768. inst.trigger(name, ev); // basic transform event
  1769. // trigger rotate event
  1770. if (rotationThreshold > inst.options.transformMinRotation) {
  1771. inst.trigger('rotate', ev);
  1772. }
  1773. // trigger pinch event
  1774. if (scaleThreshold > inst.options.transformMinScale) {
  1775. inst.trigger('pinch', ev);
  1776. inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev);
  1777. }
  1778. break;
  1779. case EVENT_RELEASE:
  1780. if (triggered && ev.changedLength < 2) {
  1781. inst.trigger(name + 'end', ev);
  1782. triggered = false;
  1783. }
  1784. break;
  1785. }
  1786. }
  1787. GestureDetector.gestures.Transform = {
  1788. name: name,
  1789. index: 45,
  1790. defaults: {
  1791. /**
  1792. * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  1793. * @property transformMinScale
  1794. * @type {Number}
  1795. * @default 0.01
  1796. */
  1797. transformMinScale: 0.01,
  1798. /**
  1799. * rotation in degrees
  1800. * @property transformMinRotation
  1801. * @type {Number}
  1802. * @default 1
  1803. */
  1804. transformMinRotation: 1
  1805. },
  1806. handler: transformGesture
  1807. };
  1808. })('transform');
  1809. export default GestureDetector;