###** Animation ========= Whenever you [update a page fragment](/up.link) you can animate the change. Let's say you are using an [`up-target`](/a-up-target) link to update an element with content from the server. You can add an attribute [`up-transition`](/a-up-target#up-transition) to smoothly fade out the old element while fading in the new element: Show users \#\#\# Transitions vs. animations When we morph between an old and a new element, we call it a *transition*. In contrast, when we animate a new element without simultaneously removing an old element, we call it an *animation*. An example for an animation is opening a new dialog. We can animate the appearance of the dialog by adding an [`[up-animation]`](/a-up-modal#up-animation) attribute to the opening link: Show users \#\#\# Which animations are available? Unpoly ships with a number of [predefined transitions](/up.morph#named-transitions) and [predefined animations](/up.animate#named-animations). You can define custom animations using [`up.transition()`](/up.transition) and [`up.animation()`](/up.animation). @module up.motion ### up.motion = do -> u = up.util e = up.element namedAnimations = {} defaultNamedAnimations = {} namedTransitions = {} defaultNamedTransitions = {} motionController = new up.MotionController('motion') ###** Sets default options for animations and transitions. @property up.motion.config @param {number} [config.duration=300] The default duration for all animations and transitions (in milliseconds). @param {number} [config.delay=0] The default delay for all animations and transitions (in milliseconds). @param {string} [config.easing='ease'] The default timing function that controls the acceleration of animations and transitions. See [W3C documentation](http://www.w3.org/TR/css3-transitions/#transition-timing-function) for a list of pre-defined timing functions. @param {boolean} [config.enabled=true] Whether animation is enabled. Set this to `false` to disable animation globally. This can be useful in full-stack integration tests like a Selenium test suite. Regardless of this setting, all animations will be skipped on browsers that do not support [CSS transitions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions). @stable ### config = new up.Config duration: 300 delay: 0 easing: 'ease' enabled: true reset = -> motionController.reset() namedAnimations = u.copy(defaultNamedAnimations) namedTransitions = u.copy(defaultNamedTransitions) config.reset() ###** Returns whether Unpoly will perform animations. Set [`up.motion.config.enabled`](/up.motion.config) `false` in order to disable animations globally. @function up.motion.isEnabled @return {boolean} @stable ### isEnabled = -> config.enabled ###** Applies the given animation to the given element. \#\#\# Example up.animate('.warning', 'fade-in') You can pass additional options: up.animate('.warning', 'fade-in', { delay: 1000, duration: 250, easing: 'linear' }) \#\#\# Named animations The following animations are pre-defined: | `fade-in` | Changes the element's opacity from 0% to 100% | | `fade-out` | Changes the element's opacity from 100% to 0% | | `move-to-top` | Moves the element upwards until it exits the screen at the top edge | | `move-from-top` | Moves the element downwards from beyond the top edge of the screen until it reaches its current position | | `move-to-bottom` | Moves the element downwards until it exits the screen at the bottom edge | | `move-from-bottom` | Moves the element upwards from beyond the bottom edge of the screen until it reaches its current position | | `move-to-left` | Moves the element leftwards until it exists the screen at the left edge | | `move-from-left` | Moves the element rightwards from beyond the left edge of the screen until it reaches its current position | | `move-to-right` | Moves the element rightwards until it exists the screen at the right edge | | `move-from-right` | Moves the element leftwards from beyond the right edge of the screen until it reaches its current position | | `none` | An animation that has no visible effect. Sounds useless at first, but can save you a lot of `if` statements. | You can define additional named animations using [`up.animation()`](/up.animation). \#\#\# Animating CSS properties directly By passing an object instead of an animation name, you can animate the CSS properties of the given element: var warning = document.querySelector('.warning') warning.style.opacity = 0 up.animate(warning, { opacity: 1 }) CSS properties must be given in `kebab-case`, not `camelCase`. \#\#\# Multiple animations on the same element Unpoly doesn't allow more than one concurrent animation on the same element. If you attempt to animate an element that is already being animated, the previous animation will instantly jump to its last frame before the new animation begins. @function up.animate @param {Element|jQuery|string} elementOrSelector The element to animate. @param {string|Function(element, options): Promise|Object} animation Can either be: - The animation's name - A function performing the animation - An object of CSS attributes describing the last frame of the animation (using kebeb-case property names) @param {number} [options.duration=300] The duration of the animation, in milliseconds. @param {number} [options.delay=0] The delay before the animation starts, in milliseconds. @param {string} [options.easing='ease'] The timing function that controls the animation's acceleration. See [W3C documentation](http://www.w3.org/TR/css3-transitions/#transition-timing-function) for a list of pre-defined timing functions. @return {Promise} A promise for the animation's end. @stable ### animate = (elementOrSelector, animation, options) -> element = e.get(elementOrSelector) options = animateOptions(options) animationFn = findAnimationFn(animation) willRun = willAnimate(element, animation, options) if willRun runNow = -> animationFn(element, options) motionController.startFunction(element, runNow, options) else skipAnimate(element, animation) willAnimate = (element, animationOrTransition, options) -> options = animateOptions(options) isEnabled() && !isNone(animationOrTransition) && options.duration > 0 && !e.isSingleton(element) skipAnimate = (element, animation) -> if u.isOptions(animation) # If we are given the final animation frame as an object of CSS properties, # the best we can do is to set the final frame without animation. e.setStyle(element, animation) # Signal that the animation is already done. Promise.resolve() animCount = 0 ###** Animates the given element's CSS properties using CSS transitions. Does not track the animation, nor does it finishes existing animations (use `up.motion.animate()` for that). It does, however, listen to the motionController's finish event. @function animateNow @param {Element|jQuery|string} elementOrSelector The element to animate. @param {Object} lastFrame The CSS properties that should be transitioned to. @param {number} [options.duration=300] The duration of the animation, in milliseconds. @param {number} [options.delay=0] The delay before the animation starts, in milliseconds. @param {string} [options.easing='ease'] The timing function that controls the animation's acceleration. See [W3C documentation](http://www.w3.org/TR/css3-transitions/#transition-timing-function) for a list of pre-defined timing functions. @return {Promise} A promise that fulfills when the animation ends. @internal ### animateNow = (element, lastFrame, options) -> options = u.merge(options, finishEvent: motionController.finishEvent) cssTransition = new up.CssTransition(element, lastFrame, options) return cssTransition.start() ###** Extracts animation-related options from the given options hash. If `element` is given, also inspects the element for animation-related attributes like `up-easing` or `up-duration`. @param {Object} userOptions @param {Element|jQuery} [element] @param {Object} [moduleDefaults] @function up.motion.animateOptions @internal ### animateOptions = (args...) -> userOptions = args.shift() ? {} moduleDefaults = u.extractOptions(args) element = args.pop() || e.none() consolidatedOptions = {} consolidatedOptions.easing = userOptions.easing ? element.getAttribute('up-easing') ? moduleDefaults.easing ? config.easing consolidatedOptions.duration = userOptions.duration ? e.numberAttr(element, 'up-duration') ? moduleDefaults.duration ? config.duration consolidatedOptions.delay = userOptions.delay ? e.numberAttr(element, 'up-delay') ? moduleDefaults.delay ? config.delay consolidatedOptions.trackMotion = userOptions.trackMotion # required by up.MotionController consolidatedOptions findNamedAnimation = (name) -> namedAnimations[name] or up.fail("Unknown animation %o", name) ###** Completes [animations](/up.animate) and [transitions](/up.morph). If called without arguments, all animations on the screen are completed. If given an element (or selector), animations on that element and its children are completed. Animations are completed by jumping to the last animation frame instantly. Promises returned by animation and transition functions instantly settle. Emits the `up:motion:finish` event that is already handled by `up.animate()`. Does nothing if there are no animation to complete. @function up.motion.finish @param {Element|jQuery|string} [elementOrSelector] @return {Promise} A promise that fulfills when animations and transitions have finished. @stable ### finish = (elementOrSelector) -> motionController.finish(elementOrSelector) ###** This event is emitted on an [animating](/up.animating) element by `up.motion.finish()` to request the animation to instantly finish and skip to the last frame. Promises returned by completed animation functions are expected to settle. Animations started by `up.animate()` already handle this event. @event up:motion:finish @param {Element} event.target The animating element. @experimental ### ###** Performs an animated transition between the `source` and `target` elements. Transitions are implement by performing two animations in parallel, causing `source` to disappear and the `target` to appear. - `target` is [inserted before](https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore) `source` - `source` is removed from the [document flow](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning) with `position: absolute`. It will be positioned over its original place in the flow that is now occupied by `target`. - Both `source` and `target` are animated in parallel - `source` is removed from the DOM \#\#\# Named transitions The following transitions are pre-defined: | `cross-fade` | Fades out the first element. Simultaneously fades in the second element. | | `move-up` | Moves the first element upwards until it exits the screen at the top edge. Simultaneously moves the second element upwards from beyond the bottom edge of the screen until it reaches its current position. | | `move-down` | Moves the first element downwards until it exits the screen at the bottom edge. Simultaneously moves the second element downwards from beyond the top edge of the screen until it reaches its current position. | | `move-left` | Moves the first element leftwards until it exists the screen at the left edge. Simultaneously moves the second element leftwards from beyond the right edge of the screen until it reaches its current position. | | `move-right` | Moves the first element rightwards until it exists the screen at the right edge. Simultaneously moves the second element rightwards from beyond the left edge of the screen until it reaches its current position. | | `none` | A transition that has no visible effect. Sounds useless at first, but can save you a lot of `if` statements. | You can define additional named transitions using [`up.transition()`](/up.transition). You can also compose a transition from two [named animations](/named-animations). separated by a slash character (`/`): - `move-to-bottom/fade-in` - `move-to-left/move-from-top` \#\#\# Implementation details During a transition both the old and new element occupy the same position on the screen. Since the CSS layout flow will usually not allow two elements to overlay the same space, Unpoly: - The old and new elements are cloned - The old element is removed from the layout flow using `display: hidden` - The new element is hidden, but still leaves space in the layout flow by setting `visibility: hidden` - The clones are [absolutely positioned](https://developer.mozilla.org/en-US/docs/Web/CSS/position#Absolute_positioning) over the original elements. - The transition is applied to the cloned elements. At no point will the hidden, original elements be animated. - When the transition has finished, the clones are removed from the DOM and the new element is shown. The old element remains hidden in the DOM. @function up.morph @param {Element|jQuery|string} source @param {Element|jQuery|string} target @param {Function(oldElement, newElement)|string} transition @param {number} [options.duration=300] The duration of the animation, in milliseconds. @param {number} [options.delay=0] The delay before the animation starts, in milliseconds. @param {string} [options.easing='ease'] The timing function that controls the transition's acceleration. See [W3C documentation](http://www.w3.org/TR/css3-transitions/#transition-timing-function) for a list of pre-defined timing functions. @param {boolean} [options.reveal=false] Whether to reveal the new element by scrolling its parent viewport. @return {Promise} A promise that fulfills when the transition ends. @stable ### morph = (oldElement, newElement, transitionObject, options) -> options = u.options(options) u.assign(options, animateOptions(options)) oldElement = e.get(oldElement) newElement = e.get(newElement) transitionFn = findTransitionFn(transitionObject) willMorph = willAnimate(oldElement, transitionFn, options) # Remove callbacks from our options hash in case transitionFn calls morph() recursively. # If we passed on these callbacks, we might call destructors, events, etc. multiple times. beforeStart = u.pluckKey(options, 'beforeStart') || u.noop afterInsert = u.pluckKey(options, 'afterInsert') || u.noop beforeDetach = u.pluckKey(options, 'beforeDetach') || u.noop afterDetach = u.pluckKey(options, 'afterDetach') || u.noop beforeStart() scrollNew = -> # Don't animate the scrolling. scrollOptions = u.merge(options, scrollBehavior: 'auto') # Scroll newElement into position before we start the enter animation. up.viewport.scrollAfterInsertFragment(newElement, scrollOptions) if willMorph if motionController.isActive(oldElement) && options.trackMotion is false return transitionFn(oldElement, newElement, options) up.puts 'Morphing %o to %o with transition %o', oldElement, newElement, transitionObject viewport = up.viewport.closest(oldElement) scrollTopBeforeReveal = viewport.scrollTop oldRemote = up.viewport.absolutize oldElement, # Because the insertion will shift elements visually, we must delay insertion # until absolutize() has measured the bounding box of the old element. afterMeasure: -> e.insertBefore(oldElement, newElement) afterInsert() trackable = -> # Scroll newElement into position before we start the enter animation. promise = scrollNew() promise = promise.then -> # Since we have scrolled the viewport (containing both oldElement and newElement), # we must shift the old copy so it looks like it it is still sitting # in the same position. scrollTopAfterReveal = viewport.scrollTop oldRemote.moveBounds(0, scrollTopAfterReveal - scrollTopBeforeReveal) transitionFn(oldElement, newElement, options) promise = promise.then -> beforeDetach() e.remove(oldRemote.bounds) afterDetach() return promise motionController.startFunction([oldElement, newElement], trackable, options) else beforeDetach() # Swapping the elements directly with replaceWith() will cause # jQuery to remove all data attributes, which we use to store destructors swapElementsDirectly(oldElement, newElement) afterInsert() afterDetach() promise = scrollNew() return promise findTransitionFn = (object) -> if isNone(object) undefined else if u.isFunction(object) object else if u.isArray(object) composeTransitionFn(object...) else if u.isString(object) if object.indexOf('/') >= 0 # Compose a transition from two animation names composeTransitionFn(object.split('/')...) else if namedTransition = namedTransitions[object] findTransitionFn(namedTransition) else up.fail("Unknown transition %o", object) composeTransitionFn = (oldAnimation, newAnimation) -> if isNone(oldAnimation) && isNone(oldAnimation) # A composition of two null-animations is a null-transform # and should be skipped. undefined else oldAnimationFn = findAnimationFn(oldAnimation) || u.asyncNoop newAnimationFn = findAnimationFn(newAnimation) || u.asyncNoop (oldElement, newElement, options) -> Promise.all([ oldAnimationFn(oldElement, options), newAnimationFn(newElement, options) ]) findAnimationFn = (object) -> if isNone(object) undefined else if u.isFunction(object) object else if u.isString(object) findNamedAnimation(object) else if u.isOptions(object) (element, options) -> animateNow(element, object, options) else up.fail('Unknown animation %o', object) # Have a separate function so we can mock it in specs. swapElementsDirectly = (oldElement, newElement) -> e.replace(oldElement, newElement) ###** Defines a named transition that [morphs](/up.element) from one element to another. \#\#\# Example Here is the definition of the pre-defined `cross-fade` animation: up.transition('cross-fade', (oldElement, newElement, options) -> Promise.all([ up.animate(oldElement, 'fade-out', options), up.animate(newElement, 'fade-in', options) ]) ) It is recommended that your transitions use [`up.animate()`](/up.animate), passing along the `options` that were passed to you. If you choose to *not* use `up.animate()` and roll your own logic instead, your code must honor the following contract: 1. It must honor the options `{ delay, duration, easing }` if given. 2. It must *not* remove any of the given elements from the DOM. 3. It returns a promise that is fulfilled when the transition has ended. 4. If during the animation an event `up:motion:finish` is emitted on either element, the transition instantly jumps to the last frame and resolves the returned promise. Calling [`up.animate()`](/up.animate) with an object argument will take care of all these points. @function up.transition @param {string} name @param {Function(oldElement, newElement, options): Promise|Array} transition @stable ### registerTransition = (name, transition) -> namedTransitions[name] = findTransitionFn(transition) ###** Defines a named animation. Here is the definition of the pre-defined `fade-in` animation: up.animation('fade-in', function(element, options) { element.style.opacity = 0 up.animate(element, { opacity: 1 }, options) }) It is recommended that your definitions always end by calling calling [`up.animate()`](/up.animate) with an object argument, passing along the `options` that were passed to you. If you choose to *not* use `up.animate()` and roll your own animation code instead, your code must honor the following contract: 1. It must honor the options `{ delay, duration, easing }` if given 2. It must *not* remove any of the given elements from the DOM. 3. It returns a promise that is fulfilled when the transition has ended 4. If during the animation an event `up:motion:finish` is emitted on the given element, the transition instantly jumps to the last frame and resolves the returned promise. Calling [`up.animate()`](/up.animate) with an object argument will take care of all these points. @function up.animation @param {string} name @param {Function(element, options): Promise} animation @stable ### registerAnimation = (name, animation) -> namedAnimations[name] = findAnimationFn(animation) snapshot = -> defaultNamedAnimations = u.copy(namedAnimations) defaultNamedTransitions = u.copy(namedTransitions) ###** Returns whether the given animation option will cause the animation to be skipped. @function up.motion.isNone @internal ### isNone = (animationOrTransition) -> # false, undefined, '', null and the string "none" are all ways to skip animations !animationOrTransition || animationOrTransition == 'none' || u.isBlank(animationOrTransition) registerAnimation('fade-in', (element, options) -> e.setStyle(element, opacity: 0) animateNow(element, { opacity: 1 }, options) ) registerAnimation('fade-out', (element, options) -> e.setStyle(element, opacity: 1) animateNow(element, { opacity: 0 }, options) ) translateCss = (x, y) -> { transform: "translate(#{x}px, #{y}px)" } registerAnimation('move-to-top', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = box.top + box.height animateNow(element, translateCss(0, -travelDistance), options) ) registerAnimation('move-from-top', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = box.top + box.height e.setStyle(element, translateCss(0, -travelDistance)) animateNow(element, translateCss(0, 0), options) ) registerAnimation('move-to-bottom', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = e.root().clientHeight - box.top animateNow(element, translateCss(0, travelDistance), options) ) registerAnimation('move-from-bottom', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = up.viewport.rootHeight() - box.top e.setStyle(element, translateCss(0, travelDistance)) animateNow(element, translateCss(0, 0), options) ) registerAnimation('move-to-left', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = box.left + box.width animateNow(element, translateCss(-travelDistance, 0), options) ) registerAnimation('move-from-left', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = box.left + box.width e.setStyle(element, translateCss(-travelDistance, 0)) animateNow(element, translateCss(0, 0), options) ) registerAnimation('move-to-right', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = up.viewport.rootWidth() - box.left animateNow(element, translateCss(travelDistance, 0), options) ) registerAnimation('move-from-right', (element, options) -> e.setStyle(element, translateCss(0, 0)) box = element.getBoundingClientRect() travelDistance = up.viewport.rootWidth() - box.left e.setStyle(element, translateCss(travelDistance, 0)) animateNow(element, translateCss(0, 0), options) ) registerAnimation('roll-down', (element, options) -> previousHeightStr = e.style(element, 'height') styleMemo = e.setTemporaryStyle(element, height: '0px' overflow: 'hidden' ) deferred = animate(element, { height: previousHeightStr }, options) deferred.then(styleMemo) deferred ) registerTransition('move-left', ['move-to-left', 'move-from-right']) registerTransition('move-right', ['move-to-right', 'move-from-left']) registerTransition('move-up', ['move-to-top', 'move-from-bottom']) registerTransition('move-down', ['move-to-bottom', 'move-from-top']) registerTransition('cross-fade', ['fade-out', 'fade-in']) up.on 'up:framework:booted', snapshot up.on 'up:framework:reset', reset <% if ENV['JS_KNIFE'] %>knife: eval(Knife.point)<% end %> morph: morph animate: animate animateOptions: animateOptions finish: finish finishCount: -> motionController.finishCount transition: registerTransition animation: registerAnimation config: config isEnabled: isEnabled isNone: isNone up.transition = up.motion.transition up.animation = up.motion.animation up.morph = up.motion.morph up.animate = up.motion.animate