You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4154 lines
147 KiB

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