angular-touch.js 26 KB

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