|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + useEffect, |
| 4 | + useState, |
| 5 | + type FunctionComponent, |
| 6 | +} from 'react'; |
| 7 | +import { |
| 8 | + cancelAnimation, |
| 9 | + Easing, |
| 10 | + useSharedValue, |
| 11 | + withRepeat, |
| 12 | + withTiming, |
| 13 | + type SharedValue, |
| 14 | +} from 'react-native-reanimated'; |
| 15 | + |
| 16 | +interface ShimmerContextType { |
| 17 | + progress: SharedValue<number>; |
| 18 | + increaseActiveShimmers: () => void; |
| 19 | + decreaseActiveShimmers: () => void; |
| 20 | +} |
| 21 | + |
| 22 | +const ShimmerContext = createContext<ShimmerContextType | null>(null); |
| 23 | + |
| 24 | +interface ShimmerProviderProps { |
| 25 | + children?: React.ReactNode; |
| 26 | + duration?: number; |
| 27 | +} |
| 28 | + |
| 29 | +const ShimmerProvider: FunctionComponent<ShimmerProviderProps> = ({ |
| 30 | + children, |
| 31 | + duration = 3000, |
| 32 | +}) => { |
| 33 | + const [activeShimmers, setActiveShimmers] = useState(0); |
| 34 | + const [isShimmerActive, setIsShimmerActive] = useState(false); |
| 35 | + const progress = useSharedValue(-300); |
| 36 | + |
| 37 | + useEffect(() => { |
| 38 | + if (!isShimmerActive && activeShimmers > 0) { |
| 39 | + setIsShimmerActive(true); |
| 40 | + progress.value = -300; |
| 41 | + progress.value = withRepeat( |
| 42 | + withTiming(300, { |
| 43 | + duration: duration, |
| 44 | + easing: Easing.ease, |
| 45 | + }), |
| 46 | + -1, |
| 47 | + false |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + if (isShimmerActive && activeShimmers === 0) { |
| 52 | + cancelAnimation(progress); |
| 53 | + setIsShimmerActive(false); |
| 54 | + } |
| 55 | + }, [activeShimmers, isShimmerActive, progress, duration]); |
| 56 | + |
| 57 | + const increaseActiveShimmers = () => { |
| 58 | + setActiveShimmers((prev) => prev + 1); |
| 59 | + }; |
| 60 | + |
| 61 | + const decreaseActiveShimmers = () => { |
| 62 | + setActiveShimmers((prev) => Math.max(prev - 1, 0)); |
| 63 | + }; |
| 64 | + |
| 65 | + return ( |
| 66 | + <ShimmerContext.Provider |
| 67 | + value={{ progress, increaseActiveShimmers, decreaseActiveShimmers }} |
| 68 | + > |
| 69 | + {children} |
| 70 | + </ShimmerContext.Provider> |
| 71 | + ); |
| 72 | +}; |
| 73 | +export { ShimmerContext, ShimmerProvider }; |
0 commit comments