|
| 1 | +import React, { useCallback, useEffect, useState, useRef } from 'react'; |
| 2 | +import './ProgressBar.scss'; |
| 3 | + |
| 4 | +export interface ProgressBarProps { |
| 5 | + percent: number; |
| 6 | +} |
| 7 | + |
| 8 | +const ProgressBar = ({ percent: initialPercent = 0 }: ProgressBarProps) => { |
| 9 | + const [percent, setPercent] = useState(initialPercent); |
| 10 | + const intervalRef = useRef<number | null>(null); |
| 11 | + const timeoutRef = useRef<number | null>(null); |
| 12 | + |
| 13 | + const clearTimeoutAndInterval = () => { |
| 14 | + if (intervalRef.current) { |
| 15 | + clearInterval(intervalRef.current); |
| 16 | + } |
| 17 | + if (timeoutRef.current) { |
| 18 | + clearTimeout(timeoutRef.current); |
| 19 | + } |
| 20 | + }; |
| 21 | + |
| 22 | + const incrementProgress = () => { |
| 23 | + setPercent(prevPercent => { |
| 24 | + const newPercent = Math.min(prevPercent + 2 / (prevPercent || 1), 100); |
| 25 | + if (newPercent === 100) { |
| 26 | + clearTimeoutAndInterval(); |
| 27 | + } |
| 28 | + 0; |
| 29 | + return newPercent; |
| 30 | + }); |
| 31 | + }; |
| 32 | + |
| 33 | + const resetProgress = () => { |
| 34 | + setPercent(0); |
| 35 | + }; |
| 36 | + |
| 37 | + const startProgress = useCallback(() => { |
| 38 | + if (percent === 0) { |
| 39 | + intervalRef.current = window.setInterval(incrementProgress, 100); |
| 40 | + } else if (percent === 100) { |
| 41 | + timeoutRef.current = window.setTimeout(resetProgress, 600); |
| 42 | + } |
| 43 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 44 | + }, []); |
| 45 | + |
| 46 | + useEffect(() => { |
| 47 | + startProgress(); |
| 48 | + return () => clearTimeoutAndInterval(); |
| 49 | + }, [percent, startProgress]); |
| 50 | + |
| 51 | + useEffect(() => { |
| 52 | + setPercent(initialPercent); |
| 53 | + }, [initialPercent]); |
| 54 | + |
| 55 | + const containerStyle = { |
| 56 | + opacity: percent > 0 && percent < 100 ? 1 : 0, |
| 57 | + transitionDelay: percent > 0 && percent < 100 ? '0' : '0.4s', |
| 58 | + } as const; |
| 59 | + |
| 60 | + return ( |
| 61 | + <div className="be-progress-container" style={containerStyle}> |
| 62 | + <div className="be-progress" role="progressbar" style={{ width: `${percent}%` }} /> |
| 63 | + </div> |
| 64 | + ); |
| 65 | +}; |
| 66 | + |
| 67 | +export default ProgressBar; |
0 commit comments