Rework javascript libraries
[clamp.git] / src / main / resources / META-INF / resources / designer / lib / angular-animate.js
1 /**
2  * @license AngularJS v1.2.32
3  * (c) 2010-2014 Google, Inc. http://angularjs.org
4  * License: MIT
5  */
6 (function(window, angular, undefined) {'use strict';
7
8 /* jshint maxlen: false */
9
10 /**
11  * @ngdoc module
12  * @name ngAnimate
13  * @description
14  *
15  * # ngAnimate
16  *
17  * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.
18  *
19  *
20  * <div doc-module-components="ngAnimate"></div>
21  *
22  * # Usage
23  *
24  * To see animations in action, all that is required is to define the appropriate CSS classes
25  * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are:
26  * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation
27  * by using the `$animate` service.
28  *
29  * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:
30  *
31  * | Directive                                                 | Supported Animations                               |
32  * |---------------------------------------------------------- |----------------------------------------------------|
33  * | {@link ng.directive:ngRepeat#usage_animations ngRepeat}         | enter, leave and move                              |
34  * | {@link ngRoute.directive:ngView#usage_animations ngView}        | enter and leave                                    |
35  * | {@link ng.directive:ngInclude#usage_animations ngInclude}       | enter and leave                                    |
36  * | {@link ng.directive:ngSwitch#usage_animations ngSwitch}         | enter and leave                                    |
37  * | {@link ng.directive:ngIf#usage_animations ngIf}                 | enter and leave                                    |
38  * | {@link ng.directive:ngClass#usage_animations ngClass}           | add and remove                                     |
39  * | {@link ng.directive:ngShow#usage_animations ngShow & ngHide}    | add and remove (the ng-hide class value)           |
40  * | {@link ng.directive:form#usage_animations form}                 | add and remove (dirty, pristine, valid, invalid & all other validations)                |
41  * | {@link ng.directive:ngModel#usage_animations ngModel}           | add and remove (dirty, pristine, valid, invalid & all other validations)                |
42  *
43  * You can find out more information about animations upon visiting each directive page.
44  *
45  * Below is an example of how to apply animations to a directive that supports animation hooks:
46  *
47  * ```html
48  * <style type="text/css">
49  * .slide.ng-enter, .slide.ng-leave {
50  *   -webkit-transition:0.5s linear all;
51  *   transition:0.5s linear all;
52  * }
53  *
54  * .slide.ng-enter { }        /&#42; starting animations for enter &#42;/
55  * .slide.ng-enter.ng-enter-active { } /&#42; terminal animations for enter &#42;/
56  * .slide.ng-leave { }        /&#42; starting animations for leave &#42;/
57  * .slide.ng-leave.ng-leave-active { } /&#42; terminal animations for leave &#42;/
58  * </style>
59  *
60  * <!--
61  * the animate service will automatically add .ng-enter and .ng-leave to the element
62  * to trigger the CSS transition/animations
63  * -->
64  * <ANY class="slide" ng-include="..."></ANY>
65  * ```
66  *
67  * Keep in mind that, by default, if an animation is running, any child elements cannot be animated
68  * until the parent element's animation has completed. This blocking feature can be overridden by
69  * placing the `ng-animate-children` attribute on a parent container tag.
70  *
71  * ```html
72  * <div class="slide-animation" ng-if="on" ng-animate-children>
73  *   <div class="fade-animation" ng-if="on">
74  *     <div class="explode-animation" ng-if="on">
75  *        ...
76  *     </div>
77  *   </div>
78  * </div>
79  * ```
80  *
81  * When the `on` expression value changes and an animation is triggered then each of the elements within
82  * will all animate without the block being applied to child elements.
83  *
84  * <h2>CSS-defined Animations</h2>
85  * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes
86  * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported
87  * and can be used to play along with this naming structure.
88  *
89  * The following code below demonstrates how to perform animations using **CSS transitions** with Angular:
90  *
91  * ```html
92  * <style type="text/css">
93  * /&#42;
94  *  The animate class is apart of the element and the ng-enter class
95  *  is attached to the element once the enter animation event is triggered
96  * &#42;/
97  * .reveal-animation.ng-enter {
98  *  -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/
99  *  transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/
100  *
101  *  /&#42; The animation preparation code &#42;/
102  *  opacity: 0;
103  * }
104  *
105  * /&#42;
106  *  Keep in mind that you want to combine both CSS
107  *  classes together to avoid any CSS-specificity
108  *  conflicts
109  * &#42;/
110  * .reveal-animation.ng-enter.ng-enter-active {
111  *  /&#42; The animation code itself &#42;/
112  *  opacity: 1;
113  * }
114  * </style>
115  *
116  * <div class="view-container">
117  *   <div ng-view class="reveal-animation"></div>
118  * </div>
119  * ```
120  *
121  * The following code below demonstrates how to perform animations using **CSS animations** with Angular:
122  *
123  * ```html
124  * <style type="text/css">
125  * .reveal-animation.ng-enter {
126  *   -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/
127  *   animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/
128  * }
129  * @-webkit-keyframes enter_sequence {
130  *   from { opacity:0; }
131  *   to { opacity:1; }
132  * }
133  * @keyframes enter_sequence {
134  *   from { opacity:0; }
135  *   to { opacity:1; }
136  * }
137  * </style>
138  *
139  * <div class="view-container">
140  *   <div ng-view class="reveal-animation"></div>
141  * </div>
142  * ```
143  *
144  * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.
145  *
146  * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add
147  * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically
148  * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be
149  * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end
150  * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element
151  * has no CSS transition/animation classes applied to it.
152  *
153  * <h3>CSS Staggering Animations</h3>
154  * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
155  * curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be
156  * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
157  * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
158  * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
159  *
160  * ```css
161  * .my-animation.ng-enter {
162  *   /&#42; standard transition code &#42;/
163  *   -webkit-transition: 1s linear all;
164  *   transition: 1s linear all;
165  *   opacity:0;
166  * }
167  * .my-animation.ng-enter-stagger {
168  *   /&#42; this will have a 100ms delay between each successive leave animation &#42;/
169  *   -webkit-transition-delay: 0.1s;
170  *   transition-delay: 0.1s;
171  *
172  *   /&#42; in case the stagger doesn't work then these two values
173  *    must be set to 0 to avoid an accidental CSS inheritance &#42;/
174  *   -webkit-transition-duration: 0s;
175  *   transition-duration: 0s;
176  * }
177  * .my-animation.ng-enter.ng-enter-active {
178  *   /&#42; standard transition styles &#42;/
179  *   opacity:1;
180  * }
181  * ```
182  *
183  * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
184  * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
185  * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
186  * will also be reset if more than 10ms has passed after the last animation has been fired.
187  *
188  * The following code will issue the **ng-leave-stagger** event on the element provided:
189  *
190  * ```js
191  * var kids = parent.children();
192  *
193  * $animate.leave(kids[0]); //stagger index=0
194  * $animate.leave(kids[1]); //stagger index=1
195  * $animate.leave(kids[2]); //stagger index=2
196  * $animate.leave(kids[3]); //stagger index=3
197  * $animate.leave(kids[4]); //stagger index=4
198  *
199  * $timeout(function() {
200  *   //stagger has reset itself
201  *   $animate.leave(kids[5]); //stagger index=0
202  *   $animate.leave(kids[6]); //stagger index=1
203  * }, 100, false);
204  * ```
205  *
206  * Stagger animations are currently only supported within CSS-defined animations.
207  *
208  * <h2>JavaScript-defined Animations</h2>
209  * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not
210  * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.
211  *
212  * ```js
213  * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.
214  * var ngModule = angular.module('YourApp', ['ngAnimate']);
215  * ngModule.animation('.my-crazy-animation', function() {
216  *   return {
217  *     enter: function(element, done) {
218  *       //run the animation here and call done when the animation is complete
219  *       return function(cancelled) {
220  *         //this (optional) function will be called when the animation
221  *         //completes or when the animation is cancelled (the cancelled
222  *         //flag will be set to true if cancelled).
223  *       };
224  *     },
225  *     leave: function(element, done) { },
226  *     move: function(element, done) { },
227  *
228  *     //animation that can be triggered before the class is added
229  *     beforeAddClass: function(element, className, done) { },
230  *
231  *     //animation that can be triggered after the class is added
232  *     addClass: function(element, className, done) { },
233  *
234  *     //animation that can be triggered before the class is removed
235  *     beforeRemoveClass: function(element, className, done) { },
236  *
237  *     //animation that can be triggered after the class is removed
238  *     removeClass: function(element, className, done) { }
239  *   };
240  * });
241  * ```
242  *
243  * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run
244  * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits
245  * the element's CSS class attribute value and then run the matching animation event function (if found).
246  * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will
247  * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).
248  *
249  * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned.
250  * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run,
251  * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation
252  * or transition code that is defined via a stylesheet).
253  *
254  */
255
256 angular.module('ngAnimate', ['ng'])
257
258   /**
259    * @ngdoc provider
260    * @name $animateProvider
261    * @description
262    *
263    * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module.
264    * When an animation is triggered, the $animate service will query the $animate service to find any animations that match
265    * the provided name value.
266    *
267    * Requires the {@link ngAnimate `ngAnimate`} module to be installed.
268    *
269    * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
270    *
271    */
272   .directive('ngAnimateChildren', function() {
273     var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';
274     return function(scope, element, attrs) {
275       var val = attrs.ngAnimateChildren;
276       if(angular.isString(val) && val.length === 0) { //empty attribute
277         element.data(NG_ANIMATE_CHILDREN, true);
278       } else {
279         scope.$watch(val, function(value) {
280           element.data(NG_ANIMATE_CHILDREN, !!value);
281         });
282       }
283     };
284   })
285
286   //this private service is only used within CSS-enabled animations
287   //IE8 + IE9 do not support rAF natively, but that is fine since they
288   //also don't support transitions and keyframes which means that the code
289   //below will never be used by the two browsers.
290   .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) {
291     var bod = $document[0].body;
292     return function(fn) {
293       //the returned function acts as the cancellation function
294       return $$rAF(function() {
295         //the line below will force the browser to perform a repaint
296         //so that all the animated elements within the animation frame
297         //will be properly updated and drawn on screen. This is
298         //required to perform multi-class CSS based animations with
299         //Firefox. DO NOT REMOVE THIS LINE. DO NOT OPTIMIZE THIS LINE.
300         //THE MINIFIER WILL REMOVE IT OTHERWISE WHICH WILL RESULT IN AN
301         //UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND WILL
302         //TAKE YEARS AWAY FROM YOUR LIFE!
303         fn(bod.offsetWidth);
304       });
305     };
306   }])
307
308   .config(['$provide', '$animateProvider', function($provide, $animateProvider) {
309     var noop = angular.noop;
310     var forEach = angular.forEach;
311     var selectors = $animateProvider.$$selectors;
312
313     var ELEMENT_NODE = 1;
314     var NG_ANIMATE_STATE = '$$ngAnimateState';
315     var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';
316     var NG_ANIMATE_CLASS_NAME = 'ng-animate';
317     var rootAnimateState = {running: true};
318
319     function extractElementNode(element) {
320       for(var i = 0; i < element.length; i++) {
321         var elm = element[i];
322         if(elm.nodeType == ELEMENT_NODE) {
323           return elm;
324         }
325       }
326     }
327
328     function prepareElement(element) {
329       return element && angular.element(element);
330     }
331
332     function stripCommentsFromElement(element) {
333       return angular.element(extractElementNode(element));
334     }
335
336     function isMatchingElement(elm1, elm2) {
337       return extractElementNode(elm1) == extractElementNode(elm2);
338     }
339
340     $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document',
341                             function($delegate,   $injector,   $sniffer,   $rootElement,   $$asyncCallback,    $rootScope,   $document) {
342
343       var globalAnimationCounter = 0;
344       $rootElement.data(NG_ANIMATE_STATE, rootAnimateState);
345
346       // disable animations during bootstrap, but once we bootstrapped, wait again
347       // for another digest until enabling animations. The reason why we digest twice
348       // is because all structural animations (enter, leave and move) all perform a
349       // post digest operation before animating. If we only wait for a single digest
350       // to pass then the structural animation would render its animation on page load.
351       // (which is what we're trying to avoid when the application first boots up.)
352       $rootScope.$$postDigest(function() {
353         $rootScope.$$postDigest(function() {
354           rootAnimateState.running = false;
355         });
356       });
357
358       var classNameFilter = $animateProvider.classNameFilter();
359       var isAnimatableClassName = !classNameFilter
360               ? function() { return true; }
361               : function(className) {
362                 return classNameFilter.test(className);
363               };
364
365       function blockElementAnimations(element) {
366         var data = element.data(NG_ANIMATE_STATE) || {};
367         data.running = true;
368         element.data(NG_ANIMATE_STATE, data);
369       }
370
371       function lookup(name) {
372         if (name) {
373           var matches = [],
374               flagMap = {},
375               classes = name.substr(1).split('.');
376
377           //the empty string value is the default animation
378           //operation which performs CSS transition and keyframe
379           //animations sniffing. This is always included for each
380           //element animation procedure if the browser supports
381           //transitions and/or keyframe animations. The default
382           //animation is added to the top of the list to prevent
383           //any previous animations from affecting the element styling
384           //prior to the element being animated.
385           if ($sniffer.transitions || $sniffer.animations) {
386             matches.push($injector.get(selectors['']));
387           }
388
389           for(var i=0; i < classes.length; i++) {
390             var klass = classes[i],
391                 selectorFactoryName = selectors[klass];
392             if(selectorFactoryName && !flagMap[klass]) {
393               matches.push($injector.get(selectorFactoryName));
394               flagMap[klass] = true;
395             }
396           }
397           return matches;
398         }
399       }
400
401       function animationRunner(element, animationEvent, className) {
402         //transcluded directives may sometimes fire an animation using only comment nodes
403         //best to catch this early on to prevent any animation operations from occurring
404         var node = element[0];
405         if(!node) {
406           return;
407         }
408
409         var isSetClassOperation = animationEvent == 'setClass';
410         var isClassBased = isSetClassOperation ||
411                            animationEvent == 'addClass' ||
412                            animationEvent == 'removeClass';
413
414         var classNameAdd, classNameRemove;
415         if(angular.isArray(className)) {
416           classNameAdd = className[0];
417           classNameRemove = className[1];
418           className = classNameAdd + ' ' + classNameRemove;
419         }
420
421         var currentClassName = element.attr('class');
422         var classes = currentClassName + ' ' + className;
423         if(!isAnimatableClassName(classes)) {
424           return;
425         }
426
427         var beforeComplete = noop,
428             beforeCancel = [],
429             before = [],
430             afterComplete = noop,
431             afterCancel = [],
432             after = [];
433
434         var animationLookup = (' ' + classes).replace(/\s+/g,'.');
435         forEach(lookup(animationLookup), function(animationFactory) {
436           var created = registerAnimation(animationFactory, animationEvent);
437           if(!created && isSetClassOperation) {
438             registerAnimation(animationFactory, 'addClass');
439             registerAnimation(animationFactory, 'removeClass');
440           }
441         });
442
443         function registerAnimation(animationFactory, event) {
444           var afterFn = animationFactory[event];
445           var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)];
446           if(afterFn || beforeFn) {
447             if(event == 'leave') {
448               beforeFn = afterFn;
449               //when set as null then animation knows to skip this phase
450               afterFn = null;
451             }
452             after.push({
453               event : event, fn : afterFn
454             });
455             before.push({
456               event : event, fn : beforeFn
457             });
458             return true;
459           }
460         }
461
462         function run(fns, cancellations, allCompleteFn) {
463           var animations = [];
464           forEach(fns, function(animation) {
465             animation.fn && animations.push(animation);
466           });
467
468           var count = 0;
469           function afterAnimationComplete(index) {
470             if(cancellations) {
471               (cancellations[index] || noop)();
472               if(++count < animations.length) return;
473               cancellations = null;
474             }
475             allCompleteFn();
476           }
477
478           //The code below adds directly to the array in order to work with
479           //both sync and async animations. Sync animations are when the done()
480           //operation is called right away. DO NOT REFACTOR!
481           forEach(animations, function(animation, index) {
482             var progress = function() {
483               afterAnimationComplete(index);
484             };
485             switch(animation.event) {
486               case 'setClass':
487                 cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress));
488                 break;
489               case 'addClass':
490                 cancellations.push(animation.fn(element, classNameAdd || className,     progress));
491                 break;
492               case 'removeClass':
493                 cancellations.push(animation.fn(element, classNameRemove || className,  progress));
494                 break;
495               default:
496                 cancellations.push(animation.fn(element, progress));
497                 break;
498             }
499           });
500
501           if(cancellations && cancellations.length === 0) {
502             allCompleteFn();
503           }
504         }
505
506         return {
507           node : node,
508           event : animationEvent,
509           className : className,
510           isClassBased : isClassBased,
511           isSetClassOperation : isSetClassOperation,
512           before : function(allCompleteFn) {
513             beforeComplete = allCompleteFn;
514             run(before, beforeCancel, function() {
515               beforeComplete = noop;
516               allCompleteFn();
517             });
518           },
519           after : function(allCompleteFn) {
520             afterComplete = allCompleteFn;
521             run(after, afterCancel, function() {
522               afterComplete = noop;
523               allCompleteFn();
524             });
525           },
526           cancel : function() {
527             if(beforeCancel) {
528               forEach(beforeCancel, function(cancelFn) {
529                 (cancelFn || noop)(true);
530               });
531               beforeComplete(true);
532             }
533             if(afterCancel) {
534               forEach(afterCancel, function(cancelFn) {
535                 (cancelFn || noop)(true);
536               });
537               afterComplete(true);
538             }
539           }
540         };
541       }
542
543       /**
544        * @ngdoc service
545        * @name $animate
546        * @kind function
547        *
548        * @description
549        * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations.
550        * When any of these operations are run, the $animate service
551        * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object)
552        * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.
553        *
554        * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives
555        * will work out of the box without any extra configuration.
556        *
557        * Requires the {@link ngAnimate `ngAnimate`} module to be installed.
558        *
559        * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
560        *
561        */
562       return {
563         /**
564          * @ngdoc method
565          * @name $animate#enter
566          * @kind function
567          *
568          * @description
569          * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once
570          * the animation is started, the following CSS classes will be present on the element for the duration of the animation:
571          *
572          * Below is a breakdown of each step that occurs during enter animation:
573          *
574          * | Animation Step                                                                               | What the element class attribute looks like |
575          * |----------------------------------------------------------------------------------------------|---------------------------------------------|
576          * | 1. $animate.enter(...) is called                                                             | class="my-animation"                        |
577          * | 2. element is inserted into the parentElement element or beside the afterElement element     | class="my-animation"                        |
578          * | 3. $animate runs any JavaScript-defined animations on the element                            | class="my-animation ng-animate"             |
579          * | 4. the .ng-enter class is added to the element                                               | class="my-animation ng-animate ng-enter"    |
580          * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay  | class="my-animation ng-animate ng-enter"    |
581          * | 6. $animate waits for 10ms (this performs a reflow)                                          | class="my-animation ng-animate ng-enter"    |
582          * | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" |
583          * | 8. $animate waits for X milliseconds for the animation to complete                           | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" |
584          * | 9. The animation ends and all generated CSS classes are removed from the element             | class="my-animation"                        |
585          * | 10. The doneCallback() callback is fired (if provided)                                       | class="my-animation"                        |
586          *
587          * @param {DOMElement} element the element that will be the focus of the enter animation
588          * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation
589          * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation
590          * @param {function()=} doneCallback the callback function that will be called once the animation is complete
591         */
592         enter : function(element, parentElement, afterElement, doneCallback) {
593           element = angular.element(element);
594           parentElement = prepareElement(parentElement);
595           afterElement = prepareElement(afterElement);
596
597           blockElementAnimations(element);
598           $delegate.enter(element, parentElement, afterElement);
599           $rootScope.$$postDigest(function() {
600             element = stripCommentsFromElement(element);
601             performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback);
602           });
603         },
604
605         /**
606          * @ngdoc method
607          * @name $animate#leave
608          * @kind function
609          *
610          * @description
611          * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once
612          * the animation is started, the following CSS classes will be added for the duration of the animation:
613          *
614          * Below is a breakdown of each step that occurs during leave animation:
615          *
616          * | Animation Step                                                                               | What the element class attribute looks like |
617          * |----------------------------------------------------------------------------------------------|---------------------------------------------|
618          * | 1. $animate.leave(...) is called                                                             | class="my-animation"                        |
619          * | 2. $animate runs any JavaScript-defined animations on the element                            | class="my-animation ng-animate"             |
620          * | 3. the .ng-leave class is added to the element                                               | class="my-animation ng-animate ng-leave"    |
621          * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay  | class="my-animation ng-animate ng-leave"    |
622          * | 5. $animate waits for 10ms (this performs a reflow)                                          | class="my-animation ng-animate ng-leave"    |
623          * | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" |
624          * | 7. $animate waits for X milliseconds for the animation to complete                           | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" |
625          * | 8. The animation ends and all generated CSS classes are removed from the element             | class="my-animation"                        |
626          * | 9. The element is removed from the DOM                                                       | ...                                         |
627          * | 10. The doneCallback() callback is fired (if provided)                                       | ...                                         |
628          *
629          * @param {DOMElement} element the element that will be the focus of the leave animation
630          * @param {function()=} doneCallback the callback function that will be called once the animation is complete
631         */
632         leave : function(element, doneCallback) {
633           element = angular.element(element);
634           cancelChildAnimations(element);
635           blockElementAnimations(element);
636           $rootScope.$$postDigest(function() {
637             performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() {
638               $delegate.leave(element);
639             }, doneCallback);
640           });
641         },
642
643         /**
644          * @ngdoc method
645          * @name $animate#move
646          * @kind function
647          *
648          * @description
649          * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or
650          * add the element directly after the afterElement element if present. Then the move animation will be run. Once
651          * the animation is started, the following CSS classes will be added for the duration of the animation:
652          *
653          * Below is a breakdown of each step that occurs during move animation:
654          *
655          * | Animation Step                                                                               | What the element class attribute looks like |
656          * |----------------------------------------------------------------------------------------------|---------------------------------------------|
657          * | 1. $animate.move(...) is called                                                              | class="my-animation"                        |
658          * | 2. element is moved into the parentElement element or beside the afterElement element        | class="my-animation"                        |
659          * | 3. $animate runs any JavaScript-defined animations on the element                            | class="my-animation ng-animate"             |
660          * | 4. the .ng-move class is added to the element                                                | class="my-animation ng-animate ng-move"     |
661          * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay  | class="my-animation ng-animate ng-move"     |
662          * | 6. $animate waits for 10ms (this performs a reflow)                                          | class="my-animation ng-animate ng-move"     |
663          * | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" |
664          * | 8. $animate waits for X milliseconds for the animation to complete                           | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" |
665          * | 9. The animation ends and all generated CSS classes are removed from the element             | class="my-animation"                        |
666          * | 10. The doneCallback() callback is fired (if provided)                                       | class="my-animation"                        |
667          *
668          * @param {DOMElement} element the element that will be the focus of the move animation
669          * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation
670          * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation
671          * @param {function()=} doneCallback the callback function that will be called once the animation is complete
672         */
673         move : function(element, parentElement, afterElement, doneCallback) {
674           element = angular.element(element);
675           parentElement = prepareElement(parentElement);
676           afterElement = prepareElement(afterElement);
677
678           cancelChildAnimations(element);
679           blockElementAnimations(element);
680           $delegate.move(element, parentElement, afterElement);
681           $rootScope.$$postDigest(function() {
682             element = stripCommentsFromElement(element);
683             performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback);
684           });
685         },
686
687         /**
688          * @ngdoc method
689          * @name $animate#addClass
690          *
691          * @description
692          * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class.
693          * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide
694          * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions
695          * or keyframes are defined on the -add or base CSS class).
696          *
697          * Below is a breakdown of each step that occurs during addClass animation:
698          *
699          * | Animation Step                                                                                 | What the element class attribute looks like |
700          * |------------------------------------------------------------------------------------------------|---------------------------------------------|
701          * | 1. $animate.addClass(element, 'super') is called                                               | class="my-animation"                        |
702          * | 2. $animate runs any JavaScript-defined animations on the element                              | class="my-animation ng-animate"             |
703          * | 3. the .super-add class are added to the element                                               | class="my-animation ng-animate super-add"   |
704          * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay    | class="my-animation ng-animate super-add"   |
705          * | 5. $animate waits for 10ms (this performs a reflow)                                            | class="my-animation ng-animate super-add"   |
706          * | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active"          |
707          * | 7. $animate waits for X milliseconds for the animation to complete                             | class="my-animation super super-add super-add-active"  |
708          * | 8. The animation ends and all generated CSS classes are removed from the element               | class="my-animation super"                  |
709          * | 9. The super class is kept on the element                                                      | class="my-animation super"                  |
710          * | 10. The doneCallback() callback is fired (if provided)                                         | class="my-animation super"                  |
711          *
712          * @param {DOMElement} element the element that will be animated
713          * @param {string} className the CSS class that will be added to the element and then animated
714          * @param {function()=} doneCallback the callback function that will be called once the animation is complete
715         */
716         addClass : function(element, className, doneCallback) {
717           element = angular.element(element);
718           element = stripCommentsFromElement(element);
719           performAnimation('addClass', className, element, null, null, function() {
720             $delegate.addClass(element, className);
721           }, doneCallback);
722         },
723
724         /**
725          * @ngdoc method
726          * @name $animate#removeClass
727          *
728          * @description
729          * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value
730          * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in
731          * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if
732          * no CSS transitions or keyframes are defined on the -remove or base CSS classes).
733          *
734          * Below is a breakdown of each step that occurs during removeClass animation:
735          *
736          * | Animation Step                                                                                | What the element class attribute looks like     |
737          * |-----------------------------------------------------------------------------------------------|---------------------------------------------|
738          * | 1. $animate.removeClass(element, 'super') is called                                           | class="my-animation super"                  |
739          * | 2. $animate runs any JavaScript-defined animations on the element                             | class="my-animation super ng-animate"       |
740          * | 3. the .super-remove class are added to the element                                           | class="my-animation super ng-animate super-remove"|
741          * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay   | class="my-animation super ng-animate super-remove"   |
742          * | 5. $animate waits for 10ms (this performs a reflow)                                           | class="my-animation super ng-animate super-remove"   |
743          * | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active"          |
744          * | 7. $animate waits for X milliseconds for the animation to complete                            | class="my-animation ng-animate ng-animate-active super-remove super-remove-active"   |
745          * | 8. The animation ends and all generated CSS classes are removed from the element              | class="my-animation"                        |
746          * | 9. The doneCallback() callback is fired (if provided)                                         | class="my-animation"                        |
747          *
748          *
749          * @param {DOMElement} element the element that will be animated
750          * @param {string} className the CSS class that will be animated and then removed from the element
751          * @param {function()=} doneCallback the callback function that will be called once the animation is complete
752         */
753         removeClass : function(element, className, doneCallback) {
754           element = angular.element(element);
755           element = stripCommentsFromElement(element);
756           performAnimation('removeClass', className, element, null, null, function() {
757             $delegate.removeClass(element, className);
758           }, doneCallback);
759         },
760
761           /**
762            *
763            * @ngdoc function
764            * @name $animate#setClass
765            * @function
766            * @description Adds and/or removes the given CSS classes to and from the element.
767            * Once complete, the done() callback will be fired (if provided).
768            * @param {DOMElement} element the element which will its CSS classes changed
769            *   removed from it
770            * @param {string} add the CSS classes which will be added to the element
771            * @param {string} remove the CSS class which will be removed from the element
772            * @param {Function=} done the callback function (if provided) that will be fired after the
773            *   CSS classes have been set on the element
774            */
775         setClass : function(element, add, remove, doneCallback) {
776           element = angular.element(element);
777           element = stripCommentsFromElement(element);
778           performAnimation('setClass', [add, remove], element, null, null, function() {
779             $delegate.setClass(element, add, remove);
780           }, doneCallback);
781         },
782
783         /**
784          * @ngdoc method
785          * @name $animate#enabled
786          * @kind function
787          *
788          * @param {boolean=} value If provided then set the animation on or off.
789          * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation
790          * @return {boolean} Current animation state.
791          *
792          * @description
793          * Globally enables/disables animations.
794          *
795         */
796         enabled : function(value, element) {
797           switch(arguments.length) {
798             case 2:
799               if(value) {
800                 cleanup(element);
801               } else {
802                 var data = element.data(NG_ANIMATE_STATE) || {};
803                 data.disabled = true;
804                 element.data(NG_ANIMATE_STATE, data);
805               }
806             break;
807
808             case 1:
809               rootAnimateState.disabled = !value;
810             break;
811
812             default:
813               value = !rootAnimateState.disabled;
814             break;
815           }
816           return !!value;
817          }
818       };
819
820       /*
821         all animations call this shared animation triggering function internally.
822         The animationEvent variable refers to the JavaScript animation event that will be triggered
823         and the className value is the name of the animation that will be applied within the
824         CSS code. Element, parentElement and afterElement are provided DOM elements for the animation
825         and the onComplete callback will be fired once the animation is fully complete.
826       */
827       function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) {
828
829         var runner = animationRunner(element, animationEvent, className);
830         if(!runner) {
831           fireDOMOperation();
832           fireBeforeCallbackAsync();
833           fireAfterCallbackAsync();
834           closeAnimation();
835           return;
836         }
837
838         className = runner.className;
839         var elementEvents = angular.element._data(runner.node);
840         elementEvents = elementEvents && elementEvents.events;
841
842         if (!parentElement) {
843           parentElement = afterElement ? afterElement.parent() : element.parent();
844         }
845
846         var ngAnimateState  = element.data(NG_ANIMATE_STATE) || {};
847         var runningAnimations     = ngAnimateState.active || {};
848         var totalActiveAnimations = ngAnimateState.totalActive || 0;
849         var lastAnimation         = ngAnimateState.last;
850
851         //only allow animations if the currently running animation is not structural
852         //or if there is no animation running at all
853         var skipAnimations;
854         if (runner.isClassBased) {
855           skipAnimations = ngAnimateState.running ||
856                            ngAnimateState.disabled ||
857                            (lastAnimation && !lastAnimation.isClassBased);
858         }
859
860         //skip the animation if animations are disabled, a parent is already being animated,
861         //the element is not currently attached to the document body or then completely close
862         //the animation if any matching animations are not found at all.
863         //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found.
864         if (skipAnimations || animationsDisabled(element, parentElement)) {
865           fireDOMOperation();
866           fireBeforeCallbackAsync();
867           fireAfterCallbackAsync();
868           closeAnimation();
869           return;
870         }
871
872         var skipAnimation = false;
873         if(totalActiveAnimations > 0) {
874           var animationsToCancel = [];
875           if(!runner.isClassBased) {
876             if(animationEvent == 'leave' && runningAnimations['ng-leave']) {
877               skipAnimation = true;
878             } else {
879               //cancel all animations when a structural animation takes place
880               for(var klass in runningAnimations) {
881                 animationsToCancel.push(runningAnimations[klass]);
882                 cleanup(element, klass);
883               }
884               runningAnimations = {};
885               totalActiveAnimations = 0;
886             }
887           } else if(lastAnimation.event == 'setClass') {
888             animationsToCancel.push(lastAnimation);
889             cleanup(element, className);
890           }
891           else if(runningAnimations[className]) {
892             var current = runningAnimations[className];
893             if(current.event == animationEvent) {
894               skipAnimation = true;
895             } else {
896               animationsToCancel.push(current);
897               cleanup(element, className);
898             }
899           }
900
901           if(animationsToCancel.length > 0) {
902             forEach(animationsToCancel, function(operation) {
903               operation.cancel();
904             });
905           }
906         }
907
908         if(runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) {
909           skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR
910         }
911
912         if(skipAnimation) {
913           fireDOMOperation();
914           fireBeforeCallbackAsync();
915           fireAfterCallbackAsync();
916           fireDoneCallbackAsync();
917           return;
918         }
919
920         if(animationEvent == 'leave') {
921           //there's no need to ever remove the listener since the element
922           //will be removed (destroyed) after the leave animation ends or
923           //is cancelled midway
924           element.one('$destroy', function(e) {
925             var element = angular.element(this);
926             var state = element.data(NG_ANIMATE_STATE);
927             if(state) {
928               var activeLeaveAnimation = state.active['ng-leave'];
929               if(activeLeaveAnimation) {
930                 activeLeaveAnimation.cancel();
931                 cleanup(element, 'ng-leave');
932               }
933             }
934           });
935         }
936
937         //the ng-animate class does nothing, but it's here to allow for
938         //parent animations to find and cancel child animations when needed
939         element.addClass(NG_ANIMATE_CLASS_NAME);
940
941         var localAnimationCount = globalAnimationCounter++;
942         totalActiveAnimations++;
943         runningAnimations[className] = runner;
944
945         element.data(NG_ANIMATE_STATE, {
946           last : runner,
947           active : runningAnimations,
948           index : localAnimationCount,
949           totalActive : totalActiveAnimations
950         });
951
952         //first we run the before animations and when all of those are complete
953         //then we perform the DOM operation and run the next set of animations
954         fireBeforeCallbackAsync();
955         runner.before(function(cancelled) {
956           var data = element.data(NG_ANIMATE_STATE);
957           cancelled = cancelled ||
958                         !data || !data.active[className] ||
959                         (runner.isClassBased && data.active[className].event != animationEvent);
960
961           fireDOMOperation();
962           if(cancelled === true) {
963             closeAnimation();
964           } else {
965             fireAfterCallbackAsync();
966             runner.after(closeAnimation);
967           }
968         });
969
970         function fireDOMCallback(animationPhase) {
971           var eventName = '$animate:' + animationPhase;
972           if(elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) {
973             $$asyncCallback(function() {
974               element.triggerHandler(eventName, {
975                 event : animationEvent,
976                 className : className
977               });
978             });
979           }
980         }
981
982         function fireBeforeCallbackAsync() {
983           fireDOMCallback('before');
984         }
985
986         function fireAfterCallbackAsync() {
987           fireDOMCallback('after');
988         }
989
990         function fireDoneCallbackAsync() {
991           fireDOMCallback('close');
992           if(doneCallback) {
993             $$asyncCallback(function() {
994               doneCallback();
995             });
996           }
997         }
998
999         //it is less complicated to use a flag than managing and canceling
1000         //timeouts containing multiple callbacks.
1001         function fireDOMOperation() {
1002           if(!fireDOMOperation.hasBeenRun) {
1003             fireDOMOperation.hasBeenRun = true;
1004             domOperation();
1005           }
1006         }
1007
1008         function closeAnimation() {
1009           if(!closeAnimation.hasBeenRun) {
1010             closeAnimation.hasBeenRun = true;
1011             var data = element.data(NG_ANIMATE_STATE);
1012             if(data) {
1013               /* only structural animations wait for reflow before removing an
1014                  animation, but class-based animations don't. An example of this
1015                  failing would be when a parent HTML tag has a ng-class attribute
1016                  causing ALL directives below to skip animations during the digest */
1017               if(runner && runner.isClassBased) {
1018                 cleanup(element, className);
1019               } else {
1020                 $$asyncCallback(function() {
1021                   var data = element.data(NG_ANIMATE_STATE) || {};
1022                   if(localAnimationCount == data.index) {
1023                     cleanup(element, className, animationEvent);
1024                   }
1025                 });
1026                 element.data(NG_ANIMATE_STATE, data);
1027               }
1028             }
1029             fireDoneCallbackAsync();
1030           }
1031         }
1032       }
1033
1034       function cancelChildAnimations(element) {
1035         var node = extractElementNode(element);
1036         if (node) {
1037           var nodes = angular.isFunction(node.getElementsByClassName) ?
1038             node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) :
1039             node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME);
1040           forEach(nodes, function(element) {
1041             element = angular.element(element);
1042             var data = element.data(NG_ANIMATE_STATE);
1043             if(data && data.active) {
1044               forEach(data.active, function(runner) {
1045                 runner.cancel();
1046               });
1047             }
1048           });
1049         }
1050       }
1051
1052       function cleanup(element, className) {
1053         if(isMatchingElement(element, $rootElement)) {
1054           if(!rootAnimateState.disabled) {
1055             rootAnimateState.running = false;
1056             rootAnimateState.structural = false;
1057           }
1058         } else if(className) {
1059           var data = element.data(NG_ANIMATE_STATE) || {};
1060
1061           var removeAnimations = className === true;
1062           if(!removeAnimations && data.active && data.active[className]) {
1063             data.totalActive--;
1064             delete data.active[className];
1065           }
1066
1067           if(removeAnimations || !data.totalActive) {
1068             element.removeClass(NG_ANIMATE_CLASS_NAME);
1069             element.removeData(NG_ANIMATE_STATE);
1070           }
1071         }
1072       }
1073
1074       function animationsDisabled(element, parentElement) {
1075         if (rootAnimateState.disabled) {
1076           return true;
1077         }
1078
1079         if (isMatchingElement(element, $rootElement)) {
1080           return rootAnimateState.running;
1081         }
1082
1083         var allowChildAnimations, parentRunningAnimation, hasParent;
1084         do {
1085           //the element did not reach the root element which means that it
1086           //is not apart of the DOM. Therefore there is no reason to do
1087           //any animations on it
1088           if (parentElement.length === 0) break;
1089
1090           var isRoot = isMatchingElement(parentElement, $rootElement);
1091           var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {});
1092           if (state.disabled) {
1093             return true;
1094           }
1095
1096           //no matter what, for an animation to work it must reach the root element
1097           //this implies that the element is attached to the DOM when the animation is run
1098           if (isRoot) {
1099             hasParent = true;
1100           }
1101
1102           //once a flag is found that is strictly false then everything before
1103           //it will be discarded and all child animations will be restricted
1104           if (allowChildAnimations !== false) {
1105             var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN);
1106             if(angular.isDefined(animateChildrenFlag)) {
1107               allowChildAnimations = animateChildrenFlag;
1108             }
1109           }
1110
1111           parentRunningAnimation = parentRunningAnimation ||
1112                                    state.running ||
1113                                    (state.last && !state.last.isClassBased);
1114         }
1115         while(parentElement = parentElement.parent());
1116
1117         return !hasParent || (!allowChildAnimations && parentRunningAnimation);
1118       }
1119     }]);
1120
1121     $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow',
1122                            function($window,   $sniffer,   $timeout,   $$animateReflow) {
1123       // Detect proper transitionend/animationend event names.
1124       var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
1125
1126       // If unprefixed events are not supported but webkit-prefixed are, use the latter.
1127       // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
1128       // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
1129       // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
1130       // Register both events in case `window.onanimationend` is not supported because of that,
1131       // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
1132       // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
1133       // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition
1134       if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {
1135         CSS_PREFIX = '-webkit-';
1136         TRANSITION_PROP = 'WebkitTransition';
1137         TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
1138       } else {
1139         TRANSITION_PROP = 'transition';
1140         TRANSITIONEND_EVENT = 'transitionend';
1141       }
1142
1143       if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {
1144         CSS_PREFIX = '-webkit-';
1145         ANIMATION_PROP = 'WebkitAnimation';
1146         ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
1147       } else {
1148         ANIMATION_PROP = 'animation';
1149         ANIMATIONEND_EVENT = 'animationend';
1150       }
1151
1152       var DURATION_KEY = 'Duration';
1153       var PROPERTY_KEY = 'Property';
1154       var DELAY_KEY = 'Delay';
1155       var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
1156       var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey';
1157       var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data';
1158       var NG_ANIMATE_BLOCK_CLASS_NAME = 'ng-animate-block-transitions';
1159       var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
1160       var CLOSING_TIME_BUFFER = 1.5;
1161       var ONE_SECOND = 1000;
1162
1163       var lookupCache = {};
1164       var parentCounter = 0;
1165       var animationReflowQueue = [];
1166       var cancelAnimationReflow;
1167       function clearCacheAfterReflow() {
1168         if (!cancelAnimationReflow) {
1169           cancelAnimationReflow = $$animateReflow(function() {
1170             animationReflowQueue = [];
1171             cancelAnimationReflow = null;
1172             lookupCache = {};
1173           });
1174         }
1175       }
1176
1177       function afterReflow(element, callback) {
1178         if(cancelAnimationReflow) {
1179           cancelAnimationReflow();
1180         }
1181         animationReflowQueue.push(callback);
1182         cancelAnimationReflow = $$animateReflow(function() {
1183           forEach(animationReflowQueue, function(fn) {
1184             fn();
1185           });
1186
1187           animationReflowQueue = [];
1188           cancelAnimationReflow = null;
1189           lookupCache = {};
1190         });
1191       }
1192
1193       var closingTimer = null;
1194       var closingTimestamp = 0;
1195       var animationElementQueue = [];
1196       function animationCloseHandler(element, totalTime) {
1197         var node = extractElementNode(element);
1198         element = angular.element(node);
1199
1200         //this item will be garbage collected by the closing
1201         //animation timeout
1202         animationElementQueue.push(element);
1203
1204         //but it may not need to cancel out the existing timeout
1205         //if the timestamp is less than the previous one
1206         var futureTimestamp = Date.now() + totalTime;
1207         if(futureTimestamp <= closingTimestamp) {
1208           return;
1209         }
1210
1211         $timeout.cancel(closingTimer);
1212
1213         closingTimestamp = futureTimestamp;
1214         closingTimer = $timeout(function() {
1215           closeAllAnimations(animationElementQueue);
1216           animationElementQueue = [];
1217         }, totalTime, false);
1218       }
1219
1220       function closeAllAnimations(elements) {
1221         forEach(elements, function(element) {
1222           var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);
1223           if(elementData) {
1224             (elementData.closeAnimationFn || noop)();
1225           }
1226         });
1227       }
1228
1229       function getElementAnimationDetails(element, cacheKey) {
1230         var data = cacheKey ? lookupCache[cacheKey] : null;
1231         if(!data) {
1232           var transitionDuration = 0;
1233           var transitionDelay = 0;
1234           var animationDuration = 0;
1235           var animationDelay = 0;
1236           var transitionDelayStyle;
1237           var animationDelayStyle;
1238           var transitionDurationStyle;
1239           var transitionPropertyStyle;
1240
1241           //we want all the styles defined before and after
1242           forEach(element, function(element) {
1243             if (element.nodeType == ELEMENT_NODE) {
1244               var elementStyles = $window.getComputedStyle(element) || {};
1245
1246               transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY];
1247
1248               transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration);
1249
1250               transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY];
1251
1252               transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY];
1253
1254               transitionDelay  = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay);
1255
1256               animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY];
1257
1258               animationDelay   = Math.max(parseMaxTime(animationDelayStyle), animationDelay);
1259
1260               var aDuration  = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]);
1261
1262               if(aDuration > 0) {
1263                 aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1;
1264               }
1265
1266               animationDuration = Math.max(aDuration, animationDuration);
1267             }
1268           });
1269           data = {
1270             total : 0,
1271             transitionPropertyStyle: transitionPropertyStyle,
1272             transitionDurationStyle: transitionDurationStyle,
1273             transitionDelayStyle: transitionDelayStyle,
1274             transitionDelay: transitionDelay,
1275             transitionDuration: transitionDuration,
1276             animationDelayStyle: animationDelayStyle,
1277             animationDelay: animationDelay,
1278             animationDuration: animationDuration
1279           };
1280           if(cacheKey) {
1281             lookupCache[cacheKey] = data;
1282           }
1283         }
1284         return data;
1285       }
1286
1287       function parseMaxTime(str) {
1288         var maxValue = 0;
1289         var values = angular.isString(str) ?
1290           str.split(/\s*,\s*/) :
1291           [];
1292         forEach(values, function(value) {
1293           maxValue = Math.max(parseFloat(value) || 0, maxValue);
1294         });
1295         return maxValue;
1296       }
1297
1298       function getCacheKey(element) {
1299         var parentElement = element.parent();
1300         var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY);
1301         if(!parentID) {
1302           parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter);
1303           parentID = parentCounter;
1304         }
1305         return parentID + '-' + extractElementNode(element).getAttribute('class');
1306       }
1307
1308       function animateSetup(animationEvent, element, className, calculationDecorator) {
1309         var cacheKey = getCacheKey(element);
1310         var eventCacheKey = cacheKey + ' ' + className;
1311         var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0;
1312
1313         var stagger = {};
1314         if(itemIndex > 0) {
1315           var staggerClassName = className + '-stagger';
1316           var staggerCacheKey = cacheKey + ' ' + staggerClassName;
1317           var applyClasses = !lookupCache[staggerCacheKey];
1318
1319           applyClasses && element.addClass(staggerClassName);
1320
1321           stagger = getElementAnimationDetails(element, staggerCacheKey);
1322
1323           applyClasses && element.removeClass(staggerClassName);
1324         }
1325
1326         /* the animation itself may need to add/remove special CSS classes
1327          * before calculating the anmation styles */
1328         calculationDecorator = calculationDecorator ||
1329                                function(fn) { return fn(); };
1330
1331         element.addClass(className);
1332
1333         var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {};
1334
1335         var timings = calculationDecorator(function() {
1336           return getElementAnimationDetails(element, eventCacheKey);
1337         });
1338
1339         var transitionDuration = timings.transitionDuration;
1340         var animationDuration = timings.animationDuration;
1341         if(transitionDuration === 0 && animationDuration === 0) {
1342           element.removeClass(className);
1343           return false;
1344         }
1345
1346         element.data(NG_ANIMATE_CSS_DATA_KEY, {
1347           running : formerData.running || 0,
1348           itemIndex : itemIndex,
1349           stagger : stagger,
1350           timings : timings,
1351           closeAnimationFn : noop
1352         });
1353
1354         //temporarily disable the transition so that the enter styles
1355         //don't animate twice (this is here to avoid a bug in Chrome/FF).
1356         var isCurrentlyAnimating = formerData.running > 0 || animationEvent == 'setClass';
1357         if(transitionDuration > 0) {
1358           blockTransitions(element, className, isCurrentlyAnimating);
1359         }
1360
1361         //staggering keyframe animations work by adjusting the `animation-delay` CSS property
1362         //on the given element, however, the delay value can only calculated after the reflow
1363         //since by that time $animate knows how many elements are being animated. Therefore,
1364         //until the reflow occurs the element needs to be blocked (where the keyframe animation
1365         //is set to `none 0s`). This blocking mechanism should only be set for when a stagger
1366         //animation is detected and when the element item index is greater than 0.
1367         if(animationDuration > 0 && stagger.animationDelay > 0 && stagger.animationDuration === 0) {
1368           blockKeyframeAnimations(element);
1369         }
1370
1371         return true;
1372       }
1373
1374       function isStructuralAnimation(className) {
1375         return className == 'ng-enter' || className == 'ng-move' || className == 'ng-leave';
1376       }
1377
1378       function blockTransitions(element, className, isAnimating) {
1379         if(isStructuralAnimation(className) || !isAnimating) {
1380           extractElementNode(element).style[TRANSITION_PROP + PROPERTY_KEY] = 'none';
1381         } else {
1382           element.addClass(NG_ANIMATE_BLOCK_CLASS_NAME);
1383         }
1384       }
1385
1386       function blockKeyframeAnimations(element) {
1387         extractElementNode(element).style[ANIMATION_PROP] = 'none 0s';
1388       }
1389
1390       function unblockTransitions(element, className) {
1391         var prop = TRANSITION_PROP + PROPERTY_KEY;
1392         var node = extractElementNode(element);
1393         if(node.style[prop] && node.style[prop].length > 0) {
1394           node.style[prop] = '';
1395         }
1396         element.removeClass(NG_ANIMATE_BLOCK_CLASS_NAME);
1397       }
1398
1399       function unblockKeyframeAnimations(element) {
1400         var prop = ANIMATION_PROP;
1401         var node = extractElementNode(element);
1402         if(node.style[prop] && node.style[prop].length > 0) {
1403           node.style[prop] = '';
1404         }
1405       }
1406
1407       function animateRun(animationEvent, element, className, activeAnimationComplete) {
1408         var node = extractElementNode(element);
1409         var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);
1410         if(node.getAttribute('class').indexOf(className) == -1 || !elementData) {
1411           activeAnimationComplete();
1412           return;
1413         }
1414
1415         var activeClassName = '';
1416         forEach(className.split(' '), function(klass, i) {
1417           activeClassName += (i > 0 ? ' ' : '') + klass + '-active';
1418         });
1419
1420         var stagger = elementData.stagger;
1421         var timings = elementData.timings;
1422         var itemIndex = elementData.itemIndex;
1423         var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration);
1424         var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay);
1425         var maxDelayTime = maxDelay * ONE_SECOND;
1426
1427         var startTime = Date.now();
1428         var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT;
1429
1430         var style = '', appliedStyles = [];
1431         if(timings.transitionDuration > 0) {
1432           var propertyStyle = timings.transitionPropertyStyle;
1433           if(propertyStyle.indexOf('all') == -1) {
1434             style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';';
1435             style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ';';
1436             appliedStyles.push(CSS_PREFIX + 'transition-property');
1437             appliedStyles.push(CSS_PREFIX + 'transition-duration');
1438           }
1439         }
1440
1441         if(itemIndex > 0) {
1442           if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) {
1443             var delayStyle = timings.transitionDelayStyle;
1444             style += CSS_PREFIX + 'transition-delay: ' +
1445                      prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; ';
1446             appliedStyles.push(CSS_PREFIX + 'transition-delay');
1447           }
1448
1449           if(stagger.animationDelay > 0 && stagger.animationDuration === 0) {
1450             style += CSS_PREFIX + 'animation-delay: ' +
1451                      prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; ';
1452             appliedStyles.push(CSS_PREFIX + 'animation-delay');
1453           }
1454         }
1455
1456         if(appliedStyles.length > 0) {
1457           //the element being animated may sometimes contain comment nodes in
1458           //the jqLite object, so we're safe to use a single variable to house
1459           //the styles since there is always only one element being animated
1460           var oldStyle = node.getAttribute('style') || '';
1461           node.setAttribute('style', oldStyle + '; ' + style);
1462         }
1463
1464         element.on(css3AnimationEvents, onAnimationProgress);
1465         element.addClass(activeClassName);
1466         elementData.closeAnimationFn = function() {
1467           onEnd();
1468           activeAnimationComplete();
1469         };
1470
1471         var staggerTime       = itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0);
1472         var animationTime     = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER;
1473         var totalTime         = (staggerTime + animationTime) * ONE_SECOND;
1474
1475         elementData.running++;
1476         animationCloseHandler(element, totalTime);
1477         return onEnd;
1478
1479         // This will automatically be called by $animate so
1480         // there is no need to attach this internally to the
1481         // timeout done method.
1482         function onEnd(cancelled) {
1483           element.off(css3AnimationEvents, onAnimationProgress);
1484           element.removeClass(activeClassName);
1485           animateClose(element, className);
1486           var node = extractElementNode(element);
1487           for (var i in appliedStyles) {
1488             node.style.removeProperty(appliedStyles[i]);
1489           }
1490         }
1491
1492         function onAnimationProgress(event) {
1493           event.stopPropagation();
1494           var ev = event.originalEvent || event;
1495           var timeStamp = ev.$manualTimeStamp || Date.now();
1496
1497           /* Firefox (or possibly just Gecko) likes to not round values up
1498            * when a ms measurement is used for the animation */
1499           var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
1500
1501           /* $manualTimeStamp is a mocked timeStamp value which is set
1502            * within browserTrigger(). This is only here so that tests can
1503            * mock animations properly. Real events fallback to Date.now(),
1504            * or, if they don't, then a timeStamp is automatically created for them.
1505            * We're checking to see if the timeStamp surpasses the expected delay,
1506            * but we're using elapsedTime instead of the timeStamp on the 2nd
1507            * pre-condition since animations sometimes close off early */
1508           if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
1509             activeAnimationComplete();
1510           }
1511         }
1512       }
1513
1514       function prepareStaggerDelay(delayStyle, staggerDelay, index) {
1515         var style = '';
1516         forEach(delayStyle.split(','), function(val, i) {
1517           style += (i > 0 ? ',' : '') +
1518                    (index * staggerDelay + parseInt(val, 10)) + 's';
1519         });
1520         return style;
1521       }
1522
1523       function animateBefore(animationEvent, element, className, calculationDecorator) {
1524         if(animateSetup(animationEvent, element, className, calculationDecorator)) {
1525           return function(cancelled) {
1526             cancelled && animateClose(element, className);
1527           };
1528         }
1529       }
1530
1531       function animateAfter(animationEvent, element, className, afterAnimationComplete) {
1532         if(element.data(NG_ANIMATE_CSS_DATA_KEY)) {
1533           return animateRun(animationEvent, element, className, afterAnimationComplete);
1534         } else {
1535           animateClose(element, className);
1536           afterAnimationComplete();
1537         }
1538       }
1539
1540       function animate(animationEvent, element, className, animationComplete) {
1541         //If the animateSetup function doesn't bother returning a
1542         //cancellation function then it means that there is no animation
1543         //to perform at all
1544         var preReflowCancellation = animateBefore(animationEvent, element, className);
1545         if (!preReflowCancellation) {
1546           clearCacheAfterReflow();
1547           animationComplete();
1548           return;
1549         }
1550
1551         //There are two cancellation functions: one is before the first
1552         //reflow animation and the second is during the active state
1553         //animation. The first function will take care of removing the
1554         //data from the element which will not make the 2nd animation
1555         //happen in the first place
1556         var cancel = preReflowCancellation;
1557         afterReflow(element, function() {
1558           unblockTransitions(element, className);
1559           unblockKeyframeAnimations(element);
1560           //once the reflow is complete then we point cancel to
1561           //the new cancellation function which will remove all of the
1562           //animation properties from the active animation
1563           cancel = animateAfter(animationEvent, element, className, animationComplete);
1564         });
1565
1566         return function(cancelled) {
1567           (cancel || noop)(cancelled);
1568         };
1569       }
1570
1571       function animateClose(element, className) {
1572         element.removeClass(className);
1573         var data = element.data(NG_ANIMATE_CSS_DATA_KEY);
1574         if(data) {
1575           if(data.running) {
1576             data.running--;
1577           }
1578           if(!data.running || data.running === 0) {
1579             element.removeData(NG_ANIMATE_CSS_DATA_KEY);
1580           }
1581         }
1582       }
1583
1584       return {
1585         enter : function(element, animationCompleted) {
1586           return animate('enter', element, 'ng-enter', animationCompleted);
1587         },
1588
1589         leave : function(element, animationCompleted) {
1590           return animate('leave', element, 'ng-leave', animationCompleted);
1591         },
1592
1593         move : function(element, animationCompleted) {
1594           return animate('move', element, 'ng-move', animationCompleted);
1595         },
1596
1597         beforeSetClass : function(element, add, remove, animationCompleted) {
1598           var className = suffixClasses(remove, '-remove') + ' ' +
1599                           suffixClasses(add, '-add');
1600           var cancellationMethod = animateBefore('setClass', element, className, function(fn) {
1601             /* when classes are removed from an element then the transition style
1602              * that is applied is the transition defined on the element without the
1603              * CSS class being there. This is how CSS3 functions outside of ngAnimate.
1604              * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */
1605             var klass = element.attr('class');
1606             element.removeClass(remove);
1607             element.addClass(add);
1608             var timings = fn();
1609             element.attr('class', klass);
1610             return timings;
1611           });
1612
1613           if(cancellationMethod) {
1614             afterReflow(element, function() {
1615               unblockTransitions(element, className);
1616               unblockKeyframeAnimations(element);
1617               animationCompleted();
1618             });
1619             return cancellationMethod;
1620           }
1621           clearCacheAfterReflow();
1622           animationCompleted();
1623         },
1624
1625         beforeAddClass : function(element, className, animationCompleted) {
1626           var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), function(fn) {
1627
1628             /* when a CSS class is added to an element then the transition style that
1629              * is applied is the transition defined on the element when the CSS class
1630              * is added at the time of the animation. This is how CSS3 functions
1631              * outside of ngAnimate. */
1632             element.addClass(className);
1633             var timings = fn();
1634             element.removeClass(className);
1635             return timings;
1636           });
1637
1638           if(cancellationMethod) {
1639             afterReflow(element, function() {
1640               unblockTransitions(element, className);
1641               unblockKeyframeAnimations(element);
1642               animationCompleted();
1643             });
1644             return cancellationMethod;
1645           }
1646           clearCacheAfterReflow();
1647           animationCompleted();
1648         },
1649
1650         setClass : function(element, add, remove, animationCompleted) {
1651           remove = suffixClasses(remove, '-remove');
1652           add = suffixClasses(add, '-add');
1653           var className = remove + ' ' + add;
1654           return animateAfter('setClass', element, className, animationCompleted);
1655         },
1656
1657         addClass : function(element, className, animationCompleted) {
1658           return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted);
1659         },
1660
1661         beforeRemoveClass : function(element, className, animationCompleted) {
1662           var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), function(fn) {
1663             /* when classes are removed from an element then the transition style
1664              * that is applied is the transition defined on the element without the
1665              * CSS class being there. This is how CSS3 functions outside of ngAnimate.
1666              * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */
1667             var klass = element.attr('class');
1668             element.removeClass(className);
1669             var timings = fn();
1670             element.attr('class', klass);
1671             return timings;
1672           });
1673
1674           if(cancellationMethod) {
1675             afterReflow(element, function() {
1676               unblockTransitions(element, className);
1677               unblockKeyframeAnimations(element);
1678               animationCompleted();
1679             });
1680             return cancellationMethod;
1681           }
1682           animationCompleted();
1683         },
1684
1685         removeClass : function(element, className, animationCompleted) {
1686           return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted);
1687         }
1688       };
1689
1690       function suffixClasses(classes, suffix) {
1691         var className = '';
1692         classes = angular.isArray(classes) ? classes : classes.split(/\s+/);
1693         forEach(classes, function(klass, i) {
1694           if(klass && klass.length > 0) {
1695             className += (i > 0 ? ' ' : '') + klass + suffix;
1696           }
1697         });
1698         return className;
1699       }
1700     }]);
1701   }]);
1702
1703
1704 })(window, window.angular);