Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / webapp / app / fusion / external / ebz / angular_js / angular-animate.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 /* jshint ignore:start */
9 var noop        = angular.noop;
10 var extend      = angular.extend;
11 var jqLite      = angular.element;
12 var forEach     = angular.forEach;
13 var isArray     = angular.isArray;
14 var isString    = angular.isString;
15 var isObject    = angular.isObject;
16 var isUndefined = angular.isUndefined;
17 var isDefined   = angular.isDefined;
18 var isFunction  = angular.isFunction;
19 var isElement   = angular.isElement;
20
21 var ELEMENT_NODE = 1;
22 var COMMENT_NODE = 8;
23
24 var NG_ANIMATE_CLASSNAME = 'ng-animate';
25 var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
26
27 var isPromiseLike = function(p) {
28   return p && p.then ? true : false;
29 }
30
31 function assertArg(arg, name, reason) {
32   if (!arg) {
33     throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
34   }
35   return arg;
36 }
37
38 function mergeClasses(a,b) {
39   if (!a && !b) return '';
40   if (!a) return b;
41   if (!b) return a;
42   if (isArray(a)) a = a.join(' ');
43   if (isArray(b)) b = b.join(' ');
44   return a + ' ' + b;
45 }
46
47 function packageStyles(options) {
48   var styles = {};
49   if (options && (options.to || options.from)) {
50     styles.to = options.to;
51     styles.from = options.from;
52   }
53   return styles;
54 }
55
56 function pendClasses(classes, fix, isPrefix) {
57   var className = '';
58   classes = isArray(classes)
59       ? classes
60       : classes && isString(classes) && classes.length
61           ? classes.split(/\s+/)
62           : [];
63   forEach(classes, function(klass, i) {
64     if (klass && klass.length > 0) {
65       className += (i > 0) ? ' ' : '';
66       className += isPrefix ? fix + klass
67                             : klass + fix;
68     }
69   });
70   return className;
71 }
72
73 function removeFromArray(arr, val) {
74   var index = arr.indexOf(val);
75   if (val >= 0) {
76     arr.splice(index, 1);
77   }
78 }
79
80 function stripCommentsFromElement(element) {
81   if (element instanceof jqLite) {
82     switch (element.length) {
83       case 0:
84         return [];
85         break;
86
87       case 1:
88         // there is no point of stripping anything if the element
89         // is the only element within the jqLite wrapper.
90         // (it's important that we retain the element instance.)
91         if (element[0].nodeType === ELEMENT_NODE) {
92           return element;
93         }
94         break;
95
96       default:
97         return jqLite(extractElementNode(element));
98         break;
99     }
100   }
101
102   if (element.nodeType === ELEMENT_NODE) {
103     return jqLite(element);
104   }
105 }
106
107 function extractElementNode(element) {
108   if (!element[0]) return element;
109   for (var i = 0; i < element.length; i++) {
110     var elm = element[i];
111     if (elm.nodeType == ELEMENT_NODE) {
112       return elm;
113     }
114   }
115 }
116
117 function $$addClass($$jqLite, element, className) {
118   forEach(element, function(elm) {
119     $$jqLite.addClass(elm, className);
120   });
121 }
122
123 function $$removeClass($$jqLite, element, className) {
124   forEach(element, function(elm) {
125     $$jqLite.removeClass(elm, className);
126   });
127 }
128
129 function applyAnimationClassesFactory($$jqLite) {
130   return function(element, options) {
131     if (options.addClass) {
132       $$addClass($$jqLite, element, options.addClass);
133       options.addClass = null;
134     }
135     if (options.removeClass) {
136       $$removeClass($$jqLite, element, options.removeClass);
137       options.removeClass = null;
138     }
139   }
140 }
141
142 function prepareAnimationOptions(options) {
143   options = options || {};
144   if (!options.$$prepared) {
145     var domOperation = options.domOperation || noop;
146     options.domOperation = function() {
147       options.$$domOperationFired = true;
148       domOperation();
149       domOperation = noop;
150     };
151     options.$$prepared = true;
152   }
153   return options;
154 }
155
156 function applyAnimationStyles(element, options) {
157   applyAnimationFromStyles(element, options);
158   applyAnimationToStyles(element, options);
159 }
160
161 function applyAnimationFromStyles(element, options) {
162   if (options.from) {
163     element.css(options.from);
164     options.from = null;
165   }
166 }
167
168 function applyAnimationToStyles(element, options) {
169   if (options.to) {
170     element.css(options.to);
171     options.to = null;
172   }
173 }
174
175 function mergeAnimationOptions(element, target, newOptions) {
176   var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
177   var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
178   var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
179
180   extend(target, newOptions);
181
182   if (classes.addClass) {
183     target.addClass = classes.addClass;
184   } else {
185     target.addClass = null;
186   }
187
188   if (classes.removeClass) {
189     target.removeClass = classes.removeClass;
190   } else {
191     target.removeClass = null;
192   }
193
194   return target;
195 }
196
197 function resolveElementClasses(existing, toAdd, toRemove) {
198   var ADD_CLASS = 1;
199   var REMOVE_CLASS = -1;
200
201   var flags = {};
202   existing = splitClassesToLookup(existing);
203
204   toAdd = splitClassesToLookup(toAdd);
205   forEach(toAdd, function(value, key) {
206     flags[key] = ADD_CLASS;
207   });
208
209   toRemove = splitClassesToLookup(toRemove);
210   forEach(toRemove, function(value, key) {
211     flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
212   });
213
214   var classes = {
215     addClass: '',
216     removeClass: ''
217   };
218
219   forEach(flags, function(val, klass) {
220     var prop, allow;
221     if (val === ADD_CLASS) {
222       prop = 'addClass';
223       allow = !existing[klass];
224     } else if (val === REMOVE_CLASS) {
225       prop = 'removeClass';
226       allow = existing[klass];
227     }
228     if (allow) {
229       if (classes[prop].length) {
230         classes[prop] += ' ';
231       }
232       classes[prop] += klass;
233     }
234   });
235
236   function splitClassesToLookup(classes) {
237     if (isString(classes)) {
238       classes = classes.split(' ');
239     }
240
241     var obj = {};
242     forEach(classes, function(klass) {
243       // sometimes the split leaves empty string values
244       // incase extra spaces were applied to the options
245       if (klass.length) {
246         obj[klass] = true;
247       }
248     });
249     return obj;
250   }
251
252   return classes;
253 }
254
255 function getDomNode(element) {
256   return (element instanceof angular.element) ? element[0] : element;
257 }
258
259 var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
260   var tickQueue = [];
261   var cancelFn;
262
263   function scheduler(tasks) {
264     // we make a copy since RAFScheduler mutates the state
265     // of the passed in array variable and this would be difficult
266     // to track down on the outside code
267     tickQueue.push([].concat(tasks));
268     nextTick();
269   }
270
271   /* waitUntilQuiet does two things:
272    * 1. It will run the FINAL `fn` value only when an uncancelled RAF has passed through
273    * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
274    *
275    * The motivation here is that animation code can request more time from the scheduler
276    * before the next wave runs. This allows for certain DOM properties such as classes to
277    * be resolved in time for the next animation to run.
278    */
279   scheduler.waitUntilQuiet = function(fn) {
280     if (cancelFn) cancelFn();
281
282     cancelFn = $$rAF(function() {
283       cancelFn = null;
284       fn();
285       nextTick();
286     });
287   };
288
289   return scheduler;
290
291   function nextTick() {
292     if (!tickQueue.length) return;
293
294     var updatedQueue = [];
295     for (var i = 0; i < tickQueue.length; i++) {
296       var innerQueue = tickQueue[i];
297       runNextTask(innerQueue);
298       if (innerQueue.length) {
299         updatedQueue.push(innerQueue);
300       }
301     }
302     tickQueue = updatedQueue;
303
304     if (!cancelFn) {
305       $$rAF(function() {
306         if (!cancelFn) nextTick();
307       });
308     }
309   }
310
311   function runNextTask(tasks) {
312     var nextTask = tasks.shift();
313     nextTask();
314   }
315 }];
316
317 var $$AnimateChildrenDirective = [function() {
318   return function(scope, element, attrs) {
319     var val = attrs.ngAnimateChildren;
320     if (angular.isString(val) && val.length === 0) { //empty attribute
321       element.data(NG_ANIMATE_CHILDREN_DATA, true);
322     } else {
323       attrs.$observe('ngAnimateChildren', function(value) {
324         value = value === 'on' || value === 'true';
325         element.data(NG_ANIMATE_CHILDREN_DATA, value);
326       });
327     }
328   };
329 }];
330
331 /**
332  * @ngdoc service
333  * @name $animateCss
334  * @kind object
335  *
336  * @description
337  * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
338  * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
339  * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
340  * directives to create more complex animations that can be purely driven using CSS code.
341  *
342  * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
343  * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
344  *
345  * ## Usage
346  * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
347  * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
348  * any automatic control over cancelling animations and/or preventing animations from being run on
349  * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
350  * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
351  * the CSS animation.
352  *
353  * The example below shows how we can create a folding animation on an element using `ng-if`:
354  *
355  * ```html
356  * <!-- notice the `fold-animation` CSS class -->
357  * <div ng-if="onOff" class="fold-animation">
358  *   This element will go BOOM
359  * </div>
360  * <button ng-click="onOff=true">Fold In</button>
361  * ```
362  *
363  * Now we create the **JavaScript animation** that will trigger the CSS transition:
364  *
365  * ```js
366  * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
367  *   return {
368  *     enter: function(element, doneFn) {
369  *       var height = element[0].offsetHeight;
370  *       return $animateCss(element, {
371  *         from: { height:'0px' },
372  *         to: { height:height + 'px' },
373  *         duration: 1 // one second
374  *       });
375  *     }
376  *   }
377  * }]);
378  * ```
379  *
380  * ## More Advanced Uses
381  *
382  * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
383  * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
384  *
385  * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
386  * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
387  * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
388  * to provide a working animation that will run in CSS.
389  *
390  * The example below showcases a more advanced version of the `.fold-animation` from the example above:
391  *
392  * ```js
393  * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
394  *   return {
395  *     enter: function(element, doneFn) {
396  *       var height = element[0].offsetHeight;
397  *       return $animateCss(element, {
398  *         addClass: 'red large-text pulse-twice',
399  *         easing: 'ease-out',
400  *         from: { height:'0px' },
401  *         to: { height:height + 'px' },
402  *         duration: 1 // one second
403  *       });
404  *     }
405  *   }
406  * }]);
407  * ```
408  *
409  * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
410  *
411  * ```css
412  * /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,
413  * the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/
414  * .red { background:red; }
415  * .large-text { font-size:20px; }
416  *
417  * /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/
418  * .pulse-twice {
419  *   animation: 0.5s pulse linear 2;
420  *   -webkit-animation: 0.5s pulse linear 2;
421  * }
422  *
423  * @keyframes pulse {
424  *   from { transform: scale(0.5); }
425  *   to { transform: scale(1.5); }
426  * }
427  *
428  * @-webkit-keyframes pulse {
429  *   from { -webkit-transform: scale(0.5); }
430  *   to { -webkit-transform: scale(1.5); }
431  * }
432  * ```
433  *
434  * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
435  *
436  * ## How the Options are handled
437  *
438  * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
439  * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
440  * styles using the `from` and `to` properties.
441  *
442  * ```js
443  * var animator = $animateCss(element, {
444  *   from: { background:'red' },
445  *   to: { background:'blue' }
446  * });
447  * animator.start();
448  * ```
449  *
450  * ```css
451  * .rotating-animation {
452  *   animation:0.5s rotate linear;
453  *   -webkit-animation:0.5s rotate linear;
454  * }
455  *
456  * @keyframes rotate {
457  *   from { transform: rotate(0deg); }
458  *   to { transform: rotate(360deg); }
459  * }
460  *
461  * @-webkit-keyframes rotate {
462  *   from { -webkit-transform: rotate(0deg); }
463  *   to { -webkit-transform: rotate(360deg); }
464  * }
465  * ```
466  *
467  * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
468  * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
469  * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
470  * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
471  * and spread across the transition and keyframe animation.
472  *
473  * ## What is returned
474  *
475  * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
476  * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
477  * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
478  *
479  * ```js
480  * var animator = $animateCss(element, { ... });
481  * ```
482  *
483  * Now what do the contents of our `animator` variable look like:
484  *
485  * ```js
486  * {
487  *   // starts the animation
488  *   start: Function,
489  *
490  *   // ends (aborts) the animation
491  *   end: Function
492  * }
493  * ```
494  *
495  * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
496  * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and stlyes may have been
497  * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
498  * and that changing them will not reconfigure the parameters of the animation.
499  *
500  * ### runner.done() vs runner.then()
501  * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
502  * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
503  * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
504  * unless you really need a digest to kick off afterwards.
505  *
506  * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
507  * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
508  * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
509  *
510  * @param {DOMElement} element the element that will be animated
511  * @param {object} options the animation-related options that will be applied during the animation
512  *
513  * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
514  * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
515  * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
516  * * `transition` - The raw CSS transition style that will be used (e.g. `1s linear all`).
517  * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
518  * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
519  * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
520  * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
521  * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
522  * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
523  * is provided then the animation will be skipped entirely.
524  * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
525  * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
526  * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
527  * CSS delay value.
528  * * `stagger` - A numeric time value representing the delay between successively animated elements
529  * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
530  * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
531  * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
532  * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occuring on the classes being added and removed.)
533  *
534  * @return {object} an object with start and end methods and details about the animation.
535  *
536  * * `start` - The method to start the animation. This will return a `Promise` when called.
537  * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
538  */
539
540 // Detect proper transitionend/animationend event names.
541 var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
542
543 // If unprefixed events are not supported but webkit-prefixed are, use the latter.
544 // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
545 // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
546 // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
547 // Register both events in case `window.onanimationend` is not supported because of that,
548 // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
549 // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
550 // therefore there is no reason to test anymore for other vendor prefixes:
551 // http://caniuse.com/#search=transition
552 if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {
553   CSS_PREFIX = '-webkit-';
554   TRANSITION_PROP = 'WebkitTransition';
555   TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
556 } else {
557   TRANSITION_PROP = 'transition';
558   TRANSITIONEND_EVENT = 'transitionend';
559 }
560
561 if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {
562   CSS_PREFIX = '-webkit-';
563   ANIMATION_PROP = 'WebkitAnimation';
564   ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
565 } else {
566   ANIMATION_PROP = 'animation';
567   ANIMATIONEND_EVENT = 'animationend';
568 }
569
570 var DURATION_KEY = 'Duration';
571 var PROPERTY_KEY = 'Property';
572 var DELAY_KEY = 'Delay';
573 var TIMING_KEY = 'TimingFunction';
574 var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
575 var ANIMATION_PLAYSTATE_KEY = 'PlayState';
576 var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
577 var CLOSING_TIME_BUFFER = 1.5;
578 var ONE_SECOND = 1000;
579 var BASE_TEN = 10;
580
581 var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
582
583 var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
584 var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
585
586 var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
587 var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
588
589 var DETECT_CSS_PROPERTIES = {
590   transitionDuration:      TRANSITION_DURATION_PROP,
591   transitionDelay:         TRANSITION_DELAY_PROP,
592   transitionProperty:      TRANSITION_PROP + PROPERTY_KEY,
593   animationDuration:       ANIMATION_DURATION_PROP,
594   animationDelay:          ANIMATION_DELAY_PROP,
595   animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
596 };
597
598 var DETECT_STAGGER_CSS_PROPERTIES = {
599   transitionDuration:      TRANSITION_DURATION_PROP,
600   transitionDelay:         TRANSITION_DELAY_PROP,
601   animationDuration:       ANIMATION_DURATION_PROP,
602   animationDelay:          ANIMATION_DELAY_PROP
603 };
604
605 function computeCssStyles($window, element, properties) {
606   var styles = Object.create(null);
607   var detectedStyles = $window.getComputedStyle(element) || {};
608   forEach(properties, function(formalStyleName, actualStyleName) {
609     var val = detectedStyles[formalStyleName];
610     if (val) {
611       var c = val.charAt(0);
612
613       // only numerical-based values have a negative sign or digit as the first value
614       if (c === '-' || c === '+' || c >= 0) {
615         val = parseMaxTime(val);
616       }
617
618       // by setting this to null in the event that the delay is not set or is set directly as 0
619       // then we can still allow for zegative values to be used later on and not mistake this
620       // value for being greater than any other negative value.
621       if (val === 0) {
622         val = null;
623       }
624       styles[actualStyleName] = val;
625     }
626   });
627
628   return styles;
629 }
630
631 function parseMaxTime(str) {
632   var maxValue = 0;
633   var values = str.split(/\s*,\s*/);
634   forEach(values, function(value) {
635     // it's always safe to consider only second values and omit `ms` values since
636     // getComputedStyle will always handle the conversion for us
637     if (value.charAt(value.length - 1) == 's') {
638       value = value.substring(0, value.length - 1);
639     }
640     value = parseFloat(value) || 0;
641     maxValue = maxValue ? Math.max(value, maxValue) : value;
642   });
643   return maxValue;
644 }
645
646 function truthyTimingValue(val) {
647   return val === 0 || val != null;
648 }
649
650 function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
651   var style = TRANSITION_PROP;
652   var value = duration + 's';
653   if (applyOnlyDuration) {
654     style += DURATION_KEY;
655   } else {
656     value += ' linear all';
657   }
658   return [style, value];
659 }
660
661 function getCssKeyframeDurationStyle(duration) {
662   return [ANIMATION_DURATION_PROP, duration + 's'];
663 }
664
665 function getCssDelayStyle(delay, isKeyframeAnimation) {
666   var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
667   return [prop, delay + 's'];
668 }
669
670 function blockTransitions(node, duration) {
671   // we use a negative delay value since it performs blocking
672   // yet it doesn't kill any existing transitions running on the
673   // same element which makes this safe for class-based animations
674   var value = duration ? '-' + duration + 's' : '';
675   applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
676   return [TRANSITION_DELAY_PROP, value];
677 }
678
679 function blockKeyframeAnimations(node, applyBlock) {
680   var value = applyBlock ? 'paused' : '';
681   var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
682   applyInlineStyle(node, [key, value]);
683   return [key, value];
684 }
685
686 function applyInlineStyle(node, styleTuple) {
687   var prop = styleTuple[0];
688   var value = styleTuple[1];
689   node.style[prop] = value;
690 }
691
692 function createLocalCacheLookup() {
693   var cache = Object.create(null);
694   return {
695     flush: function() {
696       cache = Object.create(null);
697     },
698
699     count: function(key) {
700       var entry = cache[key];
701       return entry ? entry.total : 0;
702     },
703
704     get: function(key) {
705       var entry = cache[key];
706       return entry && entry.value;
707     },
708
709     put: function(key, value) {
710       if (!cache[key]) {
711         cache[key] = { total: 1, value: value };
712       } else {
713         cache[key].total++;
714       }
715     }
716   };
717 }
718
719 var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
720   var gcsLookup = createLocalCacheLookup();
721   var gcsStaggerLookup = createLocalCacheLookup();
722
723   this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
724                '$document', '$sniffer', '$$rAFScheduler',
725        function($window,   $$jqLite,   $$AnimateRunner,   $timeout,
726                 $document,   $sniffer,   $$rAFScheduler) {
727
728     var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
729
730     var parentCounter = 0;
731     function gcsHashFn(node, extraClasses) {
732       var KEY = "$$ngAnimateParentKey";
733       var parentNode = node.parentNode;
734       var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
735       return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
736     }
737
738     function computeCachedCssStyles(node, className, cacheKey, properties) {
739       var timings = gcsLookup.get(cacheKey);
740
741       if (!timings) {
742         timings = computeCssStyles($window, node, properties);
743         if (timings.animationIterationCount === 'infinite') {
744           timings.animationIterationCount = 1;
745         }
746       }
747
748       // we keep putting this in multiple times even though the value and the cacheKey are the same
749       // because we're keeping an interal tally of how many duplicate animations are detected.
750       gcsLookup.put(cacheKey, timings);
751       return timings;
752     }
753
754     function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
755       var stagger;
756
757       // if we have one or more existing matches of matching elements
758       // containing the same parent + CSS styles (which is how cacheKey works)
759       // then staggering is possible
760       if (gcsLookup.count(cacheKey) > 0) {
761         stagger = gcsStaggerLookup.get(cacheKey);
762
763         if (!stagger) {
764           var staggerClassName = pendClasses(className, '-stagger');
765
766           $$jqLite.addClass(node, staggerClassName);
767
768           stagger = computeCssStyles($window, node, properties);
769
770           // force the conversion of a null value to zero incase not set
771           stagger.animationDuration = Math.max(stagger.animationDuration, 0);
772           stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
773
774           $$jqLite.removeClass(node, staggerClassName);
775
776           gcsStaggerLookup.put(cacheKey, stagger);
777         }
778       }
779
780       return stagger || {};
781     }
782
783     var bod = getDomNode($document).body;
784     var rafWaitQueue = [];
785     function waitUntilQuiet(callback) {
786       rafWaitQueue.push(callback);
787       $$rAFScheduler.waitUntilQuiet(function() {
788         gcsLookup.flush();
789         gcsStaggerLookup.flush();
790
791         //the line below will force the browser to perform a repaint so
792         //that all the animated elements within the animation frame will
793         //be properly updated and drawn on screen. This is required to
794         //ensure that the preparation animation is properly flushed so that
795         //the active state picks up from there. DO NOT REMOVE THIS LINE.
796         //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
797         //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
798         //WILL TAKE YEARS AWAY FROM YOUR LIFE.
799         var width = bod.offsetWidth + 1;
800
801         // we use a for loop to ensure that if the queue is changed
802         // during this looping then it will consider new requests
803         for (var i = 0; i < rafWaitQueue.length; i++) {
804           rafWaitQueue[i](width);
805         }
806         rafWaitQueue.length = 0;
807       });
808     }
809
810     return init;
811
812     function computeTimings(node, className, cacheKey) {
813       var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
814       var aD = timings.animationDelay;
815       var tD = timings.transitionDelay;
816       timings.maxDelay = aD && tD
817           ? Math.max(aD, tD)
818           : (aD || tD);
819       timings.maxDuration = Math.max(
820           timings.animationDuration * timings.animationIterationCount,
821           timings.transitionDuration);
822
823       return timings;
824     }
825
826     function init(element, options) {
827       var node = getDomNode(element);
828       if (!node || !node.parentNode) {
829         return closeAndReturnNoopAnimator();
830       }
831
832       options = prepareAnimationOptions(options);
833
834       var temporaryStyles = [];
835       var classes = element.attr('class');
836       var styles = packageStyles(options);
837       var animationClosed;
838       var animationPaused;
839       var animationCompleted;
840       var runner;
841       var runnerHost;
842       var maxDelay;
843       var maxDelayTime;
844       var maxDuration;
845       var maxDurationTime;
846
847       if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
848         return closeAndReturnNoopAnimator();
849       }
850
851       var method = options.event && isArray(options.event)
852             ? options.event.join(' ')
853             : options.event;
854
855       var isStructural = method && options.structural;
856       var structuralClassName = '';
857       var addRemoveClassName = '';
858
859       if (isStructural) {
860         structuralClassName = pendClasses(method, 'ng-', true);
861       } else if (method) {
862         structuralClassName = method;
863       }
864
865       if (options.addClass) {
866         addRemoveClassName += pendClasses(options.addClass, '-add');
867       }
868
869       if (options.removeClass) {
870         if (addRemoveClassName.length) {
871           addRemoveClassName += ' ';
872         }
873         addRemoveClassName += pendClasses(options.removeClass, '-remove');
874       }
875
876       // there may be a situation where a structural animation is combined together
877       // with CSS classes that need to resolve before the animation is computed.
878       // However this means that there is no explicit CSS code to block the animation
879       // from happening (by setting 0s none in the class name). If this is the case
880       // we need to apply the classes before the first rAF so we know to continue if
881       // there actually is a detected transition or keyframe animation
882       if (options.applyClassesEarly && addRemoveClassName.length) {
883         applyAnimationClasses(element, options);
884         addRemoveClassName = '';
885       }
886
887       var setupClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
888       var fullClassName = classes + ' ' + setupClasses;
889       var activeClasses = pendClasses(setupClasses, '-active');
890       var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
891       var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
892
893       // there is no way we can trigger an animation if no styles and
894       // no classes are being applied which would then trigger a transition,
895       // unless there a is raw keyframe value that is applied to the element.
896       if (!containsKeyframeAnimation
897            && !hasToStyles
898            && !setupClasses) {
899         return closeAndReturnNoopAnimator();
900       }
901
902       var cacheKey, stagger;
903       if (options.stagger > 0) {
904         var staggerVal = parseFloat(options.stagger);
905         stagger = {
906           transitionDelay: staggerVal,
907           animationDelay: staggerVal,
908           transitionDuration: 0,
909           animationDuration: 0
910         };
911       } else {
912         cacheKey = gcsHashFn(node, fullClassName);
913         stagger = computeCachedCssStaggerStyles(node, setupClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
914       }
915
916       $$jqLite.addClass(element, setupClasses);
917
918       var applyOnlyDuration;
919
920       if (options.transitionStyle) {
921         var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
922         applyInlineStyle(node, transitionStyle);
923         temporaryStyles.push(transitionStyle);
924       }
925
926       if (options.duration >= 0) {
927         applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
928         var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
929
930         // we set the duration so that it will be picked up by getComputedStyle later
931         applyInlineStyle(node, durationStyle);
932         temporaryStyles.push(durationStyle);
933       }
934
935       if (options.keyframeStyle) {
936         var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
937         applyInlineStyle(node, keyframeStyle);
938         temporaryStyles.push(keyframeStyle);
939       }
940
941       var itemIndex = stagger
942           ? options.staggerIndex >= 0
943               ? options.staggerIndex
944               : gcsLookup.count(cacheKey)
945           : 0;
946
947       var isFirst = itemIndex === 0;
948
949       // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
950       // without causing any combination of transitions to kick in. By adding a negative delay value
951       // it forces the setup class' transition to end immediately. We later then remove the negative
952       // transition delay to allow for the transition to naturally do it's thing. The beauty here is
953       // that if there is no transition defined then nothing will happen and this will also allow
954       // other transitions to be stacked on top of each other without any chopping them out.
955       if (isFirst) {
956         blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
957       }
958
959       var timings = computeTimings(node, fullClassName, cacheKey);
960       var relativeDelay = timings.maxDelay;
961       maxDelay = Math.max(relativeDelay, 0);
962       maxDuration = timings.maxDuration;
963
964       var flags = {};
965       flags.hasTransitions          = timings.transitionDuration > 0;
966       flags.hasAnimations           = timings.animationDuration > 0;
967       flags.hasTransitionAll        = flags.hasTransitions && timings.transitionProperty == 'all';
968       flags.applyTransitionDuration = hasToStyles && (
969                                         (flags.hasTransitions && !flags.hasTransitionAll)
970                                          || (flags.hasAnimations && !flags.hasTransitions));
971       flags.applyAnimationDuration  = options.duration && flags.hasAnimations;
972       flags.applyTransitionDelay    = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
973       flags.applyAnimationDelay     = truthyTimingValue(options.delay) && flags.hasAnimations;
974       flags.recalculateTimingStyles = addRemoveClassName.length > 0;
975
976       if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
977         maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
978
979         if (flags.applyTransitionDuration) {
980           flags.hasTransitions = true;
981           timings.transitionDuration = maxDuration;
982           applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
983           temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
984         }
985
986         if (flags.applyAnimationDuration) {
987           flags.hasAnimations = true;
988           timings.animationDuration = maxDuration;
989           temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
990         }
991       }
992
993       if (maxDuration === 0 && !flags.recalculateTimingStyles) {
994         return closeAndReturnNoopAnimator();
995       }
996
997       // we need to recalculate the delay value since we used a pre-emptive negative
998       // delay value and the delay value is required for the final event checking. This
999       // property will ensure that this will happen after the RAF phase has passed.
1000       if (options.duration == null && timings.transitionDuration > 0) {
1001         flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
1002       }
1003
1004       maxDelayTime = maxDelay * ONE_SECOND;
1005       maxDurationTime = maxDuration * ONE_SECOND;
1006       if (!options.skipBlocking) {
1007         flags.blockTransition = timings.transitionDuration > 0;
1008         flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
1009                                        stagger.animationDelay > 0 &&
1010                                        stagger.animationDuration === 0;
1011       }
1012
1013       applyAnimationFromStyles(element, options);
1014       if (!flags.blockTransition) {
1015         blockTransitions(node, false);
1016       }
1017
1018       applyBlocking(maxDuration);
1019
1020       // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
1021       return {
1022         $$willAnimate: true,
1023         end: endFn,
1024         start: function() {
1025           if (animationClosed) return;
1026
1027           runnerHost = {
1028             end: endFn,
1029             cancel: cancelFn,
1030             resume: null, //this will be set during the start() phase
1031             pause: null
1032           };
1033
1034           runner = new $$AnimateRunner(runnerHost);
1035
1036           waitUntilQuiet(start);
1037
1038           // we don't have access to pause/resume the animation
1039           // since it hasn't run yet. AnimateRunner will therefore
1040           // set noop functions for resume and pause and they will
1041           // later be overridden once the animation is triggered
1042           return runner;
1043         }
1044       };
1045
1046       function endFn() {
1047         close();
1048       }
1049
1050       function cancelFn() {
1051         close(true);
1052       }
1053
1054       function close(rejected) { // jshint ignore:line
1055         // if the promise has been called already then we shouldn't close
1056         // the animation again
1057         if (animationClosed || (animationCompleted && animationPaused)) return;
1058         animationClosed = true;
1059         animationPaused = false;
1060
1061         $$jqLite.removeClass(element, setupClasses);
1062         $$jqLite.removeClass(element, activeClasses);
1063
1064         blockKeyframeAnimations(node, false);
1065         blockTransitions(node, false);
1066
1067         forEach(temporaryStyles, function(entry) {
1068           // There is only one way to remove inline style properties entirely from elements.
1069           // By using `removeProperty` this works, but we need to convert camel-cased CSS
1070           // styles down to hyphenated values.
1071           node.style[entry[0]] = '';
1072         });
1073
1074         applyAnimationClasses(element, options);
1075         applyAnimationStyles(element, options);
1076
1077         // the reason why we have this option is to allow a synchronous closing callback
1078         // that is fired as SOON as the animation ends (when the CSS is removed) or if
1079         // the animation never takes off at all. A good example is a leave animation since
1080         // the element must be removed just after the animation is over or else the element
1081         // will appear on screen for one animation frame causing an overbearing flicker.
1082         if (options.onDone) {
1083           options.onDone();
1084         }
1085
1086         // if the preparation function fails then the promise is not setup
1087         if (runner) {
1088           runner.complete(!rejected);
1089         }
1090       }
1091
1092       function applyBlocking(duration) {
1093         if (flags.blockTransition) {
1094           blockTransitions(node, duration);
1095         }
1096
1097         if (flags.blockKeyframeAnimation) {
1098           blockKeyframeAnimations(node, !!duration);
1099         }
1100       }
1101
1102       function closeAndReturnNoopAnimator() {
1103         runner = new $$AnimateRunner({
1104           end: endFn,
1105           cancel: cancelFn
1106         });
1107
1108         close();
1109
1110         return {
1111           $$willAnimate: false,
1112           start: function() {
1113             return runner;
1114           },
1115           end: endFn
1116         };
1117       }
1118
1119       function start() {
1120         if (animationClosed) return;
1121         if (!node.parentNode) {
1122           close();
1123           return;
1124         }
1125
1126         var startTime, events = [];
1127
1128         // even though we only pause keyframe animations here the pause flag
1129         // will still happen when transitions are used. Only the transition will
1130         // not be paused since that is not possible. If the animation ends when
1131         // paused then it will not complete until unpaused or cancelled.
1132         var playPause = function(playAnimation) {
1133           if (!animationCompleted) {
1134             animationPaused = !playAnimation;
1135             if (timings.animationDuration) {
1136               var value = blockKeyframeAnimations(node, animationPaused);
1137               animationPaused
1138                   ? temporaryStyles.push(value)
1139                   : removeFromArray(temporaryStyles, value);
1140             }
1141           } else if (animationPaused && playAnimation) {
1142             animationPaused = false;
1143             close();
1144           }
1145         };
1146
1147         // checking the stagger duration prevents an accidently cascade of the CSS delay style
1148         // being inherited from the parent. If the transition duration is zero then we can safely
1149         // rely that the delay value is an intential stagger delay style.
1150         var maxStagger = itemIndex > 0
1151                          && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
1152                             (timings.animationDuration && stagger.animationDuration === 0))
1153                          && Math.max(stagger.animationDelay, stagger.transitionDelay);
1154         if (maxStagger) {
1155           $timeout(triggerAnimationStart,
1156                    Math.floor(maxStagger * itemIndex * ONE_SECOND),
1157                    false);
1158         } else {
1159           triggerAnimationStart();
1160         }
1161
1162         // this will decorate the existing promise runner with pause/resume methods
1163         runnerHost.resume = function() {
1164           playPause(true);
1165         };
1166
1167         runnerHost.pause = function() {
1168           playPause(false);
1169         };
1170
1171         function triggerAnimationStart() {
1172           // just incase a stagger animation kicks in when the animation
1173           // itself was cancelled entirely
1174           if (animationClosed) return;
1175
1176           applyBlocking(false);
1177
1178           forEach(temporaryStyles, function(entry) {
1179             var key = entry[0];
1180             var value = entry[1];
1181             node.style[key] = value;
1182           });
1183
1184           applyAnimationClasses(element, options);
1185           $$jqLite.addClass(element, activeClasses);
1186
1187           if (flags.recalculateTimingStyles) {
1188             fullClassName = node.className + ' ' + setupClasses;
1189             cacheKey = gcsHashFn(node, fullClassName);
1190
1191             timings = computeTimings(node, fullClassName, cacheKey);
1192             relativeDelay = timings.maxDelay;
1193             maxDelay = Math.max(relativeDelay, 0);
1194             maxDuration = timings.maxDuration;
1195
1196             if (maxDuration === 0) {
1197               close();
1198               return;
1199             }
1200
1201             flags.hasTransitions = timings.transitionDuration > 0;
1202             flags.hasAnimations = timings.animationDuration > 0;
1203           }
1204
1205           if (flags.applyTransitionDelay || flags.applyAnimationDelay) {
1206             relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
1207                   ? parseFloat(options.delay)
1208                   : relativeDelay;
1209
1210             maxDelay = Math.max(relativeDelay, 0);
1211
1212             var delayStyle;
1213             if (flags.applyTransitionDelay) {
1214               timings.transitionDelay = relativeDelay;
1215               delayStyle = getCssDelayStyle(relativeDelay);
1216               temporaryStyles.push(delayStyle);
1217               node.style[delayStyle[0]] = delayStyle[1];
1218             }
1219
1220             if (flags.applyAnimationDelay) {
1221               timings.animationDelay = relativeDelay;
1222               delayStyle = getCssDelayStyle(relativeDelay, true);
1223               temporaryStyles.push(delayStyle);
1224               node.style[delayStyle[0]] = delayStyle[1];
1225             }
1226           }
1227
1228           maxDelayTime = maxDelay * ONE_SECOND;
1229           maxDurationTime = maxDuration * ONE_SECOND;
1230
1231           if (options.easing) {
1232             var easeProp, easeVal = options.easing;
1233             if (flags.hasTransitions) {
1234               easeProp = TRANSITION_PROP + TIMING_KEY;
1235               temporaryStyles.push([easeProp, easeVal]);
1236               node.style[easeProp] = easeVal;
1237             }
1238             if (flags.hasAnimations) {
1239               easeProp = ANIMATION_PROP + TIMING_KEY;
1240               temporaryStyles.push([easeProp, easeVal]);
1241               node.style[easeProp] = easeVal;
1242             }
1243           }
1244
1245           if (timings.transitionDuration) {
1246             events.push(TRANSITIONEND_EVENT);
1247           }
1248
1249           if (timings.animationDuration) {
1250             events.push(ANIMATIONEND_EVENT);
1251           }
1252
1253           startTime = Date.now();
1254           element.on(events.join(' '), onAnimationProgress);
1255           $timeout(onAnimationExpired, maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime);
1256
1257           applyAnimationToStyles(element, options);
1258         }
1259
1260         function onAnimationExpired() {
1261           // although an expired animation is a failed animation, getting to
1262           // this outcome is very easy if the CSS code screws up. Therefore we
1263           // should still continue normally as if the animation completed correctly.
1264           close();
1265         }
1266
1267         function onAnimationProgress(event) {
1268           event.stopPropagation();
1269           var ev = event.originalEvent || event;
1270           var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();
1271
1272           /* Firefox (or possibly just Gecko) likes to not round values up
1273            * when a ms measurement is used for the animation */
1274           var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
1275
1276           /* $manualTimeStamp is a mocked timeStamp value which is set
1277            * within browserTrigger(). This is only here so that tests can
1278            * mock animations properly. Real events fallback to event.timeStamp,
1279            * or, if they don't, then a timeStamp is automatically created for them.
1280            * We're checking to see if the timeStamp surpasses the expected delay,
1281            * but we're using elapsedTime instead of the timeStamp on the 2nd
1282            * pre-condition since animations sometimes close off early */
1283           if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
1284             // we set this flag to ensure that if the transition is paused then, when resumed,
1285             // the animation will automatically close itself since transitions cannot be paused.
1286             animationCompleted = true;
1287             close();
1288           }
1289         }
1290       }
1291     }
1292   }];
1293 }];
1294
1295 var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
1296   $$animationProvider.drivers.push('$$animateCssDriver');
1297
1298   var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
1299   var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
1300
1301   var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
1302   var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
1303
1304   this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$document', '$sniffer',
1305        function($animateCss,   $rootScope,   $$AnimateRunner,   $rootElement,   $document,   $sniffer) {
1306
1307     // only browsers that support these properties can render animations
1308     if (!$sniffer.animations && !$sniffer.transitions) return noop;
1309
1310     var bodyNode = getDomNode($document).body;
1311     var rootNode = getDomNode($rootElement);
1312
1313     var rootBodyElement = jqLite(bodyNode.parentNode === rootNode ? bodyNode : rootNode);
1314
1315     return function initDriverFn(animationDetails) {
1316       return animationDetails.from && animationDetails.to
1317           ? prepareFromToAnchorAnimation(animationDetails.from,
1318                                          animationDetails.to,
1319                                          animationDetails.classes,
1320                                          animationDetails.anchors)
1321           : prepareRegularAnimation(animationDetails);
1322     };
1323
1324     function filterCssClasses(classes) {
1325       //remove all the `ng-` stuff
1326       return classes.replace(/\bng-\S+\b/g, '');
1327     }
1328
1329     function getUniqueValues(a, b) {
1330       if (isString(a)) a = a.split(' ');
1331       if (isString(b)) b = b.split(' ');
1332       return a.filter(function(val) {
1333         return b.indexOf(val) === -1;
1334       }).join(' ');
1335     }
1336
1337     function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
1338       var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
1339       var startingClasses = filterCssClasses(getClassVal(clone));
1340
1341       outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
1342       inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
1343
1344       clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
1345
1346       rootBodyElement.append(clone);
1347
1348       var animatorIn, animatorOut = prepareOutAnimation();
1349
1350       // the user may not end up using the `out` animation and
1351       // only making use of the `in` animation or vice-versa.
1352       // In either case we should allow this and not assume the
1353       // animation is over unless both animations are not used.
1354       if (!animatorOut) {
1355         animatorIn = prepareInAnimation();
1356         if (!animatorIn) {
1357           return end();
1358         }
1359       }
1360
1361       var startingAnimator = animatorOut || animatorIn;
1362
1363       return {
1364         start: function() {
1365           var runner;
1366
1367           var currentAnimation = startingAnimator.start();
1368           currentAnimation.done(function() {
1369             currentAnimation = null;
1370             if (!animatorIn) {
1371               animatorIn = prepareInAnimation();
1372               if (animatorIn) {
1373                 currentAnimation = animatorIn.start();
1374                 currentAnimation.done(function() {
1375                   currentAnimation = null;
1376                   end();
1377                   runner.complete();
1378                 });
1379                 return currentAnimation;
1380               }
1381             }
1382             // in the event that there is no `in` animation
1383             end();
1384             runner.complete();
1385           });
1386
1387           runner = new $$AnimateRunner({
1388             end: endFn,
1389             cancel: endFn
1390           });
1391
1392           return runner;
1393
1394           function endFn() {
1395             if (currentAnimation) {
1396               currentAnimation.end();
1397             }
1398           }
1399         }
1400       };
1401
1402       function calculateAnchorStyles(anchor) {
1403         var styles = {};
1404
1405         var coords = getDomNode(anchor).getBoundingClientRect();
1406
1407         // we iterate directly since safari messes up and doesn't return
1408         // all the keys for the coods object when iterated
1409         forEach(['width','height','top','left'], function(key) {
1410           var value = coords[key];
1411           switch (key) {
1412             case 'top':
1413               value += bodyNode.scrollTop;
1414               break;
1415             case 'left':
1416               value += bodyNode.scrollLeft;
1417               break;
1418           }
1419           styles[key] = Math.floor(value) + 'px';
1420         });
1421         return styles;
1422       }
1423
1424       function prepareOutAnimation() {
1425         var animator = $animateCss(clone, {
1426           addClass: NG_OUT_ANCHOR_CLASS_NAME,
1427           delay: true,
1428           from: calculateAnchorStyles(outAnchor)
1429         });
1430
1431         // read the comment within `prepareRegularAnimation` to understand
1432         // why this check is necessary
1433         return animator.$$willAnimate ? animator : null;
1434       }
1435
1436       function getClassVal(element) {
1437         return element.attr('class') || '';
1438       }
1439
1440       function prepareInAnimation() {
1441         var endingClasses = filterCssClasses(getClassVal(inAnchor));
1442         var toAdd = getUniqueValues(endingClasses, startingClasses);
1443         var toRemove = getUniqueValues(startingClasses, endingClasses);
1444
1445         var animator = $animateCss(clone, {
1446           to: calculateAnchorStyles(inAnchor),
1447           addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
1448           removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
1449           delay: true
1450         });
1451
1452         // read the comment within `prepareRegularAnimation` to understand
1453         // why this check is necessary
1454         return animator.$$willAnimate ? animator : null;
1455       }
1456
1457       function end() {
1458         clone.remove();
1459         outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
1460         inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
1461       }
1462     }
1463
1464     function prepareFromToAnchorAnimation(from, to, classes, anchors) {
1465       var fromAnimation = prepareRegularAnimation(from);
1466       var toAnimation = prepareRegularAnimation(to);
1467
1468       var anchorAnimations = [];
1469       forEach(anchors, function(anchor) {
1470         var outElement = anchor['out'];
1471         var inElement = anchor['in'];
1472         var animator = prepareAnchoredAnimation(classes, outElement, inElement);
1473         if (animator) {
1474           anchorAnimations.push(animator);
1475         }
1476       });
1477
1478       // no point in doing anything when there are no elements to animate
1479       if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
1480
1481       return {
1482         start: function() {
1483           var animationRunners = [];
1484
1485           if (fromAnimation) {
1486             animationRunners.push(fromAnimation.start());
1487           }
1488
1489           if (toAnimation) {
1490             animationRunners.push(toAnimation.start());
1491           }
1492
1493           forEach(anchorAnimations, function(animation) {
1494             animationRunners.push(animation.start());
1495           });
1496
1497           var runner = new $$AnimateRunner({
1498             end: endFn,
1499             cancel: endFn // CSS-driven animations cannot be cancelled, only ended
1500           });
1501
1502           $$AnimateRunner.all(animationRunners, function(status) {
1503             runner.complete(status);
1504           });
1505
1506           return runner;
1507
1508           function endFn() {
1509             forEach(animationRunners, function(runner) {
1510               runner.end();
1511             });
1512           }
1513         }
1514       };
1515     }
1516
1517     function prepareRegularAnimation(animationDetails) {
1518       var element = animationDetails.element;
1519       var options = animationDetails.options || {};
1520
1521       if (animationDetails.structural) {
1522         // structural animations ensure that the CSS classes are always applied
1523         // before the detection starts.
1524         options.structural = options.applyClassesEarly = true;
1525
1526         // we special case the leave animation since we want to ensure that
1527         // the element is removed as soon as the animation is over. Otherwise
1528         // a flicker might appear or the element may not be removed at all
1529         options.event = animationDetails.event;
1530         if (options.event === 'leave') {
1531           options.onDone = options.domOperation;
1532         }
1533       } else {
1534         options.event = null;
1535       }
1536
1537       var animator = $animateCss(element, options);
1538
1539       // the driver lookup code inside of $$animation attempts to spawn a
1540       // driver one by one until a driver returns a.$$willAnimate animator object.
1541       // $animateCss will always return an object, however, it will pass in
1542       // a flag as a hint as to whether an animation was detected or not
1543       return animator.$$willAnimate ? animator : null;
1544     }
1545   }];
1546 }];
1547
1548 // TODO(matsko): use caching here to speed things up for detection
1549 // TODO(matsko): add documentation
1550 //  by the time...
1551
1552 var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
1553   this.$get = ['$injector', '$$AnimateRunner', '$$rAFMutex', '$$jqLite',
1554        function($injector,   $$AnimateRunner,   $$rAFMutex,   $$jqLite) {
1555
1556     var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
1557          // $animateJs(element, 'enter');
1558     return function(element, event, classes, options) {
1559       // the `classes` argument is optional and if it is not used
1560       // then the classes will be resolved from the element's className
1561       // property as well as options.addClass/options.removeClass.
1562       if (arguments.length === 3 && isObject(classes)) {
1563         options = classes;
1564         classes = null;
1565       }
1566
1567       options = prepareAnimationOptions(options);
1568       if (!classes) {
1569         classes = element.attr('class') || '';
1570         if (options.addClass) {
1571           classes += ' ' + options.addClass;
1572         }
1573         if (options.removeClass) {
1574           classes += ' ' + options.removeClass;
1575         }
1576       }
1577
1578       var classesToAdd = options.addClass;
1579       var classesToRemove = options.removeClass;
1580
1581       // the lookupAnimations function returns a series of animation objects that are
1582       // matched up with one or more of the CSS classes. These animation objects are
1583       // defined via the module.animation factory function. If nothing is detected then
1584       // we don't return anything which then makes $animation query the next driver.
1585       var animations = lookupAnimations(classes);
1586       var before, after;
1587       if (animations.length) {
1588         var afterFn, beforeFn;
1589         if (event == 'leave') {
1590           beforeFn = 'leave';
1591           afterFn = 'afterLeave'; // TODO(matsko): get rid of this
1592         } else {
1593           beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
1594           afterFn = event;
1595         }
1596
1597         if (event !== 'enter' && event !== 'move') {
1598           before = packageAnimations(element, event, options, animations, beforeFn);
1599         }
1600         after  = packageAnimations(element, event, options, animations, afterFn);
1601       }
1602
1603       // no matching animations
1604       if (!before && !after) return;
1605
1606       function applyOptions() {
1607         options.domOperation();
1608         applyAnimationClasses(element, options);
1609       }
1610
1611       return {
1612         start: function() {
1613           var closeActiveAnimations;
1614           var chain = [];
1615
1616           if (before) {
1617             chain.push(function(fn) {
1618               closeActiveAnimations = before(fn);
1619             });
1620           }
1621
1622           if (chain.length) {
1623             chain.push(function(fn) {
1624               applyOptions();
1625               fn(true);
1626             });
1627           } else {
1628             applyOptions();
1629           }
1630
1631           if (after) {
1632             chain.push(function(fn) {
1633               closeActiveAnimations = after(fn);
1634             });
1635           }
1636
1637           var animationClosed = false;
1638           var runner = new $$AnimateRunner({
1639             end: function() {
1640               endAnimations();
1641             },
1642             cancel: function() {
1643               endAnimations(true);
1644             }
1645           });
1646
1647           $$AnimateRunner.chain(chain, onComplete);
1648           return runner;
1649
1650           function onComplete(success) {
1651             animationClosed = true;
1652             applyOptions();
1653             applyAnimationStyles(element, options);
1654             runner.complete(success);
1655           }
1656
1657           function endAnimations(cancelled) {
1658             if (!animationClosed) {
1659               (closeActiveAnimations || noop)(cancelled);
1660               onComplete(cancelled);
1661             }
1662           }
1663         }
1664       };
1665
1666       function executeAnimationFn(fn, element, event, options, onDone) {
1667         var args;
1668         switch (event) {
1669           case 'animate':
1670             args = [element, options.from, options.to, onDone];
1671             break;
1672
1673           case 'setClass':
1674             args = [element, classesToAdd, classesToRemove, onDone];
1675             break;
1676
1677           case 'addClass':
1678             args = [element, classesToAdd, onDone];
1679             break;
1680
1681           case 'removeClass':
1682             args = [element, classesToRemove, onDone];
1683             break;
1684
1685           default:
1686             args = [element, onDone];
1687             break;
1688         }
1689
1690         args.push(options);
1691
1692         var value = fn.apply(fn, args);
1693         if (value) {
1694           if (isFunction(value.start)) {
1695             value = value.start();
1696           }
1697
1698           if (value instanceof $$AnimateRunner) {
1699             value.done(onDone);
1700           } else if (isFunction(value)) {
1701             // optional onEnd / onCancel callback
1702             return value;
1703           }
1704         }
1705
1706         return noop;
1707       }
1708
1709       function groupEventedAnimations(element, event, options, animations, fnName) {
1710         var operations = [];
1711         forEach(animations, function(ani) {
1712           var animation = ani[fnName];
1713           if (!animation) return;
1714
1715           // note that all of these animations will run in parallel
1716           operations.push(function() {
1717             var runner;
1718             var endProgressCb;
1719
1720             var resolved = false;
1721             var onAnimationComplete = function(rejected) {
1722               if (!resolved) {
1723                 resolved = true;
1724                 (endProgressCb || noop)(rejected);
1725                 runner.complete(!rejected);
1726               }
1727             };
1728
1729             runner = new $$AnimateRunner({
1730               end: function() {
1731                 onAnimationComplete();
1732               },
1733               cancel: function() {
1734                 onAnimationComplete(true);
1735               }
1736             });
1737
1738             endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
1739               var cancelled = result === false;
1740               onAnimationComplete(cancelled);
1741             });
1742
1743             return runner;
1744           });
1745         });
1746
1747         return operations;
1748       }
1749
1750       function packageAnimations(element, event, options, animations, fnName) {
1751         var operations = groupEventedAnimations(element, event, options, animations, fnName);
1752         if (operations.length === 0) {
1753           var a,b;
1754           if (fnName === 'beforeSetClass') {
1755             a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
1756             b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
1757           } else if (fnName === 'setClass') {
1758             a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
1759             b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
1760           }
1761
1762           if (a) {
1763             operations = operations.concat(a);
1764           }
1765           if (b) {
1766             operations = operations.concat(b);
1767           }
1768         }
1769
1770         if (operations.length === 0) return;
1771
1772         // TODO(matsko): add documentation
1773         return function startAnimation(callback) {
1774           var runners = [];
1775           if (operations.length) {
1776             forEach(operations, function(animateFn) {
1777               runners.push(animateFn());
1778             });
1779           }
1780
1781           runners.length ? $$AnimateRunner.all(runners, callback) : callback();
1782
1783           return function endFn(reject) {
1784             forEach(runners, function(runner) {
1785               reject ? runner.cancel() : runner.end();
1786             });
1787           };
1788         };
1789       }
1790     };
1791
1792     function lookupAnimations(classes) {
1793       classes = isArray(classes) ? classes : classes.split(' ');
1794       var matches = [], flagMap = {};
1795       for (var i=0; i < classes.length; i++) {
1796         var klass = classes[i],
1797             animationFactory = $animateProvider.$$registeredAnimations[klass];
1798         if (animationFactory && !flagMap[klass]) {
1799           matches.push($injector.get(animationFactory));
1800           flagMap[klass] = true;
1801         }
1802       }
1803       return matches;
1804     }
1805   }];
1806 }];
1807
1808 var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
1809   $$animationProvider.drivers.push('$$animateJsDriver');
1810   this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
1811     return function initDriverFn(animationDetails) {
1812       if (animationDetails.from && animationDetails.to) {
1813         var fromAnimation = prepareAnimation(animationDetails.from);
1814         var toAnimation = prepareAnimation(animationDetails.to);
1815         if (!fromAnimation && !toAnimation) return;
1816
1817         return {
1818           start: function() {
1819             var animationRunners = [];
1820
1821             if (fromAnimation) {
1822               animationRunners.push(fromAnimation.start());
1823             }
1824
1825             if (toAnimation) {
1826               animationRunners.push(toAnimation.start());
1827             }
1828
1829             $$AnimateRunner.all(animationRunners, done);
1830
1831             var runner = new $$AnimateRunner({
1832               end: endFnFactory(),
1833               cancel: endFnFactory()
1834             });
1835
1836             return runner;
1837
1838             function endFnFactory() {
1839               return function() {
1840                 forEach(animationRunners, function(runner) {
1841                   // at this point we cannot cancel animations for groups just yet. 1.5+
1842                   runner.end();
1843                 });
1844               };
1845             }
1846
1847             function done(status) {
1848               runner.complete(status);
1849             }
1850           }
1851         };
1852       } else {
1853         return prepareAnimation(animationDetails);
1854       }
1855     };
1856
1857     function prepareAnimation(animationDetails) {
1858       // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
1859       var element = animationDetails.element;
1860       var event = animationDetails.event;
1861       var options = animationDetails.options;
1862       var classes = animationDetails.classes;
1863       return $$animateJs(element, event, classes, options);
1864     }
1865   }];
1866 }];
1867
1868 var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
1869 var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
1870 var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
1871   var PRE_DIGEST_STATE = 1;
1872   var RUNNING_STATE = 2;
1873
1874   var rules = this.rules = {
1875     skip: [],
1876     cancel: [],
1877     join: []
1878   };
1879
1880   function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
1881     return rules[ruleType].some(function(fn) {
1882       return fn(element, currentAnimation, previousAnimation);
1883     });
1884   }
1885
1886   function hasAnimationClasses(options, and) {
1887     options = options || {};
1888     var a = (options.addClass || '').length > 0;
1889     var b = (options.removeClass || '').length > 0;
1890     return and ? a && b : a || b;
1891   }
1892
1893   rules.join.push(function(element, newAnimation, currentAnimation) {
1894     // if the new animation is class-based then we can just tack that on
1895     return !newAnimation.structural && hasAnimationClasses(newAnimation.options);
1896   });
1897
1898   rules.skip.push(function(element, newAnimation, currentAnimation) {
1899     // there is no need to animate anything if no classes are being added and
1900     // there is no structural animation that will be triggered
1901     return !newAnimation.structural && !hasAnimationClasses(newAnimation.options);
1902   });
1903
1904   rules.skip.push(function(element, newAnimation, currentAnimation) {
1905     // why should we trigger a new structural animation if the element will
1906     // be removed from the DOM anyway?
1907     return currentAnimation.event == 'leave' && newAnimation.structural;
1908   });
1909
1910   rules.skip.push(function(element, newAnimation, currentAnimation) {
1911     // if there is a current animation then skip the class-based animation
1912     return currentAnimation.structural && !newAnimation.structural;
1913   });
1914
1915   rules.cancel.push(function(element, newAnimation, currentAnimation) {
1916     // there can never be two structural animations running at the same time
1917     return currentAnimation.structural && newAnimation.structural;
1918   });
1919
1920   rules.cancel.push(function(element, newAnimation, currentAnimation) {
1921     // if the previous animation is already running, but the new animation will
1922     // be triggered, but the new animation is structural
1923     return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
1924   });
1925
1926   rules.cancel.push(function(element, newAnimation, currentAnimation) {
1927     var nO = newAnimation.options;
1928     var cO = currentAnimation.options;
1929
1930     // if the exact same CSS class is added/removed then it's safe to cancel it
1931     return (nO.addClass && nO.addClass === cO.removeClass) || (nO.removeClass && nO.removeClass === cO.addClass);
1932   });
1933
1934   this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
1935                '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite',
1936        function($$rAF,   $rootScope,   $rootElement,   $document,   $$HashMap,
1937                 $$animation,   $$AnimateRunner,   $templateRequest,   $$jqLite) {
1938
1939     var activeAnimationsLookup = new $$HashMap();
1940     var disabledElementsLookup = new $$HashMap();
1941
1942     var animationsEnabled = null;
1943
1944     // Wait until all directive and route-related templates are downloaded and
1945     // compiled. The $templateRequest.totalPendingRequests variable keeps track of
1946     // all of the remote templates being currently downloaded. If there are no
1947     // templates currently downloading then the watcher will still fire anyway.
1948     var deregisterWatch = $rootScope.$watch(
1949       function() { return $templateRequest.totalPendingRequests === 0; },
1950       function(isEmpty) {
1951         if (!isEmpty) return;
1952         deregisterWatch();
1953
1954         // Now that all templates have been downloaded, $animate will wait until
1955         // the post digest queue is empty before enabling animations. By having two
1956         // calls to $postDigest calls we can ensure that the flag is enabled at the
1957         // very end of the post digest queue. Since all of the animations in $animate
1958         // use $postDigest, it's important that the code below executes at the end.
1959         // This basically means that the page is fully downloaded and compiled before
1960         // any animations are triggered.
1961         $rootScope.$$postDigest(function() {
1962           $rootScope.$$postDigest(function() {
1963             // we check for null directly in the event that the application already called
1964             // .enabled() with whatever arguments that it provided it with
1965             if (animationsEnabled === null) {
1966               animationsEnabled = true;
1967             }
1968           });
1969         });
1970       }
1971     );
1972
1973     var bodyElement = jqLite($document[0].body);
1974
1975     var callbackRegistry = {};
1976
1977     // remember that the classNameFilter is set during the provider/config
1978     // stage therefore we can optimize here and setup a helper function
1979     var classNameFilter = $animateProvider.classNameFilter();
1980     var isAnimatableClassName = !classNameFilter
1981               ? function() { return true; }
1982               : function(className) {
1983                 return classNameFilter.test(className);
1984               };
1985
1986     var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
1987
1988     function normalizeAnimationOptions(element, options) {
1989       return mergeAnimationOptions(element, options, {});
1990     }
1991
1992     function findCallbacks(element, event) {
1993       var targetNode = getDomNode(element);
1994
1995       var matches = [];
1996       var entries = callbackRegistry[event];
1997       if (entries) {
1998         forEach(entries, function(entry) {
1999           if (entry.node.contains(targetNode)) {
2000             matches.push(entry.callback);
2001           }
2002         });
2003       }
2004
2005       return matches;
2006     }
2007
2008     function triggerCallback(event, element, phase, data) {
2009       $$rAF(function() {
2010         forEach(findCallbacks(element, event), function(callback) {
2011           callback(element, phase, data);
2012         });
2013       });
2014     }
2015
2016     return {
2017       on: function(event, container, callback) {
2018         var node = extractElementNode(container);
2019         callbackRegistry[event] = callbackRegistry[event] || [];
2020         callbackRegistry[event].push({
2021           node: node,
2022           callback: callback
2023         });
2024       },
2025
2026       off: function(event, container, callback) {
2027         var entries = callbackRegistry[event];
2028         if (!entries) return;
2029
2030         callbackRegistry[event] = arguments.length === 1
2031             ? null
2032             : filterFromRegistry(entries, container, callback);
2033
2034         function filterFromRegistry(list, matchContainer, matchCallback) {
2035           var containerNode = extractElementNode(matchContainer);
2036           return list.filter(function(entry) {
2037             var isMatch = entry.node === containerNode &&
2038                             (!matchCallback || entry.callback === matchCallback);
2039             return !isMatch;
2040           });
2041         }
2042       },
2043
2044       pin: function(element, parentElement) {
2045         assertArg(isElement(element), 'element', 'not an element');
2046         assertArg(isElement(parentElement), 'parentElement', 'not an element');
2047         element.data(NG_ANIMATE_PIN_DATA, parentElement);
2048       },
2049
2050       push: function(element, event, options, domOperation) {
2051         options = options || {};
2052         options.domOperation = domOperation;
2053         return queueAnimation(element, event, options);
2054       },
2055
2056       // this method has four signatures:
2057       //  () - global getter
2058       //  (bool) - global setter
2059       //  (element) - element getter
2060       //  (element, bool) - element setter<F37>
2061       enabled: function(element, bool) {
2062         var argCount = arguments.length;
2063
2064         if (argCount === 0) {
2065           // () - Global getter
2066           bool = !!animationsEnabled;
2067         } else {
2068           var hasElement = isElement(element);
2069
2070           if (!hasElement) {
2071             // (bool) - Global setter
2072             bool = animationsEnabled = !!element;
2073           } else {
2074             var node = getDomNode(element);
2075             var recordExists = disabledElementsLookup.get(node);
2076
2077             if (argCount === 1) {
2078               // (element) - Element getter
2079               bool = !recordExists;
2080             } else {
2081               // (element, bool) - Element setter
2082               bool = !!bool;
2083               if (!bool) {
2084                 disabledElementsLookup.put(node, true);
2085               } else if (recordExists) {
2086                 disabledElementsLookup.remove(node);
2087               }
2088             }
2089           }
2090         }
2091
2092         return bool;
2093       }
2094     };
2095
2096     function queueAnimation(element, event, options) {
2097       var node, parent;
2098       element = stripCommentsFromElement(element);
2099       if (element) {
2100         node = getDomNode(element);
2101         parent = element.parent();
2102       }
2103
2104       options = prepareAnimationOptions(options);
2105
2106       // we create a fake runner with a working promise.
2107       // These methods will become available after the digest has passed
2108       var runner = new $$AnimateRunner();
2109
2110       // there are situations where a directive issues an animation for
2111       // a jqLite wrapper that contains only comment nodes... If this
2112       // happens then there is no way we can perform an animation
2113       if (!node) {
2114         close();
2115         return runner;
2116       }
2117
2118       if (isArray(options.addClass)) {
2119         options.addClass = options.addClass.join(' ');
2120       }
2121
2122       if (isArray(options.removeClass)) {
2123         options.removeClass = options.removeClass.join(' ');
2124       }
2125
2126       if (options.from && !isObject(options.from)) {
2127         options.from = null;
2128       }
2129
2130       if (options.to && !isObject(options.to)) {
2131         options.to = null;
2132       }
2133
2134       var className = [node.className, options.addClass, options.removeClass].join(' ');
2135       if (!isAnimatableClassName(className)) {
2136         close();
2137         return runner;
2138       }
2139
2140       var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
2141
2142       // this is a hard disable of all animations for the application or on
2143       // the element itself, therefore  there is no need to continue further
2144       // past this point if not enabled
2145       var skipAnimations = !animationsEnabled || disabledElementsLookup.get(node);
2146       var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
2147       var hasExistingAnimation = !!existingAnimation.state;
2148
2149       // there is no point in traversing the same collection of parent ancestors if a followup
2150       // animation will be run on the same element that already did all that checking work
2151       if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
2152         skipAnimations = !areAnimationsAllowed(element, parent, event);
2153       }
2154
2155       if (skipAnimations) {
2156         close();
2157         return runner;
2158       }
2159
2160       if (isStructural) {
2161         closeChildAnimations(element);
2162       }
2163
2164       var newAnimation = {
2165         structural: isStructural,
2166         element: element,
2167         event: event,
2168         close: close,
2169         options: options,
2170         runner: runner
2171       };
2172
2173       if (hasExistingAnimation) {
2174         var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
2175         if (skipAnimationFlag) {
2176           if (existingAnimation.state === RUNNING_STATE) {
2177             close();
2178             return runner;
2179           } else {
2180             mergeAnimationOptions(element, existingAnimation.options, options);
2181             return existingAnimation.runner;
2182           }
2183         }
2184
2185         var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
2186         if (cancelAnimationFlag) {
2187           if (existingAnimation.state === RUNNING_STATE) {
2188             // this will end the animation right away and it is safe
2189             // to do so since the animation is already running and the
2190             // runner callback code will run in async
2191             existingAnimation.runner.end();
2192           } else if (existingAnimation.structural) {
2193             // this means that the animation is queued into a digest, but
2194             // hasn't started yet. Therefore it is safe to run the close
2195             // method which will call the runner methods in async.
2196             existingAnimation.close();
2197           } else {
2198             // this will merge the existing animation options into this new follow-up animation
2199             mergeAnimationOptions(element, newAnimation.options, existingAnimation.options);
2200           }
2201         } else {
2202           // a joined animation means that this animation will take over the existing one
2203           // so an example would involve a leave animation taking over an enter. Then when
2204           // the postDigest kicks in the enter will be ignored.
2205           var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
2206           if (joinAnimationFlag) {
2207             if (existingAnimation.state === RUNNING_STATE) {
2208               normalizeAnimationOptions(element, options);
2209             } else {
2210               event = newAnimation.event = existingAnimation.event;
2211               options = mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);
2212               return runner;
2213             }
2214           }
2215         }
2216       } else {
2217         // normalization in this case means that it removes redundant CSS classes that
2218         // already exist (addClass) or do not exist (removeClass) on the element
2219         normalizeAnimationOptions(element, options);
2220       }
2221
2222       // when the options are merged and cleaned up we may end up not having to do
2223       // an animation at all, therefore we should check this before issuing a post
2224       // digest callback. Structural animations will always run no matter what.
2225       var isValidAnimation = newAnimation.structural;
2226       if (!isValidAnimation) {
2227         // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
2228         isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
2229                             || hasAnimationClasses(newAnimation.options);
2230       }
2231
2232       if (!isValidAnimation) {
2233         close();
2234         clearElementAnimationState(element);
2235         return runner;
2236       }
2237
2238       if (isStructural) {
2239         closeParentClassBasedAnimations(parent);
2240       }
2241
2242       // the counter keeps track of cancelled animations
2243       var counter = (existingAnimation.counter || 0) + 1;
2244       newAnimation.counter = counter;
2245
2246       markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
2247
2248       $rootScope.$$postDigest(function() {
2249         var animationDetails = activeAnimationsLookup.get(node);
2250         var animationCancelled = !animationDetails;
2251         animationDetails = animationDetails || {};
2252
2253         // if addClass/removeClass is called before something like enter then the
2254         // registered parent element may not be present. The code below will ensure
2255         // that a final value for parent element is obtained
2256         var parentElement = element.parent() || [];
2257
2258         // animate/structural/class-based animations all have requirements. Otherwise there
2259         // is no point in performing an animation. The parent node must also be set.
2260         var isValidAnimation = parentElement.length > 0
2261                                 && (animationDetails.event === 'animate'
2262                                     || animationDetails.structural
2263                                     || hasAnimationClasses(animationDetails.options));
2264
2265         // this means that the previous animation was cancelled
2266         // even if the follow-up animation is the same event
2267         if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
2268           // if another animation did not take over then we need
2269           // to make sure that the domOperation and options are
2270           // handled accordingly
2271           if (animationCancelled) {
2272             applyAnimationClasses(element, options);
2273             applyAnimationStyles(element, options);
2274           }
2275
2276           // if the event changed from something like enter to leave then we do
2277           // it, otherwise if it's the same then the end result will be the same too
2278           if (animationCancelled || (isStructural && animationDetails.event !== event)) {
2279             options.domOperation();
2280             runner.end();
2281           }
2282
2283           // in the event that the element animation was not cancelled or a follow-up animation
2284           // isn't allowed to animate from here then we need to clear the state of the element
2285           // so that any future animations won't read the expired animation data.
2286           if (!isValidAnimation) {
2287             clearElementAnimationState(element);
2288           }
2289
2290           return;
2291         }
2292
2293         // this combined multiple class to addClass / removeClass into a setClass event
2294         // so long as a structural event did not take over the animation
2295         event = !animationDetails.structural && hasAnimationClasses(animationDetails.options, true)
2296             ? 'setClass'
2297             : animationDetails.event;
2298
2299         if (animationDetails.structural) {
2300           closeParentClassBasedAnimations(parentElement);
2301         }
2302
2303         markElementAnimationState(element, RUNNING_STATE);
2304         var realRunner = $$animation(element, event, animationDetails.options);
2305         realRunner.done(function(status) {
2306           close(!status);
2307           var animationDetails = activeAnimationsLookup.get(node);
2308           if (animationDetails && animationDetails.counter === counter) {
2309             clearElementAnimationState(getDomNode(element));
2310           }
2311           notifyProgress(runner, event, 'close', {});
2312         });
2313
2314         // this will update the runner's flow-control events based on
2315         // the `realRunner` object.
2316         runner.setHost(realRunner);
2317         notifyProgress(runner, event, 'start', {});
2318       });
2319
2320       return runner;
2321
2322       function notifyProgress(runner, event, phase, data) {
2323         triggerCallback(event, element, phase, data);
2324         runner.progress(event, phase, data);
2325       }
2326
2327       function close(reject) { // jshint ignore:line
2328         applyAnimationClasses(element, options);
2329         applyAnimationStyles(element, options);
2330         options.domOperation();
2331         runner.complete(!reject);
2332       }
2333     }
2334
2335     function closeChildAnimations(element) {
2336       var node = getDomNode(element);
2337       var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
2338       forEach(children, function(child) {
2339         var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
2340         var animationDetails = activeAnimationsLookup.get(child);
2341         switch (state) {
2342           case RUNNING_STATE:
2343             animationDetails.runner.end();
2344             /* falls through */
2345           case PRE_DIGEST_STATE:
2346             if (animationDetails) {
2347               activeAnimationsLookup.remove(child);
2348             }
2349             break;
2350         }
2351       });
2352     }
2353
2354     function clearElementAnimationState(element) {
2355       var node = getDomNode(element);
2356       node.removeAttribute(NG_ANIMATE_ATTR_NAME);
2357       activeAnimationsLookup.remove(node);
2358     }
2359
2360     function isMatchingElement(nodeOrElmA, nodeOrElmB) {
2361       return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
2362     }
2363
2364     function closeParentClassBasedAnimations(startingElement) {
2365       var parentNode = getDomNode(startingElement);
2366       do {
2367         if (!parentNode || parentNode.nodeType !== ELEMENT_NODE) break;
2368
2369         var animationDetails = activeAnimationsLookup.get(parentNode);
2370         if (animationDetails) {
2371           examineParentAnimation(parentNode, animationDetails);
2372         }
2373
2374         parentNode = parentNode.parentNode;
2375       } while (true);
2376
2377       // since animations are detected from CSS classes, we need to flush all parent
2378       // class-based animations so that the parent classes are all present for child
2379       // animations to properly function (otherwise any CSS selectors may not work)
2380       function examineParentAnimation(node, animationDetails) {
2381         // enter/leave/move always have priority
2382         if (animationDetails.structural || !hasAnimationClasses(animationDetails.options)) return;
2383
2384         if (animationDetails.state === RUNNING_STATE) {
2385           animationDetails.runner.end();
2386         }
2387         clearElementAnimationState(node);
2388       }
2389     }
2390
2391     function areAnimationsAllowed(element, parentElement, event) {
2392       var bodyElementDetected = false;
2393       var rootElementDetected = false;
2394       var parentAnimationDetected = false;
2395       var animateChildren;
2396
2397       var parentHost = element.data(NG_ANIMATE_PIN_DATA);
2398       if (parentHost) {
2399         parentElement = parentHost;
2400       }
2401
2402       while (parentElement && parentElement.length) {
2403         if (!rootElementDetected) {
2404           // angular doesn't want to attempt to animate elements outside of the application
2405           // therefore we need to ensure that the rootElement is an ancestor of the current element
2406           rootElementDetected = isMatchingElement(parentElement, $rootElement);
2407         }
2408
2409         var parentNode = parentElement[0];
2410         if (parentNode.nodeType !== ELEMENT_NODE) {
2411           // no point in inspecting the #document element
2412           break;
2413         }
2414
2415         var details = activeAnimationsLookup.get(parentNode) || {};
2416         // either an enter, leave or move animation will commence
2417         // therefore we can't allow any animations to take place
2418         // but if a parent animation is class-based then that's ok
2419         if (!parentAnimationDetected) {
2420           parentAnimationDetected = details.structural || disabledElementsLookup.get(parentNode);
2421         }
2422
2423         if (isUndefined(animateChildren) || animateChildren === true) {
2424           var value = parentElement.data(NG_ANIMATE_CHILDREN_DATA);
2425           if (isDefined(value)) {
2426             animateChildren = value;
2427           }
2428         }
2429
2430         // there is no need to continue traversing at this point
2431         if (parentAnimationDetected && animateChildren === false) break;
2432
2433         if (!rootElementDetected) {
2434           // angular doesn't want to attempt to animate elements outside of the application
2435           // therefore we need to ensure that the rootElement is an ancestor of the current element
2436           rootElementDetected = isMatchingElement(parentElement, $rootElement);
2437           if (!rootElementDetected) {
2438             parentHost = parentElement.data(NG_ANIMATE_PIN_DATA);
2439             if (parentHost) {
2440               parentElement = parentHost;
2441             }
2442           }
2443         }
2444
2445         if (!bodyElementDetected) {
2446           // we also need to ensure that the element is or will be apart of the body element
2447           // otherwise it is pointless to even issue an animation to be rendered
2448           bodyElementDetected = isMatchingElement(parentElement, bodyElement);
2449         }
2450
2451         parentElement = parentElement.parent();
2452       }
2453
2454       var allowAnimation = !parentAnimationDetected || animateChildren;
2455       return allowAnimation && rootElementDetected && bodyElementDetected;
2456     }
2457
2458     function markElementAnimationState(element, state, details) {
2459       details = details || {};
2460       details.state = state;
2461
2462       var node = getDomNode(element);
2463       node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
2464
2465       var oldValue = activeAnimationsLookup.get(node);
2466       var newValue = oldValue
2467           ? extend(oldValue, details)
2468           : details;
2469       activeAnimationsLookup.put(node, newValue);
2470     }
2471   }];
2472 }];
2473
2474 var $$rAFMutexFactory = ['$$rAF', function($$rAF) {
2475   return function() {
2476     var passed = false;
2477     $$rAF(function() {
2478       passed = true;
2479     });
2480     return function(fn) {
2481       passed ? fn() : $$rAF(fn);
2482     };
2483   };
2484 }];
2485
2486 var $$AnimateRunnerFactory = ['$q', '$$rAFMutex', function($q, $$rAFMutex) {
2487   var INITIAL_STATE = 0;
2488   var DONE_PENDING_STATE = 1;
2489   var DONE_COMPLETE_STATE = 2;
2490
2491   AnimateRunner.chain = function(chain, callback) {
2492     var index = 0;
2493
2494     next();
2495     function next() {
2496       if (index === chain.length) {
2497         callback(true);
2498         return;
2499       }
2500
2501       chain[index](function(response) {
2502         if (response === false) {
2503           callback(false);
2504           return;
2505         }
2506         index++;
2507         next();
2508       });
2509     }
2510   };
2511
2512   AnimateRunner.all = function(runners, callback) {
2513     var count = 0;
2514     var status = true;
2515     forEach(runners, function(runner) {
2516       runner.done(onProgress);
2517     });
2518
2519     function onProgress(response) {
2520       status = status && response;
2521       if (++count === runners.length) {
2522         callback(status);
2523       }
2524     }
2525   };
2526
2527   function AnimateRunner(host) {
2528     this.setHost(host);
2529
2530     this._doneCallbacks = [];
2531     this._runInAnimationFrame = $$rAFMutex();
2532     this._state = 0;
2533   }
2534
2535   AnimateRunner.prototype = {
2536     setHost: function(host) {
2537       this.host = host || {};
2538     },
2539
2540     done: function(fn) {
2541       if (this._state === DONE_COMPLETE_STATE) {
2542         fn();
2543       } else {
2544         this._doneCallbacks.push(fn);
2545       }
2546     },
2547
2548     progress: noop,
2549
2550     getPromise: function() {
2551       if (!this.promise) {
2552         var self = this;
2553         this.promise = $q(function(resolve, reject) {
2554           self.done(function(status) {
2555             status === false ? reject() : resolve();
2556           });
2557         });
2558       }
2559       return this.promise;
2560     },
2561
2562     then: function(resolveHandler, rejectHandler) {
2563       return this.getPromise().then(resolveHandler, rejectHandler);
2564     },
2565
2566     'catch': function(handler) {
2567       return this.getPromise()['catch'](handler);
2568     },
2569
2570     'finally': function(handler) {
2571       return this.getPromise()['finally'](handler);
2572     },
2573
2574     pause: function() {
2575       if (this.host.pause) {
2576         this.host.pause();
2577       }
2578     },
2579
2580     resume: function() {
2581       if (this.host.resume) {
2582         this.host.resume();
2583       }
2584     },
2585
2586     end: function() {
2587       if (this.host.end) {
2588         this.host.end();
2589       }
2590       this._resolve(true);
2591     },
2592
2593     cancel: function() {
2594       if (this.host.cancel) {
2595         this.host.cancel();
2596       }
2597       this._resolve(false);
2598     },
2599
2600     complete: function(response) {
2601       var self = this;
2602       if (self._state === INITIAL_STATE) {
2603         self._state = DONE_PENDING_STATE;
2604         self._runInAnimationFrame(function() {
2605           self._resolve(response);
2606         });
2607       }
2608     },
2609
2610     _resolve: function(response) {
2611       if (this._state !== DONE_COMPLETE_STATE) {
2612         forEach(this._doneCallbacks, function(fn) {
2613           fn(response);
2614         });
2615         this._doneCallbacks.length = 0;
2616         this._state = DONE_COMPLETE_STATE;
2617       }
2618     }
2619   };
2620
2621   return AnimateRunner;
2622 }];
2623
2624 var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
2625   var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
2626
2627   var drivers = this.drivers = [];
2628
2629   var RUNNER_STORAGE_KEY = '$$animationRunner';
2630
2631   function setRunner(element, runner) {
2632     element.data(RUNNER_STORAGE_KEY, runner);
2633   }
2634
2635   function removeRunner(element) {
2636     element.removeData(RUNNER_STORAGE_KEY);
2637   }
2638
2639   function getRunner(element) {
2640     return element.data(RUNNER_STORAGE_KEY);
2641   }
2642
2643   this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$rAFScheduler',
2644        function($$jqLite,   $rootScope,   $injector,   $$AnimateRunner,   $$rAFScheduler) {
2645
2646     var animationQueue = [];
2647     var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
2648
2649     var totalPendingClassBasedAnimations = 0;
2650     var totalActiveClassBasedAnimations = 0;
2651     var classBasedAnimationsQueue = [];
2652
2653     // TODO(matsko): document the signature in a better way
2654     return function(element, event, options) {
2655       options = prepareAnimationOptions(options);
2656       var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
2657
2658       // there is no animation at the current moment, however
2659       // these runner methods will get later updated with the
2660       // methods leading into the driver's end/cancel methods
2661       // for now they just stop the animation from starting
2662       var runner = new $$AnimateRunner({
2663         end: function() { close(); },
2664         cancel: function() { close(true); }
2665       });
2666
2667       if (!drivers.length) {
2668         close();
2669         return runner;
2670       }
2671
2672       setRunner(element, runner);
2673
2674       var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
2675       var tempClasses = options.tempClasses;
2676       if (tempClasses) {
2677         classes += ' ' + tempClasses;
2678         options.tempClasses = null;
2679       }
2680
2681       var classBasedIndex;
2682       if (!isStructural) {
2683         classBasedIndex = totalPendingClassBasedAnimations;
2684         totalPendingClassBasedAnimations += 1;
2685       }
2686
2687       animationQueue.push({
2688         // this data is used by the postDigest code and passed into
2689         // the driver step function
2690         element: element,
2691         classes: classes,
2692         event: event,
2693         classBasedIndex: classBasedIndex,
2694         structural: isStructural,
2695         options: options,
2696         beforeStart: beforeStart,
2697         close: close
2698       });
2699
2700       element.on('$destroy', handleDestroyedElement);
2701
2702       // we only want there to be one function called within the post digest
2703       // block. This way we can group animations for all the animations that
2704       // were apart of the same postDigest flush call.
2705       if (animationQueue.length > 1) return runner;
2706
2707       $rootScope.$$postDigest(function() {
2708         totalActiveClassBasedAnimations = totalPendingClassBasedAnimations;
2709         totalPendingClassBasedAnimations = 0;
2710         classBasedAnimationsQueue.length = 0;
2711
2712         var animations = [];
2713         forEach(animationQueue, function(entry) {
2714           // the element was destroyed early on which removed the runner
2715           // form its storage. This means we can't animate this element
2716           // at all and it already has been closed due to destruction.
2717           if (getRunner(entry.element)) {
2718             animations.push(entry);
2719           }
2720         });
2721
2722         // now any future animations will be in another postDigest
2723         animationQueue.length = 0;
2724
2725         forEach(groupAnimations(animations), function(animationEntry) {
2726           if (animationEntry.structural) {
2727             triggerAnimationStart();
2728           } else {
2729             classBasedAnimationsQueue.push({
2730               node: getDomNode(animationEntry.element),
2731               fn: triggerAnimationStart
2732             });
2733
2734             if (animationEntry.classBasedIndex === totalActiveClassBasedAnimations - 1) {
2735               // we need to sort each of the animations in order of parent to child
2736               // relationships. This ensures that the child classes are applied at the
2737               // right time.
2738               classBasedAnimationsQueue = classBasedAnimationsQueue.sort(function(a,b) {
2739                 return b.node.contains(a.node);
2740               }).map(function(entry) {
2741                 return entry.fn;
2742               });
2743
2744               $$rAFScheduler(classBasedAnimationsQueue);
2745             }
2746           }
2747
2748           function triggerAnimationStart() {
2749             // it's important that we apply the `ng-animate` CSS class and the
2750             // temporary classes before we do any driver invoking since these
2751             // CSS classes may be required for proper CSS detection.
2752             animationEntry.beforeStart();
2753
2754             var startAnimationFn, closeFn = animationEntry.close;
2755
2756             // in the event that the element was removed before the digest runs or
2757             // during the RAF sequencing then we should not trigger the animation.
2758             var targetElement = animationEntry.anchors
2759                 ? (animationEntry.from.element || animationEntry.to.element)
2760                 : animationEntry.element;
2761
2762             if (getRunner(targetElement) && getDomNode(targetElement).parentNode) {
2763               var operation = invokeFirstDriver(animationEntry);
2764               if (operation) {
2765                 startAnimationFn = operation.start;
2766               }
2767             }
2768
2769             if (!startAnimationFn) {
2770               closeFn();
2771             } else {
2772               var animationRunner = startAnimationFn();
2773               animationRunner.done(function(status) {
2774                 closeFn(!status);
2775               });
2776               updateAnimationRunners(animationEntry, animationRunner);
2777             }
2778           }
2779         });
2780       });
2781
2782       return runner;
2783
2784       // TODO(matsko): change to reference nodes
2785       function getAnchorNodes(node) {
2786         var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
2787         var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
2788               ? [node]
2789               : node.querySelectorAll(SELECTOR);
2790         var anchors = [];
2791         forEach(items, function(node) {
2792           var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
2793           if (attr && attr.length) {
2794             anchors.push(node);
2795           }
2796         });
2797         return anchors;
2798       }
2799
2800       function groupAnimations(animations) {
2801         var preparedAnimations = [];
2802         var refLookup = {};
2803         forEach(animations, function(animation, index) {
2804           var element = animation.element;
2805           var node = getDomNode(element);
2806           var event = animation.event;
2807           var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
2808           var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
2809
2810           if (anchorNodes.length) {
2811             var direction = enterOrMove ? 'to' : 'from';
2812
2813             forEach(anchorNodes, function(anchor) {
2814               var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
2815               refLookup[key] = refLookup[key] || {};
2816               refLookup[key][direction] = {
2817                 animationID: index,
2818                 element: jqLite(anchor)
2819               };
2820             });
2821           } else {
2822             preparedAnimations.push(animation);
2823           }
2824         });
2825
2826         var usedIndicesLookup = {};
2827         var anchorGroups = {};
2828         forEach(refLookup, function(operations, key) {
2829           var from = operations.from;
2830           var to = operations.to;
2831
2832           if (!from || !to) {
2833             // only one of these is set therefore we can't have an
2834             // anchor animation since all three pieces are required
2835             var index = from ? from.animationID : to.animationID;
2836             var indexKey = index.toString();
2837             if (!usedIndicesLookup[indexKey]) {
2838               usedIndicesLookup[indexKey] = true;
2839               preparedAnimations.push(animations[index]);
2840             }
2841             return;
2842           }
2843
2844           var fromAnimation = animations[from.animationID];
2845           var toAnimation = animations[to.animationID];
2846           var lookupKey = from.animationID.toString();
2847           if (!anchorGroups[lookupKey]) {
2848             var group = anchorGroups[lookupKey] = {
2849               structural: true,
2850               beforeStart: function() {
2851                 fromAnimation.beforeStart();
2852                 toAnimation.beforeStart();
2853               },
2854               close: function() {
2855                 fromAnimation.close();
2856                 toAnimation.close();
2857               },
2858               classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
2859               from: fromAnimation,
2860               to: toAnimation,
2861               anchors: [] // TODO(matsko): change to reference nodes
2862             };
2863
2864             // the anchor animations require that the from and to elements both have at least
2865             // one shared CSS class which effictively marries the two elements together to use
2866             // the same animation driver and to properly sequence the anchor animation.
2867             if (group.classes.length) {
2868               preparedAnimations.push(group);
2869             } else {
2870               preparedAnimations.push(fromAnimation);
2871               preparedAnimations.push(toAnimation);
2872             }
2873           }
2874
2875           anchorGroups[lookupKey].anchors.push({
2876             'out': from.element, 'in': to.element
2877           });
2878         });
2879
2880         return preparedAnimations;
2881       }
2882
2883       function cssClassesIntersection(a,b) {
2884         a = a.split(' ');
2885         b = b.split(' ');
2886         var matches = [];
2887
2888         for (var i = 0; i < a.length; i++) {
2889           var aa = a[i];
2890           if (aa.substring(0,3) === 'ng-') continue;
2891
2892           for (var j = 0; j < b.length; j++) {
2893             if (aa === b[j]) {
2894               matches.push(aa);
2895               break;
2896             }
2897           }
2898         }
2899
2900         return matches.join(' ');
2901       }
2902
2903       function invokeFirstDriver(animationDetails) {
2904         // we loop in reverse order since the more general drivers (like CSS and JS)
2905         // may attempt more elements, but custom drivers are more particular
2906         for (var i = drivers.length - 1; i >= 0; i--) {
2907           var driverName = drivers[i];
2908           if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check
2909
2910           var factory = $injector.get(driverName);
2911           var driver = factory(animationDetails);
2912           if (driver) {
2913             return driver;
2914           }
2915         }
2916       }
2917
2918       function beforeStart() {
2919         element.addClass(NG_ANIMATE_CLASSNAME);
2920         if (tempClasses) {
2921           $$jqLite.addClass(element, tempClasses);
2922         }
2923       }
2924
2925       function updateAnimationRunners(animation, newRunner) {
2926         if (animation.from && animation.to) {
2927           update(animation.from.element);
2928           update(animation.to.element);
2929         } else {
2930           update(animation.element);
2931         }
2932
2933         function update(element) {
2934           getRunner(element).setHost(newRunner);
2935         }
2936       }
2937
2938       function handleDestroyedElement() {
2939         var runner = getRunner(element);
2940         if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
2941           runner.end();
2942         }
2943       }
2944
2945       function close(rejected) { // jshint ignore:line
2946         element.off('$destroy', handleDestroyedElement);
2947         removeRunner(element);
2948
2949         applyAnimationClasses(element, options);
2950         applyAnimationStyles(element, options);
2951         options.domOperation();
2952
2953         if (tempClasses) {
2954           $$jqLite.removeClass(element, tempClasses);
2955         }
2956
2957         element.removeClass(NG_ANIMATE_CLASSNAME);
2958         runner.complete(!rejected);
2959       }
2960     };
2961   }];
2962 }];
2963
2964 /* global angularAnimateModule: true,
2965
2966    $$rAFMutexFactory,
2967    $$rAFSchedulerFactory,
2968    $$AnimateChildrenDirective,
2969    $$AnimateRunnerFactory,
2970    $$AnimateQueueProvider,
2971    $$AnimationProvider,
2972    $AnimateCssProvider,
2973    $$AnimateCssDriverProvider,
2974    $$AnimateJsProvider,
2975    $$AnimateJsDriverProvider,
2976 */
2977
2978 /**
2979  * @ngdoc module
2980  * @name ngAnimate
2981  * @description
2982  *
2983  * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
2984  * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` then the animation hooks are enabled for an Angular app.
2985  *
2986  * <div doc-module-components="ngAnimate"></div>
2987  *
2988  * # Usage
2989  * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based
2990  * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
2991  * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
2992  * the HTML element that the animation will be triggered on.
2993  *
2994  * ## Directive Support
2995  * The following directives are "animation aware":
2996  *
2997  * | Directive                                                                                                | Supported Animations                                                     |
2998  * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
2999  * | {@link ng.directive:ngRepeat#animations ngRepeat}                                                        | enter, leave and move                                                    |
3000  * | {@link ngRoute.directive:ngView#animations ngView}                                                       | enter and leave                                                          |
3001  * | {@link ng.directive:ngInclude#animations ngInclude}                                                      | enter and leave                                                          |
3002  * | {@link ng.directive:ngSwitch#animations ngSwitch}                                                        | enter and leave                                                          |
3003  * | {@link ng.directive:ngIf#animations ngIf}                                                                | enter and leave                                                          |
3004  * | {@link ng.directive:ngClass#animations ngClass}                                                          | add and remove (the CSS class(es) present)                               |
3005  * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide}            | add and remove (the ng-hide class value)                                 |
3006  * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel}    | add and remove (dirty, pristine, valid, invalid & all other validations) |
3007  * | {@link module:ngMessages#animations ngMessages}                                                          | add and remove (ng-active & ng-inactive)                                 |
3008  * | {@link module:ngMessages#animations ngMessage}                                                           | enter and leave                                                          |
3009  *
3010  * (More information can be found by visiting each the documentation associated with each directive.)
3011  *
3012  * ## CSS-based Animations
3013  *
3014  * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML
3015  * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
3016  *
3017  * The example below shows how an `enter` animation can be made possible on a element using `ng-if`:
3018  *
3019  * ```html
3020  * <div ng-if="bool" class="fade">
3021  *    Fade me in out
3022  * </div>
3023  * <button ng-click="bool=true">Fade In!</button>
3024  * <button ng-click="bool=false">Fade Out!</button>
3025  * ```
3026  *
3027  * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
3028  *
3029  * ```css
3030  * /&#42; The starting CSS styles for the enter animation &#42;/
3031  * .fade.ng-enter {
3032  *   transition:0.5s linear all;
3033  *   opacity:0;
3034  * }
3035  *
3036  * /&#42; The finishing CSS styles for the enter animation &#42;/
3037  * .fade.ng-enter.ng-enter-active {
3038  *   opacity:1;
3039  * }
3040  * ```
3041  *
3042  * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two
3043  * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition
3044  * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
3045  *
3046  * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:
3047  *
3048  * ```css
3049  * /&#42; now the element will fade out before it is removed from the DOM &#42;/
3050  * .fade.ng-leave {
3051  *   transition:0.5s linear all;
3052  *   opacity:1;
3053  * }
3054  * .fade.ng-leave.ng-leave-active {
3055  *   opacity:0;
3056  * }
3057  * ```
3058  *
3059  * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
3060  *
3061  * ```css
3062  * /&#42; there is no need to define anything inside of the destination
3063  * CSS class since the keyframe will take charge of the animation &#42;/
3064  * .fade.ng-leave {
3065  *   animation: my_fade_animation 0.5s linear;
3066  *   -webkit-animation: my_fade_animation 0.5s linear;
3067  * }
3068  *
3069  * @keyframes my_fade_animation {
3070  *   from { opacity:1; }
3071  *   to { opacity:0; }
3072  * }
3073  *
3074  * @-webkit-keyframes my_fade_animation {
3075  *   from { opacity:1; }
3076  *   to { opacity:0; }
3077  * }
3078  * ```
3079  *
3080  * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
3081  *
3082  * ### CSS Class-based Animations
3083  *
3084  * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
3085  * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
3086  * and removed.
3087  *
3088  * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
3089  *
3090  * ```html
3091  * <div ng-show="bool" class="fade">
3092  *   Show and hide me
3093  * </div>
3094  * <button ng-click="bool=true">Toggle</button>
3095  *
3096  * <style>
3097  * .fade.ng-hide {
3098  *   transition:0.5s linear all;
3099  *   opacity:0;
3100  * }
3101  * </style>
3102  * ```
3103  *
3104  * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since
3105  * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
3106  *
3107  * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation
3108  * with CSS styles.
3109  *
3110  * ```html
3111  * <div ng-class="{on:onOff}" class="highlight">
3112  *   Highlight this box
3113  * </div>
3114  * <button ng-click="onOff=!onOff">Toggle</button>
3115  *
3116  * <style>
3117  * .highlight {
3118  *   transition:0.5s linear all;
3119  * }
3120  * .highlight.on-add {
3121  *   background:white;
3122  * }
3123  * .highlight.on {
3124  *   background:yellow;
3125  * }
3126  * .highlight.on-remove {
3127  *   background:black;
3128  * }
3129  * </style>
3130  * ```
3131  *
3132  * We can also make use of CSS keyframes by placing them within the CSS classes.
3133  *
3134  *
3135  * ### CSS Staggering Animations
3136  * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
3137  * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
3138  * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
3139  * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
3140  * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
3141  *
3142  * ```css
3143  * .my-animation.ng-enter {
3144  *   /&#42; standard transition code &#42;/
3145  *   transition: 1s linear all;
3146  *   opacity:0;
3147  * }
3148  * .my-animation.ng-enter-stagger {
3149  *   /&#42; this will have a 100ms delay between each successive leave animation &#42;/
3150  *   transition-delay: 0.1s;
3151  *
3152  *   /&#42; in case the stagger doesn't work then the duration value
3153  *    must be set to 0 to avoid an accidental CSS inheritance &#42;/
3154  *   transition-duration: 0s;
3155  * }
3156  * .my-animation.ng-enter.ng-enter-active {
3157  *   /&#42; standard transition styles &#42;/
3158  *   opacity:1;
3159  * }
3160  * ```
3161  *
3162  * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
3163  * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
3164  * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
3165  * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
3166  *
3167  * The following code will issue the **ng-leave-stagger** event on the element provided:
3168  *
3169  * ```js
3170  * var kids = parent.children();
3171  *
3172  * $animate.leave(kids[0]); //stagger index=0
3173  * $animate.leave(kids[1]); //stagger index=1
3174  * $animate.leave(kids[2]); //stagger index=2
3175  * $animate.leave(kids[3]); //stagger index=3
3176  * $animate.leave(kids[4]); //stagger index=4
3177  *
3178  * window.requestAnimationFrame(function() {
3179  *   //stagger has reset itself
3180  *   $animate.leave(kids[5]); //stagger index=0
3181  *   $animate.leave(kids[6]); //stagger index=1
3182  *
3183  *   $scope.$digest();
3184  * });
3185  * ```
3186  *
3187  * Stagger animations are currently only supported within CSS-defined animations.
3188  *
3189  * ### The `ng-animate` CSS class
3190  *
3191  * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
3192  * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
3193  *
3194  * Therefore, animations can be applied to an element using this temporary class directly via CSS.
3195  *
3196  * ```css
3197  * .zipper.ng-animate {
3198  *   transition:0.5s linear all;
3199  * }
3200  * .zipper.ng-enter {
3201  *   opacity:0;
3202  * }
3203  * .zipper.ng-enter.ng-enter-active {
3204  *   opacity:1;
3205  * }
3206  * .zipper.ng-leave {
3207  *   opacity:1;
3208  * }
3209  * .zipper.ng-leave.ng-leave-active {
3210  *   opacity:0;
3211  * }
3212  * ```
3213  *
3214  * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
3215  * the CSS class once an animation has completed.)
3216  *
3217  *
3218  * ## JavaScript-based Animations
3219  *
3220  * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
3221  * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the
3222  * `module.animation()` module function we can register the ainmation.
3223  *
3224  * Let's see an example of a enter/leave animation using `ngRepeat`:
3225  *
3226  * ```html
3227  * <div ng-repeat="item in items" class="slide">
3228  *   {{ item }}
3229  * </div>
3230  * ```
3231  *
3232  * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:
3233  *
3234  * ```js
3235  * myModule.animation('.slide', [function() {
3236  *   return {
3237  *     // make note that other events (like addClass/removeClass)
3238  *     // have different function input parameters
3239  *     enter: function(element, doneFn) {
3240  *       jQuery(element).fadeIn(1000, doneFn);
3241  *
3242  *       // remember to call doneFn so that angular
3243  *       // knows that the animation has concluded
3244  *     },
3245  *
3246  *     move: function(element, doneFn) {
3247  *       jQuery(element).fadeIn(1000, doneFn);
3248  *     },
3249  *
3250  *     leave: function(element, doneFn) {
3251  *       jQuery(element).fadeOut(1000, doneFn);
3252  *     }
3253  *   }
3254  * }]
3255  * ```
3256  *
3257  * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
3258  * greensock.js and velocity.js.
3259  *
3260  * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
3261  * our animations inside of the same registered animation, however, the function input arguments are a bit different:
3262  *
3263  * ```html
3264  * <div ng-class="color" class="colorful">
3265  *   this box is moody
3266  * </div>
3267  * <button ng-click="color='red'">Change to red</button>
3268  * <button ng-click="color='blue'">Change to blue</button>
3269  * <button ng-click="color='green'">Change to green</button>
3270  * ```
3271  *
3272  * ```js
3273  * myModule.animation('.colorful', [function() {
3274  *   return {
3275  *     addClass: function(element, className, doneFn) {
3276  *       // do some cool animation and call the doneFn
3277  *     },
3278  *     removeClass: function(element, className, doneFn) {
3279  *       // do some cool animation and call the doneFn
3280  *     },
3281  *     setClass: function(element, addedClass, removedClass, doneFn) {
3282  *       // do some cool animation and call the doneFn
3283  *     }
3284  *   }
3285  * }]
3286  * ```
3287  *
3288  * ## CSS + JS Animations Together
3289  *
3290  * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,
3291  * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking
3292  * charge of the animation**:
3293  *
3294  * ```html
3295  * <div ng-if="bool" class="slide">
3296  *   Slide in and out
3297  * </div>
3298  * ```
3299  *
3300  * ```js
3301  * myModule.animation('.slide', [function() {
3302  *   return {
3303  *     enter: function(element, doneFn) {
3304  *       jQuery(element).slideIn(1000, doneFn);
3305  *     }
3306  *   }
3307  * }]
3308  * ```
3309  *
3310  * ```css
3311  * .slide.ng-enter {
3312  *   transition:0.5s linear all;
3313  *   transform:translateY(-100px);
3314  * }
3315  * .slide.ng-enter.ng-enter-active {
3316  *   transform:translateY(0);
3317  * }
3318  * ```
3319  *
3320  * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the
3321  * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
3322  * our own JS-based animation code:
3323  *
3324  * ```js
3325  * myModule.animation('.slide', ['$animateCss', function($animateCss) {
3326  *   return {
3327  *     enter: function(element, doneFn) {
3328 *        // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
3329  *       var runner = $animateCss(element, {
3330  *         event: 'enter',
3331  *         structural: true
3332  *       }).start();
3333 *        runner.done(doneFn);
3334  *     }
3335  *   }
3336  * }]
3337  * ```
3338  *
3339  * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.
3340  *
3341  * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or
3342  * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that
3343  * data into `$animateCss` directly:
3344  *
3345  * ```js
3346  * myModule.animation('.slide', ['$animateCss', function($animateCss) {
3347  *   return {
3348  *     enter: function(element, doneFn) {
3349  *       var runner = $animateCss(element, {
3350  *         event: 'enter',
3351  *         addClass: 'maroon-setting',
3352  *         from: { height:0 },
3353  *         to: { height: 200 }
3354  *       }).start();
3355  *
3356  *       runner.done(doneFn);
3357  *     }
3358  *   }
3359  * }]
3360  * ```
3361  *
3362  * Now we can fill in the rest via our transition CSS code:
3363  *
3364  * ```css
3365  * /&#42; the transition tells ngAnimate to make the animation happen &#42;/
3366  * .slide.ng-enter { transition:0.5s linear all; }
3367  *
3368  * /&#42; this extra CSS class will be absorbed into the transition
3369  * since the $animateCss code is adding the class &#42;/
3370  * .maroon-setting { background:red; }
3371  * ```
3372  *
3373  * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.
3374  *
3375  * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
3376  *
3377  * ## Animation Anchoring (via `ng-animate-ref`)
3378  *
3379  * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
3380  * structural areas of an application (like views) by pairing up elements using an attribute
3381  * called `ng-animate-ref`.
3382  *
3383  * Let's say for example we have two views that are managed by `ng-view` and we want to show
3384  * that there is a relationship between two components situated in within these views. By using the
3385  * `ng-animate-ref` attribute we can identify that the two components are paired together and we
3386  * can then attach an animation, which is triggered when the view changes.
3387  *
3388  * Say for example we have the following template code:
3389  *
3390  * ```html
3391  * <!-- index.html -->
3392  * <div ng-view class="view-animation">
3393  * </div>
3394  *
3395  * <!-- home.html -->
3396  * <a href="#/banner-page">
3397  *   <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
3398  * </a>
3399  *
3400  * <!-- banner-page.html -->
3401  * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
3402  * ```
3403  *
3404  * Now, when the view changes (once the link is clicked), ngAnimate will examine the
3405  * HTML contents to see if there is a match reference between any components in the view
3406  * that is leaving and the view that is entering. It will scan both the view which is being
3407  * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
3408  * contain a matching ref value.
3409  *
3410  * The two images match since they share the same ref value. ngAnimate will now create a
3411  * transport element (which is a clone of the first image element) and it will then attempt
3412  * to animate to the position of the second image element in the next view. For the animation to
3413  * work a special CSS class called `ng-anchor` will be added to the transported element.
3414  *
3415  * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
3416  * ngAnimate will handle the entire transition for us as well as the addition and removal of
3417  * any changes of CSS classes between the elements:
3418  *
3419  * ```css
3420  * .banner.ng-anchor {
3421  *   /&#42; this animation will last for 1 second since there are
3422  *          two phases to the animation (an `in` and an `out` phase) &#42;/
3423  *   transition:0.5s linear all;
3424  * }
3425  * ```
3426  *
3427  * We also **must** include animations for the views that are being entered and removed
3428  * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
3429  *
3430  * ```css
3431  * .view-animation.ng-enter, .view-animation.ng-leave {
3432  *   transition:0.5s linear all;
3433  *   position:fixed;
3434  *   left:0;
3435  *   top:0;
3436  *   width:100%;
3437  * }
3438  * .view-animation.ng-enter {
3439  *   transform:translateX(100%);
3440  * }
3441  * .view-animation.ng-leave,
3442  * .view-animation.ng-enter.ng-enter-active {
3443  *   transform:translateX(0%);
3444  * }
3445  * .view-animation.ng-leave.ng-leave-active {
3446  *   transform:translateX(-100%);
3447  * }
3448  * ```
3449  *
3450  * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
3451  * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
3452  * from its origin. Once that animation is over then the `in` stage occurs which animates the
3453  * element to its destination. The reason why there are two animations is to give enough time
3454  * for the enter animation on the new element to be ready.
3455  *
3456  * The example above sets up a transition for both the in and out phases, but we can also target the out or
3457  * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
3458  *
3459  * ```css
3460  * .banner.ng-anchor-out {
3461  *   transition: 0.5s linear all;
3462  *
3463  *   /&#42; the scale will be applied during the out animation,
3464  *          but will be animated away when the in animation runs &#42;/
3465  *   transform: scale(1.2);
3466  * }
3467  *
3468  * .banner.ng-anchor-in {
3469  *   transition: 1s linear all;
3470  * }
3471  * ```
3472  *
3473  *
3474  *
3475  *
3476  * ### Anchoring Demo
3477  *
3478   <example module="anchoringExample"
3479            name="anchoringExample"
3480            id="anchoringExample"
3481            deps="angular-animate.js;angular-route.js"
3482            animations="true">
3483     <file name="index.html">
3484       <a href="#/">Home</a>
3485       <hr />
3486       <div class="view-container">
3487         <div ng-view class="view"></div>
3488       </div>
3489     </file>
3490     <file name="script.js">
3491       angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
3492         .config(['$routeProvider', function($routeProvider) {
3493           $routeProvider.when('/', {
3494             templateUrl: 'home.html',
3495             controller: 'HomeController as home'
3496           });
3497           $routeProvider.when('/profile/:id', {
3498             templateUrl: 'profile.html',
3499             controller: 'ProfileController as profile'
3500           });
3501         }])
3502         .run(['$rootScope', function($rootScope) {
3503           $rootScope.records = [
3504             { id:1, title: "Miss Beulah Roob" },
3505             { id:2, title: "Trent Morissette" },
3506             { id:3, title: "Miss Ava Pouros" },
3507             { id:4, title: "Rod Pouros" },
3508             { id:5, title: "Abdul Rice" },
3509             { id:6, title: "Laurie Rutherford Sr." },
3510             { id:7, title: "Nakia McLaughlin" },
3511             { id:8, title: "Jordon Blanda DVM" },
3512             { id:9, title: "Rhoda Hand" },
3513             { id:10, title: "Alexandrea Sauer" }
3514           ];
3515         }])
3516         .controller('HomeController', [function() {
3517           //empty
3518         }])
3519         .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
3520           var index = parseInt($routeParams.id, 10);
3521           var record = $rootScope.records[index - 1];
3522
3523           this.title = record.title;
3524           this.id = record.id;
3525         }]);
3526     </file>
3527     <file name="home.html">
3528       <h2>Welcome to the home page</h1>
3529       <p>Please click on an element</p>
3530       <a class="record"
3531          ng-href="#/profile/{{ record.id }}"
3532          ng-animate-ref="{{ record.id }}"
3533          ng-repeat="record in records">
3534         {{ record.title }}
3535       </a>
3536     </file>
3537     <file name="profile.html">
3538       <div class="profile record" ng-animate-ref="{{ profile.id }}">
3539         {{ profile.title }}
3540       </div>
3541     </file>
3542     <file name="animations.css">
3543       .record {
3544         display:block;
3545         font-size:20px;
3546       }
3547       .profile {
3548         background:black;
3549         color:white;
3550         font-size:100px;
3551       }
3552       .view-container {
3553         position:relative;
3554       }
3555       .view-container > .view.ng-animate {
3556         position:absolute;
3557         top:0;
3558         left:0;
3559         width:100%;
3560         min-height:500px;
3561       }
3562       .view.ng-enter, .view.ng-leave,
3563       .record.ng-anchor {
3564         transition:0.5s linear all;
3565       }
3566       .view.ng-enter {
3567         transform:translateX(100%);
3568       }
3569       .view.ng-enter.ng-enter-active, .view.ng-leave {
3570         transform:translateX(0%);
3571       }
3572       .view.ng-leave.ng-leave-active {
3573         transform:translateX(-100%);
3574       }
3575       .record.ng-anchor-out {
3576         background:red;
3577       }
3578     </file>
3579   </example>
3580  *
3581  * ### How is the element transported?
3582  *
3583  * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
3584  * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
3585  * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
3586  * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
3587  * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
3588  * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
3589  * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
3590  * will become visible since the shim class will be removed.
3591  *
3592  * ### How is the morphing handled?
3593  *
3594  * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
3595  * what CSS classes differ between the starting element and the destination element. These different CSS classes
3596  * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
3597  * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
3598  * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
3599  * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
3600  * the cloned element is placed inside of root element which is likely close to the body element).
3601  *
3602  * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
3603  *
3604  *
3605  * ## Using $animate in your directive code
3606  *
3607  * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?
3608  * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's
3609  * imagine we have a greeting box that shows and hides itself when the data changes
3610  *
3611  * ```html
3612  * <greeting-box active="onOrOff">Hi there</greeting-box>
3613  * ```
3614  *
3615  * ```js
3616  * ngModule.directive('greetingBox', ['$animate', function($animate) {
3617  *   return function(scope, element, attrs) {
3618  *     attrs.$observe('active', function(value) {
3619  *       value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
3620  *     });
3621  *   });
3622  * }]);
3623  * ```
3624  *
3625  * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element
3626  * in our HTML code then we can trigger a CSS or JS animation to happen.
3627  *
3628  * ```css
3629  * /&#42; normally we would create a CSS class to reference on the element &#42;/
3630  * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
3631  * ```
3632  *
3633  * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
3634  * possible be sure to visit the {@link ng.$animate $animate service API page}.
3635  *
3636  *
3637  * ### Preventing Collisions With Third Party Libraries
3638  *
3639  * Some third-party frameworks place animation duration defaults across many element or className
3640  * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which
3641  * is expecting actual animations on these elements and has to wait for their completion.
3642  *
3643  * You can prevent this unwanted behavior by using a prefix on all your animation classes:
3644  *
3645  * ```css
3646  * /&#42; prefixed with animate- &#42;/
3647  * .animate-fade-add.animate-fade-add-active {
3648  *   transition:1s linear all;
3649  *   opacity:0;
3650  * }
3651  * ```
3652  *
3653  * You then configure `$animate` to enforce this prefix:
3654  *
3655  * ```js
3656  * $animateProvider.classNameFilter(/animate-/);
3657  * ```
3658  *
3659  * This also may provide your application with a speed boost since only specific elements containing CSS class prefix
3660  * will be evaluated for animation when any DOM changes occur in the application.
3661  *
3662  * ## Callbacks and Promises
3663  *
3664  * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger
3665  * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
3666  * ended by chaining onto the returned promise that animation method returns.
3667  *
3668  * ```js
3669  * // somewhere within the depths of the directive
3670  * $animate.enter(element, parent).then(function() {
3671  *   //the animation has completed
3672  * });
3673  * ```
3674  *
3675  * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
3676  * anymore.)
3677  *
3678  * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
3679  * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
3680  * routing controller to hook into that:
3681  *
3682  * ```js
3683  * ngModule.controller('HomePageController', ['$animate', function($animate) {
3684  *   $animate.on('enter', ngViewElement, function(element) {
3685  *     // the animation for this route has completed
3686  *   }]);
3687  * }])
3688  * ```
3689  *
3690  * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
3691  */
3692
3693 /**
3694  * @ngdoc service
3695  * @name $animate
3696  * @kind object
3697  *
3698  * @description
3699  * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
3700  *
3701  * Click here {@link ng.$animate $animate to learn more about animations with `$animate`}.
3702  */
3703 angular.module('ngAnimate', [])
3704   .directive('ngAnimateChildren', $$AnimateChildrenDirective)
3705
3706   .factory('$$rAFMutex', $$rAFMutexFactory)
3707   .factory('$$rAFScheduler', $$rAFSchedulerFactory)
3708
3709   .factory('$$AnimateRunner', $$AnimateRunnerFactory)
3710
3711   .provider('$$animateQueue', $$AnimateQueueProvider)
3712   .provider('$$animation', $$AnimationProvider)
3713
3714   .provider('$animateCss', $AnimateCssProvider)
3715   .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
3716
3717   .provider('$$animateJs', $$AnimateJsProvider)
3718   .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
3719
3720
3721 })(window, window.angular);