├── Animated.js ├── Easing.js ├── Interpolation.js ├── JSXTransformer.js ├── bezier.js ├── index.html ├── react.js └── style.css /Animated.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | * @providesModule Animated 10 | */ 11 | 'use strict'; 12 | 13 | var Animated = (function() { 14 | 15 | // Note(vjeux): this would be better as an interface but flow doesn't 16 | // support them yet 17 | class Animated { 18 | attach(): void {} 19 | detach(): void {} 20 | getValue(): any {} 21 | getAnimatedValue(): any { return this.getValue(); } 22 | addChild(child: Animated) {} 23 | removeChild(child: Animated) {} 24 | getChildren(): Array { return []; } 25 | } 26 | 27 | // Important note: start() and stop() will only be called at most once. 28 | // Once an animation has been stopped or finished its course, it will 29 | // not be reused. 30 | class Animation { 31 | start( 32 | fromValue: number, 33 | onUpdate: (value: number) => void, 34 | onEnd: ?((finished: bool) => void), 35 | previousAnimation: ?Animation 36 | ): void {} 37 | stop(): void {} 38 | } 39 | 40 | class AnimatedWithChildren extends Animated { 41 | _children: Array; 42 | 43 | constructor() { 44 | super(); 45 | this._children = []; 46 | } 47 | 48 | addChild(child: Animated): void { 49 | if (this._children.length === 0) { 50 | this.attach(); 51 | } 52 | this._children.push(child); 53 | } 54 | 55 | removeChild(child: Animated): void { 56 | var index = this._children.indexOf(child); 57 | if (index === -1) { 58 | console.warn('Trying to remove a child that doesn\'t exist'); 59 | return; 60 | } 61 | this._children.splice(index, 1); 62 | if (this._children.length === 0) { 63 | this.detach(); 64 | } 65 | } 66 | 67 | getChildren(): Array { 68 | return this._children; 69 | } 70 | } 71 | 72 | /** 73 | * Animated works by building a directed acyclic graph of dependencies 74 | * transparently when you render your Animated components. 75 | * 76 | * new Animated.Value(0) 77 | * .interpolate() .interpolate() new Animated.Value(1) 78 | * opacity translateY scale 79 | * style transform 80 | * View#234 style 81 | * View#123 82 | * 83 | * A) Top Down phase 84 | * When an Animated.Value is updated, we recursively go down through this 85 | * graph in order to find leaf nodes: the views that we flag as needing 86 | * an update. 87 | * 88 | * B) Bottom Up phase 89 | * When a view is flagged as needing an update, we recursively go back up 90 | * in order to build the new value that it needs. The reason why we need 91 | * this two-phases process is to deal with composite props such as 92 | * transform which can receive values from multiple parents. 93 | */ 94 | function _flush(node: AnimatedValue): void { 95 | var animatedStyles = new Set(); 96 | function findAnimatedStyles(theNode) { 97 | if ('update' in theNode) { 98 | animatedStyles.add(theNode); 99 | } else { 100 | theNode.getChildren().forEach(findAnimatedStyles); 101 | } 102 | } 103 | findAnimatedStyles(node); 104 | animatedStyles.forEach(animatedStyle => animatedStyle.update()); 105 | } 106 | 107 | type TimingAnimationConfig = { 108 | toValue: number; 109 | easing?: (value: number) => number; 110 | duration?: number; 111 | delay?: number; 112 | }; 113 | 114 | class TimingAnimation extends Animation { 115 | _startTime: number; 116 | _fromValue: number; 117 | _toValue: number; 118 | _duration: number; 119 | _delay: number; 120 | _easing: (value: number) => number; 121 | _onUpdate: (value: number) => void; 122 | _onEnd: ?((finished: bool) => void); 123 | _animationFrame: any; 124 | _timeout: any; 125 | 126 | constructor( 127 | config: TimingAnimationConfig 128 | ) { 129 | super(); 130 | this._toValue = config.toValue; 131 | this._easing = config.easing || Easing.inOut(Easing.ease); 132 | this._duration = config.duration !== undefined ? config.duration : 500; 133 | this._delay = config.delay || 0; 134 | } 135 | 136 | start( 137 | fromValue: number, 138 | onUpdate: (value: number) => void, 139 | onEnd: ?((finished: bool) => void) 140 | ): void { 141 | this._fromValue = fromValue; 142 | this._onUpdate = onUpdate; 143 | this._onEnd = onEnd; 144 | 145 | var start = () => { 146 | this._startTime = Date.now(); 147 | this._animationFrame = window.requestAnimationFrame(this.onUpdate.bind(this)); 148 | }; 149 | if (this._delay) { 150 | this._timeout = setTimeout(start, this._delay); 151 | } else { 152 | start(); 153 | } 154 | } 155 | 156 | onUpdate(): void { 157 | var now = Date.now(); 158 | 159 | if (now > this._startTime + this._duration) { 160 | this._onUpdate( 161 | this._fromValue + this._easing(1) * (this._toValue - this._fromValue) 162 | ); 163 | var onEnd = this._onEnd; 164 | this._onEnd = null; 165 | onEnd && onEnd(/* finished */ true); 166 | return; 167 | } 168 | 169 | this._onUpdate( 170 | this._fromValue + 171 | this._easing((now - this._startTime) / this._duration) * 172 | (this._toValue - this._fromValue) 173 | ); 174 | 175 | this._animationFrame = window.requestAnimationFrame(this.onUpdate.bind(this)); 176 | } 177 | 178 | stop(): void { 179 | clearTimeout(this._timeout); 180 | window.cancelAnimationFrame(this._animationFrame); 181 | var onEnd = this._onEnd; 182 | this._onEnd = null; 183 | onEnd && onEnd(/* finished */ false); 184 | } 185 | } 186 | 187 | type DecayAnimationConfig = { 188 | velocity: number; 189 | deceleration?: number; 190 | }; 191 | 192 | class DecayAnimation extends Animation { 193 | _startTime: number; 194 | _lastValue: number; 195 | _fromValue: number; 196 | _deceleration: number; 197 | _velocity: number; 198 | _onUpdate: (value: number) => void; 199 | _onEnd: ?((finished: bool) => void); 200 | _animationFrame: any; 201 | 202 | constructor( 203 | config: DecayAnimationConfig 204 | ) { 205 | super(); 206 | this._deceleration = config.deceleration || 0.998; 207 | this._velocity = config.velocity; 208 | } 209 | 210 | start( 211 | fromValue: number, 212 | onUpdate: (value: number) => void, 213 | onEnd: ?((finished: bool) => void) 214 | ): void { 215 | this._lastValue = fromValue; 216 | this._fromValue = fromValue; 217 | this._onUpdate = onUpdate; 218 | this._onEnd = onEnd; 219 | this._startTime = Date.now(); 220 | this._animationFrame = window.requestAnimationFrame(this.onUpdate.bind(this)); 221 | } 222 | 223 | onUpdate(): void { 224 | var now = Date.now(); 225 | 226 | var value = this._fromValue + 227 | (this._velocity / (1 - this._deceleration)) * 228 | (1 - Math.exp(-(1 - this._deceleration) * (now - this._startTime))); 229 | 230 | this._onUpdate(value); 231 | 232 | if (Math.abs(this._lastValue - value) < 0.1) { 233 | var onEnd = this._onEnd; 234 | this._onEnd = null; 235 | onEnd && onEnd(/* finished */ true); 236 | return; 237 | } 238 | 239 | this._lastValue = value; 240 | this._animationFrame = window.requestAnimationFrame(this.onUpdate.bind(this)); 241 | } 242 | 243 | stop(): void { 244 | window.cancelAnimationFrame(this._animationFrame); 245 | var onEnd = this._onEnd; 246 | this._onEnd = null; 247 | onEnd && onEnd(/* finished */ false); 248 | } 249 | } 250 | 251 | type SpringAnimationConfig = { 252 | toValue: number; 253 | overshootClamping?: bool; 254 | restDisplacementThreshold?: number; 255 | restSpeedThreshold?: number; 256 | velocity?: number; 257 | bounciness?: number; 258 | speed?: number; 259 | tension?: number; 260 | friction?: number; 261 | }; 262 | 263 | function withDefault(value: ?T, defaultValue: T): T { 264 | if (value === undefined || value === null) { 265 | return defaultValue; 266 | } 267 | return value; 268 | } 269 | 270 | 271 | function tensionFromOrigamiValue(oValue) { 272 | return (oValue - 30.0) * 3.62 + 194.0; 273 | } 274 | function frictionFromOrigamiValue(oValue) { 275 | return (oValue - 8.0) * 3.0 + 25.0; 276 | } 277 | 278 | var fromOrigamiTensionAndFriction = function(tension, friction) { 279 | return { 280 | tension: tensionFromOrigamiValue(tension), 281 | friction: frictionFromOrigamiValue(friction) 282 | }; 283 | } 284 | 285 | var fromBouncinessAndSpeed = function(bounciness, speed) { 286 | function normalize(value, startValue, endValue) { 287 | return (value - startValue) / (endValue - startValue); 288 | } 289 | function projectNormal(n, start, end) { 290 | return start + (n * (end - start)); 291 | } 292 | function linearInterpolation(t, start, end) { 293 | return t * end + (1.0 - t) * start; 294 | } 295 | function quadraticOutInterpolation(t, start, end) { 296 | return linearInterpolation(2 * t - t * t, start, end); 297 | } 298 | function b3Friction1(x) { 299 | return (0.0007 * Math.pow(x, 3)) - 300 | (0.031 * Math.pow(x, 2)) + 0.64 * x + 1.28; 301 | } 302 | function b3Friction2(x) { 303 | return (0.000044 * Math.pow(x, 3)) - 304 | (0.006 * Math.pow(x, 2)) + 0.36 * x + 2.; 305 | } 306 | function b3Friction3(x) { 307 | return (0.00000045 * Math.pow(x, 3)) - 308 | (0.000332 * Math.pow(x, 2)) + 0.1078 * x + 5.84; 309 | } 310 | function b3Nobounce(tension) { 311 | if (tension <= 18) { 312 | return b3Friction1(tension); 313 | } else if (tension > 18 && tension <= 44) { 314 | return b3Friction2(tension); 315 | } else { 316 | return b3Friction3(tension); 317 | } 318 | } 319 | 320 | var b = normalize(bounciness / 1.7, 0, 20.0); 321 | b = projectNormal(b, 0.0, 0.8); 322 | var s = normalize(speed / 1.7, 0, 20.0); 323 | var bouncyTension = projectNormal(s, 0.5, 200) 324 | var bouncyFriction = quadraticOutInterpolation( 325 | b, 326 | b3Nobounce(bouncyTension), 327 | 0.01 328 | ); 329 | 330 | return { 331 | tension: tensionFromOrigamiValue(bouncyTension), 332 | friction: frictionFromOrigamiValue(bouncyFriction) 333 | }; 334 | } 335 | 336 | class SpringAnimation extends Animation { 337 | _overshootClamping: bool; 338 | _restDisplacementThreshold: number; 339 | _restSpeedThreshold: number; 340 | _lastVelocity: number; 341 | _tempVelocity: number; 342 | _startPosition: number; 343 | _lastPosition: number; 344 | _tempPosition: number; 345 | _fromValue: number; 346 | _toValue: number; 347 | _tension: number; 348 | _friction: number; 349 | _lastTime: number; 350 | _onUpdate: (value: number) => void; 351 | _onEnd: ?((finished: bool) => void); 352 | _animationFrame: any; 353 | _active: bool; 354 | 355 | constructor( 356 | config: SpringAnimationConfig 357 | ) { 358 | super(); 359 | 360 | this._overshootClamping = withDefault(config.overshootClamping, false); 361 | this._restDisplacementThreshold = withDefault(config.restDisplacementThreshold, 0.001); 362 | this._restSpeedThreshold = withDefault(config.restSpeedThreshold, 0.001); 363 | this._lastVelocity = withDefault(config.velocity, 0); 364 | this._tempVelocity = this._lastVelocity; 365 | this._toValue = config.toValue; 366 | 367 | var springConfig; 368 | if (config.bounciness !== undefined || config.speed !== undefined) { 369 | invariant( 370 | config.tension === undefined && config.friction === undefined, 371 | 'You can only define bounciness/speed or tension/friction but not both' 372 | ); 373 | springConfig = fromBouncinessAndSpeed( 374 | withDefault(config.bounciness, 8), 375 | withDefault(config.speed, 12) 376 | ); 377 | } else { 378 | springConfig = fromOrigamiTensionAndFriction( 379 | withDefault(config.tension, 40), 380 | withDefault(config.friction, 7) 381 | ); 382 | } 383 | this._tension = springConfig.tension; 384 | this._friction = springConfig.friction; 385 | } 386 | 387 | start( 388 | fromValue: number, 389 | onUpdate: (value: number) => void, 390 | onEnd: ?((finished: bool) => void), 391 | previousAnimation: ?Animation 392 | ): void { 393 | this._active = true; 394 | this._startPosition = fromValue; 395 | this._lastPosition = this._startPosition; 396 | this._tempPosition = this._lastPosition; 397 | 398 | this._onUpdate = onUpdate; 399 | this._onEnd = onEnd; 400 | this._lastTime = Date.now(); 401 | 402 | if (previousAnimation instanceof SpringAnimation) { 403 | var internalState = previousAnimation.getInternalState(); 404 | this._lastPosition = internalState.lastPosition; 405 | this._tempPosition = internalState.tempPosition; 406 | this._lastVelocity = internalState.lastVelocity; 407 | this._tempVelocity = internalState.tempVelocity; 408 | this._lastTime = internalState.lastTime; 409 | } 410 | 411 | this.onUpdate(); 412 | } 413 | 414 | getInternalState(): any { 415 | return { 416 | lastPosition: this._lastPosition, 417 | tempPosition: this._tempPosition, 418 | lastVelocity: this._lastVelocity, 419 | tempVelocity: this._tempVelocity, 420 | lastTime: this._lastTime, 421 | }; 422 | } 423 | 424 | onUpdate(): void { 425 | if (!this._active) { 426 | return; 427 | } 428 | var now = Date.now(); 429 | 430 | var position = this._lastPosition; 431 | var velocity = this._lastVelocity; 432 | 433 | var tempPosition = position; 434 | var tempVelocity = velocity; 435 | 436 | var TIMESTEP_MSEC = 4; 437 | var numSteps = Math.floor((now - this._lastTime) / TIMESTEP_MSEC); 438 | for (var i = 0; i < numSteps; ++i) { 439 | // Velocity is based on seconds instead of milliseconds 440 | var step = TIMESTEP_MSEC / 1000; 441 | 442 | var aVelocity = velocity; 443 | var aAcceleration = this._tension * (this._toValue - tempPosition) - this._friction * tempVelocity; 444 | tempPosition = position + aVelocity * step / 2; 445 | tempVelocity = velocity + aAcceleration * step / 2; 446 | 447 | var bVelocity = tempVelocity; 448 | var bAcceleration = this._tension * (this._toValue - tempPosition) - this._friction * tempVelocity; 449 | tempPosition = position + bVelocity * step / 2; 450 | tempVelocity = velocity + bAcceleration * step / 2; 451 | 452 | var cVelocity = tempVelocity; 453 | var cAcceleration = this._tension * (this._toValue - tempPosition) - this._friction * tempVelocity; 454 | tempPosition = position + cVelocity * step; 455 | tempVelocity = velocity + cAcceleration * step; 456 | 457 | var dVelocity = tempVelocity; 458 | var dAcceleration = this._tension * (this._toValue - tempPosition) - this._friction * tempVelocity; 459 | 460 | var dxdt = (aVelocity + 2 * (bVelocity + cVelocity) + dVelocity) / 6; 461 | var dvdt = (aAcceleration + 2 * (bAcceleration + cAcceleration) + dAcceleration) / 6; 462 | 463 | position += dxdt * step; 464 | velocity += dvdt * step; 465 | } 466 | 467 | this._lastTime = now; 468 | this._tempPosition = tempPosition; 469 | this._tempVelocity = tempVelocity; 470 | this._lastPosition = position; 471 | this._lastVelocity = velocity; 472 | 473 | this._onUpdate(position); 474 | 475 | // Conditions for stopping the spring animation 476 | var isOvershooting = false; 477 | if (this._overshootClamping && this._tension !== 0) { 478 | if (this._startPosition < this._toValue) { 479 | isOvershooting = position > this._toValue; 480 | } else { 481 | isOvershooting = position < this._toValue; 482 | } 483 | } 484 | var isVelocity = Math.abs(velocity) <= this._restSpeedThreshold; 485 | var isDisplacement = true; 486 | if (this._tension !== 0) { 487 | isDisplacement = Math.abs(this._toValue - position) <= this._restDisplacementThreshold; 488 | } 489 | if (isOvershooting || (isVelocity && isDisplacement)) { 490 | var onEnd = this._onEnd; 491 | this._onEnd = null; 492 | onEnd && onEnd(/* finished */ true); 493 | return; 494 | } 495 | this._animationFrame = window.requestAnimationFrame(this.onUpdate.bind(this)); 496 | } 497 | 498 | stop(): void { 499 | this._active = false; 500 | window.cancelAnimationFrame(this._animationFrame); 501 | var onEnd = this._onEnd; 502 | this._onEnd = null; 503 | onEnd && onEnd(/* finished */ false); 504 | } 505 | } 506 | 507 | type ValueListenerCallback = (state: {value: number}) => void; 508 | 509 | var _uniqueId = 1; 510 | 511 | class AnimatedValue extends AnimatedWithChildren { 512 | _value: number; 513 | _offset: number; 514 | _animation: ?Animation; 515 | _listeners: {[key: number]: ValueListenerCallback}; 516 | 517 | constructor(value: number) { 518 | super(); 519 | this._value = value; 520 | this._offset = 0; 521 | this._animation = null; 522 | this._listeners = {}; 523 | } 524 | 525 | detach() { 526 | this.stopAnimation(); 527 | } 528 | 529 | getValue(): number { 530 | return this._value + this._offset; 531 | } 532 | 533 | setValue(value: number): void { 534 | if (this._animation) { 535 | this._animation.stop(); 536 | this._animation = null; 537 | } 538 | this._updateValue(value); 539 | } 540 | 541 | getOffset(): number { 542 | return this._offset; 543 | } 544 | 545 | setOffset(offset: number): void { 546 | this._offset = offset; 547 | } 548 | 549 | addListener(callback: ValueListenerCallback): number { 550 | var id = _uniqueId++; 551 | this._listeners[id] = callback; 552 | return id; 553 | } 554 | 555 | removeListener(id: number): void { 556 | delete this._listeners[id]; 557 | } 558 | 559 | animate(animation: Animation, callback: ?((finished: bool) => void)): void { 560 | var previousAnimation = this._animation; 561 | this._animation && this._animation.stop(); 562 | this._animation = animation; 563 | animation.start( 564 | this._value, 565 | (value) => { 566 | this._updateValue(value); 567 | }, 568 | (finished) => { 569 | this._animation = null; 570 | callback && callback(finished); 571 | }, 572 | previousAnimation 573 | ); 574 | } 575 | 576 | stopAnimation(callback?: ?() => number): void { 577 | this.stopTracking(); 578 | this._animation && this._animation.stop(); 579 | callback && callback(this._value); 580 | } 581 | 582 | stopTracking(): void { 583 | this._tracking && this._tracking.detach(); 584 | } 585 | 586 | track(tracking: Animation): void { 587 | this.stopTracking(); 588 | this._tracking = tracking; 589 | } 590 | 591 | interpolate(config: InterpolationConfigType): AnimatedInterpolation { 592 | return new AnimatedInterpolation(this, Interpolation.create(config)); 593 | } 594 | 595 | _updateValue(value: number): void { 596 | if (value === this._value) { 597 | return; 598 | } 599 | this._value = value; 600 | _flush(this); 601 | for (var key in this._listeners) { 602 | this._listeners[key]({value: this.getValue()}); 603 | } 604 | } 605 | } 606 | 607 | type Vec2ListenerCallback = (state: {x: number; y: number}) => void; 608 | class AnimatedVec2 extends AnimatedWithChildren { 609 | x: AnimatedValue; 610 | y: AnimatedValue; 611 | _listeners: {[key: number]: Vec2ListenerCallback}; 612 | 613 | constructor(value?: {x: number; y: number}) { 614 | super(); 615 | value = value || {x: 0, y: 0}; 616 | if (typeof value.x === 'number') { 617 | this.x = new AnimatedValue(value.x); 618 | this.y = new AnimatedValue(value.y); 619 | } else { 620 | this.x = value.x; 621 | this.y = value.y; 622 | } 623 | this._listeners = {}; 624 | } 625 | 626 | setValue(value: {x: number; y: number}) { 627 | this.x.setValue(value.x); 628 | this.y.setValue(value.y); 629 | } 630 | 631 | setOffset(offset: {x: number; y: number}) { 632 | this.x.setOffset(offset.x); 633 | this.y.setOffset(offset.y); 634 | } 635 | 636 | addListener(callback: Vec2ListenerCallback): number { 637 | var id = _uniqueId++; 638 | var jointCallback = (value) => { 639 | callback({x: this.x.getValue(), y: this.y.getValue()}); 640 | }; 641 | this._listeners[id] = { 642 | x: this.x.addListener(jointCallback), 643 | y: this.y.addListener(jointCallback), 644 | }; 645 | return id; 646 | } 647 | 648 | removeListener(id: number): void { 649 | this.x.removeListener(this._listeners[id].x); 650 | this.y.removeListener(this._listeners[id].y); 651 | delete this._listeners[id]; 652 | } 653 | 654 | offset(theOffset) { // chunky...perf? 655 | return new AnimatedVec2({ 656 | x: this.x.interpolate({ 657 | inputRange: [0, 1], 658 | outputRange: [theOffset.x, theOffset.x + 1], 659 | }), 660 | y: this.y.interpolate({ 661 | inputRange: [0, 1], 662 | outputRange: [theOffset.y, theOffset.y + 1], 663 | }), 664 | }); 665 | } 666 | 667 | getLayout() { 668 | return { 669 | left: this.x, 670 | top: this.y, 671 | }; 672 | } 673 | 674 | getTranslateTransform() { 675 | return [ 676 | {translateX: this.x}, 677 | {translateY: this.y} 678 | ]; 679 | } 680 | } 681 | 682 | class AnimatedInterpolation extends AnimatedWithChildren { 683 | _parent: Animated; 684 | _interpolation: (input: number) => number | string; 685 | _listeners: {[key: number]: ValueListenerCallback}; 686 | _parentListener: number; 687 | 688 | constructor(parent: Animated, interpolation: (input: number) => number | string) { 689 | super(); 690 | this._parent = parent; 691 | this._interpolation = interpolation; 692 | this._listeners = {}; 693 | } 694 | 695 | getValue(): number | string { 696 | var parentValue: number = this._parent.getValue(); 697 | invariant( 698 | typeof parentValue === 'number', 699 | 'Cannot interpolate an input which is not a number.' 700 | ); 701 | return this._interpolation(parentValue); 702 | } 703 | 704 | addListener(callback: ValueListenerCallback): number { 705 | if (!this._parentListener) { 706 | this._parentListener = this._parent.addListener(() => { 707 | for (var key in this._listeners) { 708 | this._listeners[key]({value: this.getValue()}); 709 | } 710 | }) 711 | } 712 | var id = _uniqueId++; 713 | this._listeners[id] = callback; 714 | return id; 715 | } 716 | 717 | removeListener(id: number): void { 718 | delete this._listeners[id]; 719 | } 720 | 721 | interpolate(config: InterpolationConfigType): AnimatedInterpolation { 722 | return new AnimatedInterpolation(this, Interpolation.create(config)); 723 | } 724 | 725 | attach(): void { 726 | this._parent.addChild(this); 727 | } 728 | 729 | detach(): void { 730 | this._parent.removeChild(this); 731 | this._parentListener = this._parent.removeListener(this._parentListener); 732 | } 733 | } 734 | 735 | class AnimatedTransform extends AnimatedWithChildren { 736 | _transforms: Array; 737 | 738 | constructor(transforms: Array) { 739 | super(); 740 | this._transforms = transforms; 741 | } 742 | 743 | getValue(): Array { 744 | return this._transforms.map(transform => { 745 | var result = ''; 746 | for (var key in transform) { 747 | var value = transform[key]; 748 | if (value instanceof Animated) { 749 | result += key + '(' + value.getValue() + ')'; 750 | } else { 751 | result += key + '(' + value.join(',') + ')'; 752 | } 753 | } 754 | return result; 755 | }).join(' '); 756 | } 757 | 758 | getAnimatedValue(): Array { 759 | return this._transforms.map(transform => { 760 | var result = ''; 761 | for (var key in transform) { 762 | var value = transform[key]; 763 | if (value instanceof Animated) { 764 | result += key + '(' + value.getValue() + ') '; 765 | } else { 766 | // All transform components needed to recompose matrix 767 | result += key + '(' + value.join(',') + ') '; 768 | } 769 | } 770 | return result; 771 | }).join('').trim(); 772 | } 773 | 774 | attach(): void { 775 | this._transforms.forEach(transform => { 776 | for (var key in transform) { 777 | var value = transform[key]; 778 | if (value instanceof Animated) { 779 | value.addChild(this); 780 | } 781 | } 782 | }); 783 | } 784 | 785 | detach(): void { 786 | this._transforms.forEach(transform => { 787 | for (var key in transform) { 788 | var value = transform[key]; 789 | if (value instanceof Animated) { 790 | value.removeChild(this); 791 | } 792 | } 793 | }); 794 | } 795 | } 796 | 797 | class AnimatedStyle extends AnimatedWithChildren { 798 | _style: Object; 799 | 800 | constructor(style: any) { 801 | super(); 802 | style = style || {}; 803 | if (style.transform) { 804 | style = { 805 | ...style, 806 | transform: new AnimatedTransform(style.transform), 807 | }; 808 | } 809 | this._style = style; 810 | } 811 | 812 | getValue(): Object { 813 | var style = {}; 814 | for (var key in this._style) { 815 | var value = this._style[key]; 816 | if (value instanceof Animated) { 817 | style[key] = value.getValue(); 818 | } else { 819 | style[key] = value; 820 | } 821 | } 822 | return style; 823 | } 824 | 825 | getAnimatedValue(): Object { 826 | var style = {}; 827 | for (var key in this._style) { 828 | var value = this._style[key]; 829 | if (value instanceof Animated) { 830 | style[key] = value.getAnimatedValue(); 831 | } 832 | } 833 | return style; 834 | } 835 | 836 | attach(): void { 837 | for (var key in this._style) { 838 | var value = this._style[key]; 839 | if (value instanceof Animated) { 840 | value.addChild(this); 841 | } 842 | } 843 | } 844 | 845 | detach(): void { 846 | for (var key in this._style) { 847 | var value = this._style[key]; 848 | if (value instanceof Animated) { 849 | value.removeChild(this); 850 | } 851 | } 852 | } 853 | } 854 | 855 | class AnimatedProps extends Animated { 856 | _props: Object; 857 | _callback: () => void; 858 | 859 | constructor( 860 | props: Object, 861 | callback: () => void 862 | ) { 863 | super(); 864 | if (props.style) { 865 | props = { 866 | ...props, 867 | style: new AnimatedStyle(props.style), 868 | }; 869 | } 870 | this._props = props; 871 | this._callback = callback; 872 | this.attach(); 873 | } 874 | 875 | getValue(): Object { 876 | var props = {}; 877 | for (var key in this._props) { 878 | var value = this._props[key]; 879 | if (value instanceof Animated) { 880 | props[key] = value.getValue(); 881 | } else { 882 | props[key] = value; 883 | } 884 | } 885 | return props; 886 | } 887 | 888 | getAnimatedValue(): Object { 889 | var props = {}; 890 | for (var key in this._props) { 891 | var value = this._props[key]; 892 | if (value instanceof Animated) { 893 | props[key] = value.getAnimatedValue(); 894 | } 895 | } 896 | return props; 897 | } 898 | 899 | attach(): void { 900 | for (var key in this._props) { 901 | var value = this._props[key]; 902 | if (value instanceof Animated) { 903 | value.addChild(this); 904 | } 905 | } 906 | } 907 | 908 | detach(): void { 909 | for (var key in this._props) { 910 | var value = this._props[key]; 911 | if (value instanceof Animated) { 912 | value.removeChild(this); 913 | } 914 | } 915 | } 916 | 917 | update(): void { 918 | this._callback(); 919 | } 920 | } 921 | 922 | function createAnimatedComponent(Component: any): any { 923 | var refName = 'node'; 924 | 925 | class AnimatedComponent extends React.Component { 926 | _propsAnimated: AnimatedProps; 927 | 928 | componentWillUnmount() { 929 | this._propsAnimated && this._propsAnimated.detach(); 930 | } 931 | 932 | setNativeProps(props) { 933 | this.refs[refName].setNativeProps(props); 934 | } 935 | 936 | componentWillMount() { 937 | this.attachProps(this.props); 938 | } 939 | 940 | attachProps(nextProps) { 941 | var oldPropsAnimated = this._propsAnimated; 942 | 943 | // The system is best designed when setNativeProps is implemented. It is 944 | // able to avoid re-rendering and directly set the attributes that 945 | // changed. However, setNativeProps can only be implemented on leaf 946 | // native components. If you want to animate a composite component, you 947 | // need to re-render it. In this case, we have a fallback that uses 948 | // forceUpdate. 949 | var callback = () => { 950 | if (this.refs[refName].setNativeProps) { 951 | var value = this._propsAnimated.getAnimatedValue(); 952 | this.refs[refName].setNativeProps(value); 953 | } else if (this.refs[refName].getDOMNode().setAttribute) { 954 | var value = this._propsAnimated.getAnimatedValue(); 955 | var strStyle = React.CSSPropertyOperations.setValueForStyles(this.refs[refName].getDOMNode(), value.style, this.refs[refName]); 956 | } else { 957 | this.forceUpdate(); 958 | } 959 | }; 960 | 961 | this._propsAnimated = new AnimatedProps( 962 | nextProps, 963 | callback 964 | ); 965 | 966 | // When you call detach, it removes the element from the parent list 967 | // of children. If it goes to 0, then the parent also detaches itself 968 | // and so on. 969 | // An optimization is to attach the new elements and THEN detach the old 970 | // ones instead of detaching and THEN attaching. 971 | // This way the intermediate state isn't to go to 0 and trigger 972 | // this expensive recursive detaching to then re-attach everything on 973 | // the very next operation. 974 | oldPropsAnimated && oldPropsAnimated.detach(); 975 | } 976 | 977 | componentWillReceiveProps(nextProps) { 978 | this.attachProps(nextProps); 979 | } 980 | 981 | render() { 982 | return ( 983 | 987 | ); 988 | } 989 | } 990 | 991 | return AnimatedComponent; 992 | } 993 | 994 | class AnimatedTracking extends Animated { 995 | _parent: Animated; 996 | _callback: () => void; 997 | 998 | constructor( 999 | value: AnimatedValue, 1000 | parent: Animated, 1001 | animationClass: any, 1002 | animationConfig: any, 1003 | callback: any 1004 | ) { 1005 | super(); 1006 | this._value = value; 1007 | this._parent = parent; 1008 | this._animationClass = animationClass; 1009 | this._animationConfig = animationConfig; 1010 | this._callback = callback; 1011 | this.attach(); 1012 | } 1013 | 1014 | getValue(): Object { 1015 | return this._parent.getValue(); 1016 | } 1017 | 1018 | attach(): void { 1019 | this._active = true; 1020 | this._parent.addChild(this); 1021 | } 1022 | 1023 | detach(): void { 1024 | this._parent.removeChild(this); 1025 | this._active = false; 1026 | } 1027 | 1028 | update(): void { 1029 | if (!this._active) { 1030 | console.warn('calling update on detached AnimatedTracking'); 1031 | return; 1032 | } 1033 | // console.log('AnimatedTracking update with ', 1034 | // {toValue: this._animationConfig.toValue.getValue(), value: this._value.getValue()}); 1035 | this._value.animate(new this._animationClass({ 1036 | ...this._animationConfig, 1037 | toValue: (this._animationConfig.toValue: any).getValue(), 1038 | }), this._callback); 1039 | } 1040 | } 1041 | 1042 | type CompositeAnimation = { 1043 | start: (callback?: ?(finished: bool) => void) => void; 1044 | stop: () => void; 1045 | }; 1046 | 1047 | var maybeVectorAnim = function( 1048 | value: AnimatedValue, 1049 | config: Object, 1050 | anim: (value: AnimatedValue, config: Object) => CompositeAnimation 1051 | ): CompositeAnimation { 1052 | if (value instanceof AnimatedVec2) { 1053 | var configX = {...config}; 1054 | var configY = {...config}; 1055 | for (var key in config) { 1056 | var {x, y} = config[key]; 1057 | if (x !== undefined && y !== undefined) { 1058 | configX[key] = x; 1059 | configY[key] = y; 1060 | } 1061 | } 1062 | // TODO: Urg, parallel breaks tracking :( 1063 | // return parallel([ 1064 | // anim(value.x, configX), 1065 | // anim(value.y, configY), 1066 | // ]); 1067 | anim(value.x, configX).start(); 1068 | return anim(value.y, configY); 1069 | } 1070 | return null; 1071 | }; 1072 | 1073 | var spring = function( 1074 | value: AnimatedValue, 1075 | config: SpringAnimationConfig 1076 | ): CompositeAnimation { 1077 | return maybeVectorAnim(value, config, spring) || { 1078 | start: function(callback?: ?(finished: bool) => void): void { 1079 | value.stopTracking(); 1080 | if (config.toValue instanceof Animated) { 1081 | value.track(new AnimatedTracking( 1082 | value, 1083 | config.toValue, 1084 | SpringAnimation, 1085 | config, 1086 | callback 1087 | )); 1088 | } else { 1089 | value.animate(new SpringAnimation(config), callback); 1090 | } 1091 | }, 1092 | 1093 | stop: function(): void { 1094 | value.stopAnimation(); 1095 | }, 1096 | }; 1097 | }; 1098 | 1099 | var timing = function( 1100 | value: AnimatedValue, 1101 | config: TimingAnimationConfig 1102 | ): CompositeAnimation { 1103 | return maybeVectorAnim(value, config, timing) || { 1104 | start: function(callback?: ?(finished: bool) => void): void { 1105 | value.stopTracking(); 1106 | value.animate(new TimingAnimation(config), callback); 1107 | }, 1108 | 1109 | stop: function(): void { 1110 | value.stopAnimation(); 1111 | }, 1112 | }; 1113 | }; 1114 | 1115 | var decay = function( 1116 | value: AnimatedValue, 1117 | config: DecayAnimationConfig 1118 | ): CompositeAnimation { 1119 | return maybeVectorAnim(value, config, decay) || { 1120 | start: function(callback?: ?(finished: bool) => void): void { 1121 | value.stopTracking(); 1122 | value.animate(new DecayAnimation(config), callback); 1123 | }, 1124 | 1125 | stop: function(): void { 1126 | value.stopAnimation(); 1127 | }, 1128 | }; 1129 | }; 1130 | 1131 | var sequence = function( 1132 | animations: Array 1133 | ): CompositeAnimation { 1134 | var current = 0; 1135 | return { 1136 | start: function(callback?: ?(finished: bool) => void) { 1137 | var onComplete = function(finished) { 1138 | if (!finished) { 1139 | callback && callback(finished); 1140 | return; 1141 | } 1142 | 1143 | current++; 1144 | 1145 | if (current === animations.length) { 1146 | callback && callback(/* finished */ true); 1147 | return; 1148 | } 1149 | 1150 | animations[current].start(onComplete); 1151 | }; 1152 | 1153 | if (animations.length === 0) { 1154 | callback && callback(/* finished */ true); 1155 | } else { 1156 | animations[current].start(onComplete); 1157 | } 1158 | }, 1159 | 1160 | stop: function() { 1161 | if (current < animations.length) { 1162 | animations[current].stop(); 1163 | } 1164 | } 1165 | }; 1166 | }; 1167 | 1168 | var parallel = function( 1169 | animations: Array 1170 | ): CompositeAnimation { 1171 | var doneCount = 0; 1172 | // Variable to make sure we only call stop() at most once 1173 | var hasBeenStopped = false; 1174 | 1175 | var result = { 1176 | start: function(callback?: ?(finished: bool) => void) { 1177 | if (doneCount === animations.length) { 1178 | callback && callback(/* finished */ true); 1179 | return; 1180 | } 1181 | 1182 | animations.forEach((animation, idx) => { 1183 | animation.start(finished => { 1184 | doneCount++; 1185 | if (doneCount === animations.length) { 1186 | callback && callback(finished); 1187 | return; 1188 | } 1189 | 1190 | if (!finished && !hasBeenStopped) { 1191 | result.stop(); 1192 | } 1193 | }); 1194 | }); 1195 | }, 1196 | 1197 | stop: function(): void { 1198 | hasBeenStopped = true; 1199 | animations.forEach(animation => { 1200 | animation.stop(); 1201 | }); 1202 | } 1203 | }; 1204 | 1205 | return result; 1206 | }; 1207 | 1208 | var delay = function(time: number): CompositeAnimation { 1209 | // Would be nice to make a specialized implementation. 1210 | return timing(new AnimatedValue(0), {toValue: 0, delay: time, duration: 0}); 1211 | }; 1212 | 1213 | var stagger = function( 1214 | time: number, 1215 | animations: Array 1216 | ): CompositeAnimation { 1217 | return parallel(animations.map((animation, i) => { 1218 | return sequence([ 1219 | delay(time * i), 1220 | animation, 1221 | ]); 1222 | })); 1223 | }; 1224 | 1225 | type Mapping = {[key: string]: Mapping} | AnimatedValue; 1226 | 1227 | /** 1228 | * Takes an array of mappings and extracts values from each arg accordingly, 1229 | * then calls setValue on the mapped outputs. e.g. 1230 | * 1231 | * onScroll={this.AnimatedEvent( 1232 | * [{nativeEvent: {contentOffset: {x: this._scrollX}}}] 1233 | * {listener, updatePeriod: 100} // optional listener invoked every 100ms 1234 | * ) 1235 | * ... 1236 | * onPanResponderMove: this.AnimatedEvent([ 1237 | * null, // raw event arg 1238 | * {dx: this._panX}, // gestureState arg 1239 | * ]), 1240 | * 1241 | */ 1242 | var event = function( 1243 | argMapping: Array, 1244 | config?: any 1245 | ): () => void { 1246 | var lastUpdate = 0; 1247 | var timer; 1248 | var isEnabled = true; 1249 | if (config && config.ref) { 1250 | config.ref({ 1251 | enable: () => { 1252 | isEnabled = true; 1253 | }, 1254 | disable: () => { 1255 | isEnabled = false; 1256 | clearTimeout(timer); 1257 | timer = null; 1258 | }, 1259 | }); 1260 | } 1261 | var lastArgs; 1262 | return function(): void { 1263 | lastArgs = arguments; 1264 | if (!isEnabled) { 1265 | clearTimeout(timer); 1266 | timer = null; 1267 | return; 1268 | } 1269 | var traverse = function(recMapping, recEvt, key) { 1270 | if (recMapping instanceof AnimatedValue 1271 | || recMapping instanceof AnimatedInterpolation) { 1272 | invariant( 1273 | typeof recEvt === 'number', 1274 | 'Bad event element of type ' + typeof recEvt + ' for key ' + key 1275 | ); 1276 | recMapping.setValue(recEvt); 1277 | return; 1278 | } 1279 | invariant( 1280 | typeof recMapping === 'object', 1281 | 'Bad mapping of type ' + typeof recMapping + ' for key ' + key 1282 | ); 1283 | invariant( 1284 | typeof recEvt === 'object', 1285 | 'Bad event of type ' + typeof recEvt + ' for key ' + key 1286 | ); 1287 | for (var key in recMapping) { 1288 | traverse(recMapping[key], recEvt[key], key); 1289 | } 1290 | }; 1291 | argMapping.forEach((mapping, idx) => { 1292 | traverse(mapping, lastArgs[idx], null); 1293 | }); 1294 | if (config && config.listener && !timer) { 1295 | var cb = () => { 1296 | lastUpdate = Date.now(); 1297 | timer = null; 1298 | config.listener.apply(null, lastArgs); 1299 | }; 1300 | if (config.updatePeriod) { 1301 | timer = setTimeout(cb, config.updatePeriod - Date.now() + lastUpdate); 1302 | } else { 1303 | cb(); 1304 | } 1305 | } 1306 | }; 1307 | }; 1308 | 1309 | return module.exports = { 1310 | delay, 1311 | sequence, 1312 | parallel, 1313 | stagger, 1314 | 1315 | decay, 1316 | timing, 1317 | spring, 1318 | 1319 | event, 1320 | 1321 | Value: AnimatedValue, 1322 | Vec2: AnimatedVec2, 1323 | __PropsOnlyForTests: AnimatedProps, 1324 | div: createAnimatedComponent('div'), 1325 | createAnimatedComponent, 1326 | }; 1327 | 1328 | })(); 1329 | -------------------------------------------------------------------------------- /Easing.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | * @providesModule Easing 10 | */ 11 | 'use strict'; 12 | 13 | /** 14 | * This class implements common easing functions. The math is pretty obscure, 15 | * but this cool website has nice visual illustrations of what they represent: 16 | * http://xaedes.de/dev/transitions/ 17 | */ 18 | class Easing { 19 | static step0(n) { 20 | return n > 0 ? 1 : 0; 21 | } 22 | 23 | static step1(n) { 24 | return n >= 1 ? 1 : 0; 25 | } 26 | 27 | static linear(t) { 28 | return t; 29 | } 30 | 31 | static ease(t: number): number { 32 | return ease(t); 33 | } 34 | 35 | static quad(t) { 36 | return t * t; 37 | } 38 | 39 | static cubic(t) { 40 | return t * t * t; 41 | } 42 | 43 | static poly(n) { 44 | return (t) => Math.pow(t, n); 45 | } 46 | 47 | static sin(t) { 48 | return 1 - Math.cos(t * Math.PI / 2); 49 | } 50 | 51 | static circle(t) { 52 | return 1 - Math.sqrt(1 - t * t); 53 | } 54 | 55 | static exp(t) { 56 | return Math.pow(2, 10 * (t - 1)); 57 | } 58 | 59 | static elastic(a: number, p: number): (t: number) => number { 60 | var tau = Math.PI * 2; 61 | // flow isn't smart enough to figure out that s is always assigned to a 62 | // number before being used in the returned function 63 | var s: any; 64 | if (arguments.length < 2) { 65 | p = 0.45; 66 | } 67 | if (arguments.length) { 68 | s = p / tau * Math.asin(1 / a); 69 | } else { 70 | a = 1; 71 | s = p / 4; 72 | } 73 | return (t) => 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * tau / p); 74 | }; 75 | 76 | static back(s: number): (t: number) => number { 77 | if (s === undefined) { 78 | s = 1.70158; 79 | } 80 | return (t) => t * t * ((s + 1) * t - s); 81 | }; 82 | 83 | static bounce(t: number): number { 84 | if (t < 1 / 2.75) { 85 | return 7.5625 * t * t; 86 | } 87 | 88 | if (t < 2 / 2.75) { 89 | t -= 1.5 / 2.75; 90 | return 7.5625 * t * t + 0.75; 91 | } 92 | 93 | if (t < 2.5 / 2.75) { 94 | t -= 2.25 / 2.75; 95 | return 7.5625 * t * t + 0.9375; 96 | } 97 | 98 | t -= 2.625 / 2.75; 99 | return 7.5625 * t * t + 0.984375; 100 | }; 101 | 102 | static bezier( 103 | x1: number, 104 | y1: number, 105 | x2: number, 106 | y2: number, 107 | epsilon?: ?number 108 | ): (t: number) => number { 109 | if (epsilon === undefined) { 110 | // epsilon determines the precision of the solved values 111 | // a good approximation is: 112 | var duration = 500; // duration of animation in milliseconds. 113 | epsilon = (1000 / 60 / duration) / 4; 114 | } 115 | 116 | return bezier(x1, y1, x2, y2, epsilon); 117 | } 118 | 119 | static in( 120 | easing: (t: number) => number 121 | ): (t: number) => number { 122 | return easing; 123 | } 124 | 125 | static out( 126 | easing: (t: number) => number 127 | ): (t: number) => number { 128 | return (t) => 1 - easing(1 - t); 129 | } 130 | 131 | static inOut( 132 | easing: (t: number) => number 133 | ): (t: number) => number { 134 | return (t) => { 135 | if (t < 0.5) { 136 | return easing(t * 2) / 2; 137 | } 138 | return 1 - easing((1 - t) * 2) / 2; 139 | }; 140 | } 141 | } 142 | 143 | var ease = Easing.bezier(0.42, 0, 1, 1); 144 | 145 | module.exports = Easing; 146 | -------------------------------------------------------------------------------- /Interpolation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | * @providesModule Interpolation 10 | * @flow 11 | */ 12 | 'use strict'; 13 | 14 | var linear = (t) => t; 15 | 16 | /** 17 | * Very handy helper to map input ranges to output ranges with an easing 18 | * function and custom behavior outside of the ranges. 19 | */ 20 | class Interpolation { 21 | static create(config: InterpolationConfigType): (input: number) => number | string { 22 | 23 | if (config.outputRange && typeof config.outputRange[0] === 'string') { 24 | return createInterpolationFromStringOutputRange(config); 25 | } 26 | 27 | var outputRange: Array = (config.outputRange: any); 28 | checkInfiniteRange('outputRange', outputRange); 29 | 30 | var inputRange = config.inputRange; 31 | checkInfiniteRange('inputRange', inputRange); 32 | checkValidInputRange(inputRange); 33 | 34 | invariant( 35 | inputRange.length === outputRange.length, 36 | 'inputRange (' + inputRange.length + ') and outputRange (' + 37 | outputRange.length + ') must have the same length' 38 | ); 39 | 40 | var easing = config.easing || linear; 41 | 42 | var extrapolateLeft: ExtrapolateType = 'extend'; 43 | if (config.extrapolateLeft !== undefined) { 44 | extrapolateLeft = config.extrapolateLeft; 45 | } else if (config.extrapolate !== undefined) { 46 | extrapolateLeft = config.extrapolate; 47 | } 48 | 49 | var extrapolateRight: ExtrapolateType = 'extend'; 50 | if (config.extrapolateRight !== undefined) { 51 | extrapolateRight = config.extrapolateRight; 52 | } else if (config.extrapolate !== undefined) { 53 | extrapolateRight = config.extrapolate; 54 | } 55 | 56 | return (input) => { 57 | invariant( 58 | typeof input === 'number', 59 | 'Cannot interpolation an input which is not a number' 60 | ); 61 | 62 | var range = findRange(input, inputRange); 63 | return interpolate( 64 | input, 65 | inputRange[range], 66 | inputRange[range + 1], 67 | outputRange[range], 68 | outputRange[range + 1], 69 | easing, 70 | extrapolateLeft, 71 | extrapolateRight 72 | ); 73 | }; 74 | } 75 | } 76 | 77 | function interpolate( 78 | input: number, 79 | inputMin: number, 80 | inputMax: number, 81 | outputMin: number, 82 | outputMax: number, 83 | easing: ((input: number) => number), 84 | extrapolateLeft: ExtrapolateType, 85 | extrapolateRight: ExtrapolateType 86 | ) { 87 | var result = input; 88 | 89 | // Extrapolate 90 | if (result < inputMin) { 91 | if (extrapolateLeft === 'identity') { 92 | return result; 93 | } else if (extrapolateLeft === 'clamp') { 94 | result = inputMin; 95 | } else if (extrapolateLeft === 'extend') { 96 | // noop 97 | } 98 | } 99 | 100 | if (result > inputMax) { 101 | if (extrapolateRight === 'identity') { 102 | return result; 103 | } else if (extrapolateRight === 'clamp') { 104 | result = inputMax; 105 | } else if (extrapolateRight === 'extend') { 106 | // noop 107 | } 108 | } 109 | 110 | if (outputMin === outputMax) { 111 | return outputMin; 112 | } 113 | 114 | if (inputMin === inputMax) { 115 | if (input <= inputMin) { 116 | return outputMin; 117 | } 118 | return outputMax; 119 | } 120 | 121 | // Input Range 122 | if (inputMin === -Infinity) { 123 | result = -result; 124 | } else if (inputMax === Infinity) { 125 | result = result - inputMin; 126 | } else { 127 | result = (result - inputMin) / (inputMax - inputMin); 128 | } 129 | 130 | // Easing 131 | result = easing(result); 132 | 133 | // Output Range 134 | if (outputMin === -Infinity) { 135 | result = -result; 136 | } else if (outputMax === Infinity) { 137 | result = result + outputMin; 138 | } else { 139 | result = result * (outputMax - outputMin) + outputMin; 140 | } 141 | 142 | return result; 143 | } 144 | 145 | var stringShapeRegex = /[0-9\.-]+/g; 146 | 147 | /** 148 | * Supports string shapes by extracting numbers so new values can be computed, 149 | * and recombines those values into new strings of the same shape. Supports 150 | * things like: 151 | * 152 | * rgba(123, 42, 99, 0.36) // colors 153 | * -45deg // values with units 154 | */ 155 | function createInterpolationFromStringOutputRange( 156 | config: InterpolationConfigType 157 | ): (input: number) => string { 158 | var outputRange: Array = (config.outputRange: any); 159 | invariant(outputRange.length >= 2, 'Bad output range'); 160 | checkPattern(outputRange); 161 | 162 | // ['rgba(0, 100, 200, 0)', 'rgba(50, 150, 250, 0.5)'] 163 | // -> 164 | // [ 165 | // [0, 50], 166 | // [100, 150], 167 | // [200, 250], 168 | // [0, 0.5], 169 | // ] 170 | var outputRanges = outputRange[0].match(stringShapeRegex).map(() => []); 171 | outputRange.forEach(value => { 172 | value.match(stringShapeRegex).forEach((number, i) => { 173 | outputRanges[i].push(+number); 174 | }); 175 | }); 176 | 177 | var interpolations = outputRange[0].match(stringShapeRegex).map((value, i) => { 178 | return Interpolation.create({ 179 | ...config, 180 | outputRange: outputRanges[i], 181 | }); 182 | }); 183 | 184 | return (input) => { 185 | var i = 0; 186 | // 'rgba(0, 100, 200, 0)' 187 | // -> 188 | // 'rgba(${interpolations[0](input)}, ${interpolations[1](input)}, ...' 189 | return outputRange[0].replace(stringShapeRegex, () => { 190 | return String(interpolations[i++](input)); 191 | }); 192 | }; 193 | } 194 | 195 | function checkPattern(arr: Array) { 196 | var pattern = arr[0].replace(stringShapeRegex, ''); 197 | for (var i = 1; i < arr.length; ++i) { 198 | invariant( 199 | pattern === arr[i].replace(stringShapeRegex, ''), 200 | 'invalid pattern ' + arr[0] + ' and ' + arr[i] 201 | ); 202 | } 203 | } 204 | 205 | function findRange(input: number, inputRange: Array) { 206 | for (var i = 1; i < inputRange.length - 1; ++i) { 207 | if (inputRange[i] >= input) { 208 | break; 209 | } 210 | } 211 | return i - 1; 212 | } 213 | 214 | function checkValidInputRange(arr: Array) { 215 | invariant(arr.length >= 2, 'inputRange must have at least 2 elements'); 216 | for (var i = 1; i < arr.length; ++i) { 217 | invariant( 218 | arr[i] >= arr[i - 1], 219 | /* $FlowFixMe(>=0.13.0) - In the addition expression below this comment, 220 | * one or both of the operands may be something that doesn't cleanly 221 | * convert to a string, like undefined, null, and object, etc. If you really 222 | * mean this implicit string conversion, you can do something like 223 | * String(myThing) 224 | */ 225 | 'inputRange must be monolithically increasing ' + arr 226 | ); 227 | } 228 | } 229 | 230 | function checkInfiniteRange(name: string, arr: Array) { 231 | invariant(arr.length >= 2, name + ' must have at least 2 elements'); 232 | invariant( 233 | arr.length !== 2 || arr[0] !== -Infinity || arr[1] !== Infinity, 234 | /* $FlowFixMe(>=0.13.0) - In the addition expression below this comment, 235 | * one or both of the operands may be something that doesn't cleanly convert 236 | * to a string, like undefined, null, and object, etc. If you really mean 237 | * this implicit string conversion, you can do something like 238 | * String(myThing) 239 | */ 240 | name + 'cannot be ]-infinity;+infinity[ ' + arr 241 | ); 242 | } 243 | 244 | module.exports = Interpolation; 245 | -------------------------------------------------------------------------------- /bezier.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://github.com/arian/cubic-bezier 3 | * 4 | * MIT License 5 | * 6 | * Copyright (c) 2013 Arian Stolwijk 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining 9 | * a copy of this software and associated documentation files (the 10 | * "Software"), to deal in the Software without restriction, including 11 | * without limitation the rights to use, copy, modify, merge, publish, 12 | * distribute, sublicense, and/or sell copies of the Software, and to 13 | * permit persons to whom the Software is furnished to do so, subject to 14 | * the following conditions: 15 | * 16 | * The above copyright notice and this permission notice shall be 17 | * included in all copies or substantial portions of the Software. 18 | * 19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 20 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 21 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 22 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 23 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 24 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 25 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 26 | * 27 | * @providesModule bezier 28 | * @nolint 29 | */ 30 | 31 | var bezier = module.exports = function (x1, y1, x2, y2, epsilon){ 32 | 33 | var curveX = function(t){ 34 | var v = 1 - t; 35 | return 3 * v * v * t * x1 + 3 * v * t * t * x2 + t * t * t; 36 | }; 37 | 38 | var curveY = function(t){ 39 | var v = 1 - t; 40 | return 3 * v * v * t * y1 + 3 * v * t * t * y2 + t * t * t; 41 | }; 42 | 43 | var derivativeCurveX = function(t){ 44 | var v = 1 - t; 45 | return 3 * (2 * (t - 1) * t + v * v) * x1 + 3 * (- t * t * t + 2 * v * t) * x2; 46 | }; 47 | 48 | return function(t){ 49 | 50 | var x = t, t0, t1, t2, x2, d2, i; 51 | 52 | // First try a few iterations of Newton's method -- normally very fast. 53 | for (t2 = x, i = 0; i < 8; i++){ 54 | x2 = curveX(t2) - x; 55 | if (Math.abs(x2) < epsilon) return curveY(t2); 56 | d2 = derivativeCurveX(t2); 57 | if (Math.abs(d2) < 1e-6) break; 58 | t2 = t2 - x2 / d2; 59 | } 60 | 61 | t0 = 0, t1 = 1, t2 = x; 62 | 63 | if (t2 < t0) return curveY(t0); 64 | if (t2 > t1) return curveY(t1); 65 | 66 | // Fallback to the bisection method for reliability. 67 | while (t0 < t1){ 68 | x2 = curveX(t2); 69 | if (Math.abs(x2 - x) < epsilon) return curveY(t2); 70 | if (x > x2) t0 = t2; 71 | else t1 = t2; 72 | t2 = (t1 - t0) * .5 + t0; 73 | } 74 | 75 | // Failure 76 | return curveY(t2); 77 | 78 | }; 79 | 80 | }; 81 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Animated 6 | 10 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 42 | 50 | 155 | 156 | 157 | 158 | 159 |
160 | 161 |

Animated

162 |

Animations have for a long time been a weak point of the React ecosystem. The Animated 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.

163 | 164 |

Animated.Value

165 | 166 |

The basic building block of this library is Animated.Value. This is a variable that's going to drive the animation. You use it like a normal value in style attribute. Only animated components such as Animated.div will understand it.

167 | 168 | 185 | 186 |

setValue

187 | 188 |

As you can see, the value is being used inside of render() as you would expect. However, you don't call setState() in order to update the value. Instead, you can call setValue() directly on the value itself. We are using a form of data binding.

189 | 190 |

The Animated.div 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.

191 | 192 | 214 | 215 |

Animated.timing

216 | 217 |

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.

218 | 219 |

On every frame (via requestAnimationFrame), the timing 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.

220 | 221 | 243 | 244 |

Interrupt Animations

245 | 246 |

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%.

247 | 248 |

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, Animated will do that automatically for you.

249 | 250 | 276 | 277 |

Animated.spring

278 | 279 |

Unfortunately, the timing 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.

280 | 281 |

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.

282 | 283 |

It turns out that this model is useful in a very wide range of animations. I highly recommend you to always start with a spring animation instead of a timing animation. It will make your interface feels much better.

284 | 285 | 311 | 312 |

interpolate

313 | 314 |

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.

315 | 316 |

With Animated, 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.

317 | 318 |

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 interpolate() comes handy.

319 | 320 | 355 | 356 |

stopAnimation

357 | 358 |

The reason why we can get away with not calling render() and instead modify the DOM directly on updates is because the animated values are opaque. In render, you cannot know the current value, which prevents you from being able to modify the structure of the DOM.

359 | 360 |

Animated 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.

361 | 362 |

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 stopAnimation. It will not suffer from beign out of sync since the animation is no longer running.

363 | 364 | 400 | 401 | 402 |

Gesture-based Animations

403 | 404 |

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.

405 | 406 |

Animated 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.

407 | 408 |

HorizontalPan

409 | 410 |

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. removeEventListener takes the same arguments as addEventListener instead of an id like clearTimeout. 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.

411 | 412 |

We introduce a little helper called HorizontalPan which handles all this annoying code for us. It takes an Animated.Value as first argument and returns the event handlers required for it to work. We just have to bind this value to the left attribute and we're good to go.

413 | 414 | 433 | 434 |

Animated.decay

435 | 436 |

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.

437 | 438 |

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 Animated.decay.

439 | 440 | 464 | 465 |

Animation Chaining

466 | 467 |

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.

468 | 469 | 502 | 503 |

addListener

504 | 505 |

As I said earlier, if you track a spring

506 | 507 | 564 | 565 | 566 |

Animated.sequence

567 | 568 |

It is very common to animate

569 | 570 | 599 | 600 | 601 | 631 | 632 | 667 | 668 | 707 | 708 | 741 | 742 | 743 |
744 | 745 | 746 | -------------------------------------------------------------------------------- /style.css: -------------------------------------------------------------------------------- 1 | html, h1, h2 { 2 | font-family: 'Roboto', sans-serif; 3 | font-weight: 300; 4 | } 5 | 6 | .container { 7 | width: 800px; 8 | margin: 0 auto; 9 | } 10 | 11 | .circle { 12 | margin: 2px; 13 | width: 50px; 14 | height: 50px; 15 | position: absolute; 16 | display: inline-block; 17 | box-shadow: 0px 1px 2px #999; 18 | text-shadow: 0px 1px 2px #999; 19 | background-image: url(https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xtf1/v/t1.0-1/p320x320/10958296_10152690932671188_4256540723631642566_n.jpg?oh=a69694fcf15345249df14dea4c3e3066&oe=5659ED51&__gda__=1444749767_96630067bf758b113706aa1c91fde392); 20 | background-size: cover; 21 | line-height: 80px; 22 | vertical-align: bottom; 23 | text-align: center; 24 | color: white; 25 | font-size: 10px; 26 | } 27 | 28 | .circle:nth-child(2) { 29 | background-image: url(https://scontent-cdg2-1.xx.fbcdn.net/hphotos-xtf1/v/t1.0-9/1923173_716264837373_4589103_n.jpg?oh=e0ec3bd50f6567875a44ea6173e466cd&oe=5619375B); 30 | } 31 | 32 | .circle:nth-child(3) { 33 | background-image: url(https://scontent-cdg2-1.xx.fbcdn.net/hphotos-xtf1/v/t1.0-9/10170789_2386880322730_6755618519839435556_n.jpg?oh=107da1d6c5a1c7783a0e09ea7b04102f&oe=5657F184); 34 | } 35 | 36 | div.code { 37 | box-shadow: 0px 1px 2px #999; 38 | width: 600px; 39 | padding: 5px; 40 | position: relative; 41 | margin: 0 auto; 42 | margin-bottom: 40px; 43 | } 44 | 45 | div.code .reset { 46 | float: right; 47 | } 48 | 49 | div.code pre { 50 | padding: 2px; 51 | } 52 | 53 | hr { 54 | border: none; 55 | border-bottom: 1px solid #D9D9D9; 56 | margin: 0; 57 | } 58 | 59 | button { 60 | vertical-align: top; 61 | } 62 | 63 | .example > span { 64 | color: #333; 65 | font-size: 13px; 66 | } 67 | 68 | .example { 69 | position: relative; 70 | height: 60px; 71 | } 72 | 73 | .code pre { 74 | margin: 0; 75 | font-size: 11px; 76 | line-height: 1; 77 | } 78 | 79 | .highlight { 80 | background: rgb(228, 254, 253); 81 | } --------------------------------------------------------------------------------