-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgressBar.js
95 lines (90 loc) · 2.73 KB
/
ProgressBar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { View, Text, Animated } from 'react-native';
import React, { useEffect, useState, useRef } from 'react';
export default function ProgressBar(props) {
const progressAnim = useRef(new Animated.Value(0)).current;
const [state, _setState] = useState({
containerWidth: 0,
containerHeight: 0,
animationStarted: false,
});
const setState = newState => {
_setState(prevState => ({ ...prevState, ...newState }));
};
useEffect(() => {
if (props.type === 'timing' && props.duration) {
let duration = props.duration;
if (props.initialValue) {
let percentage = props.initialValue / 100;
let value = state.containerWidth * percentage;
duration = duration * (1 - percentage);
progressAnim.setValue(value);
}
if (props.animationStarted) {
setState({ animationStarted: true });
startProgressAnimation({
duration: duration,
toValue: state.containerWidth,
});
} else {
progressAnim.stopAnimation();
}
}
}, [props.animationStarted, state.containerWidth]);
useEffect(() => {
if (!props.type) {
let percentage = props.progress ? props.progress / 100 : 0;
let toValue = state.containerWidth * percentage;
if (!state.animationStarted) {
setState({ animationStarted: true });
startProgressAnimation({ toValue, duration: 500 });
} else {
progressAnim.stopAnimation();
startProgressAnimation({ toValue, duration: 500 });
}
}
}, [props.progress]);
const startProgressAnimation = ({ toValue, duration }) => {
Animated.timing(progressAnim, {
toValue: toValue,
duration: duration,
useNativeDriver: false,
}).start(() => {
setState({ animationStarted: false });
});
};
return (
<View style={{ ...props.containerShadowStyle }}>
<Animated.View
{...props}
style={{ ...props.style, overflow: 'hidden' }}
onLayout={event => {
const layout = event.nativeEvent.layout;
if (
state.containerWidth !== layout.width ||
state.containerHeight !== layout.height
) {
setState({
containerWidth: layout.width,
containerHeight: layout.height,
});
}
}}
>
<Animated.View
style={{
...props.trackStyle,
width: progressAnim,
position: 'absolute',
left: 0,
top: 0,
height: state.containerHeight,
backgroundColor: props.trackColor
? props.trackColor
: 'transparent',
}}
></Animated.View>
{props.children}
</Animated.View>
</View>
);
}