angular-touch.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. /**
  2. * @license AngularJS v1.6.3
  3. * (c) 2010-2017 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, angular) {'use strict';
  7. /* global ngTouchClickDirectiveFactory: false */
  8. /**
  9. * @ngdoc module
  10. * @name ngTouch
  11. * @description
  12. *
  13. * # ngTouch
  14. *
  15. * The `ngTouch` module provides touch events and other helpers for touch-enabled devices.
  16. * The implementation is based on jQuery Mobile touch event handling
  17. * ([jquerymobile.com](http://jquerymobile.com/)).
  18. *
  19. *
  20. * See {@link ngTouch.$swipe `$swipe`} for usage.
  21. *
  22. * <div doc-module-components="ngTouch"></div>
  23. *
  24. */
  25. // define ngTouch module
  26. /* global -ngTouch */
  27. var ngTouch = angular.module('ngTouch', []);
  28. ngTouch.info({ angularVersion: '1.6.3' });
  29. ngTouch.provider('$touch', $TouchProvider);
  30. function nodeName_(element) {
  31. return angular.lowercase(element.nodeName || (element[0] && element[0].nodeName));
  32. }
  33. /**
  34. * @ngdoc provider
  35. * @name $touchProvider
  36. *
  37. * @description
  38. * The `$touchProvider` allows enabling / disabling {@link ngTouch.ngClick ngTouch's ngClick directive}.
  39. */
  40. $TouchProvider.$inject = ['$provide', '$compileProvider'];
  41. function $TouchProvider($provide, $compileProvider) {
  42. /**
  43. * @ngdoc method
  44. * @name $touchProvider#ngClickOverrideEnabled
  45. *
  46. * @param {boolean=} enabled update the ngClickOverrideEnabled state if provided, otherwise just return the
  47. * current ngClickOverrideEnabled state
  48. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  49. *
  50. * @kind function
  51. *
  52. * @description
  53. * Call this method to enable/disable {@link ngTouch.ngClick ngTouch's ngClick directive}. If enabled,
  54. * the default ngClick directive will be replaced by a version that eliminates the 300ms delay for
  55. * click events on browser for touch-devices.
  56. *
  57. * The default is `false`.
  58. *
  59. */
  60. var ngClickOverrideEnabled = false;
  61. var ngClickDirectiveAdded = false;
  62. // eslint-disable-next-line no-invalid-this
  63. this.ngClickOverrideEnabled = function(enabled) {
  64. if (angular.isDefined(enabled)) {
  65. if (enabled && !ngClickDirectiveAdded) {
  66. ngClickDirectiveAdded = true;
  67. // Use this to identify the correct directive in the delegate
  68. ngTouchClickDirectiveFactory.$$moduleName = 'ngTouch';
  69. $compileProvider.directive('ngClick', ngTouchClickDirectiveFactory);
  70. $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
  71. if (ngClickOverrideEnabled) {
  72. // drop the default ngClick directive
  73. $delegate.shift();
  74. } else {
  75. // drop the ngTouch ngClick directive if the override has been re-disabled (because
  76. // we cannot de-register added directives)
  77. var i = $delegate.length - 1;
  78. while (i >= 0) {
  79. if ($delegate[i].$$moduleName === 'ngTouch') {
  80. $delegate.splice(i, 1);
  81. break;
  82. }
  83. i--;
  84. }
  85. }
  86. return $delegate;
  87. }]);
  88. }
  89. ngClickOverrideEnabled = enabled;
  90. return this;
  91. }
  92. return ngClickOverrideEnabled;
  93. };
  94. /**
  95. * @ngdoc service
  96. * @name $touch
  97. * @kind object
  98. *
  99. * @description
  100. * Provides the {@link ngTouch.$touch#ngClickOverrideEnabled `ngClickOverrideEnabled`} method.
  101. *
  102. */
  103. // eslint-disable-next-line no-invalid-this
  104. this.$get = function() {
  105. return {
  106. /**
  107. * @ngdoc method
  108. * @name $touch#ngClickOverrideEnabled
  109. *
  110. * @returns {*} current value of `ngClickOverrideEnabled` set in the {@link ngTouch.$touchProvider $touchProvider},
  111. * i.e. if {@link ngTouch.ngClick ngTouch's ngClick} directive is enabled.
  112. *
  113. * @kind function
  114. */
  115. ngClickOverrideEnabled: function() {
  116. return ngClickOverrideEnabled;
  117. }
  118. };
  119. };
  120. }
  121. /* global ngTouch: false */
  122. /**
  123. * @ngdoc service
  124. * @name $swipe
  125. *
  126. * @description
  127. * The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe
  128. * behavior, to make implementing swipe-related directives more convenient.
  129. *
  130. * Requires the {@link ngTouch `ngTouch`} module to be installed.
  131. *
  132. * `$swipe` is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngTouch`.
  133. *
  134. * # Usage
  135. * The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
  136. * which is to be watched for swipes, and an object with four handler functions. See the
  137. * documentation for `bind` below.
  138. */
  139. ngTouch.factory('$swipe', [function() {
  140. // The total distance in any direction before we make the call on swipe vs. scroll.
  141. var MOVE_BUFFER_RADIUS = 10;
  142. var POINTER_EVENTS = {
  143. 'mouse': {
  144. start: 'mousedown',
  145. move: 'mousemove',
  146. end: 'mouseup'
  147. },
  148. 'touch': {
  149. start: 'touchstart',
  150. move: 'touchmove',
  151. end: 'touchend',
  152. cancel: 'touchcancel'
  153. },
  154. 'pointer': {
  155. start: 'pointerdown',
  156. move: 'pointermove',
  157. end: 'pointerup',
  158. cancel: 'pointercancel'
  159. }
  160. };
  161. function getCoordinates(event) {
  162. var originalEvent = event.originalEvent || event;
  163. var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
  164. var e = (originalEvent.changedTouches && originalEvent.changedTouches[0]) || touches[0];
  165. return {
  166. x: e.clientX,
  167. y: e.clientY
  168. };
  169. }
  170. function getEvents(pointerTypes, eventType) {
  171. var res = [];
  172. angular.forEach(pointerTypes, function(pointerType) {
  173. var eventName = POINTER_EVENTS[pointerType][eventType];
  174. if (eventName) {
  175. res.push(eventName);
  176. }
  177. });
  178. return res.join(' ');
  179. }
  180. return {
  181. /**
  182. * @ngdoc method
  183. * @name $swipe#bind
  184. *
  185. * @description
  186. * The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
  187. * object containing event handlers.
  188. * The pointer types that should be used can be specified via the optional
  189. * third argument, which is an array of strings `'mouse'`, `'touch'` and `'pointer'`. By default,
  190. * `$swipe` will listen for `mouse`, `touch` and `pointer` events.
  191. *
  192. * The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
  193. * receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
  194. * `event`. `cancel` receives the raw `event` as its single parameter.
  195. *
  196. * `start` is called on either `mousedown`, `touchstart` or `pointerdown`. After this event, `$swipe` is
  197. * watching for `touchmove`, `mousemove` or `pointermove` events. These events are ignored until the total
  198. * distance moved in either dimension exceeds a small threshold.
  199. *
  200. * Once this threshold is exceeded, either the horizontal or vertical delta is greater.
  201. * - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
  202. * - If the vertical distance is greater, this is a scroll, and we let the browser take over.
  203. * A `cancel` event is sent.
  204. *
  205. * `move` is called on `mousemove`, `touchmove` and `pointermove` after the above logic has determined that
  206. * a swipe is in progress.
  207. *
  208. * `end` is called when a swipe is successfully completed with a `touchend`, `mouseup` or `pointerup`.
  209. *
  210. * `cancel` is called either on a `touchcancel` or `pointercancel` from the browser, or when we begin scrolling
  211. * as described above.
  212. *
  213. */
  214. bind: function(element, eventHandlers, pointerTypes) {
  215. // Absolute total movement, used to control swipe vs. scroll.
  216. var totalX, totalY;
  217. // Coordinates of the start position.
  218. var startCoords;
  219. // Last event's position.
  220. var lastPos;
  221. // Whether a swipe is active.
  222. var active = false;
  223. pointerTypes = pointerTypes || ['mouse', 'touch', 'pointer'];
  224. element.on(getEvents(pointerTypes, 'start'), function(event) {
  225. startCoords = getCoordinates(event);
  226. active = true;
  227. totalX = 0;
  228. totalY = 0;
  229. lastPos = startCoords;
  230. if (eventHandlers['start']) {
  231. eventHandlers['start'](startCoords, event);
  232. }
  233. });
  234. var events = getEvents(pointerTypes, 'cancel');
  235. if (events) {
  236. element.on(events, function(event) {
  237. active = false;
  238. if (eventHandlers['cancel']) {
  239. eventHandlers['cancel'](event);
  240. }
  241. });
  242. }
  243. element.on(getEvents(pointerTypes, 'move'), function(event) {
  244. if (!active) return;
  245. // Android will send a touchcancel if it thinks we're starting to scroll.
  246. // So when the total distance (+ or - or both) exceeds 10px in either direction,
  247. // we either:
  248. // - On totalX > totalY, we send preventDefault() and treat this as a swipe.
  249. // - On totalY > totalX, we let the browser handle it as a scroll.
  250. if (!startCoords) return;
  251. var coords = getCoordinates(event);
  252. totalX += Math.abs(coords.x - lastPos.x);
  253. totalY += Math.abs(coords.y - lastPos.y);
  254. lastPos = coords;
  255. if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
  256. return;
  257. }
  258. // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
  259. if (totalY > totalX) {
  260. // Allow native scrolling to take over.
  261. active = false;
  262. if (eventHandlers['cancel']) {
  263. eventHandlers['cancel'](event);
  264. }
  265. return;
  266. } else {
  267. // Prevent the browser from scrolling.
  268. event.preventDefault();
  269. if (eventHandlers['move']) {
  270. eventHandlers['move'](coords, event);
  271. }
  272. }
  273. });
  274. element.on(getEvents(pointerTypes, 'end'), function(event) {
  275. if (!active) return;
  276. active = false;
  277. if (eventHandlers['end']) {
  278. eventHandlers['end'](getCoordinates(event), event);
  279. }
  280. });
  281. }
  282. };
  283. }]);
  284. /* global ngTouch: false,
  285. nodeName_: false
  286. */
  287. /**
  288. * @ngdoc directive
  289. * @name ngClick
  290. * @deprecated
  291. * sinceVersion="v1.5.0"
  292. * This directive is deprecated and **disabled** by default.
  293. * The directive will receive no further support and might be removed from future releases.
  294. * If you need the directive, you can enable it with the {@link ngTouch.$touchProvider $touchProvider#ngClickOverrideEnabled}
  295. * function. We also recommend that you migrate to [FastClick](https://github.com/ftlabs/fastclick).
  296. * To learn more about the 300ms delay, this [Telerik article](http://developer.telerik.com/featured/300-ms-click-delay-ios-8/)
  297. * gives a good overview.
  298. *
  299. * @description
  300. * A more powerful replacement for the default ngClick designed to be used on touchscreen
  301. * devices. Most mobile browsers wait about 300ms after a tap-and-release before sending
  302. * the click event. This version handles them immediately, and then prevents the
  303. * following click event from propagating.
  304. *
  305. * Requires the {@link ngTouch `ngTouch`} module to be installed.
  306. *
  307. * This directive can fall back to using an ordinary click event, and so works on desktop
  308. * browsers as well as mobile.
  309. *
  310. * This directive also sets the CSS class `ng-click-active` while the element is being held
  311. * down (by a mouse click or touch) so you can restyle the depressed element if you wish.
  312. *
  313. * @element ANY
  314. * @param {expression} ngClick {@link guide/expression Expression} to evaluate
  315. * upon tap. (Event object is available as `$event`)
  316. *
  317. * @example
  318. <example module="ngClickExample" deps="angular-touch.js" name="ng-touch-ng-click">
  319. <file name="index.html">
  320. <button ng-click="count = count + 1" ng-init="count=0">
  321. Increment
  322. </button>
  323. count: {{ count }}
  324. </file>
  325. <file name="script.js">
  326. angular.module('ngClickExample', ['ngTouch']);
  327. </file>
  328. </example>
  329. */
  330. var ngTouchClickDirectiveFactory = ['$parse', '$timeout', '$rootElement',
  331. function($parse, $timeout, $rootElement) {
  332. var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag.
  333. var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers.
  334. var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click
  335. var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks.
  336. var ACTIVE_CLASS_NAME = 'ng-click-active';
  337. var lastPreventedTime;
  338. var touchCoordinates;
  339. var lastLabelClickCoordinates;
  340. // TAP EVENTS AND GHOST CLICKS
  341. //
  342. // Why tap events?
  343. // Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're
  344. // double-tapping, and then fire a click event.
  345. //
  346. // This delay sucks and makes mobile apps feel unresponsive.
  347. // So we detect touchstart, touchcancel and touchend ourselves and determine when
  348. // the user has tapped on something.
  349. //
  350. // What happens when the browser then generates a click event?
  351. // The browser, of course, also detects the tap and fires a click after a delay. This results in
  352. // tapping/clicking twice. We do "clickbusting" to prevent it.
  353. //
  354. // How does it work?
  355. // We attach global touchstart and click handlers, that run during the capture (early) phase.
  356. // So the sequence for a tap is:
  357. // - global touchstart: Sets an "allowable region" at the point touched.
  358. // - element's touchstart: Starts a touch
  359. // (- touchcancel ends the touch, no click follows)
  360. // - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold
  361. // too long) and fires the user's tap handler. The touchend also calls preventGhostClick().
  362. // - preventGhostClick() removes the allowable region the global touchstart created.
  363. // - The browser generates a click event.
  364. // - The global click handler catches the click, and checks whether it was in an allowable region.
  365. // - If preventGhostClick was called, the region will have been removed, the click is busted.
  366. // - If the region is still there, the click proceeds normally. Therefore clicks on links and
  367. // other elements without ngTap on them work normally.
  368. //
  369. // This is an ugly, terrible hack!
  370. // Yeah, tell me about it. The alternatives are using the slow click events, or making our users
  371. // deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular
  372. // encapsulates this ugly logic away from the user.
  373. //
  374. // Why not just put click handlers on the element?
  375. // We do that too, just to be sure. If the tap event caused the DOM to change,
  376. // it is possible another element is now in that position. To take account for these possibly
  377. // distinct elements, the handlers are global and care only about coordinates.
  378. // Checks if the coordinates are close enough to be within the region.
  379. function hit(x1, y1, x2, y2) {
  380. return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD;
  381. }
  382. // Checks a list of allowable regions against a click location.
  383. // Returns true if the click should be allowed.
  384. // Splices out the allowable region from the list after it has been used.
  385. function checkAllowableRegions(touchCoordinates, x, y) {
  386. for (var i = 0; i < touchCoordinates.length; i += 2) {
  387. if (hit(touchCoordinates[i], touchCoordinates[i + 1], x, y)) {
  388. touchCoordinates.splice(i, i + 2);
  389. return true; // allowable region
  390. }
  391. }
  392. return false; // No allowable region; bust it.
  393. }
  394. // Global click handler that prevents the click if it's in a bustable zone and preventGhostClick
  395. // was called recently.
  396. function onClick(event) {
  397. if (Date.now() - lastPreventedTime > PREVENT_DURATION) {
  398. return; // Too old.
  399. }
  400. var touches = event.touches && event.touches.length ? event.touches : [event];
  401. var x = touches[0].clientX;
  402. var y = touches[0].clientY;
  403. // Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
  404. // and on the input element). Depending on the exact browser, this second click we don't want
  405. // to bust has either (0,0), negative coordinates, or coordinates equal to triggering label
  406. // click event
  407. if (x < 1 && y < 1) {
  408. return; // offscreen
  409. }
  410. if (lastLabelClickCoordinates &&
  411. lastLabelClickCoordinates[0] === x && lastLabelClickCoordinates[1] === y) {
  412. return; // input click triggered by label click
  413. }
  414. // reset label click coordinates on first subsequent click
  415. if (lastLabelClickCoordinates) {
  416. lastLabelClickCoordinates = null;
  417. }
  418. // remember label click coordinates to prevent click busting of trigger click event on input
  419. if (nodeName_(event.target) === 'label') {
  420. lastLabelClickCoordinates = [x, y];
  421. }
  422. // Look for an allowable region containing this click.
  423. // If we find one, that means it was created by touchstart and not removed by
  424. // preventGhostClick, so we don't bust it.
  425. if (checkAllowableRegions(touchCoordinates, x, y)) {
  426. return;
  427. }
  428. // If we didn't find an allowable region, bust the click.
  429. event.stopPropagation();
  430. event.preventDefault();
  431. // Blur focused form elements
  432. if (event.target && event.target.blur) {
  433. event.target.blur();
  434. }
  435. }
  436. // Global touchstart handler that creates an allowable region for a click event.
  437. // This allowable region can be removed by preventGhostClick if we want to bust it.
  438. function onTouchStart(event) {
  439. var touches = event.touches && event.touches.length ? event.touches : [event];
  440. var x = touches[0].clientX;
  441. var y = touches[0].clientY;
  442. touchCoordinates.push(x, y);
  443. $timeout(function() {
  444. // Remove the allowable region.
  445. for (var i = 0; i < touchCoordinates.length; i += 2) {
  446. if (touchCoordinates[i] === x && touchCoordinates[i + 1] === y) {
  447. touchCoordinates.splice(i, i + 2);
  448. return;
  449. }
  450. }
  451. }, PREVENT_DURATION, false);
  452. }
  453. // On the first call, attaches some event handlers. Then whenever it gets called, it creates a
  454. // zone around the touchstart where clicks will get busted.
  455. function preventGhostClick(x, y) {
  456. if (!touchCoordinates) {
  457. $rootElement[0].addEventListener('click', onClick, true);
  458. $rootElement[0].addEventListener('touchstart', onTouchStart, true);
  459. touchCoordinates = [];
  460. }
  461. lastPreventedTime = Date.now();
  462. checkAllowableRegions(touchCoordinates, x, y);
  463. }
  464. // Actual linking function.
  465. return function(scope, element, attr) {
  466. var clickHandler = $parse(attr.ngClick),
  467. tapping = false,
  468. tapElement, // Used to blur the element after a tap.
  469. startTime, // Used to check if the tap was held too long.
  470. touchStartX,
  471. touchStartY;
  472. function resetState() {
  473. tapping = false;
  474. element.removeClass(ACTIVE_CLASS_NAME);
  475. }
  476. element.on('touchstart', function(event) {
  477. tapping = true;
  478. tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement.
  479. // Hack for Safari, which can target text nodes instead of containers.
  480. if (tapElement.nodeType === 3) {
  481. tapElement = tapElement.parentNode;
  482. }
  483. element.addClass(ACTIVE_CLASS_NAME);
  484. startTime = Date.now();
  485. // Use jQuery originalEvent
  486. var originalEvent = event.originalEvent || event;
  487. var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
  488. var e = touches[0];
  489. touchStartX = e.clientX;
  490. touchStartY = e.clientY;
  491. });
  492. element.on('touchcancel', function(event) {
  493. resetState();
  494. });
  495. element.on('touchend', function(event) {
  496. var diff = Date.now() - startTime;
  497. // Use jQuery originalEvent
  498. var originalEvent = event.originalEvent || event;
  499. var touches = (originalEvent.changedTouches && originalEvent.changedTouches.length) ?
  500. originalEvent.changedTouches :
  501. ((originalEvent.touches && originalEvent.touches.length) ? originalEvent.touches : [originalEvent]);
  502. var e = touches[0];
  503. var x = e.clientX;
  504. var y = e.clientY;
  505. var dist = Math.sqrt(Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2));
  506. if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) {
  507. // Call preventGhostClick so the clickbuster will catch the corresponding click.
  508. preventGhostClick(x, y);
  509. // Blur the focused element (the button, probably) before firing the callback.
  510. // This doesn't work perfectly on Android Chrome, but seems to work elsewhere.
  511. // I couldn't get anything to work reliably on Android Chrome.
  512. if (tapElement) {
  513. tapElement.blur();
  514. }
  515. if (!angular.isDefined(attr.disabled) || attr.disabled === false) {
  516. element.triggerHandler('click', [event]);
  517. }
  518. }
  519. resetState();
  520. });
  521. // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
  522. // something else nearby.
  523. element.onclick = function(event) { };
  524. // Actual click handler.
  525. // There are three different kinds of clicks, only two of which reach this point.
  526. // - On desktop browsers without touch events, their clicks will always come here.
  527. // - On mobile browsers, the simulated "fast" click will call this.
  528. // - But the browser's follow-up slow click will be "busted" before it reaches this handler.
  529. // Therefore it's safe to use this directive on both mobile and desktop.
  530. element.on('click', function(event, touchend) {
  531. scope.$apply(function() {
  532. clickHandler(scope, {$event: (touchend || event)});
  533. });
  534. });
  535. element.on('mousedown', function(event) {
  536. element.addClass(ACTIVE_CLASS_NAME);
  537. });
  538. element.on('mousemove mouseup', function(event) {
  539. element.removeClass(ACTIVE_CLASS_NAME);
  540. });
  541. };
  542. }];
  543. /* global ngTouch: false */
  544. /**
  545. * @ngdoc directive
  546. * @name ngSwipeLeft
  547. *
  548. * @description
  549. * Specify custom behavior when an element is swiped to the left on a touchscreen device.
  550. * A leftward swipe is a quick, right-to-left slide of the finger.
  551. * Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag
  552. * too.
  553. *
  554. * To disable the mouse click and drag functionality, add `ng-swipe-disable-mouse` to
  555. * the `ng-swipe-left` or `ng-swipe-right` DOM Element.
  556. *
  557. * Requires the {@link ngTouch `ngTouch`} module to be installed.
  558. *
  559. * @element ANY
  560. * @param {expression} ngSwipeLeft {@link guide/expression Expression} to evaluate
  561. * upon left swipe. (Event object is available as `$event`)
  562. *
  563. * @example
  564. <example module="ngSwipeLeftExample" deps="angular-touch.js" name="ng-swipe-left">
  565. <file name="index.html">
  566. <div ng-show="!showActions" ng-swipe-left="showActions = true">
  567. Some list content, like an email in the inbox
  568. </div>
  569. <div ng-show="showActions" ng-swipe-right="showActions = false">
  570. <button ng-click="reply()">Reply</button>
  571. <button ng-click="delete()">Delete</button>
  572. </div>
  573. </file>
  574. <file name="script.js">
  575. angular.module('ngSwipeLeftExample', ['ngTouch']);
  576. </file>
  577. </example>
  578. */
  579. /**
  580. * @ngdoc directive
  581. * @name ngSwipeRight
  582. *
  583. * @description
  584. * Specify custom behavior when an element is swiped to the right on a touchscreen device.
  585. * A rightward swipe is a quick, left-to-right slide of the finger.
  586. * Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag
  587. * too.
  588. *
  589. * Requires the {@link ngTouch `ngTouch`} module to be installed.
  590. *
  591. * @element ANY
  592. * @param {expression} ngSwipeRight {@link guide/expression Expression} to evaluate
  593. * upon right swipe. (Event object is available as `$event`)
  594. *
  595. * @example
  596. <example module="ngSwipeRightExample" deps="angular-touch.js" name="ng-swipe-right">
  597. <file name="index.html">
  598. <div ng-show="!showActions" ng-swipe-left="showActions = true">
  599. Some list content, like an email in the inbox
  600. </div>
  601. <div ng-show="showActions" ng-swipe-right="showActions = false">
  602. <button ng-click="reply()">Reply</button>
  603. <button ng-click="delete()">Delete</button>
  604. </div>
  605. </file>
  606. <file name="script.js">
  607. angular.module('ngSwipeRightExample', ['ngTouch']);
  608. </file>
  609. </example>
  610. */
  611. function makeSwipeDirective(directiveName, direction, eventName) {
  612. ngTouch.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) {
  613. // The maximum vertical delta for a swipe should be less than 75px.
  614. var MAX_VERTICAL_DISTANCE = 75;
  615. // Vertical distance should not be more than a fraction of the horizontal distance.
  616. var MAX_VERTICAL_RATIO = 0.3;
  617. // At least a 30px lateral motion is necessary for a swipe.
  618. var MIN_HORIZONTAL_DISTANCE = 30;
  619. return function(scope, element, attr) {
  620. var swipeHandler = $parse(attr[directiveName]);
  621. var startCoords, valid;
  622. function validSwipe(coords) {
  623. // Check that it's within the coordinates.
  624. // Absolute vertical distance must be within tolerances.
  625. // Horizontal distance, we take the current X - the starting X.
  626. // This is negative for leftward swipes and positive for rightward swipes.
  627. // After multiplying by the direction (-1 for left, +1 for right), legal swipes
  628. // (ie. same direction as the directive wants) will have a positive delta and
  629. // illegal ones a negative delta.
  630. // Therefore this delta must be positive, and larger than the minimum.
  631. if (!startCoords) return false;
  632. var deltaY = Math.abs(coords.y - startCoords.y);
  633. var deltaX = (coords.x - startCoords.x) * direction;
  634. return valid && // Short circuit for already-invalidated swipes.
  635. deltaY < MAX_VERTICAL_DISTANCE &&
  636. deltaX > 0 &&
  637. deltaX > MIN_HORIZONTAL_DISTANCE &&
  638. deltaY / deltaX < MAX_VERTICAL_RATIO;
  639. }
  640. var pointerTypes = ['touch'];
  641. if (!angular.isDefined(attr['ngSwipeDisableMouse'])) {
  642. pointerTypes.push('mouse');
  643. }
  644. $swipe.bind(element, {
  645. 'start': function(coords, event) {
  646. startCoords = coords;
  647. valid = true;
  648. },
  649. 'cancel': function(event) {
  650. valid = false;
  651. },
  652. 'end': function(coords, event) {
  653. if (validSwipe(coords)) {
  654. scope.$apply(function() {
  655. element.triggerHandler(eventName);
  656. swipeHandler(scope, {$event: event});
  657. });
  658. }
  659. }
  660. }, pointerTypes);
  661. };
  662. }]);
  663. }
  664. // Left is negative X-coordinate, right is positive.
  665. makeSwipeDirective('ngSwipeLeft', -1, 'swipeleft');
  666. makeSwipeDirective('ngSwipeRight', 1, 'swiperight');
  667. })(window, window.angular);