This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

View File

@ -0,0 +1,168 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
import AnimatedValue from './nodes/AnimatedValue';
import NativeAnimatedHelper from './NativeAnimatedHelper';
import findNodeHandle from '../../../exports/findNodeHandle';
import invariant from 'fbjs/lib/invariant';
var shouldUseNativeDriver = NativeAnimatedHelper.shouldUseNativeDriver;
function attachNativeEvent(viewRef, eventName, argMapping) {
// Find animated values in `argMapping` and create an array representing their
// key path inside the `nativeEvent` object. Ex.: ['contentOffset', 'x'].
var eventMappings = [];
var traverse = function traverse(value, path) {
if (value instanceof AnimatedValue) {
value.__makeNative();
eventMappings.push({
nativeEventPath: path,
animatedValueTag: value.__getNativeTag()
});
} else if (typeof value === 'object') {
for (var _key in value) {
traverse(value[_key], path.concat(_key));
}
}
};
invariant(argMapping[0] && argMapping[0].nativeEvent, 'Native driven events only support animated values contained inside `nativeEvent`.'); // Assume that the event containing `nativeEvent` is always the first argument.
traverse(argMapping[0].nativeEvent, []);
var viewTag = findNodeHandle(viewRef);
eventMappings.forEach(function (mapping) {
NativeAnimatedHelper.API.addAnimatedEventToView(viewTag, eventName, mapping);
});
return {
detach: function detach() {
eventMappings.forEach(function (mapping) {
NativeAnimatedHelper.API.removeAnimatedEventFromView(viewTag, eventName, mapping.animatedValueTag);
});
}
};
}
var AnimatedEvent =
/*#__PURE__*/
function () {
function AnimatedEvent(argMapping, config) {
if (config === void 0) {
config = {};
}
this._listeners = [];
this._argMapping = argMapping;
if (config.listener) {
this.__addListener(config.listener);
}
this._callListeners = this._callListeners.bind(this);
this._attachedEvent = null;
this.__isNative = shouldUseNativeDriver(config);
if (process.env.NODE_ENV !== 'production') {
this._validateMapping();
}
}
var _proto = AnimatedEvent.prototype;
_proto.__addListener = function __addListener(callback) {
this._listeners.push(callback);
};
_proto.__removeListener = function __removeListener(callback) {
this._listeners = this._listeners.filter(function (listener) {
return listener !== callback;
});
};
_proto.__attach = function __attach(viewRef, eventName) {
invariant(this.__isNative, 'Only native driven events need to be attached.');
this._attachedEvent = attachNativeEvent(viewRef, eventName, this._argMapping);
};
_proto.__detach = function __detach(viewTag, eventName) {
invariant(this.__isNative, 'Only native driven events need to be detached.');
this._attachedEvent && this._attachedEvent.detach();
};
_proto.__getHandler = function __getHandler() {
var _this = this;
if (this.__isNative) {
return this._callListeners;
}
return function () {
for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
args[_key2] = arguments[_key2];
}
var traverse = function traverse(recMapping, recEvt, key) {
if (typeof recEvt === 'number' && recMapping instanceof AnimatedValue) {
recMapping.setValue(recEvt);
} else if (typeof recMapping === 'object') {
for (var mappingKey in recMapping) {
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for
* React. To see the error delete this comment and run Flow. */
traverse(recMapping[mappingKey], recEvt[mappingKey], mappingKey);
}
}
};
if (!_this.__isNative) {
_this._argMapping.forEach(function (mapping, idx) {
traverse(mapping, args[idx], 'arg' + idx);
});
}
_this._callListeners.apply(_this, args);
};
};
_proto._callListeners = function _callListeners() {
for (var _len2 = arguments.length, args = new Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {
args[_key3] = arguments[_key3];
}
this._listeners.forEach(function (listener) {
return listener.apply(void 0, args);
});
};
_proto._validateMapping = function _validateMapping() {
var traverse = function traverse(recMapping, recEvt, key) {
if (typeof recEvt === 'number') {
invariant(recMapping instanceof AnimatedValue, 'Bad mapping of type ' + typeof recMapping + ' for key ' + key + ', event value must map to AnimatedValue');
return;
}
invariant(typeof recMapping === 'object', 'Bad mapping of type ' + typeof recMapping + ' for key ' + key);
invariant(typeof recEvt === 'object', 'Bad event of type ' + typeof recEvt + ' for key ' + key);
for (var mappingKey in recMapping) {
traverse(recMapping[mappingKey], recEvt[mappingKey], mappingKey);
}
};
};
return AnimatedEvent;
}();
export { AnimatedEvent, attachNativeEvent };
export default {
AnimatedEvent: AnimatedEvent,
attachNativeEvent: attachNativeEvent
};

View File

