1 | import { Animated } from 'react-native';
|
2 |
|
3 | const { add, multiply } = Animated;
|
4 |
|
5 | /**
|
6 | * Use an Animated Node based on a condition. Similar to Reanimated's `cond`.
|
7 | *
|
8 | * @param condition Animated Node representing the condition, must be 0 or 1, 1 means `true`, 0 means `false`
|
9 | * @param main Animated Node to use if the condition is `true`
|
10 | * @param fallback Animated Node to use if the condition is `false`
|
11 | */
|
12 | export default function conditional(
|
13 | condition: Animated.AnimatedInterpolation,
|
14 | main: Animated.AnimatedInterpolation,
|
15 | fallback: Animated.AnimatedInterpolation
|
16 | ) {
|
17 | // To implement this behavior, we multiply the main node with the condition.
|
18 | // So if condition is 0, result will be 0, and if condition is 1, result will be main node.
|
19 | // Then we multiple reverse of the condition (0 if condition is 1) with the fallback.
|
20 | // So if condition is 0, result will be fallback node, and if condition is 1, result will be 0,
|
21 | // This way, one of them will always be 0, and other one will be the value we need.
|
22 | // In the end we add them both together, 0 + value we need = value we need
|
23 | return add(
|
24 | multiply(condition, main),
|
25 | multiply(
|
26 | condition.interpolate({
|
27 | inputRange: [0, 1],
|
28 | outputRange: [1, 0],
|
29 | }),
|
30 | fallback
|
31 | )
|
32 | );
|
33 | }
|