2 * @license AngularJS v1.4.3
\r
3 * (c) 2010-2015 Google, Inc. http://angularjs.org
\r
6 (function(window, angular, undefined) {'use strict';
\r
15 * The `ngTouch` module provides touch events and other helpers for touch-enabled devices.
\r
16 * The implementation is based on jQuery Mobile touch event handling
\r
17 * ([jquerymobile.com](http://jquerymobile.com/)).
\r
20 * See {@link ngTouch.$swipe `$swipe`} for usage.
\r
22 * <div doc-module-components="ngTouch"></div>
\r
26 // define ngTouch module
\r
27 /* global -ngTouch */
\r
28 var ngTouch = angular.module('ngTouch', []);
\r
30 function nodeName_(element) {
\r
31 return angular.lowercase(element.nodeName || (element[0] && element[0].nodeName));
\r
34 /* global ngTouch: false */
\r
41 * The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe
\r
42 * behavior, to make implementing swipe-related directives more convenient.
\r
44 * Requires the {@link ngTouch `ngTouch`} module to be installed.
\r
46 * `$swipe` is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngTouch`, and by
\r
47 * `ngCarousel` in a separate component.
\r
50 * The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
\r
51 * which is to be watched for swipes, and an object with four handler functions. See the
\r
52 * documentation for `bind` below.
\r
55 ngTouch.factory('$swipe', [function() {
\r
56 // The total distance in any direction before we make the call on swipe vs. scroll.
\r
57 var MOVE_BUFFER_RADIUS = 10;
\r
59 var POINTER_EVENTS = {
\r
66 start: 'touchstart',
\r
69 cancel: 'touchcancel'
\r
73 function getCoordinates(event) {
\r
74 var originalEvent = event.originalEvent || event;
\r
75 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
\r
76 var e = (originalEvent.changedTouches && originalEvent.changedTouches[0]) || touches[0];
\r
84 function getEvents(pointerTypes, eventType) {
\r
86 angular.forEach(pointerTypes, function(pointerType) {
\r
87 var eventName = POINTER_EVENTS[pointerType][eventType];
\r
89 res.push(eventName);
\r
92 return res.join(' ');
\r
101 * The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
\r
102 * object containing event handlers.
\r
103 * The pointer types that should be used can be specified via the optional
\r
104 * third argument, which is an array of strings `'mouse'` and `'touch'`. By default,
\r
105 * `$swipe` will listen for `mouse` and `touch` events.
\r
107 * The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
\r
108 * receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
\r
109 * `event`. `cancel` receives the raw `event` as its single parameter.
\r
111 * `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
\r
112 * watching for `touchmove` or `mousemove` events. These events are ignored until the total
\r
113 * distance moved in either dimension exceeds a small threshold.
\r
115 * Once this threshold is exceeded, either the horizontal or vertical delta is greater.
\r
116 * - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
\r
117 * - If the vertical distance is greater, this is a scroll, and we let the browser take over.
\r
118 * A `cancel` event is sent.
\r
120 * `move` is called on `mousemove` and `touchmove` after the above logic has determined that
\r
121 * a swipe is in progress.
\r
123 * `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
\r
125 * `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
\r
126 * as described above.
\r
129 bind: function(element, eventHandlers, pointerTypes) {
\r
130 // Absolute total movement, used to control swipe vs. scroll.
\r
131 var totalX, totalY;
\r
132 // Coordinates of the start position.
\r
134 // Last event's position.
\r
136 // Whether a swipe is active.
\r
137 var active = false;
\r
139 pointerTypes = pointerTypes || ['mouse', 'touch'];
\r
140 element.on(getEvents(pointerTypes, 'start'), function(event) {
\r
141 startCoords = getCoordinates(event);
\r
145 lastPos = startCoords;
\r
146 eventHandlers['start'] && eventHandlers['start'](startCoords, event);
\r
148 var events = getEvents(pointerTypes, 'cancel');
\r
150 element.on(events, function(event) {
\r
152 eventHandlers['cancel'] && eventHandlers['cancel'](event);
\r
156 element.on(getEvents(pointerTypes, 'move'), function(event) {
\r
157 if (!active) return;
\r
159 // Android will send a touchcancel if it thinks we're starting to scroll.
\r
160 // So when the total distance (+ or - or both) exceeds 10px in either direction,
\r
162 // - On totalX > totalY, we send preventDefault() and treat this as a swipe.
\r
163 // - On totalY > totalX, we let the browser handle it as a scroll.
\r
165 if (!startCoords) return;
\r
166 var coords = getCoordinates(event);
\r
168 totalX += Math.abs(coords.x - lastPos.x);
\r
169 totalY += Math.abs(coords.y - lastPos.y);
\r
173 if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
\r
177 // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
\r
178 if (totalY > totalX) {
\r
179 // Allow native scrolling to take over.
\r
181 eventHandlers['cancel'] && eventHandlers['cancel'](event);
\r
184 // Prevent the browser from scrolling.
\r
185 event.preventDefault();
\r
186 eventHandlers['move'] && eventHandlers['move'](coords, event);
\r
190 element.on(getEvents(pointerTypes, 'end'), function(event) {
\r
191 if (!active) return;
\r
193 eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
\r
199 /* global ngTouch: false,
\r
208 * A more powerful replacement for the default ngClick designed to be used on touchscreen
\r
209 * devices. Most mobile browsers wait about 300ms after a tap-and-release before sending
\r
210 * the click event. This version handles them immediately, and then prevents the
\r
211 * following click event from propagating.
\r
213 * Requires the {@link ngTouch `ngTouch`} module to be installed.
\r
215 * This directive can fall back to using an ordinary click event, and so works on desktop
\r
216 * browsers as well as mobile.
\r
218 * This directive also sets the CSS class `ng-click-active` while the element is being held
\r
219 * down (by a mouse click or touch) so you can restyle the depressed element if you wish.
\r
222 * @param {expression} ngClick {@link guide/expression Expression} to evaluate
\r
223 * upon tap. (Event object is available as `$event`)
\r
226 <example module="ngClickExample" deps="angular-touch.js">
\r
227 <file name="index.html">
\r
228 <button ng-click="count = count + 1" ng-init="count=0">
\r
233 <file name="script.js">
\r
234 angular.module('ngClickExample', ['ngTouch']);
\r
239 ngTouch.config(['$provide', function($provide) {
\r
240 $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
\r
241 // drop the default ngClick directive
\r
247 ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
\r
248 function($parse, $timeout, $rootElement) {
\r
249 var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag.
\r
250 var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers.
\r
251 var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click
\r
252 var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks.
\r
254 var ACTIVE_CLASS_NAME = 'ng-click-active';
\r
255 var lastPreventedTime;
\r
256 var touchCoordinates;
\r
257 var lastLabelClickCoordinates;
\r
260 // TAP EVENTS AND GHOST CLICKS
\r
263 // Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're
\r
264 // double-tapping, and then fire a click event.
\r
266 // This delay sucks and makes mobile apps feel unresponsive.
\r
267 // So we detect touchstart, touchcancel and touchend ourselves and determine when
\r
268 // the user has tapped on something.
\r
270 // What happens when the browser then generates a click event?
\r
271 // The browser, of course, also detects the tap and fires a click after a delay. This results in
\r
272 // tapping/clicking twice. We do "clickbusting" to prevent it.
\r
274 // How does it work?
\r
275 // We attach global touchstart and click handlers, that run during the capture (early) phase.
\r
276 // So the sequence for a tap is:
\r
277 // - global touchstart: Sets an "allowable region" at the point touched.
\r
278 // - element's touchstart: Starts a touch
\r
279 // (- touchcancel ends the touch, no click follows)
\r
280 // - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold
\r
281 // too long) and fires the user's tap handler. The touchend also calls preventGhostClick().
\r
282 // - preventGhostClick() removes the allowable region the global touchstart created.
\r
283 // - The browser generates a click event.
\r
284 // - The global click handler catches the click, and checks whether it was in an allowable region.
\r
285 // - If preventGhostClick was called, the region will have been removed, the click is busted.
\r
286 // - If the region is still there, the click proceeds normally. Therefore clicks on links and
\r
287 // other elements without ngTap on them work normally.
\r
289 // This is an ugly, terrible hack!
\r
290 // Yeah, tell me about it. The alternatives are using the slow click events, or making our users
\r
291 // deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular
\r
292 // encapsulates this ugly logic away from the user.
\r
294 // Why not just put click handlers on the element?
\r
295 // We do that too, just to be sure. If the tap event caused the DOM to change,
\r
296 // it is possible another element is now in that position. To take account for these possibly
\r
297 // distinct elements, the handlers are global and care only about coordinates.
\r
299 // Checks if the coordinates are close enough to be within the region.
\r
300 function hit(x1, y1, x2, y2) {
\r
301 return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD;
\r
304 // Checks a list of allowable regions against a click location.
\r
305 // Returns true if the click should be allowed.
\r
306 // Splices out the allowable region from the list after it has been used.
\r
307 function checkAllowableRegions(touchCoordinates, x, y) {
\r
308 for (var i = 0; i < touchCoordinates.length; i += 2) {
\r
309 if (hit(touchCoordinates[i], touchCoordinates[i + 1], x, y)) {
\r
310 touchCoordinates.splice(i, i + 2);
\r
311 return true; // allowable region
\r
314 return false; // No allowable region; bust it.
\r
317 // Global click handler that prevents the click if it's in a bustable zone and preventGhostClick
\r
318 // was called recently.
\r
319 function onClick(event) {
\r
320 if (Date.now() - lastPreventedTime > PREVENT_DURATION) {
\r
321 return; // Too old.
\r
324 var touches = event.touches && event.touches.length ? event.touches : [event];
\r
325 var x = touches[0].clientX;
\r
326 var y = touches[0].clientY;
\r
327 // Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
\r
328 // and on the input element). Depending on the exact browser, this second click we don't want
\r
329 // to bust has either (0,0), negative coordinates, or coordinates equal to triggering label
\r
331 if (x < 1 && y < 1) {
\r
332 return; // offscreen
\r
334 if (lastLabelClickCoordinates &&
\r
335 lastLabelClickCoordinates[0] === x && lastLabelClickCoordinates[1] === y) {
\r
336 return; // input click triggered by label click
\r
338 // reset label click coordinates on first subsequent click
\r
339 if (lastLabelClickCoordinates) {
\r
340 lastLabelClickCoordinates = null;
\r
342 // remember label click coordinates to prevent click busting of trigger click event on input
\r
343 if (nodeName_(event.target) === 'label') {
\r
344 lastLabelClickCoordinates = [x, y];
\r
347 // Look for an allowable region containing this click.
\r
348 // If we find one, that means it was created by touchstart and not removed by
\r
349 // preventGhostClick, so we don't bust it.
\r
350 if (checkAllowableRegions(touchCoordinates, x, y)) {
\r
354 // If we didn't find an allowable region, bust the click.
\r
355 event.stopPropagation();
\r
356 event.preventDefault();
\r
358 // Blur focused form elements
\r
359 event.target && event.target.blur && event.target.blur();
\r
363 // Global touchstart handler that creates an allowable region for a click event.
\r
364 // This allowable region can be removed by preventGhostClick if we want to bust it.
\r
365 function onTouchStart(event) {
\r
366 var touches = event.touches && event.touches.length ? event.touches : [event];
\r
367 var x = touches[0].clientX;
\r
368 var y = touches[0].clientY;
\r
369 touchCoordinates.push(x, y);
\r
371 $timeout(function() {
\r
372 // Remove the allowable region.
\r
373 for (var i = 0; i < touchCoordinates.length; i += 2) {
\r
374 if (touchCoordinates[i] == x && touchCoordinates[i + 1] == y) {
\r
375 touchCoordinates.splice(i, i + 2);
\r
379 }, PREVENT_DURATION, false);
\r
382 // On the first call, attaches some event handlers. Then whenever it gets called, it creates a
\r
383 // zone around the touchstart where clicks will get busted.
\r
384 function preventGhostClick(x, y) {
\r
385 if (!touchCoordinates) {
\r
386 $rootElement[0].addEventListener('click', onClick, true);
\r
387 $rootElement[0].addEventListener('touchstart', onTouchStart, true);
\r
388 touchCoordinates = [];
\r
391 lastPreventedTime = Date.now();
\r
393 checkAllowableRegions(touchCoordinates, x, y);
\r
396 // Actual linking function.
\r
397 return function(scope, element, attr) {
\r
398 var clickHandler = $parse(attr.ngClick),
\r
400 tapElement, // Used to blur the element after a tap.
\r
401 startTime, // Used to check if the tap was held too long.
\r
405 function resetState() {
\r
407 element.removeClass(ACTIVE_CLASS_NAME);
\r
410 element.on('touchstart', function(event) {
\r
412 tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement.
\r
413 // Hack for Safari, which can target text nodes instead of containers.
\r
414 if (tapElement.nodeType == 3) {
\r
415 tapElement = tapElement.parentNode;
\r
418 element.addClass(ACTIVE_CLASS_NAME);
\r
420 startTime = Date.now();
\r
422 // Use jQuery originalEvent
\r
423 var originalEvent = event.originalEvent || event;
\r
424 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
\r
425 var e = touches[0];
\r
426 touchStartX = e.clientX;
\r
427 touchStartY = e.clientY;
\r
430 element.on('touchcancel', function(event) {
\r
434 element.on('touchend', function(event) {
\r
435 var diff = Date.now() - startTime;
\r
437 // Use jQuery originalEvent
\r
438 var originalEvent = event.originalEvent || event;
\r
439 var touches = (originalEvent.changedTouches && originalEvent.changedTouches.length) ?
\r
440 originalEvent.changedTouches :
\r
441 ((originalEvent.touches && originalEvent.touches.length) ? originalEvent.touches : [originalEvent]);
\r
442 var e = touches[0];
\r
445 var dist = Math.sqrt(Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2));
\r
447 if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) {
\r
448 // Call preventGhostClick so the clickbuster will catch the corresponding click.
\r
449 preventGhostClick(x, y);
\r
451 // Blur the focused element (the button, probably) before firing the callback.
\r
452 // This doesn't work perfectly on Android Chrome, but seems to work elsewhere.
\r
453 // I couldn't get anything to work reliably on Android Chrome.
\r
458 if (!angular.isDefined(attr.disabled) || attr.disabled === false) {
\r
459 element.triggerHandler('click', [event]);
\r
466 // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
\r
467 // something else nearby.
\r
468 element.onclick = function(event) { };
\r
470 // Actual click handler.
\r
471 // There are three different kinds of clicks, only two of which reach this point.
\r
472 // - On desktop browsers without touch events, their clicks will always come here.
\r
473 // - On mobile browsers, the simulated "fast" click will call this.
\r
474 // - But the browser's follow-up slow click will be "busted" before it reaches this handler.
\r
475 // Therefore it's safe to use this directive on both mobile and desktop.
\r
476 element.on('click', function(event, touchend) {
\r
477 scope.$apply(function() {
\r
478 clickHandler(scope, {$event: (touchend || event)});
\r
482 element.on('mousedown', function(event) {
\r
483 element.addClass(ACTIVE_CLASS_NAME);
\r
486 element.on('mousemove mouseup', function(event) {
\r
487 element.removeClass(ACTIVE_CLASS_NAME);
\r
493 /* global ngTouch: false */
\r
497 * @name ngSwipeLeft
\r
500 * Specify custom behavior when an element is swiped to the left on a touchscreen device.
\r
501 * A leftward swipe is a quick, right-to-left slide of the finger.
\r
502 * Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag
\r
505 * To disable the mouse click and drag functionality, add `ng-swipe-disable-mouse` to
\r
506 * the `ng-swipe-left` or `ng-swipe-right` DOM Element.
\r
508 * Requires the {@link ngTouch `ngTouch`} module to be installed.
\r
511 * @param {expression} ngSwipeLeft {@link guide/expression Expression} to evaluate
\r
512 * upon left swipe. (Event object is available as `$event`)
\r
515 <example module="ngSwipeLeftExample" deps="angular-touch.js">
\r
516 <file name="index.html">
\r
517 <div ng-show="!showActions" ng-swipe-left="showActions = true">
\r
518 Some list content, like an email in the inbox
\r
520 <div ng-show="showActions" ng-swipe-right="showActions = false">
\r
521 <button ng-click="reply()">Reply</button>
\r
522 <button ng-click="delete()">Delete</button>
\r
525 <file name="script.js">
\r
526 angular.module('ngSwipeLeftExample', ['ngTouch']);
\r
533 * @name ngSwipeRight
\r
536 * Specify custom behavior when an element is swiped to the right on a touchscreen device.
\r
537 * A rightward swipe is a quick, left-to-right slide of the finger.
\r
538 * Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag
\r
541 * Requires the {@link ngTouch `ngTouch`} module to be installed.
\r
544 * @param {expression} ngSwipeRight {@link guide/expression Expression} to evaluate
\r
545 * upon right swipe. (Event object is available as `$event`)
\r
548 <example module="ngSwipeRightExample" deps="angular-touch.js">
\r
549 <file name="index.html">
\r
550 <div ng-show="!showActions" ng-swipe-left="showActions = true">
\r
551 Some list content, like an email in the inbox
\r
553 <div ng-show="showActions" ng-swipe-right="showActions = false">
\r
554 <button ng-click="reply()">Reply</button>
\r
555 <button ng-click="delete()">Delete</button>
\r
558 <file name="script.js">
\r
559 angular.module('ngSwipeRightExample', ['ngTouch']);
\r
564 function makeSwipeDirective(directiveName, direction, eventName) {
\r
565 ngTouch.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) {
\r
566 // The maximum vertical delta for a swipe should be less than 75px.
\r
567 var MAX_VERTICAL_DISTANCE = 75;
\r
568 // Vertical distance should not be more than a fraction of the horizontal distance.
\r
569 var MAX_VERTICAL_RATIO = 0.3;
\r
570 // At least a 30px lateral motion is necessary for a swipe.
\r
571 var MIN_HORIZONTAL_DISTANCE = 30;
\r
573 return function(scope, element, attr) {
\r
574 var swipeHandler = $parse(attr[directiveName]);
\r
576 var startCoords, valid;
\r
578 function validSwipe(coords) {
\r
579 // Check that it's within the coordinates.
\r
580 // Absolute vertical distance must be within tolerances.
\r
581 // Horizontal distance, we take the current X - the starting X.
\r
582 // This is negative for leftward swipes and positive for rightward swipes.
\r
583 // After multiplying by the direction (-1 for left, +1 for right), legal swipes
\r
584 // (ie. same direction as the directive wants) will have a positive delta and
\r
585 // illegal ones a negative delta.
\r
586 // Therefore this delta must be positive, and larger than the minimum.
\r
587 if (!startCoords) return false;
\r
588 var deltaY = Math.abs(coords.y - startCoords.y);
\r
589 var deltaX = (coords.x - startCoords.x) * direction;
\r
590 return valid && // Short circuit for already-invalidated swipes.
\r
591 deltaY < MAX_VERTICAL_DISTANCE &&
\r
593 deltaX > MIN_HORIZONTAL_DISTANCE &&
\r
594 deltaY / deltaX < MAX_VERTICAL_RATIO;
\r
597 var pointerTypes = ['touch'];
\r
598 if (!angular.isDefined(attr['ngSwipeDisableMouse'])) {
\r
599 pointerTypes.push('mouse');
\r
601 $swipe.bind(element, {
\r
602 'start': function(coords, event) {
\r
603 startCoords = coords;
\r
606 'cancel': function(event) {
\r
609 'end': function(coords, event) {
\r
610 if (validSwipe(coords)) {
\r
611 scope.$apply(function() {
\r
612 element.triggerHandler(eventName);
\r
613 swipeHandler(scope, {$event: event});
\r
622 // Left is negative X-coordinate, right is positive.
\r
623 makeSwipeDirective('ngSwipeLeft', -1, 'swipeleft');
\r
624 makeSwipeDirective('ngSwipeRight', 1, 'swiperight');
\r
628 })(window, window.angular);
\r