react-native/Libraries/Animated/examples/demo.html

713 lines
23 KiB
HTML
Raw Normal View History

<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>Animated</title>
<link href="./style.css" rel="stylesheet" type="text/css">
<script src="https://fb.me/react-with-addons-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script src="../release/dist/animated.js"></script>
<style>
</style>
<script>
var TOTAL_EXAMPLES = 0;
function example() {
var scripts = document.getElementsByTagName('script');
var last = scripts[scripts.length - 2];
last.className = 'Example' + (++TOTAL_EXAMPLES);
}
</script>
<script type="text/jsx;harmony=true;stripTypes=true">
var HorizontalPan = function(anim, config) {
config = config || {};
return {
onMouseDown: function(event) {
anim.stopAnimation(startValue => {
config.onStart && config.onStart();
var startPosition = event.clientX;
var lastTime = Date.now();
var lastPosition = event.clientX;
var velocity = 0;
function updateVelocity(event) {
var now = Date.now();
if (event.clientX === lastPosition || now === lastTime) {
return;
}
velocity = (event.clientX - lastPosition) / (now - lastTime);
lastTime = now;
lastPosition = event.clientX;
}
var moveListener, upListener;
window.addEventListener('mousemove', moveListener = (event) => {
var value = startValue + (event.clientX - startPosition);
anim.setValue(value);
updateVelocity(event);
});
window.addEventListener('mouseup', upListener = (event) => {
updateVelocity(event);
window.removeEventListener('mousemove', moveListener);
window.removeEventListener('mouseup', upListener);
config.onEnd && config.onEnd({velocity});
});
});
}
}
};
var EXAMPLE_COUNT = 0;
function examplify(Component) {
if (EXAMPLE_COUNT) {
var previousScript = document.getElementsByClassName('Example' + EXAMPLE_COUNT)[0].innerText;
} else {
var previousScript = `
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0), // ignore
};
},
render: function() {
return (
<Animated.div // ignore
style={{left: this.state.anim}} // ignore
className="circle"
/>
);
},
}));
`;
}
var script = document.getElementsByClassName('Example' + ++EXAMPLE_COUNT)[0];
var previousLines = {};
previousScript.split(/\n/g).forEach(line => { previousLines[line.trim()] = 1; });
var code = document.createElement('div');
script.parentNode.insertBefore(code, script);
var Example = React.createClass({
render() {
return (
<div className="code">
<div className="example">
<button
className="reset"
onClick={() => this.forceUpdate()}>
Reset
</button>
<Component key={Math.random()} />
</div>
<hr />
<pre>{'React.createClass({'}</pre>
{script.innerText
.trim()
.split(/\n/g)
.slice(1, -1)
.map(line =>
<pre
className={!previousLines[line.trim()] && 'highlight'}>
{line}
</pre>
)
}
<pre>{'});'}</pre>
</div>
);
}
})
React.render(<Example />, code);
}
</script>
</head>
<body>
<div class="container">
<h1>Animated</h1>
<p>Animations have for a long time been a weak point of the React ecosystem. The <code>Animated</code> library aims at solving this problem. It embraces the declarative aspect of React and obtains performance by using raw DOM manipulation behind the scenes instead of the usual diff.</p>
<h2>Animated.Value</h2>
<p>The basic building block of this library is <code>Animated.Value</code>. This is a variable that's going to drive the animation. You use it like a normal value in <code>style</code> attribute. Only animated components such as <code>Animated.div</code> will understand it.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(100),
};
},
render: function() {
return (
<Animated.div
style={{left: this.state.anim}}
className="circle"
/>
);
},
}));
</script><script>example();</script>
<h2>setValue</h2>
<p>As you can see, the value is being used inside of <code>render()</code> as you would expect. However, you don't call <code>setState()</code> in order to update the value. Instead, you can call <code>setValue()</code> directly on the value itself. We are using a form of data binding.</p>
<p>The <code>Animated.div</code> component when rendered tracks which animated values it received. This way, whenever that value changes, we don't need to re-render the entire component, we can directly update the specific style attribute that changed.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0),
};
},
render: function() {
return (
<Animated.div
style={{left: this.state.anim}}
className="circle"
onClick={this.handleClick}>
Click
</Animated.div>
);
},
handleClick: function() {
this.state.anim.setValue(400);
},
}));
</script><script>example();</script>
<h2>Animated.timing</h2>
<p>Now that we understand how the system works, let's play with some animations! The hello world of animations is to move the element somewhere else. To do that, we're going to animate the value from the current value 0 to the value 400.</p>
<p>On every frame (via <code>requestAnimationFrame</code>), the <code>timing</code> animation is going to figure out the new value based on the current time, update the animated value which in turn is going to update the corresponding DOM node.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0),
};
},
render: function() {
return (
<Animated.div
style={{left: this.state.anim}}
className="circle"
onClick={this.handleClick}>
Click
</Animated.div>
);
},
handleClick: function() {
Animated.timing(this.state.anim, {toValue: 400}).start();
},
}));
</script><script>example();</script>
<h2>Interrupt Animations</h2>
<p>As a developer, the mental model is that most animations are fire and forget. When the user presses the button, you want it to shrink to 80% and when she releases, you want it to go back to 100%.</p>
<p>There are multiple challenges to implement this correctly. You need to stop the current animation, grab the current value and restart an animation from there. As this is pretty tedious to do manually, <code>Animated</code> will do that automatically for you.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(1),
};
},
render: function() {
return (
<Animated.div
style={{transform: [{scale: this.state.anim}]}}
className="circle"
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}>
Press
</Animated.div>
);
},
handleMouseDown: function() {
Animated.timing(this.state.anim, { toValue: 0.8 }).start();
},
handleMouseUp: function() {
Animated.timing(this.state.anim, { toValue: 1 }).start();
},
}));
</script><script>example();</script>
<h2>Animated.spring</h2>
<p>Unfortunately, the <code>timing</code> animation doesn't feel good. The main reason is that no matter how far you are in the animation, it will trigger a new one with always the same duration.</p>
<p>The commonly used solution for this problem is to use the equation of a real-world spring. Imagine that you attach a spring to the target value, stretch it to the current value and let it go. The spring movement is going to be the same as the update.</p>
<p>It turns out that this model is useful in a very wide range of animations. I highly recommend you to always start with a <code>spring</code> animation instead of a <code>timing</code> animation. It will make your interface feels much better.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(1),
};
},
render: function() {
return (
<Animated.div
style={{transform: [{scale: this.state.anim}]}}
className="circle"
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}>
Press
</Animated.div>
);
},
handleMouseDown: function() {
Animated.spring(this.state.anim, { toValue: 0.8 }).start();
},
handleMouseUp: function() {
Animated.spring(this.state.anim, { toValue: 1 }).start();
},
}));
</script><script>example();</script>
<h2>interpolate</h2>
<p>It is very common to animate multiple attributes during the same animation. The usual way to implement it is to start a separate animation for each of the attribute. The downside is that you now have to manage a different state per attribute which is not ideal.</p>
<p>With <code>Animated</code>, you can use a single state variable and render it in multiple attributes. When the value is updated, all the places will reflect the change.</p>
<p>In the following example, we're going to model the animation with a variable where 1 means fully visible and 0 means fully hidden. We can pass it directly to the scale attribute as the ranges match. But for the rotation, we need to convert [0 ; 1] range to [260deg ; 0deg]. This is where <code>interpolate()</code> comes handy.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(1),
};
},
render: function() {
return (
<Animated.div
style={{
transform: [
{rotate: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: ['260deg', '0deg']
})},
{scale: this.state.anim},
]
}}
className="circle"
onClick={this.handleClick}>
Click
</Animated.div>
);
},
handleClick: function() {
Animated.spring(this.state.anim, {toValue: 0}).start();
}
}));
</script><script>example();</script>
<h2>stopAnimation</h2>
<p>The reason why we can get away with not calling <code>render()</code> and instead modify the DOM directly on updates is because the animated values are <strong>opaque</strong>. In render, <strong>you cannot know the current value</strong>, which prevents you from being able to modify the structure of the DOM.</p>
<p><code>Animated</code> can offload the animation to a different thread (CoreAnimation, CSS transitions, main thread...) and we don't have a good way to know the real value. If you try to query the value then modify it, you are going to be out of sync and the result will look terrible.</p>
<p>There's however one exception: when you want to stop the current animation. You need to know where it stopped in order to continue from there. We cannot know the value synchronously so we give it via a callback in <code>stopAnimation</code>. It will not suffer from being out of sync since the animation is no longer running.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0)
};
},
render: function() {
return (
<div>
<button onClick={() => this.handleClick(-1)}>&lt;</button>
<Animated.div
style={{
transform: [
{rotate: this.state.anim.interpolate({
inputRange: [0, 4],
outputRange: ['0deg', '360deg']
})},
],
position: 'relative'
}}
className="circle"
/>
<button onClick={() => this.handleClick(+1)}>&gt;</button>
</div>
);
},
handleClick: function(delta) {
this.state.anim.stopAnimation(value => {
Animated.spring(this.state.anim, {
toValue: Math.round(value) + delta
}).start();
});
},
}));
</script><script>example();</script>
<h1>Gesture-based Animations</h1>
<p>Most animations libraries only deal with time-based animations. But, as we move to mobile, a lot of animations are also gesture driven. Even more problematic, they often switch between both modes: once the gesture is over, you start a time-based animation using the same interpolations.</p>
<p><code>Animated</code> has been designed with this use case in mind. The key aspect is that there are three distinct and separate concepts: inputs, value, output. The same value can be updated either from a time-based animation or a gesture-based one. Because we use this intermediate representation for the animation, we can keep the same rendering as output.</p>
<h2>HorizontalPan</h2>
<p>The code needed to drag elements around is very messy with the DOM APIs. On mousedown, you need to register a mousemove listener on window otherwise you may drop touches if you move too fast. <code>removeEventListener</code> takes the same arguments as <code>addEventListener</code> instead of an id like <code>clearTimeout</code>. It's also really easy to forget to remove a listener and have a leak. And finally, you need to store the current position and value at the beginning and update only compared to it.</p>
<p>We introduce a little helper called <code>HorizontalPan</code> which handles all this annoying code for us. It takes an <code>Animated.Value</code> as first argument and returns the event handlers required for it to work. We just have to bind this value to the <code>left</code> attribute and we're good to go.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0),
};
},
render: function() {
return (
<Animated.div
style={{left: this.state.anim}}
className="circle"
{...HorizontalPan(this.state.anim)}>
Drag
</Animated.div>
);
},
}));
</script><script>example();</script>
<h2>Animated.decay</h2>
<p>One of the big breakthrough of the iPhone is the fact that when you release the finger while scrolling, it will not abruptly stop but instead keep going for some time.</p>
<p>In order to implement this effect, we are using a second real-world simulation: an object moving on an icy surface. All it needs is two values: the current velocity and a deceleration coefficient. It is implemented by <code>Animated.decay</code>.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0),
};
},
render: function() {
return (
<Animated.div
style={{left: this.state.anim}}
className="circle"
{...HorizontalPan(this.state.anim, {
onEnd: this.handleEnd
})}>
Throw
</Animated.div>
);
},
handleEnd: function({velocity}) {
Animated.decay(this.state.anim, {velocity}).start();
}
}));
</script><script>example();</script>
<h2>Animation Chaining</h2>
<p>The target for an animation is usually a number but sometimes it is convenient to use another value as a target. This way, the first value will track the second. Using a spring animation, we can get a nice trailing effect.</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
var anims = [0, 1, 2, 3, 4].map((_, i) => new Animated.Value(0));
Animated.spring(anims[0], {toValue: anims[1]}).start();
Animated.spring(anims[1], {toValue: anims[2]}).start();
Animated.spring(anims[2], {toValue: anims[3]}).start();
Animated.spring(anims[3], {toValue: anims[4]}).start();
return {
anims: anims,
};
},
render: function() {
return (
<div>
{this.state.anims.map((anim, i) =>
<Animated.div
style={{left: anim}}
className="circle"
{...(i === 4 && HorizontalPan(anim, {
onEnd: this.handleEnd
}))}>
{i === 4 && 'Drag'}
</Animated.div>
)}
</div>
);
},
handleEnd: function({velocity}) {
Animated.decay(this.state.anims[4], {velocity}).start();
}
}));
</script><script>example();</script>
<h2>addListener</h2>
<p>As I said earlier, if you track a spring</p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
var anims = [0, 1, 2, 3, 4].map((_, i) => new Animated.Value(i * 100));
anims[0].addListener(this.handleChange);
return {
selected: null,
anims: anims,
};
},
render: function() {
return (
<div>
{this.state.anims.map((anim, i) =>
<Animated.div
style={{
left: anim,
opacity: i === 0 || i === this.state.selected ? 1 : 0.5
}}
className="circle"
{...(i === 0 && HorizontalPan(anim, { onEnd: this.handleEnd }))}>
{i === 0 && 'Drag'}
{i === this.state.selected && 'Selected!'}
</Animated.div>
)}
</div>
);
},
handleChange: function({value}) {
var selected = null;
this.state.anims.forEach((_, i) => {
if (i !== 0 && i * 100 - 50 < value && value <= i * 100 + 50) {
selected = i;
}
});
if (selected !== this.state.selected) {
this.select(selected)
}
},
select(selected) {
this.setState({selected}, () => {
this.state.anims.forEach((anim, i) => {
if (i === 0) { return; }
if (selected === i) {
Animated.spring(anim, {toValue: this.state.anims[0]}).start();
} else {
Animated.spring(anim, {toValue: i * 100}).start();
}
});
});
},
handleEnd() {
this.select(null);
Animated.spring(this.state.anims[0], {toValue: 0}).start();
}
}));
</script><script>example();</script>
<h2>Animated.sequence</h2>
<p>It is very common to animate </p>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anims: [0, 1, 2, 3, 4].map((_, i) => new Animated.Value(0.2)),
};
},
render: function() {
return (
<div>
{this.state.anims.map((anim, i) =>
<Animated.div
style={{opacity: anim, position: 'relative'}}
className="circle"
onClick={i === 0 && this.handleClick}>
{i === 0 && 'Click'}
</Animated.div>
)}
</div>
);
},
handleClick: function() {
this.state.anims.forEach(anim => { anim.setValue(0.2); });
Animated.sequence(
this.state.anims.map(anim => Animated.spring(anim, { toValue: 1 }))
).start();
},
}));
</script><script>example();</script>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anims: [0, 1, 2, 3, 4].map((_, i) => new Animated.Value(0.2)),
};
},
render: function() {
return (
<div>
{this.state.anims.map((anim, i) =>
<Animated.div
style={{opacity: anim, position: 'relative'}}
className="circle"
onClick={i === 0 && this.handleClick}>
{i === 0 && 'Click'}
</Animated.div>
)}
</div>
);
},
handleClick: function() {
this.state.anims.forEach(anim => { anim.setValue(0.2); });
Animated.stagger(
100,
this.state.anims.map(anim => Animated.spring(anim, { toValue: 1 }))
).start();
},
}));
</script><script>example();</script>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anims: [0, 1, 2, 3, 4].map((_, i) => new Animated.Value(0.2)),
};
},
render: function() {
return (
<div>
{this.state.anims.map((anim, i) =>
<Animated.div
style={{opacity: anim, position: 'relative'}}
className="circle"
onClick={i === 0 && this.handleClick}>
{i === 0 && 'Click'}
</Animated.div>
)}
</div>
);
},
handleClick: function() {
this.state.anims.forEach(anim => { anim.setValue(0.2); });
Animated.sequence([
Animated.parallel(
this.state.anims.map(anim => Animated.spring(anim, { toValue: 1 }))
),
Animated.stagger(
100,
this.state.anims.map(anim => Animated.spring(anim, { toValue: 0.2 }))
),
]).start();
},
}));
</script><script>example();</script>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0),
};
},
handleClick: function() {
var rec = () => {
Animated.sequence([
Animated.timing(this.state.anim, {toValue: -1, duration: 150}),
Animated.timing(this.state.anim, {toValue: 1, duration: 150}),
]).start(rec);
};
rec();
},
render: function() {
return (
<Animated.div
style={{
left: this.state.anim.interpolate({
inputRange: [-1, -0.5, 0.5, 1],
outputRange: [0, 5, 0, 5]
}),
transform: [
{rotate: this.state.anim.interpolate({
inputRange: [-1, 1],
outputRange: ['-10deg', '10deg']
})}
]
}}
className="circle"
onClick={this.handleClick}>
Click
</Animated.div>
);
},
}));
</script><script>example();</script>
<script type="text/jsx;harmony=true;stripTypes=true">
examplify(React.createClass({
getInitialState: function() {
return {
anim: new Animated.Value(0)
};
},
render: function() {
return (
<div
style={{overflow: 'scroll', height: 60}}
onScroll={Animated.event([
{target: {scrollLeft: this.state.anim}}
])}>
<div style={{width: 1000, height: 1}} />
{[0, 1, 2, 3, 4].map(i =>
<Animated.div
style={{
left: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: [0, (i + 1)]
}),
pointerEvents: 'none',
}}
className="circle">
{i === 4 && 'H-Scroll'}
</Animated.div>
)}
</div>
);
},
}));
</script><script>example();</script>
</div>
</body>
</html>