2 * @license AngularJS v1.5.8
3 * (c) 2010-2016 Google, Inc. http://angularjs.org
6 (function(window, angular) {'use strict';
11 var ADD_CLASS_SUFFIX = '-add';
12 var REMOVE_CLASS_SUFFIX = '-remove';
13 var EVENT_CLASS_PREFIX = 'ng-';
14 var ACTIVE_CLASS_SUFFIX = '-active';
15 var PREPARE_CLASS_SUFFIX = '-prepare';
17 var NG_ANIMATE_CLASSNAME = 'ng-animate';
18 var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
20 // Detect proper transitionend/animationend event names.
21 var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
23 // If unprefixed events are not supported but webkit-prefixed are, use the latter.
24 // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
25 // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
26 // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
27 // Register both events in case `window.onanimationend` is not supported because of that,
28 // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
29 // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
30 // therefore there is no reason to test anymore for other vendor prefixes:
31 // http://caniuse.com/#search=transition
32 if ((window.ontransitionend === void 0) && (window.onwebkittransitionend !== void 0)) {
33 CSS_PREFIX = '-webkit-';
34 TRANSITION_PROP = 'WebkitTransition';
35 TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
37 TRANSITION_PROP = 'transition';
38 TRANSITIONEND_EVENT = 'transitionend';
41 if ((window.onanimationend === void 0) && (window.onwebkitanimationend !== void 0)) {
42 CSS_PREFIX = '-webkit-';
43 ANIMATION_PROP = 'WebkitAnimation';
44 ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
46 ANIMATION_PROP = 'animation';
47 ANIMATIONEND_EVENT = 'animationend';
50 var DURATION_KEY = 'Duration';
51 var PROPERTY_KEY = 'Property';
52 var DELAY_KEY = 'Delay';
53 var TIMING_KEY = 'TimingFunction';
54 var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
55 var ANIMATION_PLAYSTATE_KEY = 'PlayState';
56 var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
58 var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
59 var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
60 var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
61 var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
63 var ngMinErr = angular.$$minErr('ng');
64 function assertArg(arg, name, reason) {
66 throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
71 function mergeClasses(a,b) {
72 if (!a && !b) return '';
75 if (isArray(a)) a = a.join(' ');
76 if (isArray(b)) b = b.join(' ');
80 function packageStyles(options) {
82 if (options && (options.to || options.from)) {
83 styles.to = options.to;
84 styles.from = options.from;
89 function pendClasses(classes, fix, isPrefix) {
91 classes = isArray(classes)
93 : classes && isString(classes) && classes.length
94 ? classes.split(/\s+/)
96 forEach(classes, function(klass, i) {
97 if (klass && klass.length > 0) {
98 className += (i > 0) ? ' ' : '';
99 className += isPrefix ? fix + klass
106 function removeFromArray(arr, val) {
107 var index = arr.indexOf(val);
109 arr.splice(index, 1);
113 function stripCommentsFromElement(element) {
114 if (element instanceof jqLite) {
115 switch (element.length) {
120 // there is no point of stripping anything if the element
121 // is the only element within the jqLite wrapper.
122 // (it's important that we retain the element instance.)
123 if (element[0].nodeType === ELEMENT_NODE) {
129 return jqLite(extractElementNode(element));
133 if (element.nodeType === ELEMENT_NODE) {
134 return jqLite(element);
138 function extractElementNode(element) {
139 if (!element[0]) return element;
140 for (var i = 0; i < element.length; i++) {
141 var elm = element[i];
142 if (elm.nodeType == ELEMENT_NODE) {
148 function $$addClass($$jqLite, element, className) {
149 forEach(element, function(elm) {
150 $$jqLite.addClass(elm, className);
154 function $$removeClass($$jqLite, element, className) {
155 forEach(element, function(elm) {
156 $$jqLite.removeClass(elm, className);
160 function applyAnimationClassesFactory($$jqLite) {
161 return function(element, options) {
162 if (options.addClass) {
163 $$addClass($$jqLite, element, options.addClass);
164 options.addClass = null;
166 if (options.removeClass) {
167 $$removeClass($$jqLite, element, options.removeClass);
168 options.removeClass = null;
173 function prepareAnimationOptions(options) {
174 options = options || {};
175 if (!options.$$prepared) {
176 var domOperation = options.domOperation || noop;
177 options.domOperation = function() {
178 options.$$domOperationFired = true;
182 options.$$prepared = true;
187 function applyAnimationStyles(element, options) {
188 applyAnimationFromStyles(element, options);
189 applyAnimationToStyles(element, options);
192 function applyAnimationFromStyles(element, options) {
194 element.css(options.from);
199 function applyAnimationToStyles(element, options) {
201 element.css(options.to);
206 function mergeAnimationDetails(element, oldAnimation, newAnimation) {
207 var target = oldAnimation.options || {};
208 var newOptions = newAnimation.options || {};
210 var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
211 var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
212 var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
214 if (newOptions.preparationClasses) {
215 target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);
216 delete newOptions.preparationClasses;
219 // noop is basically when there is no callback; otherwise something has been set
220 var realDomOperation = target.domOperation !== noop ? target.domOperation : null;
222 extend(target, newOptions);
224 // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.
225 if (realDomOperation) {
226 target.domOperation = realDomOperation;
229 if (classes.addClass) {
230 target.addClass = classes.addClass;
232 target.addClass = null;
235 if (classes.removeClass) {
236 target.removeClass = classes.removeClass;
238 target.removeClass = null;
241 oldAnimation.addClass = target.addClass;
242 oldAnimation.removeClass = target.removeClass;
247 function resolveElementClasses(existing, toAdd, toRemove) {
249 var REMOVE_CLASS = -1;
252 existing = splitClassesToLookup(existing);
254 toAdd = splitClassesToLookup(toAdd);
255 forEach(toAdd, function(value, key) {
256 flags[key] = ADD_CLASS;
259 toRemove = splitClassesToLookup(toRemove);
260 forEach(toRemove, function(value, key) {
261 flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
269 forEach(flags, function(val, klass) {
271 if (val === ADD_CLASS) {
273 allow = !existing[klass] || existing[klass + REMOVE_CLASS_SUFFIX];
274 } else if (val === REMOVE_CLASS) {
275 prop = 'removeClass';
276 allow = existing[klass] || existing[klass + ADD_CLASS_SUFFIX];
279 if (classes[prop].length) {
280 classes[prop] += ' ';
282 classes[prop] += klass;
286 function splitClassesToLookup(classes) {
287 if (isString(classes)) {
288 classes = classes.split(' ');
292 forEach(classes, function(klass) {
293 // sometimes the split leaves empty string values
294 // incase extra spaces were applied to the options
305 function getDomNode(element) {
306 return (element instanceof jqLite) ? element[0] : element;
309 function applyGeneratedPreparationClasses(element, event, options) {
312 classes = pendClasses(event, EVENT_CLASS_PREFIX, true);
314 if (options.addClass) {
315 classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));
317 if (options.removeClass) {
318 classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));
320 if (classes.length) {
321 options.preparationClasses = classes;
322 element.addClass(classes);
326 function clearGeneratedClasses(element, options) {
327 if (options.preparationClasses) {
328 element.removeClass(options.preparationClasses);
329 options.preparationClasses = null;
331 if (options.activeClasses) {
332 element.removeClass(options.activeClasses);
333 options.activeClasses = null;
337 function blockTransitions(node, duration) {
338 // we use a negative delay value since it performs blocking
339 // yet it doesn't kill any existing transitions running on the
340 // same element which makes this safe for class-based animations
341 var value = duration ? '-' + duration + 's' : '';
342 applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
343 return [TRANSITION_DELAY_PROP, value];
346 function blockKeyframeAnimations(node, applyBlock) {
347 var value = applyBlock ? 'paused' : '';
348 var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
349 applyInlineStyle(node, [key, value]);
353 function applyInlineStyle(node, styleTuple) {
354 var prop = styleTuple[0];
355 var value = styleTuple[1];
356 node.style[prop] = value;
359 function concatWithSpace(a,b) {
365 var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
368 function scheduler(tasks) {
369 // we make a copy since RAFScheduler mutates the state
370 // of the passed in array variable and this would be difficult
371 // to track down on the outside code
372 queue = queue.concat(tasks);
376 queue = scheduler.queue = [];
378 /* waitUntilQuiet does two things:
379 * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through
380 * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
382 * The motivation here is that animation code can request more time from the scheduler
383 * before the next wave runs. This allows for certain DOM properties such as classes to
384 * be resolved in time for the next animation to run.
386 scheduler.waitUntilQuiet = function(fn) {
387 if (cancelFn) cancelFn();
389 cancelFn = $$rAF(function() {
398 function nextTick() {
399 if (!queue.length) return;
401 var items = queue.shift();
402 for (var i = 0; i < items.length; i++) {
408 if (!cancelFn) nextTick();
416 * @name ngAnimateChildren
422 * ngAnimateChildren allows you to specify that children of this element should animate even if any
423 * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move`
424 * (structural) animation, child elements that also have an active structural animation are not animated.
426 * Note that even if `ngAnimteChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation).
429 * @param {string} ngAnimateChildren If the value is empty, `true` or `on`,
430 * then child animations are allowed. If the value is `false`, child animations are not allowed.
433 * <example module="ngAnimateChildren" name="ngAnimateChildren" deps="angular-animate.js" animations="true">
434 <file name="index.html">
435 <div ng-controller="mainController as main">
436 <label>Show container? <input type="checkbox" ng-model="main.enterElement" /></label>
437 <label>Animate children? <input type="checkbox" ng-model="main.animateChildren" /></label>
439 <div ng-animate-children="{{main.animateChildren}}">
440 <div ng-if="main.enterElement" class="container">
442 <div ng-repeat="item in [0, 1, 2, 3]" class="item">Item {{item}}</div>
447 <file name="animations.css">
450 .container.ng-leave {
451 transition: all ease 1.5s;
455 .container.ng-leave-active {
460 .container.ng-enter-active {
465 background: firebrick;
472 transition: transform 1.5s ease;
476 transform: translateX(50px);
479 .item.ng-enter-active {
480 transform: translateX(0);
483 <file name="script.js">
484 angular.module('ngAnimateChildren', ['ngAnimate'])
485 .controller('mainController', function() {
486 this.animateChildren = false;
487 this.enterElement = false;
492 var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) {
494 link: function(scope, element, attrs) {
495 var val = attrs.ngAnimateChildren;
496 if (isString(val) && val.length === 0) { //empty attribute
497 element.data(NG_ANIMATE_CHILDREN_DATA, true);
499 // Interpolate and set the value, so that it is available to
500 // animations that run right after compilation
501 setData($interpolate(val)(scope));
502 attrs.$observe('ngAnimateChildren', setData);
505 function setData(value) {
506 value = value === 'on' || value === 'true';
507 element.data(NG_ANIMATE_CHILDREN_DATA, value);
513 var ANIMATE_TIMER_KEY = '$$animateCss';
521 * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
522 * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
523 * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
524 * directives to create more complex animations that can be purely driven using CSS code.
526 * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
527 * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
530 * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
531 * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
532 * any automatic control over cancelling animations and/or preventing animations from being run on
533 * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
534 * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
537 * The example below shows how we can create a folding animation on an element using `ng-if`:
540 * <!-- notice the `fold-animation` CSS class -->
541 * <div ng-if="onOff" class="fold-animation">
542 * This element will go BOOM
544 * <button ng-click="onOff=true">Fold In</button>
547 * Now we create the **JavaScript animation** that will trigger the CSS transition:
550 * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
552 * enter: function(element, doneFn) {
553 * var height = element[0].offsetHeight;
554 * return $animateCss(element, {
555 * from: { height:'0px' },
556 * to: { height:height + 'px' },
557 * duration: 1 // one second
564 * ## More Advanced Uses
566 * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
567 * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
569 * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
570 * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
571 * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
572 * to provide a working animation that will run in CSS.
574 * The example below showcases a more advanced version of the `.fold-animation` from the example above:
577 * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
579 * enter: function(element, doneFn) {
580 * var height = element[0].offsetHeight;
581 * return $animateCss(element, {
582 * addClass: 'red large-text pulse-twice',
583 * easing: 'ease-out',
584 * from: { height:'0px' },
585 * to: { height:height + 'px' },
586 * duration: 1 // one second
593 * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
596 * /* since a hardcoded duration value of 1 was provided in the JavaScript animation code,
597 * the CSS classes below will be transitioned despite them being defined as regular CSS classes */
598 * .red { background:red; }
599 * .large-text { font-size:20px; }
601 * /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */
603 * animation: 0.5s pulse linear 2;
604 * -webkit-animation: 0.5s pulse linear 2;
608 * from { transform: scale(0.5); }
609 * to { transform: scale(1.5); }
612 * @-webkit-keyframes pulse {
613 * from { -webkit-transform: scale(0.5); }
614 * to { -webkit-transform: scale(1.5); }
618 * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
620 * ## How the Options are handled
622 * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
623 * 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
624 * styles using the `from` and `to` properties.
627 * var animator = $animateCss(element, {
628 * from: { background:'red' },
629 * to: { background:'blue' }
635 * .rotating-animation {
636 * animation:0.5s rotate linear;
637 * -webkit-animation:0.5s rotate linear;
640 * @keyframes rotate {
641 * from { transform: rotate(0deg); }
642 * to { transform: rotate(360deg); }
645 * @-webkit-keyframes rotate {
646 * from { -webkit-transform: rotate(0deg); }
647 * to { -webkit-transform: rotate(360deg); }
651 * 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
652 * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
653 * 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
654 * 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
655 * and spread across the transition and keyframe animation.
657 * ## What is returned
659 * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
660 * 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
661 * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
664 * var animator = $animateCss(element, { ... });
667 * Now what do the contents of our `animator` variable look like:
671 * // starts the animation
674 * // ends (aborts) the animation
679 * 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.
680 * 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 styles may have been
681 * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
682 * and that changing them will not reconfigure the parameters of the animation.
684 * ### runner.done() vs runner.then()
685 * 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
686 * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
687 * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
688 * unless you really need a digest to kick off afterwards.
690 * 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
691 * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
692 * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
694 * @param {DOMElement} element the element that will be animated
695 * @param {object} options the animation-related options that will be applied during the animation
697 * * `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
698 * 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.)
699 * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
700 * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
701 * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
702 * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
703 * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
704 * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
705 * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
706 * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
707 * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
708 * * `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`
709 * is provided then the animation will be skipped entirely.
710 * * `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
711 * 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
712 * 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
714 * * `stagger` - A numeric time value representing the delay between successively animated elements
715 * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
716 * * `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
717 * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
718 * * `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 occurring on the classes being added and removed.)
719 * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
720 * the animation is closed. This is useful for when the styles are used purely for the sake of
721 * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation).
722 * By default this value is set to `false`.
724 * @return {object} an object with start and end methods and details about the animation.
726 * * `start` - The method to start the animation. This will return a `Promise` when called.
727 * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
729 var ONE_SECOND = 1000;
732 var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
733 var CLOSING_TIME_BUFFER = 1.5;
735 var DETECT_CSS_PROPERTIES = {
736 transitionDuration: TRANSITION_DURATION_PROP,
737 transitionDelay: TRANSITION_DELAY_PROP,
738 transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
739 animationDuration: ANIMATION_DURATION_PROP,
740 animationDelay: ANIMATION_DELAY_PROP,
741 animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
744 var DETECT_STAGGER_CSS_PROPERTIES = {
745 transitionDuration: TRANSITION_DURATION_PROP,
746 transitionDelay: TRANSITION_DELAY_PROP,
747 animationDuration: ANIMATION_DURATION_PROP,
748 animationDelay: ANIMATION_DELAY_PROP
751 function getCssKeyframeDurationStyle(duration) {
752 return [ANIMATION_DURATION_PROP, duration + 's'];
755 function getCssDelayStyle(delay, isKeyframeAnimation) {
756 var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
757 return [prop, delay + 's'];
760 function computeCssStyles($window, element, properties) {
761 var styles = Object.create(null);
762 var detectedStyles = $window.getComputedStyle(element) || {};
763 forEach(properties, function(formalStyleName, actualStyleName) {
764 var val = detectedStyles[formalStyleName];
766 var c = val.charAt(0);
768 // only numerical-based values have a negative sign or digit as the first value
769 if (c === '-' || c === '+' || c >= 0) {
770 val = parseMaxTime(val);
773 // by setting this to null in the event that the delay is not set or is set directly as 0
774 // then we can still allow for negative values to be used later on and not mistake this
775 // value for being greater than any other negative value.
779 styles[actualStyleName] = val;
786 function parseMaxTime(str) {
788 var values = str.split(/\s*,\s*/);
789 forEach(values, function(value) {
790 // it's always safe to consider only second values and omit `ms` values since
791 // getComputedStyle will always handle the conversion for us
792 if (value.charAt(value.length - 1) == 's') {
793 value = value.substring(0, value.length - 1);
795 value = parseFloat(value) || 0;
796 maxValue = maxValue ? Math.max(value, maxValue) : value;
801 function truthyTimingValue(val) {
802 return val === 0 || val != null;
805 function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
806 var style = TRANSITION_PROP;
807 var value = duration + 's';
808 if (applyOnlyDuration) {
809 style += DURATION_KEY;
811 value += ' linear all';
813 return [style, value];
816 function createLocalCacheLookup() {
817 var cache = Object.create(null);
820 cache = Object.create(null);
823 count: function(key) {
824 var entry = cache[key];
825 return entry ? entry.total : 0;
829 var entry = cache[key];
830 return entry && entry.value;
833 put: function(key, value) {
835 cache[key] = { total: 1, value: value };
843 // we do not reassign an already present style value since
844 // if we detect the style property value again we may be
845 // detecting styles that were added via the `from` styles.
846 // We make use of `isDefined` here since an empty string
847 // or null value (which is what getPropertyValue will return
848 // for a non-existing style) will still be marked as a valid
849 // value for the style (a falsy value implies that the style
850 // is to be removed at the end of the animation). If we had a simple
851 // "OR" statement then it would not be enough to catch that.
852 function registerRestorableStyles(backup, node, properties) {
853 forEach(properties, function(prop) {
854 backup[prop] = isDefined(backup[prop])
856 : node.style.getPropertyValue(prop);
860 var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
861 var gcsLookup = createLocalCacheLookup();
862 var gcsStaggerLookup = createLocalCacheLookup();
864 this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
865 '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue',
866 function($window, $$jqLite, $$AnimateRunner, $timeout,
867 $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) {
869 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
871 var parentCounter = 0;
872 function gcsHashFn(node, extraClasses) {
873 var KEY = "$$ngAnimateParentKey";
874 var parentNode = node.parentNode;
875 var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
876 return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
879 function computeCachedCssStyles(node, className, cacheKey, properties) {
880 var timings = gcsLookup.get(cacheKey);
883 timings = computeCssStyles($window, node, properties);
884 if (timings.animationIterationCount === 'infinite') {
885 timings.animationIterationCount = 1;
889 // we keep putting this in multiple times even though the value and the cacheKey are the same
890 // because we're keeping an internal tally of how many duplicate animations are detected.
891 gcsLookup.put(cacheKey, timings);
895 function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
898 // if we have one or more existing matches of matching elements
899 // containing the same parent + CSS styles (which is how cacheKey works)
900 // then staggering is possible
901 if (gcsLookup.count(cacheKey) > 0) {
902 stagger = gcsStaggerLookup.get(cacheKey);
905 var staggerClassName = pendClasses(className, '-stagger');
907 $$jqLite.addClass(node, staggerClassName);
909 stagger = computeCssStyles($window, node, properties);
911 // force the conversion of a null value to zero incase not set
912 stagger.animationDuration = Math.max(stagger.animationDuration, 0);
913 stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
915 $$jqLite.removeClass(node, staggerClassName);
917 gcsStaggerLookup.put(cacheKey, stagger);
921 return stagger || {};
924 var cancelLastRAFRequest;
925 var rafWaitQueue = [];
926 function waitUntilQuiet(callback) {
927 rafWaitQueue.push(callback);
928 $$rAFScheduler.waitUntilQuiet(function() {
930 gcsStaggerLookup.flush();
932 // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
933 // PLEASE EXAMINE THE `$$forceReflow` service to understand why.
934 var pageWidth = $$forceReflow();
936 // we use a for loop to ensure that if the queue is changed
937 // during this looping then it will consider new requests
938 for (var i = 0; i < rafWaitQueue.length; i++) {
939 rafWaitQueue[i](pageWidth);
941 rafWaitQueue.length = 0;
945 function computeTimings(node, className, cacheKey) {
946 var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
947 var aD = timings.animationDelay;
948 var tD = timings.transitionDelay;
949 timings.maxDelay = aD && tD
952 timings.maxDuration = Math.max(
953 timings.animationDuration * timings.animationIterationCount,
954 timings.transitionDuration);
959 return function init(element, initialOptions) {
960 // all of the animation functions should create
961 // a copy of the options data, however, if a
962 // parent service has already created a copy then
963 // we should stick to using that
964 var options = initialOptions || {};
965 if (!options.$$prepared) {
966 options = prepareAnimationOptions(copy(options));
969 var restoreStyles = {};
970 var node = getDomNode(element);
973 || !$$animateQueue.enabled()) {
974 return closeAndReturnNoopAnimator();
977 var temporaryStyles = [];
978 var classes = element.attr('class');
979 var styles = packageStyles(options);
982 var animationCompleted;
992 if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
993 return closeAndReturnNoopAnimator();
996 var method = options.event && isArray(options.event)
997 ? options.event.join(' ')
1000 var isStructural = method && options.structural;
1001 var structuralClassName = '';
1002 var addRemoveClassName = '';
1005 structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
1006 } else if (method) {
1007 structuralClassName = method;
1010 if (options.addClass) {
1011 addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
1014 if (options.removeClass) {
1015 if (addRemoveClassName.length) {
1016 addRemoveClassName += ' ';
1018 addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
1021 // there may be a situation where a structural animation is combined together
1022 // with CSS classes that need to resolve before the animation is computed.
1023 // However this means that there is no explicit CSS code to block the animation
1024 // from happening (by setting 0s none in the class name). If this is the case
1025 // we need to apply the classes before the first rAF so we know to continue if
1026 // there actually is a detected transition or keyframe animation
1027 if (options.applyClassesEarly && addRemoveClassName.length) {
1028 applyAnimationClasses(element, options);
1031 var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
1032 var fullClassName = classes + ' ' + preparationClasses;
1033 var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
1034 var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
1035 var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
1037 // there is no way we can trigger an animation if no styles and
1038 // no classes are being applied which would then trigger a transition,
1039 // unless there a is raw keyframe value that is applied to the element.
1040 if (!containsKeyframeAnimation
1042 && !preparationClasses) {
1043 return closeAndReturnNoopAnimator();
1046 var cacheKey, stagger;
1047 if (options.stagger > 0) {
1048 var staggerVal = parseFloat(options.stagger);
1050 transitionDelay: staggerVal,
1051 animationDelay: staggerVal,
1052 transitionDuration: 0,
1053 animationDuration: 0
1056 cacheKey = gcsHashFn(node, fullClassName);
1057 stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
1060 if (!options.$$skipPreparationClasses) {
1061 $$jqLite.addClass(element, preparationClasses);
1064 var applyOnlyDuration;
1066 if (options.transitionStyle) {
1067 var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
1068 applyInlineStyle(node, transitionStyle);
1069 temporaryStyles.push(transitionStyle);
1072 if (options.duration >= 0) {
1073 applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
1074 var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
1076 // we set the duration so that it will be picked up by getComputedStyle later
1077 applyInlineStyle(node, durationStyle);
1078 temporaryStyles.push(durationStyle);
1081 if (options.keyframeStyle) {
1082 var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
1083 applyInlineStyle(node, keyframeStyle);
1084 temporaryStyles.push(keyframeStyle);
1087 var itemIndex = stagger
1088 ? options.staggerIndex >= 0
1089 ? options.staggerIndex
1090 : gcsLookup.count(cacheKey)
1093 var isFirst = itemIndex === 0;
1095 // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
1096 // without causing any combination of transitions to kick in. By adding a negative delay value
1097 // it forces the setup class' transition to end immediately. We later then remove the negative
1098 // transition delay to allow for the transition to naturally do it's thing. The beauty here is
1099 // that if there is no transition defined then nothing will happen and this will also allow
1100 // other transitions to be stacked on top of each other without any chopping them out.
1101 if (isFirst && !options.skipBlocking) {
1102 blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
1105 var timings = computeTimings(node, fullClassName, cacheKey);
1106 var relativeDelay = timings.maxDelay;
1107 maxDelay = Math.max(relativeDelay, 0);
1108 maxDuration = timings.maxDuration;
1111 flags.hasTransitions = timings.transitionDuration > 0;
1112 flags.hasAnimations = timings.animationDuration > 0;
1113 flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
1114 flags.applyTransitionDuration = hasToStyles && (
1115 (flags.hasTransitions && !flags.hasTransitionAll)
1116 || (flags.hasAnimations && !flags.hasTransitions));
1117 flags.applyAnimationDuration = options.duration && flags.hasAnimations;
1118 flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
1119 flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
1120 flags.recalculateTimingStyles = addRemoveClassName.length > 0;
1122 if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
1123 maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
1125 if (flags.applyTransitionDuration) {
1126 flags.hasTransitions = true;
1127 timings.transitionDuration = maxDuration;
1128 applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
1129 temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
1132 if (flags.applyAnimationDuration) {
1133 flags.hasAnimations = true;
1134 timings.animationDuration = maxDuration;
1135 temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
1139 if (maxDuration === 0 && !flags.recalculateTimingStyles) {
1140 return closeAndReturnNoopAnimator();
1143 if (options.delay != null) {
1145 if (typeof options.delay !== "boolean") {
1146 delayStyle = parseFloat(options.delay);
1147 // number in options.delay means we have to recalculate the delay for the closing timeout
1148 maxDelay = Math.max(delayStyle, 0);
1151 if (flags.applyTransitionDelay) {
1152 temporaryStyles.push(getCssDelayStyle(delayStyle));
1155 if (flags.applyAnimationDelay) {
1156 temporaryStyles.push(getCssDelayStyle(delayStyle, true));
1160 // we need to recalculate the delay value since we used a pre-emptive negative
1161 // delay value and the delay value is required for the final event checking. This
1162 // property will ensure that this will happen after the RAF phase has passed.
1163 if (options.duration == null && timings.transitionDuration > 0) {
1164 flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
1167 maxDelayTime = maxDelay * ONE_SECOND;
1168 maxDurationTime = maxDuration * ONE_SECOND;
1169 if (!options.skipBlocking) {
1170 flags.blockTransition = timings.transitionDuration > 0;
1171 flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
1172 stagger.animationDelay > 0 &&
1173 stagger.animationDuration === 0;
1177 if (options.cleanupStyles) {
1178 registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
1180 applyAnimationFromStyles(element, options);
1183 if (flags.blockTransition || flags.blockKeyframeAnimation) {
1184 applyBlocking(maxDuration);
1185 } else if (!options.skipBlocking) {
1186 blockTransitions(node, false);
1189 // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
1191 $$willAnimate: true,
1194 if (animationClosed) return;
1199 resume: null, //this will be set during the start() phase
1203 runner = new $$AnimateRunner(runnerHost);
1205 waitUntilQuiet(start);
1207 // we don't have access to pause/resume the animation
1208 // since it hasn't run yet. AnimateRunner will therefore
1209 // set noop functions for resume and pause and they will
1210 // later be overridden once the animation is triggered
1219 function cancelFn() {
1223 function close(rejected) { // jshint ignore:line
1224 // if the promise has been called already then we shouldn't close
1225 // the animation again
1226 if (animationClosed || (animationCompleted && animationPaused)) return;
1227 animationClosed = true;
1228 animationPaused = false;
1230 if (!options.$$skipPreparationClasses) {
1231 $$jqLite.removeClass(element, preparationClasses);
1233 $$jqLite.removeClass(element, activeClasses);
1235 blockKeyframeAnimations(node, false);
1236 blockTransitions(node, false);
1238 forEach(temporaryStyles, function(entry) {
1239 // There is only one way to remove inline style properties entirely from elements.
1240 // By using `removeProperty` this works, but we need to convert camel-cased CSS
1241 // styles down to hyphenated values.
1242 node.style[entry[0]] = '';
1245 applyAnimationClasses(element, options);
1246 applyAnimationStyles(element, options);
1248 if (Object.keys(restoreStyles).length) {
1249 forEach(restoreStyles, function(value, prop) {
1250 value ? node.style.setProperty(prop, value)
1251 : node.style.removeProperty(prop);
1255 // the reason why we have this option is to allow a synchronous closing callback
1256 // that is fired as SOON as the animation ends (when the CSS is removed) or if
1257 // the animation never takes off at all. A good example is a leave animation since
1258 // the element must be removed just after the animation is over or else the element
1259 // will appear on screen for one animation frame causing an overbearing flicker.
1260 if (options.onDone) {
1264 if (events && events.length) {
1265 // Remove the transitionend / animationend listener(s)
1266 element.off(events.join(' '), onAnimationProgress);
1269 //Cancel the fallback closing timeout and remove the timer data
1270 var animationTimerData = element.data(ANIMATE_TIMER_KEY);
1271 if (animationTimerData) {
1272 $timeout.cancel(animationTimerData[0].timer);
1273 element.removeData(ANIMATE_TIMER_KEY);
1276 // if the preparation function fails then the promise is not setup
1278 runner.complete(!rejected);
1282 function applyBlocking(duration) {
1283 if (flags.blockTransition) {
1284 blockTransitions(node, duration);
1287 if (flags.blockKeyframeAnimation) {
1288 blockKeyframeAnimations(node, !!duration);
1292 function closeAndReturnNoopAnimator() {
1293 runner = new $$AnimateRunner({
1298 // should flush the cache animation
1299 waitUntilQuiet(noop);
1303 $$willAnimate: false,
1311 function onAnimationProgress(event) {
1312 event.stopPropagation();
1313 var ev = event.originalEvent || event;
1315 // we now always use `Date.now()` due to the recent changes with
1316 // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info)
1317 var timeStamp = ev.$manualTimeStamp || Date.now();
1319 /* Firefox (or possibly just Gecko) likes to not round values up
1320 * when a ms measurement is used for the animation */
1321 var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
1323 /* $manualTimeStamp is a mocked timeStamp value which is set
1324 * within browserTrigger(). This is only here so that tests can
1325 * mock animations properly. Real events fallback to event.timeStamp,
1326 * or, if they don't, then a timeStamp is automatically created for them.
1327 * We're checking to see if the timeStamp surpasses the expected delay,
1328 * but we're using elapsedTime instead of the timeStamp on the 2nd
1329 * pre-condition since animationPauseds sometimes close off early */
1330 if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
1331 // we set this flag to ensure that if the transition is paused then, when resumed,
1332 // the animation will automatically close itself since transitions cannot be paused.
1333 animationCompleted = true;
1339 if (animationClosed) return;
1340 if (!node.parentNode) {
1345 // even though we only pause keyframe animations here the pause flag
1346 // will still happen when transitions are used. Only the transition will
1347 // not be paused since that is not possible. If the animation ends when
1348 // paused then it will not complete until unpaused or cancelled.
1349 var playPause = function(playAnimation) {
1350 if (!animationCompleted) {
1351 animationPaused = !playAnimation;
1352 if (timings.animationDuration) {
1353 var value = blockKeyframeAnimations(node, animationPaused);
1355 ? temporaryStyles.push(value)
1356 : removeFromArray(temporaryStyles, value);
1358 } else if (animationPaused && playAnimation) {
1359 animationPaused = false;
1364 // checking the stagger duration prevents an accidentally cascade of the CSS delay style
1365 // being inherited from the parent. If the transition duration is zero then we can safely
1366 // rely that the delay value is an intentional stagger delay style.
1367 var maxStagger = itemIndex > 0
1368 && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
1369 (timings.animationDuration && stagger.animationDuration === 0))
1370 && Math.max(stagger.animationDelay, stagger.transitionDelay);
1372 $timeout(triggerAnimationStart,
1373 Math.floor(maxStagger * itemIndex * ONE_SECOND),
1376 triggerAnimationStart();
1379 // this will decorate the existing promise runner with pause/resume methods
1380 runnerHost.resume = function() {
1384 runnerHost.pause = function() {
1388 function triggerAnimationStart() {
1389 // just incase a stagger animation kicks in when the animation
1390 // itself was cancelled entirely
1391 if (animationClosed) return;
1393 applyBlocking(false);
1395 forEach(temporaryStyles, function(entry) {
1397 var value = entry[1];
1398 node.style[key] = value;
1401 applyAnimationClasses(element, options);
1402 $$jqLite.addClass(element, activeClasses);
1404 if (flags.recalculateTimingStyles) {
1405 fullClassName = node.className + ' ' + preparationClasses;
1406 cacheKey = gcsHashFn(node, fullClassName);
1408 timings = computeTimings(node, fullClassName, cacheKey);
1409 relativeDelay = timings.maxDelay;
1410 maxDelay = Math.max(relativeDelay, 0);
1411 maxDuration = timings.maxDuration;
1413 if (maxDuration === 0) {
1418 flags.hasTransitions = timings.transitionDuration > 0;
1419 flags.hasAnimations = timings.animationDuration > 0;
1422 if (flags.applyAnimationDelay) {
1423 relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
1424 ? parseFloat(options.delay)
1427 maxDelay = Math.max(relativeDelay, 0);
1428 timings.animationDelay = relativeDelay;
1429 delayStyle = getCssDelayStyle(relativeDelay, true);
1430 temporaryStyles.push(delayStyle);
1431 node.style[delayStyle[0]] = delayStyle[1];
1434 maxDelayTime = maxDelay * ONE_SECOND;
1435 maxDurationTime = maxDuration * ONE_SECOND;
1437 if (options.easing) {
1438 var easeProp, easeVal = options.easing;
1439 if (flags.hasTransitions) {
1440 easeProp = TRANSITION_PROP + TIMING_KEY;
1441 temporaryStyles.push([easeProp, easeVal]);
1442 node.style[easeProp] = easeVal;
1444 if (flags.hasAnimations) {
1445 easeProp = ANIMATION_PROP + TIMING_KEY;
1446 temporaryStyles.push([easeProp, easeVal]);
1447 node.style[easeProp] = easeVal;
1451 if (timings.transitionDuration) {
1452 events.push(TRANSITIONEND_EVENT);
1455 if (timings.animationDuration) {
1456 events.push(ANIMATIONEND_EVENT);
1459 startTime = Date.now();
1460 var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
1461 var endTime = startTime + timerTime;
1463 var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
1464 var setupFallbackTimer = true;
1465 if (animationsData.length) {
1466 var currentTimerData = animationsData[0];
1467 setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
1468 if (setupFallbackTimer) {
1469 $timeout.cancel(currentTimerData.timer);
1471 animationsData.push(close);
1475 if (setupFallbackTimer) {
1476 var timer = $timeout(onAnimationExpired, timerTime, false);
1477 animationsData[0] = {
1479 expectedEndTime: endTime
1481 animationsData.push(close);
1482 element.data(ANIMATE_TIMER_KEY, animationsData);
1485 if (events.length) {
1486 element.on(events.join(' '), onAnimationProgress);
1490 if (options.cleanupStyles) {
1491 registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
1493 applyAnimationToStyles(element, options);
1497 function onAnimationExpired() {
1498 var animationsData = element.data(ANIMATE_TIMER_KEY);
1500 // this will be false in the event that the element was
1501 // removed from the DOM (via a leave animation or something
1503 if (animationsData) {
1504 for (var i = 1; i < animationsData.length; i++) {
1505 animationsData[i]();
1507 element.removeData(ANIMATE_TIMER_KEY);
1515 var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
1516 $$animationProvider.drivers.push('$$animateCssDriver');
1518 var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
1519 var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
1521 var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
1522 var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
1524 function isDocumentFragment(node) {
1525 return node.parentNode && node.parentNode.nodeType === 11;
1528 this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',
1529 function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) {
1531 // only browsers that support these properties can render animations
1532 if (!$sniffer.animations && !$sniffer.transitions) return noop;
1534 var bodyNode = $document[0].body;
1535 var rootNode = getDomNode($rootElement);
1537 var rootBodyElement = jqLite(
1538 // this is to avoid using something that exists outside of the body
1539 // we also special case the doc fragment case because our unit test code
1540 // appends the $rootElement to the body after the app has been bootstrapped
1541 isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode
1544 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
1546 return function initDriverFn(animationDetails) {
1547 return animationDetails.from && animationDetails.to
1548 ? prepareFromToAnchorAnimation(animationDetails.from,
1549 animationDetails.to,
1550 animationDetails.classes,
1551 animationDetails.anchors)
1552 : prepareRegularAnimation(animationDetails);
1555 function filterCssClasses(classes) {
1556 //remove all the `ng-` stuff
1557 return classes.replace(/\bng-\S+\b/g, '');
1560 function getUniqueValues(a, b) {
1561 if (isString(a)) a = a.split(' ');
1562 if (isString(b)) b = b.split(' ');
1563 return a.filter(function(val) {
1564 return b.indexOf(val) === -1;
1568 function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
1569 var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
1570 var startingClasses = filterCssClasses(getClassVal(clone));
1572 outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
1573 inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
1575 clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
1577 rootBodyElement.append(clone);
1579 var animatorIn, animatorOut = prepareOutAnimation();
1581 // the user may not end up using the `out` animation and
1582 // only making use of the `in` animation or vice-versa.
1583 // In either case we should allow this and not assume the
1584 // animation is over unless both animations are not used.
1586 animatorIn = prepareInAnimation();
1592 var startingAnimator = animatorOut || animatorIn;
1598 var currentAnimation = startingAnimator.start();
1599 currentAnimation.done(function() {
1600 currentAnimation = null;
1602 animatorIn = prepareInAnimation();
1604 currentAnimation = animatorIn.start();
1605 currentAnimation.done(function() {
1606 currentAnimation = null;
1610 return currentAnimation;
1613 // in the event that there is no `in` animation
1618 runner = new $$AnimateRunner({
1626 if (currentAnimation) {
1627 currentAnimation.end();
1633 function calculateAnchorStyles(anchor) {
1636 var coords = getDomNode(anchor).getBoundingClientRect();
1638 // we iterate directly since safari messes up and doesn't return
1639 // all the keys for the coords object when iterated
1640 forEach(['width','height','top','left'], function(key) {
1641 var value = coords[key];
1644 value += bodyNode.scrollTop;
1647 value += bodyNode.scrollLeft;
1650 styles[key] = Math.floor(value) + 'px';
1655 function prepareOutAnimation() {
1656 var animator = $animateCss(clone, {
1657 addClass: NG_OUT_ANCHOR_CLASS_NAME,
1659 from: calculateAnchorStyles(outAnchor)
1662 // read the comment within `prepareRegularAnimation` to understand
1663 // why this check is necessary
1664 return animator.$$willAnimate ? animator : null;
1667 function getClassVal(element) {
1668 return element.attr('class') || '';
1671 function prepareInAnimation() {
1672 var endingClasses = filterCssClasses(getClassVal(inAnchor));
1673 var toAdd = getUniqueValues(endingClasses, startingClasses);
1674 var toRemove = getUniqueValues(startingClasses, endingClasses);
1676 var animator = $animateCss(clone, {
1677 to: calculateAnchorStyles(inAnchor),
1678 addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
1679 removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
1683 // read the comment within `prepareRegularAnimation` to understand
1684 // why this check is necessary
1685 return animator.$$willAnimate ? animator : null;
1690 outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
1691 inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
1695 function prepareFromToAnchorAnimation(from, to, classes, anchors) {
1696 var fromAnimation = prepareRegularAnimation(from, noop);
1697 var toAnimation = prepareRegularAnimation(to, noop);
1699 var anchorAnimations = [];
1700 forEach(anchors, function(anchor) {
1701 var outElement = anchor['out'];
1702 var inElement = anchor['in'];
1703 var animator = prepareAnchoredAnimation(classes, outElement, inElement);
1705 anchorAnimations.push(animator);
1709 // no point in doing anything when there are no elements to animate
1710 if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
1714 var animationRunners = [];
1716 if (fromAnimation) {
1717 animationRunners.push(fromAnimation.start());
1721 animationRunners.push(toAnimation.start());
1724 forEach(anchorAnimations, function(animation) {
1725 animationRunners.push(animation.start());
1728 var runner = new $$AnimateRunner({
1730 cancel: endFn // CSS-driven animations cannot be cancelled, only ended
1733 $$AnimateRunner.all(animationRunners, function(status) {
1734 runner.complete(status);
1740 forEach(animationRunners, function(runner) {
1748 function prepareRegularAnimation(animationDetails) {
1749 var element = animationDetails.element;
1750 var options = animationDetails.options || {};
1752 if (animationDetails.structural) {
1753 options.event = animationDetails.event;
1754 options.structural = true;
1755 options.applyClassesEarly = true;
1757 // we special case the leave animation since we want to ensure that
1758 // the element is removed as soon as the animation is over. Otherwise
1759 // a flicker might appear or the element may not be removed at all
1760 if (animationDetails.event === 'leave') {
1761 options.onDone = options.domOperation;
1765 // We assign the preparationClasses as the actual animation event since
1766 // the internals of $animateCss will just suffix the event token values
1767 // with `-active` to trigger the animation.
1768 if (options.preparationClasses) {
1769 options.event = concatWithSpace(options.event, options.preparationClasses);
1772 var animator = $animateCss(element, options);
1774 // the driver lookup code inside of $$animation attempts to spawn a
1775 // driver one by one until a driver returns a.$$willAnimate animator object.
1776 // $animateCss will always return an object, however, it will pass in
1777 // a flag as a hint as to whether an animation was detected or not
1778 return animator.$$willAnimate ? animator : null;
1783 // TODO(matsko): use caching here to speed things up for detection
1784 // TODO(matsko): add documentation
1787 var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
1788 this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
1789 function($injector, $$AnimateRunner, $$jqLite) {
1791 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
1792 // $animateJs(element, 'enter');
1793 return function(element, event, classes, options) {
1794 var animationClosed = false;
1796 // the `classes` argument is optional and if it is not used
1797 // then the classes will be resolved from the element's className
1798 // property as well as options.addClass/options.removeClass.
1799 if (arguments.length === 3 && isObject(classes)) {
1804 options = prepareAnimationOptions(options);
1806 classes = element.attr('class') || '';
1807 if (options.addClass) {
1808 classes += ' ' + options.addClass;
1810 if (options.removeClass) {
1811 classes += ' ' + options.removeClass;
1815 var classesToAdd = options.addClass;
1816 var classesToRemove = options.removeClass;
1818 // the lookupAnimations function returns a series of animation objects that are
1819 // matched up with one or more of the CSS classes. These animation objects are
1820 // defined via the module.animation factory function. If nothing is detected then
1821 // we don't return anything which then makes $animation query the next driver.
1822 var animations = lookupAnimations(classes);
1824 if (animations.length) {
1825 var afterFn, beforeFn;
1826 if (event == 'leave') {
1828 afterFn = 'afterLeave'; // TODO(matsko): get rid of this
1830 beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
1834 if (event !== 'enter' && event !== 'move') {
1835 before = packageAnimations(element, event, options, animations, beforeFn);
1837 after = packageAnimations(element, event, options, animations, afterFn);
1840 // no matching animations
1841 if (!before && !after) return;
1843 function applyOptions() {
1844 options.domOperation();
1845 applyAnimationClasses(element, options);
1849 animationClosed = true;
1851 applyAnimationStyles(element, options);
1857 $$willAnimate: true,
1863 runner = new $$AnimateRunner();
1864 runner.complete(true);
1873 runner = new $$AnimateRunner();
1874 var closeActiveAnimations;
1878 chain.push(function(fn) {
1879 closeActiveAnimations = before(fn);
1884 chain.push(function(fn) {
1893 chain.push(function(fn) {
1894 closeActiveAnimations = after(fn);
1902 cancel: function() {
1903 endAnimations(true);
1907 $$AnimateRunner.chain(chain, onComplete);
1910 function onComplete(success) {
1912 runner.complete(success);
1915 function endAnimations(cancelled) {
1916 if (!animationClosed) {
1917 (closeActiveAnimations || noop)(cancelled);
1918 onComplete(cancelled);
1924 function executeAnimationFn(fn, element, event, options, onDone) {
1928 args = [element, options.from, options.to, onDone];
1932 args = [element, classesToAdd, classesToRemove, onDone];
1936 args = [element, classesToAdd, onDone];
1940 args = [element, classesToRemove, onDone];
1944 args = [element, onDone];
1950 var value = fn.apply(fn, args);
1952 if (isFunction(value.start)) {
1953 value = value.start();
1956 if (value instanceof $$AnimateRunner) {
1958 } else if (isFunction(value)) {
1959 // optional onEnd / onCancel callback
1967 function groupEventedAnimations(element, event, options, animations, fnName) {
1968 var operations = [];
1969 forEach(animations, function(ani) {
1970 var animation = ani[fnName];
1971 if (!animation) return;
1973 // note that all of these animations will run in parallel
1974 operations.push(function() {
1978 var resolved = false;
1979 var onAnimationComplete = function(rejected) {
1982 (endProgressCb || noop)(rejected);
1983 runner.complete(!rejected);
1987 runner = new $$AnimateRunner({
1989 onAnimationComplete();
1991 cancel: function() {
1992 onAnimationComplete(true);
1996 endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
1997 var cancelled = result === false;
1998 onAnimationComplete(cancelled);
2008 function packageAnimations(element, event, options, animations, fnName) {
2009 var operations = groupEventedAnimations(element, event, options, animations, fnName);
2010 if (operations.length === 0) {
2012 if (fnName === 'beforeSetClass') {
2013 a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
2014 b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
2015 } else if (fnName === 'setClass') {
2016 a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
2017 b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
2021 operations = operations.concat(a);
2024 operations = operations.concat(b);
2028 if (operations.length === 0) return;
2030 // TODO(matsko): add documentation
2031 return function startAnimation(callback) {
2033 if (operations.length) {
2034 forEach(operations, function(animateFn) {
2035 runners.push(animateFn());
2039 runners.length ? $$AnimateRunner.all(runners, callback) : callback();
2041 return function endFn(reject) {
2042 forEach(runners, function(runner) {
2043 reject ? runner.cancel() : runner.end();
2050 function lookupAnimations(classes) {
2051 classes = isArray(classes) ? classes : classes.split(' ');
2052 var matches = [], flagMap = {};
2053 for (var i=0; i < classes.length; i++) {
2054 var klass = classes[i],
2055 animationFactory = $animateProvider.$$registeredAnimations[klass];
2056 if (animationFactory && !flagMap[klass]) {
2057 matches.push($injector.get(animationFactory));
2058 flagMap[klass] = true;
2066 var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
2067 $$animationProvider.drivers.push('$$animateJsDriver');
2068 this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
2069 return function initDriverFn(animationDetails) {
2070 if (animationDetails.from && animationDetails.to) {
2071 var fromAnimation = prepareAnimation(animationDetails.from);
2072 var toAnimation = prepareAnimation(animationDetails.to);
2073 if (!fromAnimation && !toAnimation) return;
2077 var animationRunners = [];
2079 if (fromAnimation) {
2080 animationRunners.push(fromAnimation.start());
2084 animationRunners.push(toAnimation.start());
2087 $$AnimateRunner.all(animationRunners, done);
2089 var runner = new $$AnimateRunner({
2090 end: endFnFactory(),
2091 cancel: endFnFactory()
2096 function endFnFactory() {
2098 forEach(animationRunners, function(runner) {
2099 // at this point we cannot cancel animations for groups just yet. 1.5+
2105 function done(status) {
2106 runner.complete(status);
2111 return prepareAnimation(animationDetails);
2115 function prepareAnimation(animationDetails) {
2116 // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
2117 var element = animationDetails.element;
2118 var event = animationDetails.event;
2119 var options = animationDetails.options;
2120 var classes = animationDetails.classes;
2121 return $$animateJs(element, event, classes, options);
2126 var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
2127 var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
2128 var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
2129 var PRE_DIGEST_STATE = 1;
2130 var RUNNING_STATE = 2;
2131 var ONE_SPACE = ' ';
2133 var rules = this.rules = {
2139 function makeTruthyCssClassMap(classString) {
2144 var keys = classString.split(ONE_SPACE);
2145 var map = Object.create(null);
2147 forEach(keys, function(key) {
2153 function hasMatchingClasses(newClassString, currentClassString) {
2154 if (newClassString && currentClassString) {
2155 var currentClassMap = makeTruthyCssClassMap(currentClassString);
2156 return newClassString.split(ONE_SPACE).some(function(className) {
2157 return currentClassMap[className];
2162 function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
2163 return rules[ruleType].some(function(fn) {
2164 return fn(element, currentAnimation, previousAnimation);
2168 function hasAnimationClasses(animation, and) {
2169 var a = (animation.addClass || '').length > 0;
2170 var b = (animation.removeClass || '').length > 0;
2171 return and ? a && b : a || b;
2174 rules.join.push(function(element, newAnimation, currentAnimation) {
2175 // if the new animation is class-based then we can just tack that on
2176 return !newAnimation.structural && hasAnimationClasses(newAnimation);
2179 rules.skip.push(function(element, newAnimation, currentAnimation) {
2180 // there is no need to animate anything if no classes are being added and
2181 // there is no structural animation that will be triggered
2182 return !newAnimation.structural && !hasAnimationClasses(newAnimation);
2185 rules.skip.push(function(element, newAnimation, currentAnimation) {
2186 // why should we trigger a new structural animation if the element will
2187 // be removed from the DOM anyway?
2188 return currentAnimation.event == 'leave' && newAnimation.structural;
2191 rules.skip.push(function(element, newAnimation, currentAnimation) {
2192 // if there is an ongoing current animation then don't even bother running the class-based animation
2193 return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;
2196 rules.cancel.push(function(element, newAnimation, currentAnimation) {
2197 // there can never be two structural animations running at the same time
2198 return currentAnimation.structural && newAnimation.structural;
2201 rules.cancel.push(function(element, newAnimation, currentAnimation) {
2202 // if the previous animation is already running, but the new animation will
2203 // be triggered, but the new animation is structural
2204 return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
2207 rules.cancel.push(function(element, newAnimation, currentAnimation) {
2208 // cancel the animation if classes added / removed in both animation cancel each other out,
2209 // but only if the current animation isn't structural
2211 if (currentAnimation.structural) return false;
2213 var nA = newAnimation.addClass;
2214 var nR = newAnimation.removeClass;
2215 var cA = currentAnimation.addClass;
2216 var cR = currentAnimation.removeClass;
2218 // early detection to save the global CPU shortage :)
2219 if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) {
2223 return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA);
2226 this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
2227 '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',
2228 function($$rAF, $rootScope, $rootElement, $document, $$HashMap,
2229 $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) {
2231 var activeAnimationsLookup = new $$HashMap();
2232 var disabledElementsLookup = new $$HashMap();
2233 var animationsEnabled = null;
2235 function postDigestTaskFactory() {
2236 var postDigestCalled = false;
2237 return function(fn) {
2238 // we only issue a call to postDigest before
2239 // it has first passed. This prevents any callbacks
2240 // from not firing once the animation has completed
2241 // since it will be out of the digest cycle.
2242 if (postDigestCalled) {
2245 $rootScope.$$postDigest(function() {
2246 postDigestCalled = true;
2253 // Wait until all directive and route-related templates are downloaded and
2254 // compiled. The $templateRequest.totalPendingRequests variable keeps track of
2255 // all of the remote templates being currently downloaded. If there are no
2256 // templates currently downloading then the watcher will still fire anyway.
2257 var deregisterWatch = $rootScope.$watch(
2258 function() { return $templateRequest.totalPendingRequests === 0; },
2260 if (!isEmpty) return;
2263 // Now that all templates have been downloaded, $animate will wait until
2264 // the post digest queue is empty before enabling animations. By having two
2265 // calls to $postDigest calls we can ensure that the flag is enabled at the
2266 // very end of the post digest queue. Since all of the animations in $animate
2267 // use $postDigest, it's important that the code below executes at the end.
2268 // This basically means that the page is fully downloaded and compiled before
2269 // any animations are triggered.
2270 $rootScope.$$postDigest(function() {
2271 $rootScope.$$postDigest(function() {
2272 // we check for null directly in the event that the application already called
2273 // .enabled() with whatever arguments that it provided it with
2274 if (animationsEnabled === null) {
2275 animationsEnabled = true;
2282 var callbackRegistry = Object.create(null);
2284 // remember that the classNameFilter is set during the provider/config
2285 // stage therefore we can optimize here and setup a helper function
2286 var classNameFilter = $animateProvider.classNameFilter();
2287 var isAnimatableClassName = !classNameFilter
2288 ? function() { return true; }
2289 : function(className) {
2290 return classNameFilter.test(className);
2293 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
2295 function normalizeAnimationDetails(element, animation) {
2296 return mergeAnimationDetails(element, animation, {});
2299 // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
2300 var contains = window.Node.prototype.contains || function(arg) {
2301 // jshint bitwise: false
2302 return this === arg || !!(this.compareDocumentPosition(arg) & 16);
2303 // jshint bitwise: true
2306 function findCallbacks(parent, element, event) {
2307 var targetNode = getDomNode(element);
2308 var targetParentNode = getDomNode(parent);
2311 var entries = callbackRegistry[event];
2313 forEach(entries, function(entry) {
2314 if (contains.call(entry.node, targetNode)) {
2315 matches.push(entry.callback);
2316 } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) {
2317 matches.push(entry.callback);
2325 function filterFromRegistry(list, matchContainer, matchCallback) {
2326 var containerNode = extractElementNode(matchContainer);
2327 return list.filter(function(entry) {
2328 var isMatch = entry.node === containerNode &&
2329 (!matchCallback || entry.callback === matchCallback);
2334 function cleanupEventListeners(phase, element) {
2335 if (phase === 'close' && !element[0].parentNode) {
2336 // If the element is not attached to a parentNode, it has been removed by
2337 // the domOperation, and we can safely remove the event callbacks
2338 $animate.off(element);
2343 on: function(event, container, callback) {
2344 var node = extractElementNode(container);
2345 callbackRegistry[event] = callbackRegistry[event] || [];
2346 callbackRegistry[event].push({
2351 // Remove the callback when the element is removed from the DOM
2352 jqLite(container).on('$destroy', function() {
2353 var animationDetails = activeAnimationsLookup.get(node);
2355 if (!animationDetails) {
2356 // If there's an animation ongoing, the callback calling code will remove
2357 // the event listeners. If we'd remove here, the callbacks would be removed
2358 // before the animation ends
2359 $animate.off(event, container, callback);
2364 off: function(event, container, callback) {
2365 if (arguments.length === 1 && !isString(arguments[0])) {
2366 container = arguments[0];
2367 for (var eventType in callbackRegistry) {
2368 callbackRegistry[eventType] = filterFromRegistry(callbackRegistry[eventType], container);
2374 var entries = callbackRegistry[event];
2375 if (!entries) return;
2377 callbackRegistry[event] = arguments.length === 1
2379 : filterFromRegistry(entries, container, callback);
2382 pin: function(element, parentElement) {
2383 assertArg(isElement(element), 'element', 'not an element');
2384 assertArg(isElement(parentElement), 'parentElement', 'not an element');
2385 element.data(NG_ANIMATE_PIN_DATA, parentElement);
2388 push: function(element, event, options, domOperation) {
2389 options = options || {};
2390 options.domOperation = domOperation;
2391 return queueAnimation(element, event, options);
2394 // this method has four signatures:
2395 // () - global getter
2396 // (bool) - global setter
2397 // (element) - element getter
2398 // (element, bool) - element setter<F37>
2399 enabled: function(element, bool) {
2400 var argCount = arguments.length;
2402 if (argCount === 0) {
2403 // () - Global getter
2404 bool = !!animationsEnabled;
2406 var hasElement = isElement(element);
2409 // (bool) - Global setter
2410 bool = animationsEnabled = !!element;
2412 var node = getDomNode(element);
2414 if (argCount === 1) {
2415 // (element) - Element getter
2416 bool = !disabledElementsLookup.get(node);
2418 // (element, bool) - Element setter
2419 disabledElementsLookup.put(node, !bool);
2430 function queueAnimation(element, event, initialOptions) {
2431 // we always make a copy of the options since
2432 // there should never be any side effects on
2433 // the input data when running `$animateCss`.
2434 var options = copy(initialOptions);
2437 element = stripCommentsFromElement(element);
2439 node = getDomNode(element);
2440 parent = element.parent();
2443 options = prepareAnimationOptions(options);
2445 // we create a fake runner with a working promise.
2446 // These methods will become available after the digest has passed
2447 var runner = new $$AnimateRunner();
2449 // this is used to trigger callbacks in postDigest mode
2450 var runInNextPostDigestOrNow = postDigestTaskFactory();
2452 if (isArray(options.addClass)) {
2453 options.addClass = options.addClass.join(' ');
2456 if (options.addClass && !isString(options.addClass)) {
2457 options.addClass = null;
2460 if (isArray(options.removeClass)) {
2461 options.removeClass = options.removeClass.join(' ');
2464 if (options.removeClass && !isString(options.removeClass)) {
2465 options.removeClass = null;
2468 if (options.from && !isObject(options.from)) {
2469 options.from = null;
2472 if (options.to && !isObject(options.to)) {
2476 // there are situations where a directive issues an animation for
2477 // a jqLite wrapper that contains only comment nodes... If this
2478 // happens then there is no way we can perform an animation
2484 var className = [node.className, options.addClass, options.removeClass].join(' ');
2485 if (!isAnimatableClassName(className)) {
2490 var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
2492 var documentHidden = $document[0].hidden;
2494 // this is a hard disable of all animations for the application or on
2495 // the element itself, therefore there is no need to continue further
2496 // past this point if not enabled
2497 // Animations are also disabled if the document is currently hidden (page is not visible
2498 // to the user), because browsers slow down or do not flush calls to requestAnimationFrame
2499 var skipAnimations = !animationsEnabled || documentHidden || disabledElementsLookup.get(node);
2500 var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
2501 var hasExistingAnimation = !!existingAnimation.state;
2503 // there is no point in traversing the same collection of parent ancestors if a followup
2504 // animation will be run on the same element that already did all that checking work
2505 if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
2506 skipAnimations = !areAnimationsAllowed(element, parent, event);
2509 if (skipAnimations) {
2510 // Callbacks should fire even if the document is hidden (regression fix for issue #14120)
2511 if (documentHidden) notifyProgress(runner, event, 'start');
2513 if (documentHidden) notifyProgress(runner, event, 'close');
2518 closeChildAnimations(element);
2521 var newAnimation = {
2522 structural: isStructural,
2525 addClass: options.addClass,
2526 removeClass: options.removeClass,
2532 if (hasExistingAnimation) {
2533 var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
2534 if (skipAnimationFlag) {
2535 if (existingAnimation.state === RUNNING_STATE) {
2539 mergeAnimationDetails(element, existingAnimation, newAnimation);
2540 return existingAnimation.runner;
2543 var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
2544 if (cancelAnimationFlag) {
2545 if (existingAnimation.state === RUNNING_STATE) {
2546 // this will end the animation right away and it is safe
2547 // to do so since the animation is already running and the
2548 // runner callback code will run in async
2549 existingAnimation.runner.end();
2550 } else if (existingAnimation.structural) {
2551 // this means that the animation is queued into a digest, but
2552 // hasn't started yet. Therefore it is safe to run the close
2553 // method which will call the runner methods in async.
2554 existingAnimation.close();
2556 // this will merge the new animation options into existing animation options
2557 mergeAnimationDetails(element, existingAnimation, newAnimation);
2559 return existingAnimation.runner;
2562 // a joined animation means that this animation will take over the existing one
2563 // so an example would involve a leave animation taking over an enter. Then when
2564 // the postDigest kicks in the enter will be ignored.
2565 var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
2566 if (joinAnimationFlag) {
2567 if (existingAnimation.state === RUNNING_STATE) {
2568 normalizeAnimationDetails(element, newAnimation);
2570 applyGeneratedPreparationClasses(element, isStructural ? event : null, options);
2572 event = newAnimation.event = existingAnimation.event;
2573 options = mergeAnimationDetails(element, existingAnimation, newAnimation);
2575 //we return the same runner since only the option values of this animation will
2576 //be fed into the `existingAnimation`.
2577 return existingAnimation.runner;
2582 // normalization in this case means that it removes redundant CSS classes that
2583 // already exist (addClass) or do not exist (removeClass) on the element
2584 normalizeAnimationDetails(element, newAnimation);
2587 // when the options are merged and cleaned up we may end up not having to do
2588 // an animation at all, therefore we should check this before issuing a post
2589 // digest callback. Structural animations will always run no matter what.
2590 var isValidAnimation = newAnimation.structural;
2591 if (!isValidAnimation) {
2592 // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
2593 isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
2594 || hasAnimationClasses(newAnimation);
2597 if (!isValidAnimation) {
2599 clearElementAnimationState(element);
2603 // the counter keeps track of cancelled animations
2604 var counter = (existingAnimation.counter || 0) + 1;
2605 newAnimation.counter = counter;
2607 markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
2609 $rootScope.$$postDigest(function() {
2610 var animationDetails = activeAnimationsLookup.get(node);
2611 var animationCancelled = !animationDetails;
2612 animationDetails = animationDetails || {};
2614 // if addClass/removeClass is called before something like enter then the
2615 // registered parent element may not be present. The code below will ensure
2616 // that a final value for parent element is obtained
2617 var parentElement = element.parent() || [];
2619 // animate/structural/class-based animations all have requirements. Otherwise there
2620 // is no point in performing an animation. The parent node must also be set.
2621 var isValidAnimation = parentElement.length > 0
2622 && (animationDetails.event === 'animate'
2623 || animationDetails.structural
2624 || hasAnimationClasses(animationDetails));
2626 // this means that the previous animation was cancelled
2627 // even if the follow-up animation is the same event
2628 if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
2629 // if another animation did not take over then we need
2630 // to make sure that the domOperation and options are
2631 // handled accordingly
2632 if (animationCancelled) {
2633 applyAnimationClasses(element, options);
2634 applyAnimationStyles(element, options);
2637 // if the event changed from something like enter to leave then we do
2638 // it, otherwise if it's the same then the end result will be the same too
2639 if (animationCancelled || (isStructural && animationDetails.event !== event)) {
2640 options.domOperation();
2644 // in the event that the element animation was not cancelled or a follow-up animation
2645 // isn't allowed to animate from here then we need to clear the state of the element
2646 // so that any future animations won't read the expired animation data.
2647 if (!isValidAnimation) {
2648 clearElementAnimationState(element);
2654 // this combined multiple class to addClass / removeClass into a setClass event
2655 // so long as a structural event did not take over the animation
2656 event = !animationDetails.structural && hasAnimationClasses(animationDetails, true)
2658 : animationDetails.event;
2660 markElementAnimationState(element, RUNNING_STATE);
2661 var realRunner = $$animation(element, event, animationDetails.options);
2663 // this will update the runner's flow-control events based on
2664 // the `realRunner` object.
2665 runner.setHost(realRunner);
2666 notifyProgress(runner, event, 'start', {});
2668 realRunner.done(function(status) {
2670 var animationDetails = activeAnimationsLookup.get(node);
2671 if (animationDetails && animationDetails.counter === counter) {
2672 clearElementAnimationState(getDomNode(element));
2674 notifyProgress(runner, event, 'close', {});
2680 function notifyProgress(runner, event, phase, data) {
2681 runInNextPostDigestOrNow(function() {
2682 var callbacks = findCallbacks(parent, element, event);
2683 if (callbacks.length) {
2684 // do not optimize this call here to RAF because
2685 // we don't know how heavy the callback code here will
2686 // be and if this code is buffered then this can
2687 // lead to a performance regression.
2689 forEach(callbacks, function(callback) {
2690 callback(element, phase, data);
2692 cleanupEventListeners(phase, element);
2695 cleanupEventListeners(phase, element);
2698 runner.progress(event, phase, data);
2701 function close(reject) { // jshint ignore:line
2702 clearGeneratedClasses(element, options);
2703 applyAnimationClasses(element, options);
2704 applyAnimationStyles(element, options);
2705 options.domOperation();
2706 runner.complete(!reject);
2710 function closeChildAnimations(element) {
2711 var node = getDomNode(element);
2712 var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
2713 forEach(children, function(child) {
2714 var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
2715 var animationDetails = activeAnimationsLookup.get(child);
2716 if (animationDetails) {
2719 animationDetails.runner.end();
2721 case PRE_DIGEST_STATE:
2722 activeAnimationsLookup.remove(child);
2729 function clearElementAnimationState(element) {
2730 var node = getDomNode(element);
2731 node.removeAttribute(NG_ANIMATE_ATTR_NAME);
2732 activeAnimationsLookup.remove(node);
2735 function isMatchingElement(nodeOrElmA, nodeOrElmB) {
2736 return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
2740 * This fn returns false if any of the following is true:
2741 * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed
2742 * b) a parent element has an ongoing structural animation, and animateChildren is false
2743 * c) the element is not a child of the body
2744 * d) the element is not a child of the $rootElement
2746 function areAnimationsAllowed(element, parentElement, event) {
2747 var bodyElement = jqLite($document[0].body);
2748 var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';
2749 var rootElementDetected = isMatchingElement(element, $rootElement);
2750 var parentAnimationDetected = false;
2751 var animateChildren;
2752 var elementDisabled = disabledElementsLookup.get(getDomNode(element));
2754 var parentHost = jqLite.data(element[0], NG_ANIMATE_PIN_DATA);
2756 parentElement = parentHost;
2759 parentElement = getDomNode(parentElement);
2761 while (parentElement) {
2762 if (!rootElementDetected) {
2763 // angular doesn't want to attempt to animate elements outside of the application
2764 // therefore we need to ensure that the rootElement is an ancestor of the current element
2765 rootElementDetected = isMatchingElement(parentElement, $rootElement);
2768 if (parentElement.nodeType !== ELEMENT_NODE) {
2769 // no point in inspecting the #document element
2773 var details = activeAnimationsLookup.get(parentElement) || {};
2774 // either an enter, leave or move animation will commence
2775 // therefore we can't allow any animations to take place
2776 // but if a parent animation is class-based then that's ok
2777 if (!parentAnimationDetected) {
2778 var parentElementDisabled = disabledElementsLookup.get(parentElement);
2780 if (parentElementDisabled === true && elementDisabled !== false) {
2781 // disable animations if the user hasn't explicitly enabled animations on the
2783 elementDisabled = true;
2784 // element is disabled via parent element, no need to check anything else
2786 } else if (parentElementDisabled === false) {
2787 elementDisabled = false;
2789 parentAnimationDetected = details.structural;
2792 if (isUndefined(animateChildren) || animateChildren === true) {
2793 var value = jqLite.data(parentElement, NG_ANIMATE_CHILDREN_DATA);
2794 if (isDefined(value)) {
2795 animateChildren = value;
2799 // there is no need to continue traversing at this point
2800 if (parentAnimationDetected && animateChildren === false) break;
2802 if (!bodyElementDetected) {
2803 // we also need to ensure that the element is or will be a part of the body element
2804 // otherwise it is pointless to even issue an animation to be rendered
2805 bodyElementDetected = isMatchingElement(parentElement, bodyElement);
2808 if (bodyElementDetected && rootElementDetected) {
2809 // If both body and root have been found, any other checks are pointless,
2810 // as no animation data should live outside the application
2814 if (!rootElementDetected) {
2815 // If no rootElement is detected, check if the parentElement is pinned to another element
2816 parentHost = jqLite.data(parentElement, NG_ANIMATE_PIN_DATA);
2818 // The pin target element becomes the next parent element
2819 parentElement = getDomNode(parentHost);
2824 parentElement = parentElement.parentNode;
2827 var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true;
2828 return allowAnimation && rootElementDetected && bodyElementDetected;
2831 function markElementAnimationState(element, state, details) {
2832 details = details || {};
2833 details.state = state;
2835 var node = getDomNode(element);
2836 node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
2838 var oldValue = activeAnimationsLookup.get(node);
2839 var newValue = oldValue
2840 ? extend(oldValue, details)
2842 activeAnimationsLookup.put(node, newValue);
2847 var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
2848 var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
2850 var drivers = this.drivers = [];
2852 var RUNNER_STORAGE_KEY = '$$animationRunner';
2854 function setRunner(element, runner) {
2855 element.data(RUNNER_STORAGE_KEY, runner);
2858 function removeRunner(element) {
2859 element.removeData(RUNNER_STORAGE_KEY);
2862 function getRunner(element) {
2863 return element.data(RUNNER_STORAGE_KEY);
2866 this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',
2867 function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) {
2869 var animationQueue = [];
2870 var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
2872 function sortAnimations(animations) {
2873 var tree = { children: [] };
2874 var i, lookup = new $$HashMap();
2876 // this is done first beforehand so that the hashmap
2877 // is filled with a list of the elements that will be animated
2878 for (i = 0; i < animations.length; i++) {
2879 var animation = animations[i];
2880 lookup.put(animation.domNode, animations[i] = {
2881 domNode: animation.domNode,
2887 for (i = 0; i < animations.length; i++) {
2888 processNode(animations[i]);
2891 return flatten(tree);
2893 function processNode(entry) {
2894 if (entry.processed) return entry;
2895 entry.processed = true;
2897 var elementNode = entry.domNode;
2898 var parentNode = elementNode.parentNode;
2899 lookup.put(elementNode, entry);
2902 while (parentNode) {
2903 parentEntry = lookup.get(parentNode);
2905 if (!parentEntry.processed) {
2906 parentEntry = processNode(parentEntry);
2910 parentNode = parentNode.parentNode;
2913 (parentEntry || tree).children.push(entry);
2917 function flatten(tree) {
2922 for (i = 0; i < tree.children.length; i++) {
2923 queue.push(tree.children[i]);
2926 var remainingLevelEntries = queue.length;
2927 var nextLevelEntries = 0;
2930 for (i = 0; i < queue.length; i++) {
2931 var entry = queue[i];
2932 if (remainingLevelEntries <= 0) {
2933 remainingLevelEntries = nextLevelEntries;
2934 nextLevelEntries = 0;
2939 entry.children.forEach(function(childEntry) {
2941 queue.push(childEntry);
2943 remainingLevelEntries--;
2954 // TODO(matsko): document the signature in a better way
2955 return function(element, event, options) {
2956 options = prepareAnimationOptions(options);
2957 var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
2959 // there is no animation at the current moment, however
2960 // these runner methods will get later updated with the
2961 // methods leading into the driver's end/cancel methods
2962 // for now they just stop the animation from starting
2963 var runner = new $$AnimateRunner({
2964 end: function() { close(); },
2965 cancel: function() { close(true); }
2968 if (!drivers.length) {
2973 setRunner(element, runner);
2975 var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
2976 var tempClasses = options.tempClasses;
2978 classes += ' ' + tempClasses;
2979 options.tempClasses = null;
2982 var prepareClassName;
2984 prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX;
2985 $$jqLite.addClass(element, prepareClassName);
2988 animationQueue.push({
2989 // this data is used by the postDigest code and passed into
2990 // the driver step function
2994 structural: isStructural,
2996 beforeStart: beforeStart,
3000 element.on('$destroy', handleDestroyedElement);
3002 // we only want there to be one function called within the post digest
3003 // block. This way we can group animations for all the animations that
3004 // were apart of the same postDigest flush call.
3005 if (animationQueue.length > 1) return runner;
3007 $rootScope.$$postDigest(function() {
3008 var animations = [];
3009 forEach(animationQueue, function(entry) {
3010 // the element was destroyed early on which removed the runner
3011 // form its storage. This means we can't animate this element
3012 // at all and it already has been closed due to destruction.
3013 if (getRunner(entry.element)) {
3014 animations.push(entry);
3020 // now any future animations will be in another postDigest
3021 animationQueue.length = 0;
3023 var groupedAnimations = groupAnimations(animations);
3024 var toBeSortedAnimations = [];
3026 forEach(groupedAnimations, function(animationEntry) {
3027 toBeSortedAnimations.push({
3028 domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),
3029 fn: function triggerAnimationStart() {
3030 // it's important that we apply the `ng-animate` CSS class and the
3031 // temporary classes before we do any driver invoking since these
3032 // CSS classes may be required for proper CSS detection.
3033 animationEntry.beforeStart();
3035 var startAnimationFn, closeFn = animationEntry.close;
3037 // in the event that the element was removed before the digest runs or
3038 // during the RAF sequencing then we should not trigger the animation.
3039 var targetElement = animationEntry.anchors
3040 ? (animationEntry.from.element || animationEntry.to.element)
3041 : animationEntry.element;
3043 if (getRunner(targetElement)) {
3044 var operation = invokeFirstDriver(animationEntry);
3046 startAnimationFn = operation.start;
3050 if (!startAnimationFn) {
3053 var animationRunner = startAnimationFn();
3054 animationRunner.done(function(status) {
3057 updateAnimationRunners(animationEntry, animationRunner);
3063 // we need to sort each of the animations in order of parent to child
3064 // relationships. This ensures that the child classes are applied at the
3066 $$rAFScheduler(sortAnimations(toBeSortedAnimations));
3071 // TODO(matsko): change to reference nodes
3072 function getAnchorNodes(node) {
3073 var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
3074 var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
3076 : node.querySelectorAll(SELECTOR);
3078 forEach(items, function(node) {
3079 var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
3080 if (attr && attr.length) {
3087 function groupAnimations(animations) {
3088 var preparedAnimations = [];
3090 forEach(animations, function(animation, index) {
3091 var element = animation.element;
3092 var node = getDomNode(element);
3093 var event = animation.event;
3094 var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
3095 var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
3097 if (anchorNodes.length) {
3098 var direction = enterOrMove ? 'to' : 'from';
3100 forEach(anchorNodes, function(anchor) {
3101 var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
3102 refLookup[key] = refLookup[key] || {};
3103 refLookup[key][direction] = {
3105 element: jqLite(anchor)
3109 preparedAnimations.push(animation);
3113 var usedIndicesLookup = {};
3114 var anchorGroups = {};
3115 forEach(refLookup, function(operations, key) {
3116 var from = operations.from;
3117 var to = operations.to;
3120 // only one of these is set therefore we can't have an
3121 // anchor animation since all three pieces are required
3122 var index = from ? from.animationID : to.animationID;
3123 var indexKey = index.toString();
3124 if (!usedIndicesLookup[indexKey]) {
3125 usedIndicesLookup[indexKey] = true;
3126 preparedAnimations.push(animations[index]);
3131 var fromAnimation = animations[from.animationID];
3132 var toAnimation = animations[to.animationID];
3133 var lookupKey = from.animationID.toString();
3134 if (!anchorGroups[lookupKey]) {
3135 var group = anchorGroups[lookupKey] = {
3137 beforeStart: function() {
3138 fromAnimation.beforeStart();
3139 toAnimation.beforeStart();
3142 fromAnimation.close();
3143 toAnimation.close();
3145 classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
3146 from: fromAnimation,
3148 anchors: [] // TODO(matsko): change to reference nodes
3151 // the anchor animations require that the from and to elements both have at least
3152 // one shared CSS class which effectively marries the two elements together to use
3153 // the same animation driver and to properly sequence the anchor animation.
3154 if (group.classes.length) {
3155 preparedAnimations.push(group);
3157 preparedAnimations.push(fromAnimation);
3158 preparedAnimations.push(toAnimation);
3162 anchorGroups[lookupKey].anchors.push({
3163 'out': from.element, 'in': to.element
3167 return preparedAnimations;
3170 function cssClassesIntersection(a,b) {
3175 for (var i = 0; i < a.length; i++) {
3177 if (aa.substring(0,3) === 'ng-') continue;
3179 for (var j = 0; j < b.length; j++) {
3187 return matches.join(' ');
3190 function invokeFirstDriver(animationDetails) {
3191 // we loop in reverse order since the more general drivers (like CSS and JS)
3192 // may attempt more elements, but custom drivers are more particular
3193 for (var i = drivers.length - 1; i >= 0; i--) {
3194 var driverName = drivers[i];
3195 var factory = $injector.get(driverName);
3196 var driver = factory(animationDetails);
3203 function beforeStart() {
3204 element.addClass(NG_ANIMATE_CLASSNAME);
3206 $$jqLite.addClass(element, tempClasses);
3208 if (prepareClassName) {
3209 $$jqLite.removeClass(element, prepareClassName);
3210 prepareClassName = null;
3214 function updateAnimationRunners(animation, newRunner) {
3215 if (animation.from && animation.to) {
3216 update(animation.from.element);
3217 update(animation.to.element);
3219 update(animation.element);
3222 function update(element) {
3223 var runner = getRunner(element);
3224 if (runner) runner.setHost(newRunner);
3228 function handleDestroyedElement() {
3229 var runner = getRunner(element);
3230 if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
3235 function close(rejected) { // jshint ignore:line
3236 element.off('$destroy', handleDestroyedElement);
3237 removeRunner(element);
3239 applyAnimationClasses(element, options);
3240 applyAnimationStyles(element, options);
3241 options.domOperation();
3244 $$jqLite.removeClass(element, tempClasses);
3247 element.removeClass(NG_ANIMATE_CLASSNAME);
3248 runner.complete(!rejected);
3256 * @name ngAnimateSwap
3262 * ngAnimateSwap is a animation-oriented directive that allows for the container to
3263 * be removed and entered in whenever the associated expression changes. A
3264 * common usecase for this directive is a rotating banner or slider component which
3265 * contains one image being present at a time. When the active image changes
3266 * then the old image will perform a `leave` animation and the new element
3267 * will be inserted via an `enter` animation.
3270 * | Animation | Occurs |
3271 * |----------------------------------|--------------------------------------|
3272 * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
3273 * | {@link ng.$animate#leave leave} | when the old element is removed from the DOM |
3276 * <example name="ngAnimateSwap-directive" module="ngAnimateSwapExample"
3277 * deps="angular-animate.js"
3278 * animations="true" fixBase="true">
3279 * <file name="index.html">
3280 * <div class="container" ng-controller="AppCtrl">
3281 * <div ng-animate-swap="number" class="cell swap-animation" ng-class="colorClass(number)">
3286 * <file name="script.js">
3287 * angular.module('ngAnimateSwapExample', ['ngAnimate'])
3288 * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) {
3289 * $scope.number = 0;
3290 * $interval(function() {
3294 * var colors = ['red','blue','green','yellow','orange'];
3295 * $scope.colorClass = function(number) {
3296 * return colors[number % colors.length];
3300 * <file name="animations.css">
3304 * position:relative;
3306 * border:2px solid black;
3308 * .container .cell {
3310 * text-align:center;
3311 * line-height:250px;
3312 * position:absolute;
3316 * border-bottom:2px solid black;
3318 * .swap-animation.ng-enter, .swap-animation.ng-leave {
3319 * transition:0.5s linear all;
3321 * .swap-animation.ng-enter {
3324 * .swap-animation.ng-enter-active {
3327 * .swap-animation.ng-leave {
3330 * .swap-animation.ng-leave-active {
3333 * .red { background:red; }
3334 * .green { background:green; }
3335 * .blue { background:blue; }
3336 * .yellow { background:yellow; }
3337 * .orange { background:orange; }
3341 var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) {
3344 transclude: 'element',
3346 priority: 600, // we use 600 here to ensure that the directive is caught before others
3347 link: function(scope, $element, attrs, ctrl, $transclude) {
3348 var previousElement, previousScope;
3349 scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
3350 if (previousElement) {
3351 $animate.leave(previousElement);
3353 if (previousScope) {
3354 previousScope.$destroy();
3355 previousScope = null;
3357 if (value || value === 0) {
3358 previousScope = scope.$new();
3359 $transclude(previousScope, function(element) {
3360 previousElement = element;
3361 $animate.enter(element, null, $element);
3374 * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
3375 * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.
3377 * <div doc-module-components="ngAnimate"></div>
3380 * 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
3381 * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
3382 * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
3383 * the HTML element that the animation will be triggered on.
3385 * ## Directive Support
3386 * The following directives are "animation aware":
3388 * | Directive | Supported Animations |
3389 * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
3390 * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
3391 * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
3392 * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
3393 * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
3394 * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
3395 * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
3396 * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
3397 * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
3398 * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
3399 * | {@link module:ngMessages#animations ngMessage} | enter and leave |
3401 * (More information can be found by visiting each the documentation associated with each directive.)
3403 * ## CSS-based Animations
3405 * 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
3406 * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
3408 * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:
3411 * <div ng-if="bool" class="fade">
3414 * <button ng-click="bool=true">Fade In!</button>
3415 * <button ng-click="bool=false">Fade Out!</button>
3418 * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
3421 * /* The starting CSS styles for the enter animation */
3423 * transition:0.5s linear all;
3427 * /* The finishing CSS styles for the enter animation */
3428 * .fade.ng-enter.ng-enter-active {
3433 * 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
3434 * 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
3435 * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
3437 * 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:
3440 * /* now the element will fade out before it is removed from the DOM */
3442 * transition:0.5s linear all;
3445 * .fade.ng-leave.ng-leave-active {
3450 * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
3453 * /* there is no need to define anything inside of the destination
3454 * CSS class since the keyframe will take charge of the animation */
3456 * animation: my_fade_animation 0.5s linear;
3457 * -webkit-animation: my_fade_animation 0.5s linear;
3460 * @keyframes my_fade_animation {
3461 * from { opacity:1; }
3465 * @-webkit-keyframes my_fade_animation {
3466 * from { opacity:1; }
3471 * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
3473 * ### CSS Class-based Animations
3475 * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
3476 * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
3479 * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
3482 * <div ng-show="bool" class="fade">
3485 * <button ng-click="bool=!bool">Toggle</button>
3489 * transition:0.5s linear all;
3495 * 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
3496 * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
3498 * 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
3502 * <div ng-class="{on:onOff}" class="highlight">
3503 * Highlight this box
3505 * <button ng-click="onOff=!onOff">Toggle</button>
3509 * transition:0.5s linear all;
3511 * .highlight.on-add {
3515 * background:yellow;
3517 * .highlight.on-remove {
3523 * We can also make use of CSS keyframes by placing them within the CSS classes.
3526 * ### CSS Staggering Animations
3527 * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
3528 * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
3529 * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
3530 * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
3531 * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
3534 * .my-animation.ng-enter {
3535 * /* standard transition code */
3536 * transition: 1s linear all;
3539 * .my-animation.ng-enter-stagger {
3540 * /* this will have a 100ms delay between each successive leave animation */
3541 * transition-delay: 0.1s;
3543 * /* As of 1.4.4, this must always be set: it signals ngAnimate
3544 * to not accidentally inherit a delay property from another CSS class */
3545 * transition-duration: 0s;
3547 * .my-animation.ng-enter.ng-enter-active {
3548 * /* standard transition styles */
3553 * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
3554 * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
3555 * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
3556 * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
3558 * The following code will issue the **ng-leave-stagger** event on the element provided:
3561 * var kids = parent.children();
3563 * $animate.leave(kids[0]); //stagger index=0
3564 * $animate.leave(kids[1]); //stagger index=1
3565 * $animate.leave(kids[2]); //stagger index=2
3566 * $animate.leave(kids[3]); //stagger index=3
3567 * $animate.leave(kids[4]); //stagger index=4
3569 * window.requestAnimationFrame(function() {
3570 * //stagger has reset itself
3571 * $animate.leave(kids[5]); //stagger index=0
3572 * $animate.leave(kids[6]); //stagger index=1
3578 * Stagger animations are currently only supported within CSS-defined animations.
3580 * ### The `ng-animate` CSS class
3582 * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
3583 * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
3585 * Therefore, animations can be applied to an element using this temporary class directly via CSS.
3588 * .zipper.ng-animate {
3589 * transition:0.5s linear all;
3591 * .zipper.ng-enter {
3594 * .zipper.ng-enter.ng-enter-active {
3597 * .zipper.ng-leave {
3600 * .zipper.ng-leave.ng-leave-active {
3605 * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
3606 * the CSS class once an animation has completed.)
3609 * ### The `ng-[event]-prepare` class
3611 * This is a special class that can be used to prevent unwanted flickering / flash of content before
3612 * the actual animation starts. The class is added as soon as an animation is initialized, but removed
3613 * before the actual animation starts (after waiting for a $digest).
3614 * It is also only added for *structural* animations (`enter`, `move`, and `leave`).
3616 * In practice, flickering can appear when nesting elements with structural animations such as `ngIf`
3617 * into elements that have class-based animations such as `ngClass`.
3620 * <div ng-class="{red: myProp}">
3621 * <div ng-class="{blue: myProp}">
3622 * <div class="message" ng-if="myProp"></div>
3627 * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating.
3628 * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts:
3631 * .message.ng-enter-prepare {
3637 * ## JavaScript-based Animations
3639 * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
3640 * 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
3641 * `module.animation()` module function we can register the animation.
3643 * Let's see an example of a enter/leave animation using `ngRepeat`:
3646 * <div ng-repeat="item in items" class="slide">
3651 * 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`:
3654 * myModule.animation('.slide', [function() {
3656 * // make note that other events (like addClass/removeClass)
3657 * // have different function input parameters
3658 * enter: function(element, doneFn) {
3659 * jQuery(element).fadeIn(1000, doneFn);
3661 * // remember to call doneFn so that angular
3662 * // knows that the animation has concluded
3665 * move: function(element, doneFn) {
3666 * jQuery(element).fadeIn(1000, doneFn);
3669 * leave: function(element, doneFn) {
3670 * jQuery(element).fadeOut(1000, doneFn);
3676 * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
3677 * greensock.js and velocity.js.
3679 * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
3680 * our animations inside of the same registered animation, however, the function input arguments are a bit different:
3683 * <div ng-class="color" class="colorful">
3686 * <button ng-click="color='red'">Change to red</button>
3687 * <button ng-click="color='blue'">Change to blue</button>
3688 * <button ng-click="color='green'">Change to green</button>
3692 * myModule.animation('.colorful', [function() {
3694 * addClass: function(element, className, doneFn) {
3695 * // do some cool animation and call the doneFn
3697 * removeClass: function(element, className, doneFn) {
3698 * // do some cool animation and call the doneFn
3700 * setClass: function(element, addedClass, removedClass, doneFn) {
3701 * // do some cool animation and call the doneFn
3707 * ## CSS + JS Animations Together
3709 * 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,
3710 * 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
3711 * charge of the animation**:
3714 * <div ng-if="bool" class="slide">
3720 * myModule.animation('.slide', [function() {
3722 * enter: function(element, doneFn) {
3723 * jQuery(element).slideIn(1000, doneFn);
3731 * transition:0.5s linear all;
3732 * transform:translateY(-100px);
3734 * .slide.ng-enter.ng-enter-active {
3735 * transform:translateY(0);
3739 * 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
3740 * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
3741 * our own JS-based animation code:
3744 * myModule.animation('.slide', ['$animateCss', function($animateCss) {
3746 * enter: function(element) {
3747 * // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
3748 * return $animateCss(element, {
3757 * 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.
3759 * 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
3760 * 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
3761 * data into `$animateCss` directly:
3764 * myModule.animation('.slide', ['$animateCss', function($animateCss) {
3766 * enter: function(element) {
3767 * return $animateCss(element, {
3770 * addClass: 'maroon-setting',
3771 * from: { height:0 },
3772 * to: { height: 200 }
3779 * Now we can fill in the rest via our transition CSS code:
3782 * /* the transition tells ngAnimate to make the animation happen */
3783 * .slide.ng-enter { transition:0.5s linear all; }
3785 * /* this extra CSS class will be absorbed into the transition
3786 * since the $animateCss code is adding the class */
3787 * .maroon-setting { background:red; }
3790 * 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.
3792 * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
3794 * ## Animation Anchoring (via `ng-animate-ref`)
3796 * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
3797 * structural areas of an application (like views) by pairing up elements using an attribute
3798 * called `ng-animate-ref`.
3800 * Let's say for example we have two views that are managed by `ng-view` and we want to show
3801 * that there is a relationship between two components situated in within these views. By using the
3802 * `ng-animate-ref` attribute we can identify that the two components are paired together and we
3803 * can then attach an animation, which is triggered when the view changes.
3805 * Say for example we have the following template code:
3808 * <!-- index.html -->
3809 * <div ng-view class="view-animation">
3812 * <!-- home.html -->
3813 * <a href="#/banner-page">
3814 * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
3817 * <!-- banner-page.html -->
3818 * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
3821 * Now, when the view changes (once the link is clicked), ngAnimate will examine the
3822 * HTML contents to see if there is a match reference between any components in the view
3823 * that is leaving and the view that is entering. It will scan both the view which is being
3824 * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
3825 * contain a matching ref value.
3827 * The two images match since they share the same ref value. ngAnimate will now create a
3828 * transport element (which is a clone of the first image element) and it will then attempt
3829 * to animate to the position of the second image element in the next view. For the animation to
3830 * work a special CSS class called `ng-anchor` will be added to the transported element.
3832 * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
3833 * ngAnimate will handle the entire transition for us as well as the addition and removal of
3834 * any changes of CSS classes between the elements:
3837 * .banner.ng-anchor {
3838 * /* this animation will last for 1 second since there are
3839 * two phases to the animation (an `in` and an `out` phase) */
3840 * transition:0.5s linear all;
3844 * We also **must** include animations for the views that are being entered and removed
3845 * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
3848 * .view-animation.ng-enter, .view-animation.ng-leave {
3849 * transition:0.5s linear all;
3855 * .view-animation.ng-enter {
3856 * transform:translateX(100%);
3858 * .view-animation.ng-leave,
3859 * .view-animation.ng-enter.ng-enter-active {
3860 * transform:translateX(0%);
3862 * .view-animation.ng-leave.ng-leave-active {
3863 * transform:translateX(-100%);
3867 * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
3868 * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
3869 * from its origin. Once that animation is over then the `in` stage occurs which animates the
3870 * element to its destination. The reason why there are two animations is to give enough time
3871 * for the enter animation on the new element to be ready.
3873 * The example above sets up a transition for both the in and out phases, but we can also target the out or
3874 * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
3877 * .banner.ng-anchor-out {
3878 * transition: 0.5s linear all;
3880 * /* the scale will be applied during the out animation,
3881 * but will be animated away when the in animation runs */
3882 * transform: scale(1.2);
3885 * .banner.ng-anchor-in {
3886 * transition: 1s linear all;
3893 * ### Anchoring Demo
3895 <example module="anchoringExample"
3896 name="anchoringExample"
3897 id="anchoringExample"
3898 deps="angular-animate.js;angular-route.js"
3900 <file name="index.html">
3901 <a href="#/">Home</a>
3903 <div class="view-container">
3904 <div ng-view class="view"></div>
3907 <file name="script.js">
3908 angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
3909 .config(['$routeProvider', function($routeProvider) {
3910 $routeProvider.when('/', {
3911 templateUrl: 'home.html',
3912 controller: 'HomeController as home'
3914 $routeProvider.when('/profile/:id', {
3915 templateUrl: 'profile.html',
3916 controller: 'ProfileController as profile'
3919 .run(['$rootScope', function($rootScope) {
3920 $rootScope.records = [
3921 { id:1, title: "Miss Beulah Roob" },
3922 { id:2, title: "Trent Morissette" },
3923 { id:3, title: "Miss Ava Pouros" },
3924 { id:4, title: "Rod Pouros" },
3925 { id:5, title: "Abdul Rice" },
3926 { id:6, title: "Laurie Rutherford Sr." },
3927 { id:7, title: "Nakia McLaughlin" },
3928 { id:8, title: "Jordon Blanda DVM" },
3929 { id:9, title: "Rhoda Hand" },
3930 { id:10, title: "Alexandrea Sauer" }
3933 .controller('HomeController', [function() {
3936 .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
3937 var index = parseInt($routeParams.id, 10);
3938 var record = $rootScope.records[index - 1];
3940 this.title = record.title;
3941 this.id = record.id;
3944 <file name="home.html">
3945 <h2>Welcome to the home page</h1>
3946 <p>Please click on an element</p>
3948 ng-href="#/profile/{{ record.id }}"
3949 ng-animate-ref="{{ record.id }}"
3950 ng-repeat="record in records">
3954 <file name="profile.html">
3955 <div class="profile record" ng-animate-ref="{{ profile.id }}">
3959 <file name="animations.css">
3972 .view-container > .view.ng-animate {
3979 .view.ng-enter, .view.ng-leave,
3981 transition:0.5s linear all;
3984 transform:translateX(100%);
3986 .view.ng-enter.ng-enter-active, .view.ng-leave {
3987 transform:translateX(0%);
3989 .view.ng-leave.ng-leave-active {
3990 transform:translateX(-100%);
3992 .record.ng-anchor-out {
3998 * ### How is the element transported?
4000 * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
4001 * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
4002 * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
4003 * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
4004 * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
4005 * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
4006 * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
4007 * will become visible since the shim class will be removed.
4009 * ### How is the morphing handled?
4011 * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
4012 * what CSS classes differ between the starting element and the destination element. These different CSS classes
4013 * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
4014 * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
4015 * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
4016 * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
4017 * the cloned element is placed inside of root element which is likely close to the body element).
4019 * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
4022 * ## Using $animate in your directive code
4024 * 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?
4025 * 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
4026 * imagine we have a greeting box that shows and hides itself when the data changes
4029 * <greeting-box active="onOrOff">Hi there</greeting-box>
4033 * ngModule.directive('greetingBox', ['$animate', function($animate) {
4034 * return function(scope, element, attrs) {
4035 * attrs.$observe('active', function(value) {
4036 * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
4042 * 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
4043 * in our HTML code then we can trigger a CSS or JS animation to happen.
4046 * /* normally we would create a CSS class to reference on the element */
4047 * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
4050 * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
4051 * possible be sure to visit the {@link ng.$animate $animate service API page}.
4054 * ## Callbacks and Promises
4056 * 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
4057 * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
4058 * ended by chaining onto the returned promise that animation method returns.
4061 * // somewhere within the depths of the directive
4062 * $animate.enter(element, parent).then(function() {
4063 * //the animation has completed
4067 * (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
4070 * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
4071 * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
4072 * routing controller to hook into that:
4075 * ngModule.controller('HomePageController', ['$animate', function($animate) {
4076 * $animate.on('enter', ngViewElement, function(element) {
4077 * // the animation for this route has completed
4082 * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
4104 * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
4106 * Click here {@link ng.$animate to learn more about animations with `$animate`}.
4108 angular.module('ngAnimate', [], function initAngularHelpers() {
4109 // Access helpers from angular core.
4110 // Do it inside a `config` block to ensure `window.angular` is available.
4111 noop = angular.noop;
4112 copy = angular.copy;
4113 extend = angular.extend;
4114 jqLite = angular.element;
4115 forEach = angular.forEach;
4116 isArray = angular.isArray;
4117 isString = angular.isString;
4118 isObject = angular.isObject;
4119 isUndefined = angular.isUndefined;
4120 isDefined = angular.isDefined;
4121 isFunction = angular.isFunction;
4122 isElement = angular.isElement;
4124 .directive('ngAnimateSwap', ngAnimateSwapDirective)
4126 .directive('ngAnimateChildren', $$AnimateChildrenDirective)
4127 .factory('$$rAFScheduler', $$rAFSchedulerFactory)
4129 .provider('$$animateQueue', $$AnimateQueueProvider)
4130 .provider('$$animation', $$AnimationProvider)
4132 .provider('$animateCss', $AnimateCssProvider)
4133 .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
4135 .provider('$$animateJs', $$AnimateJsProvider)
4136 .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
4139 })(window, window.angular);