@ -0,0 +1,616 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
* @preventMunge
*/
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import { AnimatedEvent, attachNativeEvent } from './AnimatedEvent';
import AnimatedAddition from './nodes/AnimatedAddition';
import AnimatedDiffClamp from './nodes/AnimatedDiffClamp';
import AnimatedDivision from './nodes/AnimatedDivision';
import AnimatedInterpolation from './nodes/AnimatedInterpolation';
import AnimatedModulo from './nodes/AnimatedModulo';
import AnimatedMultiplication from './nodes/AnimatedMultiplication';
import AnimatedNode from './nodes/AnimatedNode';
import AnimatedProps from './nodes/AnimatedProps';
import AnimatedSubtraction from './nodes/AnimatedSubtraction';
import AnimatedTracking from './nodes/AnimatedTracking';
import AnimatedValue from './nodes/AnimatedValue';
import AnimatedValueXY from './nodes/AnimatedValueXY';
import DecayAnimation from './animations/DecayAnimation';
import SpringAnimation from './animations/SpringAnimation';
import TimingAnimation from './animations/TimingAnimation';
import createAnimatedComponent from './createAnimatedComponent';
var add = function add(a, b) {
return new AnimatedAddition(a, b);
};
var subtract = function subtract(a, b) {
return new AnimatedSubtraction(a, b);
};
var divide = function divide(a, b) {
return new AnimatedDivision(a, b);
};
var multiply = function multiply(a, b) {
return new AnimatedMultiplication(a, b);
};
var modulo = function modulo(a, modulus) {
return new AnimatedModulo(a, modulus);
};
var diffClamp = function diffClamp(a, min, max) {
return new AnimatedDiffClamp(a, min, max);
};
var _combineCallbacks = function _combineCallbacks(callback, config) {
if (callback && config.onComplete) {
return function () {
config.onComplete && config.onComplete.apply(config, arguments);
callback && callback.apply(void 0, arguments);
};
} else {
return callback || config.onComplete;
}
};
var maybeVectorAnim = function maybeVectorAnim(value, config, anim) {
if (value instanceof AnimatedValueXY) {
var configX = _objectSpread({}, config);
var configY = _objectSpread({}, config);
for (var key in config) {
var _config$key = config[key],
x = _config$key.x,
y = _config$key.y;
if (x !== undefined && y !== undefined) {
configX[key] = x;
configY[key] = y;
}
}
var aX = anim(value.x, configX);
var aY = anim(value.y, configY); // We use `stopTogether: false` here because otherwise tracking will break
// because the second animation will get stopped before it can update.
return parallel([aX, aY], {
stopTogether: false
});
}
return null;
};
var spring = function spring(value, config) {
var _start = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
if (configuration.toValue instanceof AnimatedNode) {
singleValue.track(new AnimatedTracking(singleValue, configuration.toValue, SpringAnimation, singleConfig, callback));
} else {
singleValue.animate(new SpringAnimation(singleConfig), callback);
}
};
return maybeVectorAnim(value, config, spring) || {
start: function start(callback) {
_start(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = _objectSpread({}, config, {
iterations: iterations
});
_start(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var timing = function timing(value, config) {
var _start2 = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
if (configuration.toValue instanceof AnimatedNode) {
singleValue.track(new AnimatedTracking(singleValue, configuration.toValue, TimingAnimation, singleConfig, callback));
} else {
singleValue.animate(new TimingAnimation(singleConfig), callback);
}
};
return maybeVectorAnim(value, config, timing) || {
start: function start(callback) {
_start2(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = _objectSpread({}, config, {
iterations: iterations
});
_start2(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var decay = function decay(value, config) {
var _start3 = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
singleValue.animate(new DecayAnimation(singleConfig), callback);
};
return maybeVectorAnim(value, config, decay) || {
start: function start(callback) {
_start3(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = _objectSpread({}, config, {
iterations: iterations
});
_start3(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var sequence = function sequence(animations) {
var current = 0;
return {
start: function start(callback) {
var onComplete = function onComplete(result) {
if (!result.finished) {
callback && callback(result);
return;
}
current++;
if (current === animations.length) {
callback && callback(result);
return;
}
animations[current].start(onComplete);
};
if (animations.length === 0) {
callback && callback({
finished: true
});
} else {
animations[current].start(onComplete);
}
},
stop: function stop() {
if (current < animations.length) {
animations[current].stop();
}
},
reset: function reset() {
animations.forEach(function (animation, idx) {
if (idx <= current) {
animation.reset();
}
});
current = 0;
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.sequence animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return false;
}
};
};
var parallel = function parallel(animations, config) {
var doneCount = 0; // Make sure we only call stop() at most once for each animation
var hasEnded = {};
var stopTogether = !(config && config.stopTogether === false);
var result = {
start: function start(callback) {
if (doneCount === animations.length) {
callback && callback({
finished: true
});
return;
}
animations.forEach(function (animation, idx) {
var cb = function cb(endResult) {
hasEnded[idx] = true;
doneCount++;
if (doneCount === animations.length) {
doneCount = 0;
callback && callback(endResult);
return;
}
if (!endResult.finished && stopTogether) {
result.stop();
}
};
if (!animation) {
cb({
finished: true
});
} else {
animation.start(cb);
}
});
},
stop: function stop() {
animations.forEach(function (animation, idx) {
!hasEnded[idx] && animation.stop();
hasEnded[idx] = true;
});
},
reset: function reset() {
animations.forEach(function (animation, idx) {
animation.reset();
hasEnded[idx] = false;
doneCount = 0;
});
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.parallel animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return false;
}
};
return result;
};
var delay = function delay(time) {
// Would be nice to make a specialized implementation
return timing(new AnimatedValue(0), {
toValue: 0,
delay: time,
duration: 0
});
};
var stagger = function stagger(time, animations) {
return parallel(animations.map(function (animation, i) {
return sequence([delay(time * i), animation]);
}));
};
var loop = function loop(animation, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$iterations = _ref.iterations,
iterations = _ref$iterations === void 0 ? -1 : _ref$iterations,
_ref$resetBeforeItera = _ref.resetBeforeIteration,
resetBeforeIteration = _ref$resetBeforeItera === void 0 ? true : _ref$resetBeforeItera;
var isFinished = false;
var iterationsSoFar = 0;
return {
start: function start(callback) {
var restart = function restart(result) {
if (result === void 0) {
result = {
finished: true
};
}
if (isFinished || iterationsSoFar === iterations || result.finished === false) {
callback && callback(result);
} else {
iterationsSoFar++;
resetBeforeIteration && animation.reset();
animation.start(restart);
}
};
if (!animation || iterations === 0) {
callback && callback({
finished: true
});
} else {
if (animation._isUsingNativeDriver()) {
animation._startNativeLoop(iterations);
} else {
restart(); // Start looping recursively on the js thread
}
}
},
stop: function stop() {
isFinished = true;
animation.stop();
},
reset: function reset() {
iterationsSoFar = 0;
isFinished = false;
animation.reset();
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.loop animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return animation._isUsingNativeDriver();
}
};
};
function forkEvent(event, listener) {
if (!event) {
return listener;
} else if (event instanceof AnimatedEvent) {
event.__addListener(listener);
return event;
} else {
return function () {
typeof event === 'function' && event.apply(void 0, arguments);
listener.apply(void 0, arguments);
};
}
}
function unforkEvent(event, listener) {
if (event && event instanceof AnimatedEvent) {
event.__removeListener(listener);
}
}
var event = function event(argMapping, config) {
var animatedEvent = new AnimatedEvent(argMapping, config);
if (animatedEvent.__isNative) {
return animatedEvent;
} else {
return animatedEvent.__getHandler();
}
};
/**
* The `Animated` library is designed to make animations fluid, powerful, and
* easy to build and maintain. `Animated` focuses on declarative relationships
* between inputs and outputs, with configurable transforms in between, and
* simple `start`/`stop` methods to control time-based animation execution.
* If additional transforms are added, be sure to include them in
* AnimatedMock.js as well.
*
* See http://facebook.github.io/react-native/docs/animated.html
*/
var AnimatedImplementation = {
/**
* Standard value class for driving animations. Typically initialized with
* `new Animated.Value(0);`
*
* See http://facebook.github.io/react-native/docs/animated.html#value
*/
Value: AnimatedValue,
/**
* 2D value class for driving 2D animations, such as pan gestures.
*
* See https://facebook.github.io/react-native/docs/animatedvaluexy.html
*/
ValueXY: AnimatedValueXY,
/**
* Exported to use the Interpolation type in flow.
*
* See http://facebook.github.io/react-native/docs/animated.html#interpolation
*/
Interpolation: AnimatedInterpolation,
/**
* Exported for ease of type checking. All animated values derive from this
* class.
*
* See http://facebook.github.io/react-native/docs/animated.html#node
*/
Node: AnimatedNode,
/**
* Animates a value from an initial velocity to zero based on a decay
* coefficient.
*
* See http://facebook.github.io/react-native/docs/animated.html#decay
*/
decay: decay,
/**
* Animates a value along a timed easing curve. The Easing module has tons of
* predefined curves, or you can use your own function.
*
* See http://facebook.github.io/react-native/docs/animated.html#timing
*/
timing: timing,
/**
* Animates a value according to an analytical spring model based on
* damped harmonic oscillation.
*
* See http://facebook.github.io/react-native/docs/animated.html#spring
*/
spring: spring,
/**
* Creates a new Animated value composed from two Animated values added
* together.
*
* See http://facebook.github.io/react-native/docs/animated.html#add
*/
add: add,
/**
* Creates a new Animated value composed by subtracting the second Animated
* value from the first Animated value.
*
* See http://facebook.github.io/react-native/docs/animated.html#subtract
*/
subtract: subtract,
/**
* Creates a new Animated value composed by dividing the first Animated value
* by the second Animated value.
*
* See http://facebook.github.io/react-native/docs/animated.html#divide
*/
divide: divide,
/**
* Creates a new Animated value composed from two Animated values multiplied
* together.
*
* See http://facebook.github.io/react-native/docs/animated.html#multiply
*/
multiply: multiply,
/**
* Creates a new Animated value that is the (non-negative) modulo of the
* provided Animated value.
*
* See http://facebook.github.io/react-native/docs/animated.html#modulo
*/
modulo: modulo,
/**
* Create a new Animated value that is limited between 2 values. It uses the
* difference between the last value so even if the value is far from the
* bounds it will start changing when the value starts getting closer again.
*
* See http://facebook.github.io/react-native/docs/animated.html#diffclamp
*/
diffClamp: diffClamp,
/**
* Starts an animation after the given delay.
*
* See http://facebook.github.io/react-native/docs/animated.html#delay
*/
delay: delay,
/**
* Starts an array of animations in order, waiting for each to complete
* before starting the next. If the current running animation is stopped, no
* following animations will be started.
*
* See http://facebook.github.io/react-native/docs/animated.html#sequence
*/
sequence: sequence,
/**
* Starts an array of animations all at the same time. By default, if one
* of the animations is stopped, they will all be stopped. You can override
* this with the `stopTogether` flag.
*
* See http://facebook.github.io/react-native/docs/animated.html#parallel
*/
parallel: parallel,
/**
* Array of animations may run in parallel (overlap), but are started in
* sequence with successive delays. Nice for doing trailing effects.
*
* See http://facebook.github.io/react-native/docs/animated.html#stagger
*/
stagger: stagger,
/**
* Loops a given animation continuously, so that each time it reaches the
* end, it resets and begins again from the start.
*
* See http://facebook.github.io/react-native/docs/animated.html#loop
*/
loop: loop,
/**
* Takes an array of mappings and extracts values from each arg accordingly,
* then calls `setValue` on the mapped outputs.
*
* See http://facebook.github.io/react-native/docs/animated.html#event
*/
event: event,
/**
* Make any React component Animatable. Used to create `Animated.View`, etc.
*
* See http://facebook.github.io/react-native/docs/animated.html#createanimatedcomponent
*/
createAnimatedComponent: createAnimatedComponent,
/**
* Imperative API to attach an animated value to an event on a view. Prefer
* using `Animated.event` with `useNativeDrive: true` if possible.
*
* See http://facebook.github.io/react-native/docs/animated.html#attachnativeevent
*/
attachNativeEvent: attachNativeEvent,
/**
* Advanced imperative API for snooping on animated events that are passed in
* through props. Use values directly where possible.
*
* See http://facebook.github.io/react-native/docs/animated.html#forkevent
*/
forkEvent: forkEvent,
unforkEvent: unforkEvent,
/**
* Expose Event class, so it can be used as a type for type checkers.
*/
Event: AnimatedEvent,
__PropsOnlyForTests: AnimatedProps
};
export default AnimatedImplementation;

View File

@ -0,0 +1,290 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*
*/
'use strict';
import _bezier from './bezier';
var _ease;
/**
* The `Easing` module implements common easing functions. This module is used
* by [Animate.timing()](docs/animate.html#timing) to convey physically
* believable motion in animations.
*
* You can find a visualization of some common easing functions at
* http://easings.net/
*
* ### Predefined animations
*
* The `Easing` module provides several predefined animations through the
* following methods:
*
* - [`back`](docs/easing.html#back) provides a simple animation where the
* object goes slightly back before moving forward
* - [`bounce`](docs/easing.html#bounce) provides a bouncing animation
* - [`ease`](docs/easing.html#ease) provides a simple inertial animation
* - [`elastic`](docs/easing.html#elastic) provides a simple spring interaction
*
* ### Standard functions
*
* Three standard easing functions are provided:
*
* - [`linear`](docs/easing.html#linear)
* - [`quad`](docs/easing.html#quad)
* - [`cubic`](docs/easing.html#cubic)
*
* The [`poly`](docs/easing.html#poly) function can be used to implement
* quartic, quintic, and other higher power functions.
*
* ### Additional functions
*
* Additional mathematical functions are provided by the following methods:
*
* - [`bezier`](docs/easing.html#bezier) provides a cubic bezier curve
* - [`circle`](docs/easing.html#circle) provides a circular function
* - [`sin`](docs/easing.html#sin) provides a sinusoidal function
* - [`exp`](docs/easing.html#exp) provides an exponential function
*
* The following helpers are used to modify other easing functions.
*
* - [`in`](docs/easing.html#in) runs an easing function forwards
* - [`inOut`](docs/easing.html#inout) makes any easing function symmetrical
* - [`out`](docs/easing.html#out) runs an easing function backwards
*/
var Easing =
/*#__PURE__*/
function () {
function Easing() {}
/**
* A stepping function, returns 1 for any positive value of `n`.
*/
Easing.step0 = function step0(n) {
return n > 0 ? 1 : 0;
}
/**
* A stepping function, returns 1 if `n` is greater than or equal to 1.
*/
;
Easing.step1 = function step1(n) {
return n >= 1 ? 1 : 0;
}
/**
* A linear function, `f(t) = t`. Position correlates to elapsed time one to
* one.
*
* http://cubic-bezier.com/#0,0,1,1
*/
;
Easing.linear = function linear(t) {
return t;
}
/**
* A simple inertial interaction, similar to an object slowly accelerating to
* speed.
*
* http://cubic-bezier.com/#.42,0,1,1
*/
;
Easing.ease = function ease(t) {
if (!_ease) {
_ease = Easing.bezier(0.42, 0, 1, 1);
}
return _ease(t);
}
/**
* A quadratic function, `f(t) = t * t`. Position equals the square of elapsed
* time.
*
* http://easings.net/#easeInQuad
*/
;
Easing.quad = function quad(t) {
return t * t;
}
/**
* A cubic function, `f(t) = t * t * t`. Position equals the cube of elapsed
* time.
*
* http://easings.net/#easeInCubic
*/
;
Easing.cubic = function cubic(t) {
return t * t * t;
}
/**
* A power function. Position is equal to the Nth power of elapsed time.
*
* n = 4: http://easings.net/#easeInQuart
* n = 5: http://easings.net/#easeInQuint
*/
;
Easing.poly = function poly(n) {
return function (t) {
return Math.pow(t, n);
};
}
/**
* A sinusoidal function.
*
* http://easings.net/#easeInSine
*/
;
Easing.sin = function sin(t) {
return 1 - Math.cos(t * Math.PI / 2);
}
/**
* A circular function.
*
* http://easings.net/#easeInCirc
*/
;
Easing.circle = function circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
/**
* An exponential function.
*
* http://easings.net/#easeInExpo
*/
;
Easing.exp = function exp(t) {
return Math.pow(2, 10 * (t - 1));
}
/**
* A simple elastic interaction, similar to a spring oscillating back and
* forth.
*
* Default bounciness is 1, which overshoots a little bit once. 0 bounciness
* doesn't overshoot at all, and bounciness of N > 1 will overshoot about N
* times.
*
* http://easings.net/#easeInElastic
*/
;
Easing.elastic = function elastic(bounciness) {
if (bounciness === void 0) {
bounciness = 1;
}
var p = bounciness * Math.PI;
return function (t) {
return 1 - Math.pow(Math.cos(t * Math.PI / 2), 3) * Math.cos(t * p);
};
}
/**
* Use with `Animated.parallel()` to create a simple effect where the object
* animates back slightly as the animation starts.
*
* Wolfram Plot:
*
* - http://tiny.cc/back_default (s = 1.70158, default)
*/
;
Easing.back = function back(s) {
if (s === void 0) {
s = 1.70158;
}
return function (t) {
return t * t * ((s + 1) * t - s);
};
}
/**
* Provides a simple bouncing effect.
*
* http://easings.net/#easeInBounce
*/
;
Easing.bounce = function bounce(t) {
if (t < 1 / 2.75) {
return 7.5625 * t * t;
}
if (t < 2 / 2.75) {
var _t = t - 1.5 / 2.75;
return 7.5625 * _t * _t + 0.75;
}
if (t < 2.5 / 2.75) {
var _t2 = t - 2.25 / 2.75;
return 7.5625 * _t2 * _t2 + 0.9375;
}
var t2 = t - 2.625 / 2.75;
return 7.5625 * t2 * t2 + 0.984375;
}
/**
* Provides a cubic bezier curve, equivalent to CSS Transitions'
* `transition-timing-function`.
*
* A useful tool to visualize cubic bezier curves can be found at
* http://cubic-bezier.com/
*/
;
Easing.bezier = function bezier(x1, y1, x2, y2) {
return _bezier(x1, y1, x2, y2);
}
/**
* Runs an easing function forwards.
*/
;
Easing.in = function _in(easing) {
return easing;
}
/**
* Runs an easing function backwards.
*/
;
Easing.out = function out(easing) {
return function (t) {
return 1 - easing(1 - t);
};
}
/**
* Makes any easing function symmetrical. The easing function will run
* forwards for half of the duration, then backwards for the rest of the
* duration.
*/
;
Easing.inOut = function inOut(easing) {
return function (t) {
if (t < 0.5) {
return easing(t * 2) / 2;
}
return 1 - easing((1 - t) * 2) / 2;
};
};
return Easing;
}();
export default Easing;

View File

@ -0,0 +1,261 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
import NativeEventEmitter from '../NativeEventEmitter';
import NativeAnimatedModule from './NativeAnimatedModule';
import invariant from 'fbjs/lib/invariant';
var __nativeAnimatedNodeTagCount = 1;
/* used for animated nodes */
var __nativeAnimationIdCount = 1;
/* used for started animations */
var nativeEventEmitter;
var queueConnections = false;
var queue = [];
/**
* Simple wrappers around NativeAnimatedModule to provide flow and autocmplete support for
* the native module methods
*/
var API = {
enableQueue: function enableQueue() {
queueConnections = true;
},
disableQueue: function disableQueue() {
invariant(NativeAnimatedModule, 'Native animated module is not available');
queueConnections = false;
for (var q = 0, l = queue.length; q < l; q++) {
var args = queue[q];
NativeAnimatedModule.connectAnimatedNodes(args[0], args[1]);
}
queue.length = 0;
},
createAnimatedNode: function createAnimatedNode(tag, config) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.createAnimatedNode(tag, config);
},
startListeningToAnimatedNodeValue: function startListeningToAnimatedNodeValue(tag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.startListeningToAnimatedNodeValue(tag);
},
stopListeningToAnimatedNodeValue: function stopListeningToAnimatedNodeValue(tag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.stopListeningToAnimatedNodeValue(tag);
},
connectAnimatedNodes: function connectAnimatedNodes(parentTag, childTag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
if (queueConnections) {
queue.push([parentTag, childTag]);
return;
}
NativeAnimatedModule.connectAnimatedNodes(parentTag, childTag);
},
disconnectAnimatedNodes: function disconnectAnimatedNodes(parentTag, childTag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.disconnectAnimatedNodes(parentTag, childTag);
},
startAnimatingNode: function startAnimatingNode(animationId, nodeTag, config, endCallback) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.startAnimatingNode(animationId, nodeTag, config, endCallback);
},
stopAnimation: function stopAnimation(animationId) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.stopAnimation(animationId);
},
setAnimatedNodeValue: function setAnimatedNodeValue(nodeTag, value) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.setAnimatedNodeValue(nodeTag, value);
},
setAnimatedNodeOffset: function setAnimatedNodeOffset(nodeTag, offset) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.setAnimatedNodeOffset(nodeTag, offset);
},
flattenAnimatedNodeOffset: function flattenAnimatedNodeOffset(nodeTag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.flattenAnimatedNodeOffset(nodeTag);
},
extractAnimatedNodeOffset: function extractAnimatedNodeOffset(nodeTag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.extractAnimatedNodeOffset(nodeTag);
},
connectAnimatedNodeToView: function connectAnimatedNodeToView(nodeTag, viewTag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.connectAnimatedNodeToView(nodeTag, viewTag);
},
disconnectAnimatedNodeFromView: function disconnectAnimatedNodeFromView(nodeTag, viewTag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.disconnectAnimatedNodeFromView(nodeTag, viewTag);
},
dropAnimatedNode: function dropAnimatedNode(tag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.dropAnimatedNode(tag);
},
addAnimatedEventToView: function addAnimatedEventToView(viewTag, eventName, eventMapping) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.addAnimatedEventToView(viewTag, eventName, eventMapping);
},
removeAnimatedEventFromView: function removeAnimatedEventFromView(viewTag, eventName, animatedNodeTag) {
invariant(NativeAnimatedModule, 'Native animated module is not available');
NativeAnimatedModule.removeAnimatedEventFromView(viewTag, eventName, animatedNodeTag);
}
};
/**
* Styles allowed by the native animated implementation.
*
* In general native animated implementation should support any numeric property that doesn't need
* to be updated through the shadow view hierarchy (all non-layout properties).
*/
var STYLES_WHITELIST = {
opacity: true,
transform: true,
borderRadius: true,
borderBottomEndRadius: true,
borderBottomLeftRadius: true,
borderBottomRightRadius: true,
borderBottomStartRadius: true,
borderTopEndRadius: true,
borderTopLeftRadius: true,
borderTopRightRadius: true,
borderTopStartRadius: true,
elevation: true,
/* ios styles */
shadowOpacity: true,
shadowRadius: true,
/* legacy android transform properties */
scaleX: true,
scaleY: true,
translateX: true,
translateY: true
};
var TRANSFORM_WHITELIST = {
translateX: true,
translateY: true,
scale: true,
scaleX: true,
scaleY: true,
rotate: true,
rotateX: true,
rotateY: true,
perspective: true
};
var SUPPORTED_INTERPOLATION_PARAMS = {
inputRange: true,
outputRange: true,
extrapolate: true,
extrapolateRight: true,
extrapolateLeft: true
};
function addWhitelistedStyleProp(prop) {
STYLES_WHITELIST[prop] = true;
}
function addWhitelistedTransformProp(prop) {
TRANSFORM_WHITELIST[prop] = true;
}
function addWhitelistedInterpolationParam(param) {
SUPPORTED_INTERPOLATION_PARAMS[param] = true;
}
function validateTransform(configs) {
configs.forEach(function (config) {
if (!TRANSFORM_WHITELIST.hasOwnProperty(config.property)) {
throw new Error("Property '" + config.property + "' is not supported by native animated module");
}
});
}
function validateStyles(styles) {
for (var _key in styles) {
if (!STYLES_WHITELIST.hasOwnProperty(_key)) {
throw new Error("Style property '" + _key + "' is not supported by native animated module");
}
}
}
function validateInterpolation(config) {
for (var _key2 in config) {
if (!SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(_key2)) {
throw new Error("Interpolation property '" + _key2 + "' is not supported by native animated module");
}
}
}
function generateNewNodeTag() {
return __nativeAnimatedNodeTagCount++;
}
function generateNewAnimationId() {
return __nativeAnimationIdCount++;
}
function assertNativeAnimatedModule() {
invariant(NativeAnimatedModule, 'Native animated module is not available');
}
function shouldUseNativeDriver(config) {
if (config.useNativeDriver === true && !NativeAnimatedModule) {
return false;
}
return config.useNativeDriver || false;
}
function transformDataType(value) {
// Change the string type to number type so we can reuse the same logic in
// iOS and Android platform
if (typeof value !== 'string') {
return value;
}
if (/deg$/.test(value)) {
var degrees = parseFloat(value) || 0;
var radians = degrees * Math.PI / 180.0;
return radians;
} else {
return value;
}
}
var NativeAnimatedHelper = {
API: API,
addWhitelistedStyleProp: addWhitelistedStyleProp,
addWhitelistedTransformProp: addWhitelistedTransformProp,
addWhitelistedInterpolationParam: addWhitelistedInterpolationParam,
validateStyles: validateStyles,
validateTransform: validateTransform,
validateInterpolation: validateInterpolation,
generateNewNodeTag: generateNewNodeTag,
generateNewAnimationId: generateNewAnimationId,
assertNativeAnimatedModule: assertNativeAnimatedModule,
shouldUseNativeDriver: shouldUseNativeDriver,
transformDataType: transformDataType,
get nativeEventEmitter() {
if (!nativeEventEmitter) {
nativeEventEmitter = new NativeEventEmitter(NativeAnimatedModule);
}
return nativeEventEmitter;
}
};
export { API, addWhitelistedStyleProp, addWhitelistedTransformProp, addWhitelistedInterpolationParam, validateStyles, validateTransform, validateInterpolation, generateNewNodeTag, generateNewAnimationId, assertNativeAnimatedModule, shouldUseNativeDriver, transformDataType };
export default NativeAnimatedHelper;

View File

@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry';
export default TurboModuleRegistry.get('NativeAnimatedModule');

View File

@ -0,0 +1,81 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*
*/
'use strict';
function stiffnessFromOrigamiValue(oValue) {
return (oValue - 30) * 3.62 + 194;
}
function dampingFromOrigamiValue(oValue) {
return (oValue - 8) * 3 + 25;
}
function fromOrigamiTensionAndFriction(tension, friction) {
return {
stiffness: stiffnessFromOrigamiValue(tension),
damping: dampingFromOrigamiValue(friction)
};
}
function fromBouncinessAndSpeed(bounciness, speed) {
function normalize(value, startValue, endValue) {
return (value - startValue) / (endValue - startValue);
}
function projectNormal(n, start, end) {
return start + n * (end - start);
}
function linearInterpolation(t, start, end) {
return t * end + (1 - t) * start;
}
function quadraticOutInterpolation(t, start, end) {
return linearInterpolation(2 * t - t * t, start, end);
}
function b3Friction1(x) {
return 0.0007 * Math.pow(x, 3) - 0.031 * Math.pow(x, 2) + 0.64 * x + 1.28;
}
function b3Friction2(x) {
return 0.000044 * Math.pow(x, 3) - 0.006 * Math.pow(x, 2) + 0.36 * x + 2;
}
function b3Friction3(x) {
return 0.00000045 * Math.pow(x, 3) - 0.000332 * Math.pow(x, 2) + 0.1078 * x + 5.84;
}
function b3Nobounce(tension) {
if (tension <= 18) {
return b3Friction1(tension);
} else if (tension > 18 && tension <= 44) {
return b3Friction2(tension);
} else {
return b3Friction3(tension);
}
}
var b = normalize(bounciness / 1.7, 0, 20);
b = projectNormal(b, 0, 0.8);
var s = normalize(speed / 1.7, 0, 20);
var bouncyTension = projectNormal(s, 0.5, 200);
var bouncyFriction = quadraticOutInterpolation(b, b3Nobounce(bouncyTension), 0.01);
return {
stiffness: stiffnessFromOrigamiValue(bouncyTension),
damping: dampingFromOrigamiValue(bouncyFriction)
};
}
export { fromOrigamiTensionAndFriction, fromBouncinessAndSpeed };
export default {
fromOrigamiTensionAndFriction: fromOrigamiTensionAndFriction,
fromBouncinessAndSpeed: fromBouncinessAndSpeed
};

View File

@ -0,0 +1,58 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
// Important note: start() and stop() will only be called at most once.
// Once an animation has been stopped or finished its course, it will
// not be reused.
var Animation =
/*#__PURE__*/
function () {
function Animation() {}
var _proto = Animation.prototype;
_proto.start = function start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {};
_proto.stop = function stop() {
if (this.__nativeId) {
NativeAnimatedHelper.API.stopAnimation(this.__nativeId);
}
};
_proto.__getNativeAnimationConfig = function __getNativeAnimationConfig() {
// Subclasses that have corresponding animation implementation done in native
// should override this method
throw new Error('This animation type cannot be offloaded to native');
} // Helper function for subclasses to make sure onEnd is only called once.
;
_proto.__debouncedOnEnd = function __debouncedOnEnd(result) {
var onEnd = this.__onEnd;
this.__onEnd = null;
onEnd && onEnd(result);
};
_proto.__startNativeAnimation = function __startNativeAnimation(animatedValue) {
NativeAnimatedHelper.API.enableQueue();
animatedValue.__makeNative();
NativeAnimatedHelper.API.disableQueue();
this.__nativeId = NativeAnimatedHelper.generateNewAnimationId();
NativeAnimatedHelper.API.startAnimatingNode(this.__nativeId, animatedValue.__getNativeTag(), this.__getNativeAnimationConfig(), this.__debouncedOnEnd.bind(this));
};
return Animation;
}();
export default Animation;

View File

@ -0,0 +1,97 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import Animation from './Animation';
import { shouldUseNativeDriver } from '../NativeAnimatedHelper';
var DecayAnimation =
/*#__PURE__*/
function (_Animation) {
_inheritsLoose(DecayAnimation, _Animation);
function DecayAnimation(config) {
var _config$deceleration, _config$isInteraction, _config$iterations;
var _this;
_this = _Animation.call(this) || this;
_this._deceleration = (_config$deceleration = config.deceleration) !== null && _config$deceleration !== void 0 ? _config$deceleration : 0.998;
_this._velocity = config.velocity;
_this._useNativeDriver = shouldUseNativeDriver(config);
_this.__isInteraction = (_config$isInteraction = config.isInteraction) !== null && _config$isInteraction !== void 0 ? _config$isInteraction : !_this._useNativeDriver;
_this.__iterations = (_config$iterations = config.iterations) !== null && _config$iterations !== void 0 ? _config$iterations : 1;
return _this;
}
var _proto = DecayAnimation.prototype;
_proto.__getNativeAnimationConfig = function __getNativeAnimationConfig() {
return {
type: 'decay',
deceleration: this._deceleration,
velocity: this._velocity,
iterations: this.__iterations
};
};
_proto.start = function start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {
this.__active = true;
this._lastValue = fromValue;
this._fromValue = fromValue;
this._onUpdate = onUpdate;
this.__onEnd = onEnd;
this._startTime = Date.now();
if (this._useNativeDriver) {
this.__startNativeAnimation(animatedValue);
} else {
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
}
};
_proto.onUpdate = function onUpdate() {
var now = Date.now();
var value = this._fromValue + this._velocity / (1 - this._deceleration) * (1 - Math.exp(-(1 - this._deceleration) * (now - this._startTime)));
this._onUpdate(value);
if (Math.abs(this._lastValue - value) < 0.1) {
this.__debouncedOnEnd({
finished: true
});
return;
}
this._lastValue = value;
if (this.__active) {
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
}
};
_proto.stop = function stop() {
_Animation.prototype.stop.call(this);
this.__active = false;
global.cancelAnimationFrame(this._animationFrame);
this.__debouncedOnEnd({
finished: false
});
};
return DecayAnimation;
}(Animation);
export default DecayAnimation;

View File

@ -0,0 +1,272 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedValue from '../nodes/AnimatedValue';
import AnimatedValueXY from '../nodes/AnimatedValueXY';
import Animation from './Animation';
import SpringConfig from '../SpringConfig';
import invariant from 'fbjs/lib/invariant';
import { shouldUseNativeDriver } from '../NativeAnimatedHelper';
var SpringAnimation =
/*#__PURE__*/
function (_Animation) {
_inheritsLoose(SpringAnimation, _Animation);
function SpringAnimation(config) {
var _config$overshootClam, _config$restDisplacem, _config$restSpeedThre, _config$velocity, _config$velocity2, _config$delay, _config$isInteraction, _config$iterations;
var _this;
_this = _Animation.call(this) || this;
_this._overshootClamping = (_config$overshootClam = config.overshootClamping) !== null && _config$overshootClam !== void 0 ? _config$overshootClam : false;
_this._restDisplacementThreshold = (_config$restDisplacem = config.restDisplacementThreshold) !== null && _config$restDisplacem !== void 0 ? _config$restDisplacem : 0.001;
_this._restSpeedThreshold = (_config$restSpeedThre = config.restSpeedThreshold) !== null && _config$restSpeedThre !== void 0 ? _config$restSpeedThre : 0.001;
_this._initialVelocity = (_config$velocity = config.velocity) !== null && _config$velocity !== void 0 ? _config$velocity : 0;
_this._lastVelocity = (_config$velocity2 = config.velocity) !== null && _config$velocity2 !== void 0 ? _config$velocity2 : 0;
_this._toValue = config.toValue;
_this._delay = (_config$delay = config.delay) !== null && _config$delay !== void 0 ? _config$delay : 0;
_this._useNativeDriver = shouldUseNativeDriver(config);
_this.__isInteraction = (_config$isInteraction = config.isInteraction) !== null && _config$isInteraction !== void 0 ? _config$isInteraction : !_this._useNativeDriver;
_this.__iterations = (_config$iterations = config.iterations) !== null && _config$iterations !== void 0 ? _config$iterations : 1;
if (config.stiffness !== undefined || config.damping !== undefined || config.mass !== undefined) {
var _config$stiffness, _config$damping, _config$mass;
invariant(config.bounciness === undefined && config.speed === undefined && config.tension === undefined && config.friction === undefined, 'You can define one of bounciness/speed, tension/friction, or stiffness/damping/mass, but not more than one');
_this._stiffness = (_config$stiffness = config.stiffness) !== null && _config$stiffness !== void 0 ? _config$stiffness : 100;
_this._damping = (_config$damping = config.damping) !== null && _config$damping !== void 0 ? _config$damping : 10;
_this._mass = (_config$mass = config.mass) !== null && _config$mass !== void 0 ? _config$mass : 1;
} else if (config.bounciness !== undefined || config.speed !== undefined) {
var _config$bounciness, _config$speed;
// Convert the origami bounciness/speed values to stiffness/damping
// We assume mass is 1.
invariant(config.tension === undefined && config.friction === undefined && config.stiffness === undefined && config.damping === undefined && config.mass === undefined, 'You can define one of bounciness/speed, tension/friction, or stiffness/damping/mass, but not more than one');
var springConfig = SpringConfig.fromBouncinessAndSpeed((_config$bounciness = config.bounciness) !== null && _config$bounciness !== void 0 ? _config$bounciness : 8, (_config$speed = config.speed) !== null && _config$speed !== void 0 ? _config$speed : 12);
_this._stiffness = springConfig.stiffness;
_this._damping = springConfig.damping;
_this._mass = 1;
} else {
var _config$tension, _config$friction;
// Convert the origami tension/friction values to stiffness/damping
// We assume mass is 1.
var _springConfig = SpringConfig.fromOrigamiTensionAndFriction((_config$tension = config.tension) !== null && _config$tension !== void 0 ? _config$tension : 40, (_config$friction = config.friction) !== null && _config$friction !== void 0 ? _config$friction : 7);
_this._stiffness = _springConfig.stiffness;
_this._damping = _springConfig.damping;
_this._mass = 1;
}
invariant(_this._stiffness > 0, 'Stiffness value must be greater than 0');
invariant(_this._damping > 0, 'Damping value must be greater than 0');
invariant(_this._mass > 0, 'Mass value must be greater than 0');
return _this;
}
var _proto = SpringAnimation.prototype;
_proto.__getNativeAnimationConfig = function __getNativeAnimationConfig() {
var _this$_initialVelocit;
return {
type: 'spring',
overshootClamping: this._overshootClamping,
restDisplacementThreshold: this._restDisplacementThreshold,
restSpeedThreshold: this._restSpeedThreshold,
stiffness: this._stiffness,
damping: this._damping,
mass: this._mass,
initialVelocity: (_this$_initialVelocit = this._initialVelocity) !== null && _this$_initialVelocit !== void 0 ? _this$_initialVelocit : this._lastVelocity,
toValue: this._toValue,
iterations: this.__iterations
};
};
_proto.start = function start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {
var _this2 = this;
this.__active = true;
this._startPosition = fromValue;
this._lastPosition = this._startPosition;
this._onUpdate = onUpdate;
this.__onEnd = onEnd;
this._lastTime = Date.now();
this._frameTime = 0.0;
if (previousAnimation instanceof SpringAnimation) {
var internalState = previousAnimation.getInternalState();
this._lastPosition = internalState.lastPosition;
this._lastVelocity = internalState.lastVelocity; // Set the initial velocity to the last velocity
this._initialVelocity = this._lastVelocity;
this._lastTime = internalState.lastTime;
}
var start = function start() {
if (_this2._useNativeDriver) {
_this2.__startNativeAnimation(animatedValue);
} else {
_this2.onUpdate();
}
}; // If this._delay is more than 0, we start after the timeout.
if (this._delay) {
this._timeout = setTimeout(start, this._delay);
} else {
start();
}
};
_proto.getInternalState = function getInternalState() {
return {
lastPosition: this._lastPosition,
lastVelocity: this._lastVelocity,
lastTime: this._lastTime
};
}
/**
* This spring model is based off of a damped harmonic oscillator
* (https://en.wikipedia.org/wiki/Harmonic_oscillator#Damped_harmonic_oscillator).
*
* We use the closed form of the second order differential equation:
*
* x'' + (2ζ⍵_0)x' + ⍵^2x = 0
*
* where
* ⍵_0 = √(k / m) (undamped angular frequency of the oscillator),
* ζ = c / 2√mk (damping ratio),
* c = damping constant
* k = stiffness
* m = mass
*
* The derivation of the closed form is described in detail here:
* http://planetmath.org/sites/default/files/texpdf/39745.pdf
*
* This algorithm happens to match the algorithm used by CASpringAnimation,
* a QuartzCore (iOS) API that creates spring animations.
*/
;
_proto.onUpdate = function onUpdate() {
// If for some reason we lost a lot of frames (e.g. process large payload or
// stopped in the debugger), we only advance by 4 frames worth of
// computation and will continue on the next frame. It's better to have it
// running at faster speed than jumping to the end.
var MAX_STEPS = 64;
var now = Date.now();
if (now > this._lastTime + MAX_STEPS) {
now = this._lastTime + MAX_STEPS;
}
var deltaTime = (now - this._lastTime) / 1000;
this._frameTime += deltaTime;
var c = this._damping;
var m = this._mass;
var k = this._stiffness;
var v0 = -this._initialVelocity;
var zeta = c / (2 * Math.sqrt(k * m)); // damping ratio
var omega0 = Math.sqrt(k / m); // undamped angular frequency of the oscillator (rad/ms)
var omega1 = omega0 * Math.sqrt(1.0 - zeta * zeta); // exponential decay
var x0 = this._toValue - this._startPosition; // calculate the oscillation from x0 = 1 to x = 0
var position = 0.0;
var velocity = 0.0;
var t = this._frameTime;
if (zeta < 1) {
// Under damped
var envelope = Math.exp(-zeta * omega0 * t);
position = this._toValue - envelope * ((v0 + zeta * omega0 * x0) / omega1 * Math.sin(omega1 * t) + x0 * Math.cos(omega1 * t)); // This looks crazy -- it's actually just the derivative of the
// oscillation function
velocity = zeta * omega0 * envelope * (Math.sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 + x0 * Math.cos(omega1 * t)) - envelope * (Math.cos(omega1 * t) * (v0 + zeta * omega0 * x0) - omega1 * x0 * Math.sin(omega1 * t));
} else {
// Critically damped
var _envelope = Math.exp(-omega0 * t);
position = this._toValue - _envelope * (x0 + (v0 + omega0 * x0) * t);
velocity = _envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0));
}
this._lastTime = now;
this._lastPosition = position;
this._lastVelocity = velocity;
this._onUpdate(position);
if (!this.__active) {
// a listener might have stopped us in _onUpdate
return;
} // Conditions for stopping the spring animation
var isOvershooting = false;
if (this._overshootClamping && this._stiffness !== 0) {
if (this._startPosition < this._toValue) {
isOvershooting = position > this._toValue;
} else {
isOvershooting = position < this._toValue;
}
}
var isVelocity = Math.abs(velocity) <= this._restSpeedThreshold;
var isDisplacement = true;
if (this._stiffness !== 0) {
isDisplacement = Math.abs(this._toValue - position) <= this._restDisplacementThreshold;
}
if (isOvershooting || isVelocity && isDisplacement) {
if (this._stiffness !== 0) {
// Ensure that we end up with a round value
this._lastPosition = this._toValue;
this._lastVelocity = 0;
this._onUpdate(this._toValue);
}
this.__debouncedOnEnd({
finished: true
});
return;
}
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
};
_proto.stop = function stop() {
_Animation.prototype.stop.call(this);
this.__active = false;
clearTimeout(this._timeout);
global.cancelAnimationFrame(this._animationFrame);
this.__debouncedOnEnd({
finished: false
});
};
return SpringAnimation;
}(Animation);
export default SpringAnimation;

View File

@ -0,0 +1,145 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedValue from '../nodes/AnimatedValue';
import AnimatedValueXY from '../nodes/AnimatedValueXY';
import Animation from './Animation';
import Easing from '../Easing';
import { shouldUseNativeDriver } from '../NativeAnimatedHelper';
var _easeInOut;
function easeInOut() {
if (!_easeInOut) {
_easeInOut = Easing.inOut(Easing.ease);
}
return _easeInOut;
}
var TimingAnimation =
/*#__PURE__*/
function (_Animation) {
_inheritsLoose(TimingAnimation, _Animation);
function TimingAnimation(config) {
var _config$easing, _config$duration, _config$delay, _config$iterations, _config$isInteraction;
var _this;
_this = _Animation.call(this) || this;
_this._toValue = config.toValue;
_this._easing = (_config$easing = config.easing) !== null && _config$easing !== void 0 ? _config$easing : easeInOut();
_this._duration = (_config$duration = config.duration) !== null && _config$duration !== void 0 ? _config$duration : 500;
_this._delay = (_config$delay = config.delay) !== null && _config$delay !== void 0 ? _config$delay : 0;
_this.__iterations = (_config$iterations = config.iterations) !== null && _config$iterations !== void 0 ? _config$iterations : 1;
_this._useNativeDriver = shouldUseNativeDriver(config);
_this.__isInteraction = (_config$isInteraction = config.isInteraction) !== null && _config$isInteraction !== void 0 ? _config$isInteraction : !_this._useNativeDriver;
return _this;
}
var _proto = TimingAnimation.prototype;
_proto.__getNativeAnimationConfig = function __getNativeAnimationConfig() {
var frameDuration = 1000.0 / 60.0;
var frames = [];
for (var dt = 0.0; dt < this._duration; dt += frameDuration) {
frames.push(this._easing(dt / this._duration));
}
frames.push(this._easing(1));
return {
type: 'frames',
frames: frames,
toValue: this._toValue,
iterations: this.__iterations
};
};
_proto.start = function start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {
var _this2 = this;
this.__active = true;
this._fromValue = fromValue;
this._onUpdate = onUpdate;
this.__onEnd = onEnd;
var start = function start() {
// Animations that sometimes have 0 duration and sometimes do not
// still need to use the native driver when duration is 0 so as to
// not cause intermixed JS and native animations.
if (_this2._duration === 0 && !_this2._useNativeDriver) {
_this2._onUpdate(_this2._toValue);
_this2.__debouncedOnEnd({
finished: true
});
} else {
_this2._startTime = Date.now();
if (_this2._useNativeDriver) {
_this2.__startNativeAnimation(animatedValue);
} else {
_this2._animationFrame = requestAnimationFrame(_this2.onUpdate.bind(_this2));
}
}
};
if (this._delay) {
this._timeout = setTimeout(start, this._delay);
} else {
start();
}
};
_proto.onUpdate = function onUpdate() {
var now = Date.now();
if (now >= this._startTime + this._duration) {
if (this._duration === 0) {
this._onUpdate(this._toValue);
} else {
this._onUpdate(this._fromValue + this._easing(1) * (this._toValue - this._fromValue));
}
this.__debouncedOnEnd({
finished: true
});
return;
}
this._onUpdate(this._fromValue + this._easing((now - this._startTime) / this._duration) * (this._toValue - this._fromValue));
if (this.__active) {
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
}
};
_proto.stop = function stop() {
_Animation.prototype.stop.call(this);
this.__active = false;
clearTimeout(this._timeout);
global.cancelAnimationFrame(this._animationFrame);
this.__debouncedOnEnd({
finished: false
});
};
return TimingAnimation;
}(Animation);
export default TimingAnimation;

View File

@ -0,0 +1,138 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* BezierEasing - use bezier curve for transition easing function
* https://github.com/gre/bezier-easing
*
*
* @format
* @copyright 2014-2015 Gaëtan Renaudeau. MIT License.
*/
'use strict'; // These values are established by empiricism with tests (tradeoff: performance VS precision)
var NEWTON_ITERATIONS = 4;
var NEWTON_MIN_SLOPE = 0.001;
var SUBDIVISION_PRECISION = 0.0000001;
var SUBDIVISION_MAX_ITERATIONS = 10;
var kSplineTableSize = 11;
var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
var float32ArraySupported = typeof Float32Array === 'function';
function A(aA1, aA2) {
return 1.0 - 3.0 * aA2 + 3.0 * aA1;
}
function B(aA1, aA2) {
return 3.0 * aA2 - 6.0 * aA1;
}
function C(aA1) {
return 3.0 * aA1;
} // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
function calcBezier(aT, aA1, aA2) {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
} // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
function getSlope(aT, aA1, aA2) {
return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide(aX, _aA, _aB, mX1, mX2) {
var currentX,
currentT,
i = 0,
aA = _aA,
aB = _aB;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function newtonRaphsonIterate(aX, _aGuessT, mX1, mX2) {
var aGuessT = _aGuessT;
for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) {
return aGuessT;
}
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
module.exports = function bezier(mX1, mY1, mX2, mY2) {
if (!(mX1 >= 0 && mX1 <= 1 && mX2 >= 0 && mX2 <= 1)) {
throw new Error('bezier x values must be in [0, 1] range');
} // Precompute samples table
var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) {
for (var i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
function getTForX(aX) {
var intervalStart = 0.0;
var currentSample = 1;
var lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample; // Interpolate to provide an initial guess for t
var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
var guessForT = intervalStart + dist * kSampleStepSize;
var initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
}
return function BezierEasing(x) {
if (mX1 === mY1 && mX2 === mY2) {
return x; // linear
} // Because JavaScript number are imprecise, we should guarantee the extremes are right.
if (x === 0) {
return 0;
}
if (x === 1) {
return 1;
}
return calcBezier(getTForX(x), mY1, mY2);
};
};

View File

@ -0,0 +1,186 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import { AnimatedEvent } from './AnimatedEvent';
import AnimatedProps from './nodes/AnimatedProps';
import React from 'react';
import invariant from 'fbjs/lib/invariant';
import mergeRefs from '../../../modules/mergeRefs';
function createAnimatedComponent(Component, defaultProps) {
invariant(typeof Component !== 'function' || Component.prototype && Component.prototype.isReactComponent, '`createAnimatedComponent` does not support stateless functional components; ' + 'use a class component instead.');
var AnimatedComponent =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(AnimatedComponent, _React$Component);
function AnimatedComponent(props) {
var _this;
_this = _React$Component.call(this, props) || this;
_this._invokeAnimatedPropsCallbackOnMount = false;
_this._eventDetachers = [];
_this._animatedPropsCallback = function () {
if (_this._component == null) {
// AnimatedProps is created in will-mount because it's used in render.
// But this callback may be invoked before mount in async mode,
// In which case we should defer the setNativeProps() call.
// React may throw away uncommitted work in async mode,
// So a deferred call won't always be invoked.
_this._invokeAnimatedPropsCallbackOnMount = true;
} else if (AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY || typeof _this._component.setNativeProps !== 'function') {
_this.forceUpdate();
} else if (!_this._propsAnimated.__isNative) {
_this._component.setNativeProps(_this._propsAnimated.__getAnimatedValue());
} else {
throw new Error('Attempting to run JS driven animation on animated ' + 'node that has been moved to "native" earlier by starting an ' + 'animation with `useNativeDriver: true`');
}
};
_this._setComponentRef = mergeRefs(_this.props.forwardedRef, function (ref) {
_this._prevComponent = _this._component;
_this._component = ref; // TODO: Delete this in a future release.
if (ref != null && ref.getNode == null) {
ref.getNode = function () {
var _ref$constructor$name;
console.warn('%s: Calling `getNode()` on the ref of an Animated component ' + 'is no longer necessary. You can now directly use the ref ' + 'instead. This method will be removed in a future release.', (_ref$constructor$name = ref.constructor.name) !== null && _ref$constructor$name !== void 0 ? _ref$constructor$name : '<<anonymous>>');
return ref;
};
}
});
return _this;
}
var _proto = AnimatedComponent.prototype;
_proto.componentWillUnmount = function componentWillUnmount() {
this._propsAnimated && this._propsAnimated.__detach();
this._detachNativeEvents();
};
_proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() {
this._attachProps(this.props);
};
_proto.componentDidMount = function componentDidMount() {
if (this._invokeAnimatedPropsCallbackOnMount) {
this._invokeAnimatedPropsCallbackOnMount = false;
this._animatedPropsCallback();
}
this._propsAnimated.setNativeView(this._component);
this._attachNativeEvents();
};
_proto._attachNativeEvents = function _attachNativeEvents() {
var _this2 = this;
// Make sure to get the scrollable node for components that implement
// `ScrollResponder.Mixin`.
var scrollableNode = this._component && this._component.getScrollableNode ? this._component.getScrollableNode() : this._component;
var _loop = function _loop(key) {
var prop = _this2.props[key];
if (prop instanceof AnimatedEvent && prop.__isNative) {
prop.__attach(scrollableNode, key);
_this2._eventDetachers.push(function () {
return prop.__detach(scrollableNode, key);
});
}
};
for (var key in this.props) {
_loop(key);
}
};
_proto._detachNativeEvents = function _detachNativeEvents() {
this._eventDetachers.forEach(function (remove) {
return remove();
});
this._eventDetachers = [];
} // The system is best designed when setNativeProps is implemented. It is
// able to avoid re-rendering and directly set the attributes that changed.
// However, setNativeProps can only be implemented on leaf native
// components. If you want to animate a composite component, you need to
// re-render it. In this case, we have a fallback that uses forceUpdate.
;
_proto._attachProps = function _attachProps(nextProps) {
var oldPropsAnimated = this._propsAnimated;
this._propsAnimated = new AnimatedProps(nextProps, this._animatedPropsCallback); // When you call detach, it removes the element from the parent list
// of children. If it goes to 0, then the parent also detaches itself
// and so on.
// An optimization is to attach the new elements and THEN detach the old
// ones instead of detaching and THEN attaching.
// This way the intermediate state isn't to go to 0 and trigger
// this expensive recursive detaching to then re-attach everything on
// the very next operation.
oldPropsAnimated && oldPropsAnimated.__detach();
};
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(newProps) {
this._attachProps(newProps);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
if (this._component !== this._prevComponent) {
this._propsAnimated.setNativeView(this._component);
}
if (this._component !== this._prevComponent || prevProps !== this.props) {
this._detachNativeEvents();
this._attachNativeEvents();
}
};
_proto.render = function render() {
var props = this._propsAnimated.__getValue();
return React.createElement(Component, _extends({}, defaultProps, props, {
ref: this._setComponentRef // The native driver updates views directly through the UI thread so we
// have to make sure the view doesn't get optimized away because it cannot
// go through the NativeViewHierarchyManager since it operates on the shadow
// thread.
,
collapsable: false
}));
};
return AnimatedComponent;
}(React.Component);
AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY = false;
var propTypes = Component.propTypes;
return React.forwardRef(function AnimatedComponentWrapper(props, ref) {
return React.createElement(AnimatedComponent, _extends({}, props, ref == null ? null : {
forwardedRef: ref
}));
});
}
export default createAnimatedComponent;

View File

@ -0,0 +1,75 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedNode from './AnimatedNode';
import AnimatedValue from './AnimatedValue';
import AnimatedWithChildren from './AnimatedWithChildren';
var AnimatedAddition =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedAddition, _AnimatedWithChildren);
function AnimatedAddition(a, b) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._a = typeof a === 'number' ? new AnimatedValue(a) : a;
_this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
return _this;
}
var _proto = AnimatedAddition.prototype;
_proto.__makeNative = function __makeNative() {
this._a.__makeNative();
this._b.__makeNative();
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.__getValue = function __getValue() {
return this._a.__getValue() + this._b.__getValue();
};
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
};
_proto.__attach = function __attach() {
this._a.__addChild(this);
this._b.__addChild(this);
};
_proto.__detach = function __detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
return {
type: 'addition',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
};
return AnimatedAddition;
}(AnimatedWithChildren);
export default AnimatedAddition;

View File

@ -0,0 +1,77 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedNode from './AnimatedNode';
import AnimatedWithChildren from './AnimatedWithChildren';
var AnimatedDiffClamp =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedDiffClamp, _AnimatedWithChildren);
function AnimatedDiffClamp(a, min, max) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._a = a;
_this._min = min;
_this._max = max;
_this._value = _this._lastValue = _this._a.__getValue();
return _this;
}
var _proto = AnimatedDiffClamp.prototype;
_proto.__makeNative = function __makeNative() {
this._a.__makeNative();
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
};
_proto.__getValue = function __getValue() {
var value = this._a.__getValue();
var diff = value - this._lastValue;
this._lastValue = value;
this._value = Math.min(Math.max(this._value + diff, this._min), this._max);
return this._value;
};
_proto.__attach = function __attach() {
this._a.__addChild(this);
};
_proto.__detach = function __detach() {
this._a.__removeChild(this);
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
return {
type: 'diffclamp',
input: this._a.__getNativeTag(),
min: this._min,
max: this._max
};
};
return AnimatedDiffClamp;
}(AnimatedWithChildren);
export default AnimatedDiffClamp;

