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