demo.html 23.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

<!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>