View File

@ -0,0 +1,83 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedNode from './AnimatedNode';
import AnimatedValue from './AnimatedValue';
import AnimatedWithChildren from './AnimatedWithChildren';
var AnimatedDivision =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedDivision, _AnimatedWithChildren);
function AnimatedDivision(a, b) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._a = typeof a === 'number' ? new AnimatedValue(a) : a;
_this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
return _this;
}
var _proto = AnimatedDivision.prototype;
_proto.__makeNative = function __makeNative() {
this._a.__makeNative();
this._b.__makeNative();
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.__getValue = function __getValue() {
var a = this._a.__getValue();
var b = this._b.__getValue();
if (b === 0) {
console.error('Detected division by zero in AnimatedDivision');
}
return a / b;
};
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
};
_proto.__attach = function __attach() {
this._a.__addChild(this);
this._b.__addChild(this);
};
_proto.__detach = function __detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
return {
type: 'division',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
};
return AnimatedDivision;
}(AnimatedWithChildren);
export default AnimatedDivision;

View File

@ -0,0 +1,330 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
/* eslint no-bitwise: 0 */
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import AnimatedNode from './AnimatedNode';
import AnimatedWithChildren from './AnimatedWithChildren';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
import invariant from 'fbjs/lib/invariant';
import normalizeColor from 'normalize-css-color';
var linear = function linear(t) {
return t;
};
/**
* Very handy helper to map input ranges to output ranges with an easing
* function and custom behavior outside of the ranges.
*/
function createInterpolation(config) {
if (config.outputRange && typeof config.outputRange[0] === 'string') {
return createInterpolationFromStringOutputRange(config);
}
var outputRange = config.outputRange;
checkInfiniteRange('outputRange', outputRange);
var inputRange = config.inputRange;
checkInfiniteRange('inputRange', inputRange);
checkValidInputRange(inputRange);
invariant(inputRange.length === outputRange.length, 'inputRange (' + inputRange.length + ') and outputRange (' + outputRange.length + ') must have the same length');
var easing = config.easing || linear;
var extrapolateLeft = 'extend';
if (config.extrapolateLeft !== undefined) {
extrapolateLeft = config.extrapolateLeft;
} else if (config.extrapolate !== undefined) {
extrapolateLeft = config.extrapolate;
}
var extrapolateRight = 'extend';
if (config.extrapolateRight !== undefined) {
extrapolateRight = config.extrapolateRight;
} else if (config.extrapolate !== undefined) {
extrapolateRight = config.extrapolate;
}
return function (input) {
invariant(typeof input === 'number', 'Cannot interpolation an input which is not a number');
var range = findRange(input, inputRange);
return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight);
};
}
function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight) {
var result = input; // Extrapolate
if (result < inputMin) {
if (extrapolateLeft === 'identity') {
return result;
} else if (extrapolateLeft === 'clamp') {
result = inputMin;
} else if (extrapolateLeft === 'extend') {// noop
}
}
if (result > inputMax) {
if (extrapolateRight === 'identity') {
return result;
} else if (extrapolateRight === 'clamp') {
result = inputMax;
} else if (extrapolateRight === 'extend') {// noop
}
}
if (outputMin === outputMax) {
return outputMin;
}
if (inputMin === inputMax) {
if (input <= inputMin) {
return outputMin;
}
return outputMax;
} // Input Range
if (inputMin === -Infinity) {
result = -result;
} else if (inputMax === Infinity) {
result = result - inputMin;
} else {
result = (result - inputMin) / (inputMax - inputMin);
} // Easing
result = easing(result); // Output Range
if (outputMin === -Infinity) {
result = -result;
} else if (outputMax === Infinity) {
result = result + outputMin;
} else {
result = result * (outputMax - outputMin) + outputMin;
}
return result;
}
function colorToRgba(input) {
var int32Color = normalizeColor(input);
if (int32Color === null) {
return input;
}
int32Color = int32Color || 0;
var r = (int32Color & 0xff000000) >>> 24;
var g = (int32Color & 0x00ff0000) >>> 16;
var b = (int32Color & 0x0000ff00) >>> 8;
var a = (int32Color & 0x000000ff) / 255;
return "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
}
var stringShapeRegex = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
/**
* Supports string shapes by extracting numbers so new values can be computed,
* and recombines those values into new strings of the same shape. Supports
* things like:
*
* rgba(123, 42, 99, 0.36) // colors
* -45deg // values with units
*/
function createInterpolationFromStringOutputRange(config) {
var outputRange = config.outputRange;
invariant(outputRange.length >= 2, 'Bad output range');
outputRange = outputRange.map(colorToRgba);
checkPattern(outputRange); // ['rgba(0, 100, 200, 0)', 'rgba(50, 150, 250, 0.5)']
// ->
// [
// [0, 50],
// [100, 150],
// [200, 250],
// [0, 0.5],
// ]
/* $FlowFixMe(>=0.18.0): `outputRange[0].match()` can return `null`. Need to
* guard against this possibility.
*/
var outputRanges = outputRange[0].match(stringShapeRegex).map(function () {
return [];
});
outputRange.forEach(function (value) {
/* $FlowFixMe(>=0.18.0): `value.match()` can return `null`. Need to guard
* against this possibility.
*/
value.match(stringShapeRegex).forEach(function (number, i) {
outputRanges[i].push(+number);
});
});
/* $FlowFixMe(>=0.18.0): `outputRange[0].match()` can return `null`. Need to
* guard against this possibility.
*/
var interpolations = outputRange[0].match(stringShapeRegex).map(function (value, i) {
return createInterpolation(_objectSpread({}, config, {
outputRange: outputRanges[i]
}));
}); // rgba requires that the r,g,b are integers.... so we want to round them, but we *dont* want to
// round the opacity (4th column).
var shouldRound = isRgbOrRgba(outputRange[0]);
return function (input) {
var i = 0; // 'rgba(0, 100, 200, 0)'
// ->
// 'rgba(${interpolations[0](input)}, ${interpolations[1](input)}, ...'
return outputRange[0].replace(stringShapeRegex, function () {
var val = +interpolations[i++](input);
if (shouldRound) {
val = i < 4 ? Math.round(val) : Math.round(val * 1000) / 1000;
}
return String(val);
});
};
}
function isRgbOrRgba(range) {
return typeof range === 'string' && range.startsWith('rgb');
}
function checkPattern(arr) {
var pattern = arr[0].replace(stringShapeRegex, '');
for (var i = 1; i < arr.length; ++i) {
invariant(pattern === arr[i].replace(stringShapeRegex, ''), 'invalid pattern ' + arr[0] + ' and ' + arr[i]);
}
}
function findRange(input, inputRange) {
var i;
for (i = 1; i < inputRange.length - 1; ++i) {
if (inputRange[i] >= input) {
break;
}
}
return i - 1;
}
function checkValidInputRange(arr) {
invariant(arr.length >= 2, 'inputRange must have at least 2 elements');
for (var i = 1; i < arr.length; ++i) {
invariant(arr[i] >= arr[i - 1],
/* $FlowFixMe(>=0.13.0) - In the addition expression below this comment,
* one or both of the operands may be something that doesn't cleanly
* convert to a string, like undefined, null, and object, etc. If you really
* mean this implicit string conversion, you can do something like
* String(myThing)
*/
'inputRange must be monotonically non-decreasing ' + arr);
}
}
function checkInfiniteRange(name, arr) {
invariant(arr.length >= 2, name + ' must have at least 2 elements');
invariant(arr.length !== 2 || arr[0] !== -Infinity || arr[1] !== Infinity,
/* $FlowFixMe(>=0.13.0) - In the addition expression below this comment,
* one or both of the operands may be something that doesn't cleanly convert
* to a string, like undefined, null, and object, etc. If you really mean
* this implicit string conversion, you can do something like
* String(myThing)
*/
name + 'cannot be ]-infinity;+infinity[ ' + arr);
}
var AnimatedInterpolation =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedInterpolation, _AnimatedWithChildren);
// Export for testing.
function AnimatedInterpolation(parent, config) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._parent = parent;
_this._config = config;
_this._interpolation = createInterpolation(config);
return _this;
}
var _proto = AnimatedInterpolation.prototype;
_proto.__makeNative = function __makeNative() {
this._parent.__makeNative();
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.__getValue = function __getValue() {
var parentValue = this._parent.__getValue();
invariant(typeof parentValue === 'number', 'Cannot interpolate an input which is not a number.');
return this._interpolation(parentValue);
};
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
};
_proto.__attach = function __attach() {
this._parent.__addChild(this);
};
_proto.__detach = function __detach() {
this._parent.__removeChild(this);
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__transformDataType = function __transformDataType(range) {
// $FlowFixMe
return range.map(NativeAnimatedHelper.transformDataType);
};
_proto.__getNativeConfig = function __getNativeConfig() {
if (process.env.NODE_ENV !== 'production') {
NativeAnimatedHelper.validateInterpolation(this._config);
}
return {
inputRange: this._config.inputRange,
// Only the `outputRange` can contain strings so we don't need to transform `inputRange` here
outputRange: this.__transformDataType(this._config.outputRange),
extrapolateLeft: this._config.extrapolateLeft || this._config.extrapolate || 'extend',
extrapolateRight: this._config.extrapolateRight || this._config.extrapolate || 'extend',
type: 'interpolation'
};
};
return AnimatedInterpolation;
}(AnimatedWithChildren);
AnimatedInterpolation.__createInterpolation = createInterpolation;
export default AnimatedInterpolation;

