Clean up Animated docs

Summary:
After taking a look at the existing animation docs, I found that most of the documentation on using `Animated` was spread out throughout the Animations guide and the `Animated` API reference, without any particular structure in place.

This PR aims to clean up the API reference, focusing on documenting all the provided methods exhaustively, and deferring to the Animations guide for long form examples and supporting content.

The `Easing` module is referred to at various points in the API reference, so I decided to clean up this doc as well. easings.net provides some handy visualizations that should make it easier for the reader to understand what sort of easing curve each method provides.

The site was built locally, and I verified all three documents render correctly.

![screencapture-localhost-8079-react-native-docs-animations-html-1487212173651](https://cloud.githubusercontent.com/assets/165856/23004694/d3db1670-f3ac-11e6-9d4e-0dd6079b7c5c.png)

Closes https://github.com/facebook/react-native/pull/12410

Differential Revision: D4581314

Pulled By: hramos

fbshipit-source-id: 27c0bce2afac8f084311b9d6113a2641133b42e5
This commit is contained in:
Hector Ramos 2017-02-17 14:41:23 -08:00 committed by Facebook Github Bot
parent e81258a15b
commit 6ad41a81bc
5 changed files with 581 additions and 436 deletions

View File

@ -98,11 +98,13 @@ class AnExSet extends React.Component {
toValue: this.state.dismissY.interpolate({ // Track dismiss gesture
inputRange: [0, 300], // and interpolate pixel distance
outputRange: [1, 0], // to a fraction.
})
}),
useNativeDriver: true,
}).start();
},
onPanResponderMove: Animated.event(
[null, {dy: this.state.dismissY}] // track pan gesture
[null, {dy: this.state.dismissY}], // track pan gesture
{useNativeDriver: true}
),
onPanResponderRelease: (e, gestureState) => {
if (gestureState.dy > 100) {
@ -110,6 +112,7 @@ class AnExSet extends React.Component {
} else {
Animated.spring(this.props.openVal, {
toValue: 1, // animate back open if released early
useNativeDriver: true,
}).start();
}
},

View File

@ -925,7 +925,9 @@ type ValueXYListenerCallback = (value: {x: number, y: number}) => void;
/**
* 2D Value for driving 2D animations, such as pan gestures. Almost identical
* API to normal `Animated.Value`, but multiplexed. Contains two regular
* `Animated.Value`s under the hood. Example:
* `Animated.Value`s under the hood.
*
* #### Example
*
*```javascript
* class DraggableView extends React.Component {
@ -2276,122 +2278,222 @@ var event = function(
};
/**
* Animations are an important part of modern UX, and the `Animated`
* library is designed to make them fluid, powerful, and easy to build and
* maintain.
* The `Animated` library is designed to make animations fluid, powerful, and
* easy to build and maintain. `Animated` focuses on declarative relationships
* between inputs and outputs, with configurable transforms in between, and
* simple `start`/`stop` methods to control time-based animation execution.
*
* The simplest workflow is to create an `Animated.Value`, hook it up to one or
* more style attributes of an animated component, and then drive updates either
* via animations, such as `Animated.timing`, or by hooking into gestures like
* panning or scrolling via `Animated.event`. `Animated.Value` can also bind to
* props other than style, and can be interpolated as well. Here is a basic
* example of a container view that will fade in when it's mounted:
* The simplest workflow for creating an animation is to to create an
* `Animated.Value`, hook it up to one or more style attributes of an animated
* component, and then drive updates via animations using `Animated.timing()`:
*
*```javascript
* class FadeInView extends React.Component {
* constructor(props) {
* super(props);
* this.state = {
* fadeAnim: new Animated.Value(0), // init opacity 0
* };
* }
* componentDidMount() {
* Animated.timing( // Uses easing functions
* this.state.fadeAnim, // The value to drive
* {toValue: 1} // Configuration
* ).start(); // Don't forget start!
* }
* render() {
* return (
* <Animated.View // Special animatable View
* style={{opacity: this.state.fadeAnim}}> // Binds
* {this.props.children}
* </Animated.View>
* );
* }
* }
*```
* ```javascript
* Animated.timing( // Animate value over time
* this.state.fadeAnim, // The value to drive
* {
* toValue: 1, // Animate to final value of 1
* }
* ).start(); // Start the animation
* ```
*
* Note that only animatable components can be animated. `View`, `Text`, and
* `Image` are already provided, and you can create custom ones with
* `createAnimatedComponent`. These special components do the magic of binding
* the animated values to the properties, and do targeted native updates to
* avoid the cost of the react render and reconciliation process on every frame.
* They also handle cleanup on unmount so they are safe by default.
* Refer to the [Animations](docs/animations.html#animated-api) guide to see
* additional examples of `Animated` in action.
*
* Animations are heavily configurable. Custom and pre-defined easing
* functions, delays, durations, decay factors, spring constants, and more can
* all be tweaked depending on the type of animation.
* ## Overview
*
* A single `Animated.Value` can drive any number of properties, and each
* property can be run through an interpolation first. An interpolation maps
* input ranges to output ranges, typically using a linear interpolation but
* also supports easing functions. By default, it will extrapolate the curve
* beyond the ranges given, but you can also have it clamp the output value.
* There are two value types you can use with `Animated`:
*
* For example, you may want to think about your `Animated.Value` as going from
* 0 to 1, but animate the position from 150px to 0px and the opacity from 0 to
* 1. This can easily be done by modifying `style` in the example above like so:
* - [`Animated.Value()`](docs/animated.html#value) for single values
* - [`Animated.ValueXY()`](docs/animated.html#valuexy) for vectors
*
*```javascript
* style={{
* opacity: this.state.fadeAnim, // Binds directly
* transform: [{
* translateY: this.state.fadeAnim.interpolate({
* inputRange: [0, 1],
* outputRange: [150, 0] // 0 : 150, 0.5 : 75, 1 : 0
* }),
* }],
* }}>
*```
* `Animated.Value` can bind to style properties or other props, and can be
* interpolated as well. A single `Animated.Value` can drive any number of
* properties.
*
* Animations can also be combined in complex ways using composition functions
* such as `sequence` and `parallel`, and can also be chained together simply
* by setting the `toValue` of one animation to be another `Animated.Value`.
* ### Configuring animations
*
* `Animated.ValueXY` is handy for 2D animations, like panning, and there are
* other helpful additions like `setOffset` and `getLayout` to aid with typical
* interaction patterns, like drag-and-drop.
* `Animated` provides three types of animation types. Each animation type
* provides a particular animation curve that controls how your values animate
* from their initial value to the final value:
*
* You can see more example usage in `AnimationExample.js`, the Gratuitous
* Animation App, and [Animations documentation guide](docs/animations.html).
* - [`Animated.decay()`](docs/animated.html#decay) starts with an initial
* velocity and gradually slows to a stop.
* - [`Animated.spring()`](docs/animated.html#spring) provides a simple
* spring physics model.
* - [`Animated.timing()`](docs/animated.html#timing) animates a value over time
* using [easing functions](docs/easing.html).
*
* In most cases, you will be using `timing()`. By default, it uses a symmetric
* easeInOut curve that conveys the gradual acceleration of an object to full
* speed and concludes by gradually decelerating to a stop.
*
* ### Working with animations
*
* Animations are started by calling `start()` on your animation. `start()`
* takes a completion callback that will be called when the animation is done.
* If the animation finished running normally, the completion callback will be
* invoked with `{finished: true}`. If the animation is done because `stop()`
* was called on it before it could finish (e.g. because it was interrupted by a
* gesture or another animation), then it will receive `{finished: false}`.
*
* ### Using the native driver
*
* By using the native driver, we send everything about the animation to native
* before starting the animation, allowing native code to perform the animation
* on the UI thread without having to go through the bridge on every frame.
* Once the animation has started, the JS thread can be blocked without
* affecting the animation.
*
* You can use the native driver by specifying `useNativeDriver: true` in your
* animation configuration. See the
* [Animations](docs/animations.html#using-the-native-driver) guide to learn
* more.
*
* ### Animatable components
*
* Only animatable components can be animated. These special components do the
* magic of binding the animated values to the properties, and do targeted
* native updates to avoid the cost of the react render and reconciliation
* process on every frame. They also handle cleanup on unmount so they are safe
* by default.
*
* - [`createAnimatedComponent()`](docs/animated.html#createanimatedcomponent)
* can be used to make a component animatable.
*
* `Animated` exports the following animatable components using the above
* wrapper:
*
* - `Animated.Image`
* - `Animated.ScrollView`
* - `Animated.Text`
* - `Animated.View`
*
* ### Composing animations
*
* Animations can also be combined in complex ways using composition functions:
*
* - [`Animated.delay()`](docs/animated.html#delay) starts an animation after
* a given delay.
* - [`Animated.parallel()`](docs/animated.html#parallel) starts a number of
* animations at the same time.
* - [`Animated.sequence()`](docs/animated.html#sequence) starts the animations
* in order, waiting for each to complete before starting the next.
* - [`Animated.stagger()`](docs/animated.html#stagger) starts animations in
* order and in parallel, but with successive delays.
*
* Animations can also be chained together simply by setting the `toValue` of
* one animation to be another `Animated.Value`. See
* [Tracking dynamic values](docs/animations.html#tracking-dynamic-values) in
* the Animations guide.
*
* By default, if one animation is stopped or interrupted, then all other
* animations in the group are also stopped.
*
* ### Combining animated values
*
* You can combine two animated values via addition, multiplication, division,
* or modulo to make a new animated value:
*
* - [`Animated.add()`](docs/animated.html#add)
* - [`Animated.divide()`](docs/animated.html#divide)
* - [`Animated.modulo()`](docs/animated.html#modulo)
* - [`Animated.multiply()`](docs/animated.html#multiply)
*
* ### Interpolation
*
* The `interpolate()` function allows input ranges to map to different output
* ranges. By default, it will extrapolate the curve beyond the ranges given,
* but you can also have it clamp the output value. It uses lineal interpolation
* by default but also supports easing functions.
*
* - [`interpolate()`](docs/animated.html#interpolate)
*
* Read more about interpolation in the
* [Animation](docs/animations.html#interpolation) guide.
*
* ### Handling gestures and other events
*
* Gestures, like panning or scrolling, and other events can map directly to
* animated values using `Animated.event()`. This is done with a structured map
* syntax so that values can be extracted from complex event objects. The first
* level is an array to allow mapping across multiple args, and that array
* contains nested objects.
*
* - [`Animated.event()`](docs/animated.html#event)
*
* For example, when working with horizontal scrolling gestures, you would do
* the following in order to map `event.nativeEvent.contentOffset.x` to
* `scrollX` (an `Animated.Value`):
*
* ```javascript
* onScroll={Animated.event(
* // scrollX = e.nativeEvent.contentOffset.x
* [{ nativeEvent: {
* contentOffset: {
* x: scrollX
* }
* }
* }]
* )}
* ```
*
* Note that `Animated` is designed to be fully serializable so that animations
* can be run in a high performance way, independent of the normal JavaScript
* event loop. This does influence the API, so keep that in mind when it seems a
* little trickier to do something compared to a fully synchronous system.
* Checkout `Animated.Value.addListener` as a way to work around some of these
* limitations, but use it sparingly since it might have performance
* implications in the future.
*/
module.exports = {
/**
* Standard value class for driving animations. Typically initialized with
* `new Animated.Value(0);`
*
* See also [`AnimatedValue`](docs/animated.html#animatedvalue).
*/
Value: AnimatedValue,
/**
* 2D value class for driving 2D animations, such as pan gestures.
*
* See also [`AnimatedValueXY`](docs/animated.html#animatedvaluexy).
*/
ValueXY: AnimatedValueXY,
/**
* exported to use the Interpolation type in flow
*
* See also [`AnimatedInterpolation`](docs/animated.html#animatedinterpolation).
*/
Interpolation: AnimatedInterpolation,
/**
* Animates a value from an initial velocity to zero based on a decay
* coefficient.
*
* Config is an object that may have the following options:
*
* - `velocity`: Initial velocity. Required.
* - `deceleration`: Rate of decay. Default 0.997.
* - `useNativeDriver`: Uses the native driver when true. Default false.
*/
decay,
/**
* Animates a value along a timed easing curve. The `Easing` module has tons
* of pre-defined curves, or you can use your own function.
* Animates a value along a timed easing curve. The
* [`Easing`](docs/easing.html) module has tons of predefined curves, or you
* can use your own function.
*
* Config is an object that may have the following options:
*
* - `duration`: Length of animation (milliseconds). Default 500.
* - `easing`: Easing function to define curve.
* Default is `Easing.inOut(Easing.ease)`.
* - `delay`: Start the animation after delay (milliseconds). Default 0.
* - `useNativeDriver`: Uses the native driver when true. Default false.
*/
timing,
/**
* Spring animation based on Rebound and Origami. Tracks velocity state to
* Spring animation based on Rebound and
* [Origami](https://facebook.github.io/origami/). Tracks velocity state to
* create fluid motions as the `toValue` updates, and can be chained together.
*
* Config is an object that may have the following options:
*
* - `friction`: Controls "bounciness"/overshoot. Default 7.
* - `tension`: Controls speed. Default 40.
* - `useNativeDriver`: Uses the native driver when true. Default false.
*/
spring,
@ -2453,8 +2555,8 @@ module.exports = {
stagger,
/**
* Takes an array of mappings and extracts values from each arg accordingly,
* then calls `setValue` on the mapped outputs. e.g.
* Takes an array of mappings and extracts values from each arg accordingly,
* then calls `setValue` on the mapped outputs. e.g.
*
*```javascript
* onScroll={Animated.event(
@ -2467,6 +2569,11 @@ module.exports = {
* {dx: this._panX}, // gestureState arg
* ]),
*```
*
* Config is an object that may have the following options:
*
* - `listener`: Optional async listener.
* - `useNativeDriver`: Uses the native driver when true. Default false.
*/
event,

View File

@ -14,23 +14,81 @@
let ease;
/**
* This class implements common easing functions. The math is pretty obscure,
* but this cool website has nice visual illustrations of what they represent:
* http://xaedes.de/dev/transitions/
* The `Easing` module implements common easing functions. This module is used
* by [Animate.timing()](docs/animate.html#timing) to convey physically
* believable motion in animations.
*
* You can find a visualization of some common easing functions at
* http://easings.net/
*
* ### Predefined animations
*
* The `Easing` module provides several predefined animations through the
* following methods:
*
* - [`back`](docs/easing.html#back) provides a simple animation where the
* object goes slightly back before moving forward
* - [`bounce`](docs/easing.html#bounce) provides a bouncing animation
* - [`ease`](docs/easing.html#ease) provides a simple inertial animation
* - [`elastic`](docs/easing.html#elastic) provides a simple spring interaction
*
* ### Standard functions
*
* Three standard easing functions are provided:
*
* - [`linear`](docs/easing.html#linear)
* - [`quad`](docs/easing.html#quad)
* - [`cubic`](docs/easing.html#cubic)
*
* The [`poly`](docs/easing.html#poly) function can be used to implement
* quartic, quintic, and other higher power functions.
*
* ### Additional functions
*
* Additional mathematical functions are provided by the following methods:
*
* - [`bezier`](docs/easing.html#bezier) provides a cubic bezier curve
* - [`circle`](docs/easing.html#circle) provides a circular function
* - [`sin`](docs/easing.html#sin) provides a sinusoidal function
* - [`exp`](docs/easing.html#exp) provides an exponential function
*
* The following helpers are used to modify other easing functions.
*
* - [`in`](docs/easing.html#in) runs an easing function forwards
* - [`inOut`](docs/easing.html#inout) makes any easing function symmetrical
* - [`out`](docs/easing.html#out) runs an easing function backwards
*/
class Easing {
/**
* A stepping function, returns 1 for any positive value of `n`.
*/
static step0(n) {
return n > 0 ? 1 : 0;
}
/**
* A stepping function, returns 1 if `n` is greater than or equal to 1.
*/
static step1(n) {
return n >= 1 ? 1 : 0;
}
/**
* A linear function, `f(t) = t`. Position correlates to elapsed time one to
* one.
*
* http://cubic-bezier.com/#0,0,1,1
*/
static linear(t) {
return t;
}
/**
* A simple inertial interaction, similar to an object slowly accelerating to
* speed.
*
* http://cubic-bezier.com/#.42,0,1,1
*/
static ease(t: number): number {
if (!ease) {
ease = Easing.bezier(0.42, 0, 1, 1);
@ -38,45 +96,91 @@ class Easing {
return ease(t);
}
/**
* A quadratic function, `f(t) = t * t`. Position equals the square of elapsed
* time.
*
* http://easings.net/#easeInQuad
*/
static quad(t) {
return t * t;
}
/**
* A cubic function, `f(t) = t * t * t`. Position equals the cube of elapsed
* time.
*
* http://easings.net/#easeInCubic
*/
static cubic(t) {
return t * t * t;
}
/**
* A power function. Position is equal to the Nth power of elapsed time.
*
* n = 4: http://easings.net/#easeInQuart
* n = 5: http://easings.net/#easeInQuint
*/
static poly(n) {
return (t) => Math.pow(t, n);
}
/**
* A sinusoidal function.
*
* http://easings.net/#easeInSine
*/
static sin(t) {
return 1 - Math.cos(t * Math.PI / 2);
}
/**
* A circular function.
*
* http://easings.net/#easeInCirc
*/
static circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
/**
* An exponential function.
*
* http://easings.net/#easeInExpo
*/
static exp(t) {
return Math.pow(2, 10 * (t - 1));
}
/**
* A simple elastic interaction, similar to a spring. Default bounciness
* is 1, which overshoots a little bit once. 0 bounciness doesn't overshoot
* at all, and bounciness of N > 1 will overshoot about N times.
* A simple elastic interaction, similar to a spring oscillating back and
* forth.
*
* Default bounciness is 1, which overshoots a little bit once. 0 bounciness
* doesn't overshoot at all, and bounciness of N > 1 will overshoot about N
* times.
*
* http://easings.net/#easeInElastic
*
* Wolfram Plots:
*
* http://tiny.cc/elastic_b_1 (default bounciness = 1)
* http://tiny.cc/elastic_b_3 (bounciness = 3)
* - http://tiny.cc/elastic_b_1 (bounciness = 1, default)
* - http://tiny.cc/elastic_b_3 (bounciness = 3)
*/
static elastic(bounciness: number = 1): (t: number) => number {
const p = bounciness * Math.PI;
return (t) => 1 - Math.pow(Math.cos(t * Math.PI / 2), 3) * Math.cos(t * p);
}
/**
* Use with `Animated.parallel()` to create a simple effect where the object
* animates back slightly as the animation starts.
*
* Wolfram Plot:
*
* - http://tiny.cc/back_default (s = 1.70158, default)
*/
static back(s: number): (t: number) => number {
if (s === undefined) {
s = 1.70158;
@ -84,6 +188,11 @@ class Easing {
return (t) => t * t * ((s + 1) * t - s);
}
/**
* Provides a simple bouncing effect.
*
* http://easings.net/#easeInBounce
*/
static bounce(t: number): number {
if (t < 1 / 2.75) {
return 7.5625 * t * t;
@ -103,6 +212,13 @@ class Easing {
return 7.5625 * t * t + 0.984375;
}
/**
* Provides a cubic bezier curve, equivalent to CSS Transitions'
* `transition-timing-function`.
*
* A useful tool to visualize cubic bezier curves can be found at
* http://cubic-bezier.com/
*/
static bezier(
x1: number,
y1: number,
@ -113,6 +229,9 @@ class Easing {
return _bezier(x1, y1, x2, y2);
}
/**
* Runs an easing function forwards.
*/
static in(
easing: (t: number) => number,
): (t: number) => number {
@ -129,7 +248,9 @@ class Easing {
}
/**
* Makes any easing function symmetrical.
* Makes any easing function symmetrical. The easing function will run
* forwards for half of the duration, then backwards for the rest of the
* duration.
*/
static inOut(
easing: (t: number) => number,

View File

@ -8,103 +8,128 @@ next: accessibility
previous: handling-touches
---
Fluid, meaningful animations are essential to the mobile user experience. Like
everything in React Native, Animation APIs for React Native are currently under
development, but have started to coalesce around two complementary systems:
`LayoutAnimation` for animated global layout transactions, and `Animated` for
more granular and interactive control of specific values.
Animations are very important to create a great user experience.
Stationary objects must overcome inertia as they start moving.
Objects in motion have momentum and rarely come to a stop immediately.
Animations allow you to convey physically believable motion in your interface.
### Animated ###
React Native provides two complementary animation systems:
[`Animated`](docs/animations.html#animated-api) for granular and interactive control of specific values, and
[`LayoutAnimation`](docs/animations.html#layoutanimation) for animated global layout transactions.
The `Animated` library is designed to make it very easy to concisely express a
wide variety of interesting animation and interaction patterns in a very
performant way. `Animated` focuses on declarative relationships between inputs
and outputs, with configurable transforms in between, and simple `start`/`stop`
methods to control time-based animation execution. For example, a complete
component with a simple spring bounce on mount looks like this:
## `Animated` API
The [`Animated`](docs/animated.html) API is designed to make it very easy to concisely express a wide variety of interesting animation and interaction patterns in a very performant way.
`Animated` focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and simple `start`/`stop` methods to control time-based animation execution.
`Animated` exports four animatable component types: `View`, `Text`, `Image`, and `ScrollView`, but you can also create your own using `Animated.createAnimatedComponent()`.
For example, a container view that fades in when it is mounted may look like this:
```javascript
class Playground extends React.Component {
// FadeInView.js
import React, { Component } from 'react';
import {
Animated,
} from 'react-native';
class FadeInView extends Component {
constructor(props) {
super(props);
this.state = {
bounceValue: new Animated.Value(0),
fadeAnim: new Animated.Value(0), // Initial value for opacity: 0
};
}
componentDidMount() {
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: 1, // Animate to opacity: 1, or fully opaque
}
).start(); // Starts the animation
}
render() {
return (
<Animated.Image // Base: Image, Text, View
source={{uri: 'http://i.imgur.com/XMKOH81.jpg'}}
<Animated.View // Special animatable View
style={{
flex: 1,
transform: [ // `transform` is an ordered array
{scale: this.state.bounceValue}, // Map `bounceValue` to `scale`
]
...this.props.style,
opacity: this.state.fadeAnim, // Bind opacity to animated value
}}
/>
>
{this.props.children}
</Animated.View>
);
}
componentDidMount() {
this.state.bounceValue.setValue(1.5); // Start large
Animated.spring( // Base: spring, decay, timing
this.state.bounceValue, // Animate `bounceValue`
{
toValue: 0.8, // Animate to smaller size
friction: 1, // Bouncier spring
}
).start(); // Start the animation
}
}
module.exports = FadeInView;
```
You can then use your `FadeInView` in place of a `View` in your components, like so:
```javascript
render() {
return (
<FadeInView style={{width: 250, height: 50, backgroundColor: 'powderblue'}}>
<Text style={{fontSize: 28, textAlign: 'center', margin: 10}}>Fading in</Text>
</FadeInView>
)
}
```
`bounceValue` is initialized as part of `state` in the constructor, and mapped
to the scale transform on the image. Behind the scenes, the numeric value is
extracted and used to set scale. When the component mounts, the scale is set to
1.5 and then a spring animation is started on `bounceValue` which will update
all of its dependent mappings on each frame as the spring animates (in this
case, just the scale). This is done in an optimized way that is faster than
calling `setState` and re-rendering. Because the entire configuration is
declarative, we will be able to implement further optimizations that serialize
the configuration and runs the animation on a high-priority thread.
![FadeInView](img/AnimatedFadeInView.gif)
#### Core API
Let's break down what's happening here.
In the `FadeInView` constructor, a new `Animated.Value` called `fadeAnim` is initialized as part of `state`.
The opacity property on the `View` is mapped to this animated value.
Behind the scenes, the numeric value is extracted and used to set opacity.
Most everything you need hangs directly off the `Animated` module. This
includes two value types, `Value` for single values and `ValueXY` for vectors,
three animation types, `spring`, `decay`, and `timing`, and three component
types, `View`, `Text`, and `Image`. You can make any other component animated with
`Animated.createAnimatedComponent`.
When the component mounts, the opacity is set to 0.
Then, an easing animation is started on the `fadeAnim` animated value,
which will update all of its dependent mappings (in this case, just the opacity) on each frame as the value animates to the final value of 1.
The three animation types can be used to create almost any animation curve you
want because each can be customized:
This is done in an optimized way that is faster than calling `setState` and re-rendering.
Because the entire configuration is declarative, we will be able to implement further optimizations that serialize the configuration and runs the animation on a high-priority thread.
* `spring`: Simple single-spring physics model that matches [Origami](https://facebook.github.io/origami/).
* `friction`: Controls "bounciness"/overshoot. Default 7.
* `tension`: Controls speed. Default 40.
* `decay`: Starts with an initial velocity and gradually slows to a stop.
* `velocity`: Initial velocity. Required.
* `deceleration`: Rate of decay. Default 0.997.
* `timing`: Maps time range to easing value.
* `duration`: Length of animation (milliseconds). Default 500.
* `easing`: Easing function to define curve. See `Easing` module for several
predefined functions. iOS default is `Easing.inOut(Easing.ease)`.
* `delay`: Start the animation after delay (milliseconds). Default 0.
### Configuring animations
Animations are started by calling `start`. `start` takes a completion callback
that will be called when the animation is done. If the animation is done
because it finished running normally, the completion callback will be invoked
with `{finished: true}`, but if the animation is done because `stop` was called
on it before it could finish (e.g. because it was interrupted by a gesture or
another animation), then it will receive `{finished: false}`.
Animations are heavily configurable. Custom and predefined easing functions, delays, durations, decay factors, spring constants, and more can all be tweaked depending on the type of animation.
#### Composing Animations
`Animated` provides several animation types, the most commonly used one being [`Animated.timing()`](docs/animated.html#timing).
It supports animating a value over time using one of various predefined easing functions, or you can use your own.
Easing functions are typically used in animation to convey gradual acceleration and deceleration of objects.
Animations can also be composed with `parallel`, `sequence`, `stagger`, and
`delay`, each of which simply take an array of animations to execute and
automatically calls start/stop as appropriate. For example:
By default, `timing` will use a easeInOut curve that conveys gradual acceleration to full speed and concludes by gradually decelerating to a stop.
You can specify a different easing function by passing a `easing` parameter.
Custom `duration` or even a `delay` before the animation starts is also supported.
For example, if we want to create a 2-second long animation of an object that slightly backs up before moving to its final position:
```javascript
Animated.sequence([ // spring to start and twirl after decay finishes
Animated.timing(
this.state.xPosition,
{
toValue: 100,
easing: Easing.back,
duration: 2000,
}
).start();
```
Take a look at the [Configuring animations](docs/animated.html#configuring-animations) section of the `Animated` API reference to learn more about all the config parameters supported by the built-in animations.
### Composing animations
Animations can be combined and played in sequence or in parallel.
Sequential animations can play immediately after the previous animation has finished,
or they can start after a specified delay.
The `Animated` API provides several methods, such as `sequence()` and `delay()`,
each of which simply take an array of animations to execute and automatically calls `start()`/`stop()` as needed.
For example, the following animation coasts to a stop, then it springs back while twirling in parallel:
```javascript
Animated.sequence([ // decay, then spring to start and twirl
Animated.decay(position, { // coast to a stop
velocity: {x: gestureState.vx, y: gestureState.vy}, // velocity from gesture release
deceleration: 0.997,
@ -120,15 +145,35 @@ Animated.sequence([ // spring to start and twirl after decay finishes
]).start(); // start the sequence group
```
By default, if one animation is stopped or interrupted, then all other
animations in the group are also stopped. Parallel has a `stopTogether` option
that can be set to `false` to disable this.
If one animation is stopped or interrupted, then all other animations in the group are also stopped.
`Animated.parallel` has a `stopTogether` option that can be set to `false` to disable this.
#### Interpolation
You can find a full list of composition methods in the [Composing animations](docs/animated.html#composing-animations) section of the `Animated` API reference.
Another powerful part of the `Animated` API is the `interpolate` function. It
allows input ranges to map to different output ranges. For example, a simple
mapping to convert a 0-1 range to a 0-100 range would be
### Combining animated values
You can [combine two animated values](docs/animated.html#combining-animated-values) via addition, multiplication, division, or modulo to make a new animated value.
There are some cases where an animated value needs to invert another animated value for calculation.
An example is inverting a scale (2x --> 0.5x):
```javascript
const a = Animated.Value(1);
const b = Animated.divide(1, a);
Animated.spring(a, {
toValue: 2,
}).start();
```
### Interpolation
Each property can be run through an interpolation first.
An interpolation maps input ranges to output ranges,
typically using a linear interpolation but also supports easing functions.
By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value.
A simple mapping to convert a 0-1 range to a 0-100 range would be:
```javascript
value.interpolate({
@ -137,11 +182,24 @@ value.interpolate({
});
```
`interpolate` supports multiple range segments as well, which is handy for
defining dead zones and other handy tricks. For example, to get an negation
relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then
back down to zero at 100 followed by a dead-zone that remains at 0 for
everything beyond that, you could do:
For example, you may want to think about your `Animated.Value` as going from 0 to 1,
but animate the position from 150px to 0px and the opacity from 0 to 1.
This can easily be done by modifying `style` from the example above like so:
```javascript
style={{
opacity: this.state.fadeAnim, // Binds directly
transform: [{
translateY: this.state.fadeAnim.interpolate({
inputRange: [0, 1],
outputRange: [150, 0] // 0 : 150, 0.5 : 75, 1 : 0
}),
}],
}}
```
[`interpolate()`](docs/animated.html#interpolate) supports multiple range segments as well, which is handy for defining dead zones and other handy tricks.
For example, to get an negation relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then back down to zero at 100 followed by a dead-zone that remains at 0 for everything beyond that, you could do:
```javascript
value.interpolate({
@ -152,6 +210,7 @@ value.interpolate({
Which would map like so:
```
Input | Output
------|-------
-400| 450
@ -164,8 +223,9 @@ Input | Output
100| 0
101| 0
200| 0
```
`interpolate` also supports mapping to strings, allowing you to animate colors as well as values with units. For example, if you wanted to animate a rotation you could do:
`interpolate()` also supports mapping to strings, allowing you to animate colors as well as values with units. For example, if you wanted to animate a rotation you could do:
```javascript
value.interpolate({
@ -174,23 +234,18 @@ value.interpolate({
})
```
`interpolation` also supports arbitrary easing functions, many of which are
already implemented in the
[`Easing`](https://github.com/facebook/react-native/blob/master/Libraries/Animation/Animated/Easing.js)
class including quadratic, exponential, and bezier curves as well as functions
like step and bounce. `interpolation` also has configurable behavior for
extrapolating the `outputRange`. You can set the extrapolation by setting the `extrapolate`,
`extrapolateLeft` or `extrapolateRight` options. The default value is
`extend` but you can use `clamp` to prevent the output value from exceeding
`outputRange`.
`interpolate()` also supports arbitrary easing functions, many of which are already implemented in the
[`Easing`](docs/easing.html) module.
`interpolate()` also has configurable behavior for extrapolating the `outputRange`.
You can set the extrapolation by setting the `extrapolate`, `extrapolateLeft`, or `extrapolateRight` options.
The default value is `extend` but you can use `clamp` to prevent the output value from exceeding `outputRange`.
#### Tracking Dynamic Values
### Tracking dynamic values
Animated values can also track other values. Just set the `toValue` of an
animation to another animated value instead of a plain number, for example with
spring physics for an interaction like "Chat Heads", or via `timing` with
`duration: 0` for rigid/instant tracking. They can also be composed with
interpolations:
Animated values can also track other values.
Just set the `toValue` of an animation to another animated value instead of a plain number.
For example, a "Chat Heads" animation like the one used by Messenger on Android could be implemented with a `spring()` pinned on another animated value, or with `timing()` and a `duration` of 0 for rigid tracking.
They can also be composed with interpolations:
```javascript
Animated.spring(follower, {toValue: leader}).start();
@ -202,66 +257,121 @@ Animated.timing(opacity, {
}).start();
```
`ValueXY` is a handy way to deal with 2D interactions, such as panning/dragging.
It is a simple wrapper that basically just contains two `Animated.Value`
instances and some helper functions that call through to them, making `ValueXY`
a drop-in replacement for `Value` in many cases. For example, in the code
snippet above, `leader` and `follower` could both be of type `ValueXY` and the x
and y values will both track as you would expect.
The `leader` and `follower` animated values would be implemented using `Animated.ValueXY()`.
`ValueXY` is a handy way to deal with 2D interactions, such as panning or dragging.
It is a simple wrapper that basically contains two `Animated.Value` instances and some helper functions that call through to them,
making `ValueXY` a drop-in replacement for `Value` in many cases.
It allows us to track both x and y values in the example above.
#### Input Events
### Tracking gestures
`Animated.event` is the input side of the Animated API, allowing gestures and
other events to map directly to animated values. This is done with a structured
map syntax so that values can be extracted from complex event objects. The
first level is an array to allow mapping across multiple args, and that array
contains nested objects. In the example, you can see that `scrollX` maps to
`event.nativeEvent.contentOffset.x` (`event` is normally the first arg to the
handler), and `pan.x` and `pan.y` map to `gestureState.dx` and `gestureState.dy`,
respectively (`gestureState` is the second arg passed to the `PanResponder` handler).
Gestures, like panning or scrolling, and other events can map directly to animated values using [`Animated.event`](docs/animated.html#event).
This is done with a structured map syntax so that values can be extracted from complex event objects.
The first level is an array to allow mapping across multiple args, and that array contains nested objects.
For example, when working with horizontal scrolling gestures,
you would do the following in order to map `event.nativeEvent.contentOffset.x` to `scrollX` (an `Animated.Value`):
```javascript
onScroll={Animated.event(
// scrollX = e.nativeEvent.contentOffset.x
[{nativeEvent: {contentOffset: {x: scrollX}}}]
)}
onPanResponderMove={Animated.event([
null, // ignore the native event
onScroll={Animated.event(
// scrollX = e.nativeEvent.contentOffset.x
[{ nativeEvent: {
contentOffset: {
x: scrollX
}
}
}]
)}
```
When using `PanResponder`, you could use the following code to extract the x and y positions from `gestureState.dx` and `gestureState.dy`.
We use a `null` in the first position of the array, as we are only interested in the second argument passed to the `PanResponder` handler,
which is the `gestureState`.
```javascript
onPanResponderMove={Animated.event(
[null, // ignore the native event
// extract dx and dy from gestureState
// like 'pan.x = gestureState.dx, pan.y = gestureState.dy'
{dx: pan.x, dy: pan.y}
]);
])}
```
#### Responding to the Current Animation Value
### Responding to the current animation value
You may notice that there is no obvious way to read the current value while
animating - this is because the value may only be known in the native runtime
due to optimizations. If you need to run JavaScript in response to the current
value, there are two approaches:
You may notice that there is no obvious way to read the current value while animating.
This is because the value may only be known in the native runtime due to optimizations.
If you need to run JavaScript in response to the current value, there are two approaches:
- `spring.stopAnimation(callback)` will stop the animation and invoke `callback`
with the final value - this is useful when making gesture transitions.
- `spring.addListener(callback)` will invoke `callback` asynchronously while the
animation is running, providing a recent value. This is useful for triggering
state changes, for example snapping a bobble to a new option as the user drags
it closer, because these larger state changes are less sensitive to a few frames
of lag compared to continuous gestures like panning which need to run at 60fps.
- `spring.stopAnimation(callback)` will stop the animation and invoke `callback` with the final value. This is useful when making gesture transitions.
- `spring.addListener(callback)` will invoke `callback` asynchronously while the animation is running, providing a recent value.
This is useful for triggering state changes,
for example snapping a bobble to a new option as the user drags it closer,
because these larger state changes are less sensitive to a few frames of lag compared to continuous gestures like panning which need to run at 60 fps.
#### Future Work
`Animated` is designed to be fully serializable so that animations can be run in a high performance way, independent of the normal JavaScript event loop.
This does influence the API, so keep that in mind when it seems a little trickier to do something compared to a fully synchronous system.
Check out `Animated.Value.addListener` as a way to work around some of these limitations,
but use it sparingly since it might have performance implications in the future.
As previously mentioned, we're planning on optimizing Animated under the hood to
make it even more performant. We would also like to experiment with more
declarative and higher level gestures and triggers, such as horizontal vs.
vertical panning.
### Using the native driver
The above API gives a powerful tool for expressing all sorts of animations in a
concise, robust, and performant way. Check out more example code in
[UIExplorer/AnimationExample](https://github.com/facebook/react-native/tree/master/Examples/UIExplorer/js/AnimatedGratuitousApp). Of course there may still be times where `Animated`
doesn't support what you need, and the following sections cover other animation
systems.
The `Animated` API is designed to be serializable.
By using the [native driver](http://facebook.github.io/react-native/blog/2017/02/14/using-native-driver-for-animated.html),
we send everything about the animation to native before starting the animation,
allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame.
Once the animation has started, the JS thread can be blocked without affecting the animation.
### LayoutAnimation
Using the native driver for normal animations is quite simple.
Just add `useNativeDriver: true` to the animation config when starting it.
```javascript
Animated.timing(this.state.animatedValue, {
toValue: 1,
duration: 500,
useNativeDriver: true, // <-- Add this
}).start();
```
Animated values are only compatible with one driver so if you use native driver when starting an animation on a value,
make sure every animation on that value also uses the native driver.
The native driver also works with `Animated.event`.
This is specially useful for animations that follow the scroll position as without the native driver,
the animation will always run a frame behind the gesture due to the async nature of React Native.
```javascript
<Animated.ScrollView // <-- Use the Animated ScrollView wrapper
scrollEventThrottle={1} // <-- Use 1 here to make sure no events are ever missed
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.animatedValue } } }],
{ useNativeDriver: true } // <-- Add this
)}
>
{content}
</Animated.ScrollView>
```
You can see the native driver in action by running the [UIExplorer sample app](https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/),
then loading the Native Animated Example.
You can also take a look at the [source code](https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/js/NativeAnimationsExample.js) to learn how these examples were produced.
#### Caveats
Not everything you can do with `Animated` is currently supported by the native driver.
The main limitation is that you can only animate non-layout properties:
things like `transform`, `opacity` and `backgroundColor` will work, but flexbox and position properties will not.
When using `Animated.event`, it will only work with direct events and not bubbling events.
This means it does not work with `PanResponder` but does work with things like `ScrollView#onScroll`.
### Additional examples
The UIExplorer sample app has various examples of `Animated` in use:
- [AnimatedGratuitousApp](https://github.com/facebook/react-native/tree/master/Examples/UIExplorer/js/AnimatedGratuitousApp)
- [NativeAnimationsExample](https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/js/NativeAnimationsExample.js)
## `LayoutAnimation` API
`LayoutAnimation` allows you to globally configure `create` and `update`
animations that will be used for all views in the next render/layout cycle.
@ -324,7 +434,9 @@ This example uses a preset value, you can customize the animations as
you need, see [LayoutAnimation.js](https://github.com/facebook/react-native/blob/master/Libraries/LayoutAnimation/LayoutAnimation.js)
for more information.
### requestAnimationFrame
## Additional notes
### `requestAnimationFrame`
`requestAnimationFrame` is a polyfill from the browser that you might be
familiar with. It accepts a function as its only argument and calls that
@ -333,165 +445,7 @@ animations that underlies all of the JavaScript-based animation APIs. In
general, you shouldn't need to call this yourself - the animation APIs will
manage frame updates for you.
### react-tween-state (Not recommended - use [Animated](docs/animations.html#animated) instead)
[react-tween-state](https://github.com/chenglou/react-tween-state) is a
minimal library that does exactly what its name suggests: it *tweens* a
value in a component's state, starting at a **from** value and ending at
a **to** value. This means that it generates the values in between those
two values, and it sets the state on every `requestAnimationFrame` with
the intermediary value.
> Tweening definition from [Wikipedia](https://en.wikipedia.org/wiki/Inbetweening)
>
> "... tweening is the process of generating intermediate frames between two
> images to give the appearance that the first image evolves smoothly
> into the second image. [Tweens] are the drawings between the key
> frames which help to create the illusion of motion."
The most obvious way to animate from one value to another is linearly:
you subtract the end value from the start value and divide the result by
the number of frames over which the animation occurs, and then add that
value to the current value on each frame until the end value is reached.
Linear easing often looks awkward and unnatural, so react-tween-state
provides a selection of popular [easing functions](http://easings.net/)
that can be applied to make your animations more pleasing.
This library does not ship with React Native - in order to use it on
your project, you will need to install it with `npm i react-tween-state
--save` from your project directory.
```javascript
import tweenState from 'react-tween-state';
import reactMixin from 'react-mixin'; // https://github.com/brigand/react-mixin
class App extends React.Component {
constructor(props) {
super(props);
this.state = { opacity: 1 };
this._animateOpacity = this._animateOpacity.bind(this);
}
_animateOpacity() {
this.tweenState('opacity', {
easing: tweenState.easingTypes.easeOutQuint,
duration: 1000,
endValue: this.state.opacity === 0.2 ? 1 : 0.2,
});
}
render() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<TouchableWithoutFeedback onPress={this._animateOpacity}>
<View ref={component => this._box = component}
style={{width: 200, height: 200, backgroundColor: 'red',
opacity: this.getTweeningValue('opacity')}} />
</TouchableWithoutFeedback>
</View>
)
}
}
reactMixin.onClass(App, tweenState.Mixin);
```
[Run this example](https://rnplay.org/apps/4FUQ-A)
![](img/TweenState.gif)
Here we animated the opacity, but as you might guess, we can animate any
numeric value. Read more about react-tween-state in its
[README](https://github.com/chenglou/react-tween-state).
### Rebound (Not recommended - use [Animated](docs/animations.html#animated) instead)
[Rebound.js](https://github.com/facebook/rebound-js) is a JavaScript port of
[Rebound for Android](https://github.com/facebook/rebound). It is
similar in concept to react-tween-state: you have an initial value and
set an end value, then Rebound generates intermediate values that you can
use for your animation. Rebound is modeled after spring physics; we
don't provide a duration when animating with springs, it is
calculated for us depending on the spring tension, friction, current
value and end value. Rebound [is used
internally](https://github.com/facebook/react-native/search?utf8=%E2%9C%93&q=rebound)
by React Native on `Navigator` and `WarningBox`.
![](img/ReboundImage.gif)
Notice that Rebound animations can be interrupted - if you release in
the middle of a press, it will animate back from the current state to
the original value.
```javascript
import rebound from 'rebound';
class App extends React.Component {
constructor(props) {
super(props);
this._onPressIn = this._onPressIn.bind(this);
this._onPressOut = this._onPressOut.bind(this);
}
// First we initialize the spring and add a listener, which calls
// setState whenever it updates
componentWillMount() {
// Initialize the spring that will drive animations
this.springSystem = new rebound.SpringSystem();
this._scrollSpring = this.springSystem.createSpring();
var springConfig = this._scrollSpring.getSpringConfig();
springConfig.tension = 230;
springConfig.friction = 10;
this._scrollSpring.addListener({
onSpringUpdate: () => {
this.setState({scale: this._scrollSpring.getCurrentValue()});
},
});
// Initialize the spring value at 1
this._scrollSpring.setCurrentValue(1);
}
_onPressIn() {
this._scrollSpring.setEndValue(0.5);
}
_onPressOut() {
this._scrollSpring.setEndValue(1);
}
render() {
var imageStyle = {
width: 250,
height: 200,
transform: [{scaleX: this.state.scale}, {scaleY: this.state.scale}],
};
var imageUri = "img/ReboundExample.png";
return (
<View style={styles.container}>
<TouchableWithoutFeedback onPressIn={this._onPressIn}
onPressOut={this._onPressOut}>
<Image source={{uri: imageUri}} style={imageStyle} />
</TouchableWithoutFeedback>
</View>
);
}
}
```
[Run this example](https://rnplay.org/apps/NNI5eA)
You can also clamp the spring values so that they don't overshoot and
oscillate around the end value. In the above example, we would add
`this._scrollSpring.setOvershootClampingEnabled(true)` to change this.
See the below gif for an example of where in your interface you might
use this.
![](img/Rebound.gif) Screenshot from
[react-native-scrollable-tab-view](https://github.com/brentvatne/react-native-scrollable-tab-view).
You can run a similar example [here](https://rnplay.org/apps/qHU_5w).
#### A sidenote about setNativeProps
### `setNativeProps`
As mentioned [in the Direction Manipulation section](docs/direct-manipulation.html),
`setNativeProps` allows us to modify properties of native-backed
@ -545,43 +499,3 @@ using the
[InteractionManager](docs/interactionmanager.html). You
can monitor the frame rate by using the In-App Developer Menu "FPS
Monitor" tool.
### Navigator Scene Transitions
As mentioned in the [Navigator
Comparison](docs/navigator-comparison.html#content),
`Navigator` is implemented in JavaScript and `NavigatorIOS` is a wrapper
around native functionality provided by `UINavigationController`, so
these scene transitions apply only to `Navigator`. In order to re-create
the various animations provided by `UINavigationController` and also
make them customizable, React Native exposes a
[NavigatorSceneConfigs](https://github.com/facebook/react-native/blob/master/Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js) API which is then handed over to the [Navigator](https://github.com/facebook/react-native/blob/master/Libraries/CustomComponents/Navigator/Navigator.js) `configureScene` prop.
```javascript
import { Dimensions } from 'react-native';
var SCREEN_WIDTH = Dimensions.get('window').width;
var BaseConfig = Navigator.SceneConfigs.FloatFromRight;
var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, {
// Make it snap back really quickly after canceling pop
snapVelocity: 8,
// Make it so we can drag anywhere on the screen
edgeHitWidth: SCREEN_WIDTH,
});
var CustomSceneConfig = Object.assign({}, BaseConfig, {
// A very tightly wound spring will make this transition fast
springTension: 100,
springFriction: 1,
// Use our custom gesture defined above
gestures: {
pop: CustomLeftToRightGesture,
}
});
```
[Run this example](https://rnplay.org/apps/HPy6UA)
For further information about customizing scene transitions, [read the
source](https://github.com/facebook/react-native/blob/master/Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js).

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB