angular-touch.js 32 KB

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