View File

@ -0,0 +1,69 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedNode from './AnimatedNode';
import AnimatedWithChildren from './AnimatedWithChildren';
var AnimatedModulo =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedModulo, _AnimatedWithChildren);
function AnimatedModulo(a, modulus) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._a = a;
_this._modulus = modulus;
return _this;
}
var _proto = AnimatedModulo.prototype;
_proto.__makeNative = function __makeNative() {
this._a.__makeNative();
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.__getValue = function __getValue() {
return (this._a.__getValue() % this._modulus + this._modulus) % this._modulus;
};
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
};
_proto.__attach = function __attach() {
this._a.__addChild(this);
};
_proto.__detach = function __detach() {
this._a.__removeChild(this);
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
return {
type: 'modulus',
input: this._a.__getNativeTag(),
modulus: this._modulus
};
};
return AnimatedModulo;
}(AnimatedWithChildren);
export default AnimatedModulo;

View File

@ -0,0 +1,75 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedNode from './AnimatedNode';
import AnimatedValue from './AnimatedValue';
import AnimatedWithChildren from './AnimatedWithChildren';
var AnimatedMultiplication =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedMultiplication, _AnimatedWithChildren);
function AnimatedMultiplication(a, b) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._a = typeof a === 'number' ? new AnimatedValue(a) : a;
_this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
return _this;
}
var _proto = AnimatedMultiplication.prototype;
_proto.__makeNative = function __makeNative() {
this._a.__makeNative();
this._b.__makeNative();
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.__getValue = function __getValue() {
return this._a.__getValue() * this._b.__getValue();
};
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
};
_proto.__attach = function __attach() {
this._a.__addChild(this);
this._b.__addChild(this);
};
_proto.__detach = function __detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
return {
type: 'multiplication',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
};
return AnimatedMultiplication;
}(AnimatedWithChildren);
export default AnimatedMultiplication;

View File

@ -0,0 +1,185 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
import invariant from 'fbjs/lib/invariant';
var NativeAnimatedAPI = NativeAnimatedHelper.API;
var _uniqueId = 1; // Note(vjeux): this would be better as an interface but flow doesn't
// support them yet
var AnimatedNode =
/*#__PURE__*/
function () {
var _proto = AnimatedNode.prototype;
_proto.__attach = function __attach() {};
_proto.__detach = function __detach() {
if (this.__isNative && this.__nativeTag != null) {
NativeAnimatedHelper.API.dropAnimatedNode(this.__nativeTag);
this.__nativeTag = undefined;
}
};
_proto.__getValue = function __getValue() {};
_proto.__getAnimatedValue = function __getAnimatedValue() {
return this.__getValue();
};
_proto.__addChild = function __addChild(child) {};
_proto.__removeChild = function __removeChild(child) {};
_proto.__getChildren = function __getChildren() {
return [];
}
/* Methods and props used by native Animated impl */
;
function AnimatedNode() {
this._listeners = {};
}
_proto.__makeNative = function __makeNative() {
if (!this.__isNative) {
throw new Error('This node cannot be made a "native" animated node');
}
if (this.hasListeners()) {
this._startListeningToNativeValueUpdates();
}
}
/**
* Adds an asynchronous listener to the value so you can observe updates from
* animations. This is useful because there is no way to
* synchronously read the value because it might be driven natively.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#addlistener
*/
;
_proto.addListener = function addListener(callback) {
var id = String(_uniqueId++);
this._listeners[id] = callback;
if (this.__isNative) {
this._startListeningToNativeValueUpdates();
}
return id;
}
/**
* Unregister a listener. The `id` param shall match the identifier
* previously returned by `addListener()`.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#removelistener
*/
;
_proto.removeListener = function removeListener(id) {
delete this._listeners[id];
if (this.__isNative && !this.hasListeners()) {
this._stopListeningForNativeValueUpdates();
}
}
/**
* Remove all registered listeners.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#removealllisteners
*/
;
_proto.removeAllListeners = function removeAllListeners() {
this._listeners = {};
if (this.__isNative) {
this._stopListeningForNativeValueUpdates();
}
};
_proto.hasListeners = function hasListeners() {
return !!Object.keys(this._listeners).length;
};
_proto._startListeningToNativeValueUpdates = function _startListeningToNativeValueUpdates() {
var _this = this;
if (this.__nativeAnimatedValueListener && !this.__shouldUpdateListenersForNewNativeTag) {
return;
}
if (this.__shouldUpdateListenersForNewNativeTag) {
this.__shouldUpdateListenersForNewNativeTag = false;
this._stopListeningForNativeValueUpdates();
}
NativeAnimatedAPI.startListeningToAnimatedNodeValue(this.__getNativeTag());
this.__nativeAnimatedValueListener = NativeAnimatedHelper.nativeEventEmitter.addListener('onAnimatedValueUpdate', function (data) {
if (data.tag !== _this.__getNativeTag()) {
return;
}
_this._onAnimatedValueUpdateReceived(data.value);
});
};
_proto._onAnimatedValueUpdateReceived = function _onAnimatedValueUpdateReceived(value) {
this.__callListeners(value);
};
_proto.__callListeners = function __callListeners(value) {
for (var _key in this._listeners) {
this._listeners[_key]({
value: value
});
}
};
_proto._stopListeningForNativeValueUpdates = function _stopListeningForNativeValueUpdates() {
if (!this.__nativeAnimatedValueListener) {
return;
}
this.__nativeAnimatedValueListener.remove();
this.__nativeAnimatedValueListener = null;
NativeAnimatedAPI.stopListeningToAnimatedNodeValue(this.__getNativeTag());
};
_proto.__getNativeTag = function __getNativeTag() {
NativeAnimatedHelper.assertNativeAnimatedModule();
invariant(this.__isNative, 'Attempt to get native tag from node not marked as "native"');
if (this.__nativeTag == null) {
var nativeTag = NativeAnimatedHelper.generateNewNodeTag();
this.__nativeTag = nativeTag;
NativeAnimatedHelper.API.createAnimatedNode(nativeTag, this.__getNativeConfig());
this.__shouldUpdateListenersForNewNativeTag = true;
}
return this.__nativeTag;
};
_proto.__getNativeConfig = function __getNativeConfig() {
throw new Error('This JS animated node type cannot be used as native animated node');
};
_proto.toJSON = function toJSON() {
return this.__getValue();
};
return AnimatedNode;
}();
export default AnimatedNode;

View File

@ -0,0 +1,185 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import { AnimatedEvent } from '../AnimatedEvent';
import AnimatedNode from './AnimatedNode';
import AnimatedStyle from './AnimatedStyle';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
import findNodeHandle from '../../../../exports/findNodeHandle';
import invariant from 'fbjs/lib/invariant';
var AnimatedProps =
/*#__PURE__*/
function (_AnimatedNode) {
_inheritsLoose(AnimatedProps, _AnimatedNode);
function AnimatedProps(props, callback) {
var _this;
_this = _AnimatedNode.call(this) || this;
if (props.style) {
props = _objectSpread({}, props, {
style: new AnimatedStyle(props.style)
});
}
_this._props = props;
_this._callback = callback;
_this.__attach();
return _this;
}
var _proto = AnimatedProps.prototype;
_proto.__getValue = function __getValue() {
var props = {};
for (var key in this._props) {
var value = this._props[key];
if (value instanceof AnimatedNode) {
if (!value.__isNative || value instanceof AnimatedStyle) {
// We cannot use value of natively driven nodes this way as the value we have access from
// JS may not be up to date.
props[key] = value.__getValue();
}
} else if (value instanceof AnimatedEvent) {
props[key] = value.__getHandler();
} else {
props[key] = value;
}
}
return props;
};
_proto.__getAnimatedValue = function __getAnimatedValue() {
var props = {};
for (var key in this._props) {
var value = this._props[key];
if (value instanceof AnimatedNode) {
props[key] = value.__getAnimatedValue();
}
}
return props;
};
_proto.__attach = function __attach() {
for (var key in this._props) {
var value = this._props[key];
if (value instanceof AnimatedNode) {
value.__addChild(this);
}
}
};
_proto.__detach = function __detach() {
if (this.__isNative && this._animatedView) {
this.__disconnectAnimatedView();
}
for (var key in this._props) {
var value = this._props[key];
if (value instanceof AnimatedNode) {
value.__removeChild(this);
}
}
_AnimatedNode.prototype.__detach.call(this);
};
_proto.update = function update() {
this._callback();
};
_proto.__makeNative = function __makeNative() {
if (!this.__isNative) {
this.__isNative = true;
for (var key in this._props) {
var value = this._props[key];
if (value instanceof AnimatedNode) {
value.__makeNative();
}
}
if (this._animatedView) {
this.__connectAnimatedView();
}
}
};
_proto.setNativeView = function setNativeView(animatedView) {
if (this._animatedView === animatedView) {
return;
}
this._animatedView = animatedView;
if (this.__isNative) {
this.__connectAnimatedView();
}
};
_proto.__connectAnimatedView = function __connectAnimatedView() {
invariant(this.__isNative, 'Expected node to be marked as "native"');
var nativeViewTag = findNodeHandle(this._animatedView);
invariant(nativeViewTag != null, 'Unable to locate attached view in the native tree');
NativeAnimatedHelper.API.connectAnimatedNodeToView(this.__getNativeTag(), nativeViewTag);
};
_proto.__disconnectAnimatedView = function __disconnectAnimatedView() {
invariant(this.__isNative, 'Expected node to be marked as "native"');
var nativeViewTag = findNodeHandle(this._animatedView);
invariant(nativeViewTag != null, 'Unable to locate attached view in the native tree');
NativeAnimatedHelper.API.disconnectAnimatedNodeFromView(this.__getNativeTag(), nativeViewTag);
};
_proto.__getNativeConfig = function __getNativeConfig() {
var propsConfig = {};
for (var propKey in this._props) {
var value = this._props[propKey];
if (value instanceof AnimatedNode) {
value.__makeNative();
propsConfig[propKey] = value.__getNativeTag();
}
}
return {
type: 'props',
props: propsConfig
};
};
return AnimatedProps;
}(AnimatedNode);
export default AnimatedProps;

View File

@ -0,0 +1,159 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedNode from './AnimatedNode';
import AnimatedTransform from './AnimatedTransform';
import AnimatedWithChildren from './AnimatedWithChildren';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
import StyleSheet from '../../../../exports/StyleSheet';
var flattenStyle = StyleSheet.flatten;
var AnimatedStyle =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedStyle, _AnimatedWithChildren);
function AnimatedStyle(style) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
style = flattenStyle(style) || {};
if (style.transform) {
style = _objectSpread({}, style, {
transform: new AnimatedTransform(style.transform)
});
}
_this._style = style;
return _this;
} // Recursively get values for nested styles (like iOS's shadowOffset)
var _proto = AnimatedStyle.prototype;
_proto._walkStyleAndGetValues = function _walkStyleAndGetValues(style) {
var updatedStyle = {};
for (var key in style) {
var value = style[key];
if (value instanceof AnimatedNode) {
if (!value.__isNative) {
// We cannot use value of natively driven nodes this way as the value we have access from
// JS may not be up to date.
updatedStyle[key] = value.__getValue();
}
} else if (value && !Array.isArray(value) && typeof value === 'object') {
// Support animating nested values (for example: shadowOffset.height)
updatedStyle[key] = this._walkStyleAndGetValues(value);
} else {
updatedStyle[key] = value;
}
}
return updatedStyle;
};
_proto.__getValue = function __getValue() {
return this._walkStyleAndGetValues(this._style);
} // Recursively get animated values for nested styles (like iOS's shadowOffset)
;
_proto._walkStyleAndGetAnimatedValues = function _walkStyleAndGetAnimatedValues(style) {
var updatedStyle = {};
for (var key in style) {
var value = style[key];
if (value instanceof AnimatedNode) {
updatedStyle[key] = value.__getAnimatedValue();
} else if (value && !Array.isArray(value) && typeof value === 'object') {
// Support animating nested values (for example: shadowOffset.height)
updatedStyle[key] = this._walkStyleAndGetAnimatedValues(value);
}
}
return updatedStyle;
};
_proto.__getAnimatedValue = function __getAnimatedValue() {
return this._walkStyleAndGetAnimatedValues(this._style);
};
_proto.__attach = function __attach() {
for (var key in this._style) {
var value = this._style[key];
if (value instanceof AnimatedNode) {
value.__addChild(this);
}
}
};
_proto.__detach = function __detach() {
for (var key in this._style) {
var value = this._style[key];
if (value instanceof AnimatedNode) {
value.__removeChild(this);
}
}
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__makeNative = function __makeNative() {
for (var key in this._style) {
var value = this._style[key];
if (value instanceof AnimatedNode) {
value.__makeNative();
}
}
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
var styleConfig = {};
for (var styleKey in this._style) {
if (this._style[styleKey] instanceof AnimatedNode) {
var style = this._style[styleKey];
style.__makeNative();
styleConfig[styleKey] = style.__getNativeTag();
} // Non-animated styles are set using `setNativeProps`, no need
// to pass those as a part of the node config
}
NativeAnimatedHelper.validateStyles(styleConfig);
return {
type: 'style',
style: styleConfig
};
};
return AnimatedStyle;
}(AnimatedWithChildren);
export default AnimatedStyle;

View File

@ -0,0 +1,75 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedNode from './AnimatedNode';
import AnimatedValue from './AnimatedValue';
import AnimatedWithChildren from './AnimatedWithChildren';
var AnimatedSubtraction =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedSubtraction, _AnimatedWithChildren);
function AnimatedSubtraction(a, b) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._a = typeof a === 'number' ? new AnimatedValue(a) : a;
_this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
return _this;
}
var _proto = AnimatedSubtraction.prototype;
_proto.__makeNative = function __makeNative() {
this._a.__makeNative();
this._b.__makeNative();
_AnimatedWithChildren.prototype.__makeNative.call(this);
};
_proto.__getValue = function __getValue() {
return this._a.__getValue() - this._b.__getValue();
};
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
};
_proto.__attach = function __attach() {
this._a.__addChild(this);
this._b.__addChild(this);
};
_proto.__detach = function __detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
return {
type: 'subtraction',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
};
return AnimatedSubtraction;
}(AnimatedWithChildren);
export default AnimatedSubtraction;

View File

@ -0,0 +1,106 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedValue from './AnimatedValue';
import AnimatedNode from './AnimatedNode';
import { generateNewAnimationId, shouldUseNativeDriver } from '../NativeAnimatedHelper';
var AnimatedTracking =
/*#__PURE__*/
function (_AnimatedNode) {
_inheritsLoose(AnimatedTracking, _AnimatedNode);
function AnimatedTracking(value, parent, animationClass, animationConfig, callback) {
var _this;
_this = _AnimatedNode.call(this) || this;
_this._value = value;
_this._parent = parent;
_this._animationClass = animationClass;
_this._animationConfig = animationConfig;
_this._useNativeDriver = shouldUseNativeDriver(animationConfig);
_this._callback = callback;
_this.__attach();
return _this;
}
var _proto = AnimatedTracking.prototype;
_proto.__makeNative = function __makeNative() {
this.__isNative = true;
this._parent.__makeNative();
_AnimatedNode.prototype.__makeNative.call(this);
this._value.__makeNative();
};
_proto.__getValue = function __getValue() {
return this._parent.__getValue();
};
_proto.__attach = function __attach() {
this._parent.__addChild(this);
if (this._useNativeDriver) {
// when the tracking starts we need to convert this node to a "native node"
// so that the parent node will be made "native" too. This is necessary as
// if we don't do this `update` method will get called. At that point it
// may be too late as it would mean the JS driver has already started
// updating node values
this.__makeNative();
}
};
_proto.__detach = function __detach() {
this._parent.__removeChild(this);
_AnimatedNode.prototype.__detach.call(this);
};
_proto.update = function update() {
this._value.animate(new this._animationClass(_objectSpread({}, this._animationConfig, {
toValue: this._animationConfig.toValue.__getValue()
})), this._callback);
};
_proto.__getNativeConfig = function __getNativeConfig() {
var animation = new this._animationClass(_objectSpread({}, this._animationConfig, {
// remove toValue from the config as it's a ref to Animated.Value
toValue: undefined
}));
var animationConfig = animation.__getNativeAnimationConfig();
return {
type: 'tracking',
animationId: generateNewAnimationId(),
animationConfig: animationConfig,
toValue: this._parent.__getNativeTag(),
value: this._value.__getNativeTag()
};
};
return AnimatedTracking;
}(AnimatedNode);
export default AnimatedTracking;

View File

@ -0,0 +1,147 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedNode from './AnimatedNode';
import AnimatedWithChildren from './AnimatedWithChildren';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
var AnimatedTransform =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedTransform, _AnimatedWithChildren);
function AnimatedTransform(transforms) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._transforms = transforms;
return _this;
}
var _proto = AnimatedTransform.prototype;
_proto.__makeNative = function __makeNative() {
_AnimatedWithChildren.prototype.__makeNative.call(this);
this._transforms.forEach(function (transform) {
for (var key in transform) {
var value = transform[key];
if (value instanceof AnimatedNode) {
value.__makeNative();
}
}
});
};
_proto.__getValue = function __getValue() {
return this._transforms.map(function (transform) {
var result = {};
for (var key in transform) {
var value = transform[key];
if (value instanceof AnimatedNode) {
result[key] = value.__getValue();
} else {
result[key] = value;
}
}
return result;
});
};
_proto.__getAnimatedValue = function __getAnimatedValue() {
return this._transforms.map(function (transform) {
var result = {};
for (var key in transform) {
var value = transform[key];
if (value instanceof AnimatedNode) {
result[key] = value.__getAnimatedValue();
} else {
// All transform components needed to recompose matrix
result[key] = value;
}
}
return result;
});
};
_proto.__attach = function __attach() {
var _this2 = this;
this._transforms.forEach(function (transform) {
for (var key in transform) {
var value = transform[key];
if (value instanceof AnimatedNode) {
value.__addChild(_this2);
}
}
});
};
_proto.__detach = function __detach() {
var _this3 = this;
this._transforms.forEach(function (transform) {
for (var key in transform) {
var value = transform[key];
if (value instanceof AnimatedNode) {
value.__removeChild(_this3);
}
}
});
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getNativeConfig = function __getNativeConfig() {
var transConfigs = [];
this._transforms.forEach(function (transform) {
for (var key in transform) {
var value = transform[key];
if (value instanceof AnimatedNode) {
transConfigs.push({
type: 'animated',
property: key,
nodeTag: value.__getNativeTag()
});
} else {
transConfigs.push({
type: 'static',
property: key,
value: value
});
}
}
});
NativeAnimatedHelper.validateTransform(transConfigs);
return {
type: 'transform',
transforms: transConfigs
};
};
return AnimatedTransform;
}(AnimatedWithChildren);
export default AnimatedTransform;

View File

@ -0,0 +1,287 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedInterpolation from './AnimatedInterpolation';
import AnimatedWithChildren from './AnimatedWithChildren';
import InteractionManager from '../../../../exports/InteractionManager';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
var NativeAnimatedAPI = NativeAnimatedHelper.API;
/**
* Animated works by building a directed acyclic graph of dependencies
* transparently when you render your Animated components.
*
* new Animated.Value(0)
* .interpolate() .interpolate() new Animated.Value(1)
* opacity translateY scale
* style transform
* View#234 style
* View#123
*
* A) Top Down phase
* When an Animated.Value is updated, we recursively go down through this
* graph in order to find leaf nodes: the views that we flag as needing
* an update.
*
* B) Bottom Up phase
* When a view is flagged as needing an update, we recursively go back up
* in order to build the new value that it needs. The reason why we need
* this two-phases process is to deal with composite props such as
* transform which can receive values from multiple parents.
*/
function _flush(rootNode) {
var animatedStyles = new Set();
function findAnimatedStyles(node) {
/* $FlowFixMe(>=0.68.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.68 was deployed. To see the error delete this
* comment and run Flow. */
if (typeof node.update === 'function') {
animatedStyles.add(node);
} else {
node.__getChildren().forEach(findAnimatedStyles);
}
}
findAnimatedStyles(rootNode);
/* $FlowFixMe */
animatedStyles.forEach(function (animatedStyle) {
return animatedStyle.update();
});
}
/**
* Standard value for driving animations. One `Animated.Value` can drive
* multiple properties in a synchronized fashion, but can only be driven by one
* mechanism at a time. Using a new mechanism (e.g. starting a new animation,
* or calling `setValue`) will stop any previous ones.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html
*/
var AnimatedValue =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedValue, _AnimatedWithChildren);
function AnimatedValue(value) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
_this._startingValue = _this._value = value;
_this._offset = 0;
_this._animation = null;
return _this;
}
var _proto = AnimatedValue.prototype;
_proto.__detach = function __detach() {
this.stopAnimation();
_AnimatedWithChildren.prototype.__detach.call(this);
};
_proto.__getValue = function __getValue() {
return this._value + this._offset;
}
/**
* Directly set the value. This will stop any animations running on the value
* and update all the bound properties.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#setvalue
*/
;
_proto.setValue = function setValue(value) {
if (this._animation) {
this._animation.stop();
this._animation = null;
}
this._updateValue(value, !this.__isNative
/* don't perform a flush for natively driven values */
);
if (this.__isNative) {
NativeAnimatedAPI.setAnimatedNodeValue(this.__getNativeTag(), value);
}
}
/**
* Sets an offset that is applied on top of whatever value is set, whether via
* `setValue`, an animation, or `Animated.event`. Useful for compensating
* things like the start of a pan gesture.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#setoffset
*/
;
_proto.setOffset = function setOffset(offset) {
this._offset = offset;
if (this.__isNative) {
NativeAnimatedAPI.setAnimatedNodeOffset(this.__getNativeTag(), offset);
}
}
/**
* Merges the offset value into the base value and resets the offset to zero.
* The final output of the value is unchanged.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#flattenoffset
*/
;
_proto.flattenOffset = function flattenOffset() {
this._value += this._offset;
this._offset = 0;
if (this.__isNative) {
NativeAnimatedAPI.flattenAnimatedNodeOffset(this.__getNativeTag());
}
}
/**
* Sets the offset value to the base value, and resets the base value to zero.
* The final output of the value is unchanged.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#extractoffset
*/
;
_proto.extractOffset = function extractOffset() {
this._offset += this._value;
this._value = 0;
if (this.__isNative) {
NativeAnimatedAPI.extractAnimatedNodeOffset(this.__getNativeTag());
}
}
/**
* Stops any running animation or tracking. `callback` is invoked with the
* final value after stopping the animation, which is useful for updating
* state to match the animation position with layout.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#stopanimation
*/
;
_proto.stopAnimation = function stopAnimation(callback) {
this.stopTracking();
this._animation && this._animation.stop();
this._animation = null;
callback && callback(this.__getValue());
}
/**
* Stops any animation and resets the value to its original.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#resetanimation
*/
;
_proto.resetAnimation = function resetAnimation(callback) {
this.stopAnimation(callback);
this._value = this._startingValue;
};
_proto._onAnimatedValueUpdateReceived = function _onAnimatedValueUpdateReceived(value) {
this._updateValue(value, false
/*flush*/
);
}
/**
* Interpolates the value before updating the property, e.g. mapping 0-1 to
* 0-10.
*/
;
_proto.interpolate = function interpolate(config) {
return new AnimatedInterpolation(this, config);
}
/**
* Typically only used internally, but could be used by a custom Animation
* class.
*
* See http://facebook.github.io/react-native/docs/animatedvalue.html#animate
*/
;
_proto.animate = function animate(animation, callback) {
var _this2 = this;
var handle = null;
if (animation.__isInteraction) {
handle = InteractionManager.createInteractionHandle();
}
var previousAnimation = this._animation;
this._animation && this._animation.stop();
this._animation = animation;
animation.start(this._value, function (value) {
// Natively driven animations will never call into that callback, therefore we can always
// pass flush = true to allow the updated value to propagate to native with setNativeProps
_this2._updateValue(value, true
/* flush */
);
}, function (result) {
_this2._animation = null;
if (handle !== null) {
InteractionManager.clearInteractionHandle(handle);
}
callback && callback(result);
}, previousAnimation, this);
}
/**
* Typically only used internally.
*/
;
_proto.stopTracking = function stopTracking() {
this._tracking && this._tracking.__detach();
this._tracking = null;
}
/**
* Typically only used internally.
*/
;
_proto.track = function track(tracking) {
this.stopTracking();
this._tracking = tracking;
};
_proto._updateValue = function _updateValue(value, flush) {
this._value = value;
if (flush) {
_flush(this);
}
_AnimatedWithChildren.prototype.__callListeners.call(this, this.__getValue());
};
_proto.__getNativeConfig = function __getNativeConfig() {
return {
type: 'value',
value: this._value,
offset: this._offset
};
};
return AnimatedValue;
}(AnimatedWithChildren);
export default AnimatedValue;

View File

@ -0,0 +1,220 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedValue from './AnimatedValue';
import AnimatedWithChildren from './AnimatedWithChildren';
import invariant from 'fbjs/lib/invariant';
var _uniqueId = 1;
/**
* 2D Value for driving 2D animations, such as pan gestures. Almost identical
* API to normal `Animated.Value`, but multiplexed.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html
*/
var AnimatedValueXY =
/*#__PURE__*/
function (_AnimatedWithChildren) {
_inheritsLoose(AnimatedValueXY, _AnimatedWithChildren);
// $FlowFixMe
function AnimatedValueXY(valueIn) {
var _this;
_this = _AnimatedWithChildren.call(this) || this;
var value = valueIn || {
x: 0,
y: 0
}; // fixme: shouldn't need `: any`
if (typeof value.x === 'number' && typeof value.y === 'number') {
_this.x = new AnimatedValue(value.x);
_this.y = new AnimatedValue(value.y);
} else {
invariant(value.x instanceof AnimatedValue && value.y instanceof AnimatedValue, 'AnimatedValueXY must be initialized with an object of numbers or ' + 'AnimatedValues.');
_this.x = value.x;
_this.y = value.y;
}
_this._listeners = {};
return _this;
}
/**
* Directly set the value. This will stop any animations running on the value
* and update all the bound properties.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#setvalue
*/
var _proto = AnimatedValueXY.prototype;
_proto.setValue = function setValue(value) {
this.x.setValue(value.x);
this.y.setValue(value.y);
}
/**
* Sets an offset that is applied on top of whatever value is set, whether
* via `setValue`, an animation, or `Animated.event`. Useful for compensating
* things like the start of a pan gesture.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#setoffset
*/
;
_proto.setOffset = function setOffset(offset) {
this.x.setOffset(offset.x);
this.y.setOffset(offset.y);
}
/**
* Merges the offset value into the base value and resets the offset to zero.
* The final output of the value is unchanged.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#flattenoffset
*/
;
_proto.flattenOffset = function flattenOffset() {
this.x.flattenOffset();
this.y.flattenOffset();
}
/**
* Sets the offset value to the base value, and resets the base value to
* zero. The final output of the value is unchanged.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#extractoffset
*/
;
_proto.extractOffset = function extractOffset() {
this.x.extractOffset();
this.y.extractOffset();
};
_proto.__getValue = function __getValue() {
return {
x: this.x.__getValue(),
y: this.y.__getValue()
};
}
/**
* Stops any animation and resets the value to its original.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#resetanimation
*/
;
_proto.resetAnimation = function resetAnimation(callback) {
this.x.resetAnimation();
this.y.resetAnimation();
callback && callback(this.__getValue());
}
/**
* Stops any running animation or tracking. `callback` is invoked with the
* final value after stopping the animation, which is useful for updating
* state to match the animation position with layout.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#stopanimation
*/
;
_proto.stopAnimation = function stopAnimation(callback) {
this.x.stopAnimation();
this.y.stopAnimation();
callback && callback(this.__getValue());
}
/**
* Adds an asynchronous listener to the value so you can observe updates from
* animations. This is useful because there is no way to synchronously read
* the value because it might be driven natively.
*
* Returns a string that serves as an identifier for the listener.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#addlistener
*/
// $FlowFixMe
;
_proto.addListener = function addListener(callback) {
var _this2 = this;
var id = String(_uniqueId++);
var jointCallback = function jointCallback(_ref) {
var number = _ref.value;
callback(_this2.__getValue());
};
this._listeners[id] = {
x: this.x.addListener(jointCallback),
y: this.y.addListener(jointCallback)
};
return id;
}
/**
* Unregister a listener. The `id` param shall match the identifier
* previously returned by `addListener()`.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#removelistener
*/
;
_proto.removeListener = function removeListener(id) {
this.x.removeListener(this._listeners[id].x);
this.y.removeListener(this._listeners[id].y);
delete this._listeners[id];
}
/**
* Remove all registered listeners.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#removealllisteners
*/
;
_proto.removeAllListeners = function removeAllListeners() {
this.x.removeAllListeners();
this.y.removeAllListeners();
this._listeners = {};
}
/**
* Converts `{x, y}` into `{left, top}` for use in style.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#getlayout
*/
;
_proto.getLayout = function getLayout() {
return {
left: this.x,
top: this.y
};
}
/**
* Converts `{x, y}` into a useable translation transform.
*
* See http://facebook.github.io/react-native/docs/animatedvaluexy.html#gettranslatetransform
*/
;
_proto.getTranslateTransform = function getTranslateTransform() {
return [{
translateX: this.x
}, {
translateY: this.y
}];
};
return AnimatedValueXY;
}(AnimatedWithChildren);
export default AnimatedValueXY;

View File

@ -0,0 +1,125 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
import AnimatedNode from './AnimatedNode';
import NativeAnimatedHelper from '../NativeAnimatedHelper';
var AnimatedWithChildren =
/*#__PURE__*/
function (_AnimatedNode) {
_inheritsLoose(AnimatedWithChildren, _AnimatedNode);
function AnimatedWithChildren() {
var _this;
_this = _AnimatedNode.call(this) || this;
_this._children = [];
return _this;
}
var _proto = AnimatedWithChildren.prototype;
_proto.__makeNative = function __makeNative() {
if (!this.__isNative) {
this.__isNative = true;
for (var _iterator = this._children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var child = _ref;
child.__makeNative();
NativeAnimatedHelper.API.connectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
}
}
_AnimatedNode.prototype.__makeNative.call(this);
};
_proto.__addChild = function __addChild(child) {
if (this._children.length === 0) {
this.__attach();
}
this._children.push(child);
if (this.__isNative) {
// Only accept "native" animated nodes as children
child.__makeNative();
NativeAnimatedHelper.API.connectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
}
};
_proto.__removeChild = function __removeChild(child) {
var index = this._children.indexOf(child);
if (index === -1) {
console.warn("Trying to remove a child that doesn't exist");
return;
}
if (this.__isNative && child.__isNative) {
NativeAnimatedHelper.API.disconnectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
}
this._children.splice(index, 1);
if (this._children.length === 0) {
this.__detach();
}
};
_proto.__getChildren = function __getChildren() {
return this._children;
};
_proto.__callListeners = function __callListeners(value) {
_AnimatedNode.prototype.__callListeners.call(this, value);
if (!this.__isNative) {
for (var _iterator2 = this._children, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var child = _ref2;
if (child.__getValue) {
child.__callListeners(child.__getValue());
}
}
}
};
return AnimatedWithChildren;
}(AnimatedNode);
export default AnimatedWithChildren;

View File

@ -0,0 +1,12 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
createInteractionHandle: function createInteractionHandle() {},
clearInteractionHandle: function clearInteractionHandle() {}
};

View File

@ -0,0 +1,23 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
function SetPolyfill() {
this._cache = [];
}
SetPolyfill.prototype.add = function (e) {
if (this._cache.indexOf(e) === -1) {
this._cache.push(e);
}
};
SetPolyfill.prototype.forEach = function (cb) {
this._cache.forEach(cb);
};
module.exports = SetPolyfill;

View File

@ -0,0 +1,11 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = function (style) {
return style;
};