Nav apraksta

angular-touch.js 26KB

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