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