|
| 1 | +import React, { ReactElement } from 'react'; |
| 2 | +import { View, StyleSheet, LayoutRectangle } from 'react-native'; |
| 3 | +import MaskedView from '@react-native-masked-view/masked-view'; |
| 4 | +import { LinearGradient } from 'expo-linear-gradient'; |
| 5 | +import Reanimated, { |
| 6 | + useSharedValue, |
| 7 | + withRepeat, |
| 8 | + useAnimatedStyle, |
| 9 | + withTiming, |
| 10 | + interpolate, |
| 11 | +} from 'react-native-reanimated'; |
| 12 | + |
| 13 | +interface SkeletonProps { |
| 14 | + background?: string; |
| 15 | + highlight?: string; |
| 16 | + children: ReactElement; |
| 17 | + show?: boolean; |
| 18 | +} |
| 19 | + |
| 20 | +const BaseSkeleton: React.FC<SkeletonProps> = ({ |
| 21 | + children, |
| 22 | + background = '#636e72', |
| 23 | + highlight = '#b2bec3', |
| 24 | +}) => { |
| 25 | + const [layout, setLayout] = React.useState<LayoutRectangle>(); |
| 26 | + const shared = useSharedValue(0); |
| 27 | + |
| 28 | + const animStyle = useAnimatedStyle(() => { |
| 29 | + const x = interpolate( |
| 30 | + shared.value, |
| 31 | + [0, 1], |
| 32 | + [layout ? -layout.width : 0, layout ? layout.width : 0] |
| 33 | + ); |
| 34 | + return { |
| 35 | + transform: [{ translateX: x }], |
| 36 | + }; |
| 37 | + }); |
| 38 | + |
| 39 | + React.useEffect(() => { |
| 40 | + shared.value = withRepeat(withTiming(1, { duration: 1000 }), Infinity); |
| 41 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 42 | + }, []); |
| 43 | + |
| 44 | + if (!layout) { |
| 45 | + return ( |
| 46 | + <View onLayout={(event) => setLayout(event.nativeEvent.layout)}> |
| 47 | + {children} |
| 48 | + </View> |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + return ( |
| 53 | + <MaskedView |
| 54 | + maskElement={children} |
| 55 | + style={{ width: layout.width, height: layout.height }} |
| 56 | + > |
| 57 | + <View style={[styles.container, { backgroundColor: background }]} /> |
| 58 | + <Reanimated.View style={[StyleSheet.absoluteFill, animStyle]}> |
| 59 | + <MaskedView |
| 60 | + style={StyleSheet.absoluteFill} |
| 61 | + maskElement={ |
| 62 | + <LinearGradient |
| 63 | + start={{ x: 0, y: 0 }} |
| 64 | + end={{ x: 1, y: 0 }} |
| 65 | + style={StyleSheet.absoluteFill} |
| 66 | + colors={['transparent', highlight, 'transparent']} |
| 67 | + /> |
| 68 | + } |
| 69 | + > |
| 70 | + <View |
| 71 | + style={[StyleSheet.absoluteFill, { backgroundColor: highlight }]} |
| 72 | + /> |
| 73 | + </MaskedView> |
| 74 | + </Reanimated.View> |
| 75 | + </MaskedView> |
| 76 | + ); |
| 77 | +}; |
| 78 | + |
| 79 | +export const Skeleton = ({ children, show, ...rest }: SkeletonProps) => { |
| 80 | + if (!show) { |
| 81 | + return children; |
| 82 | + } |
| 83 | + |
| 84 | + return <BaseSkeleton {...rest}>{children}</BaseSkeleton>; |
| 85 | +}; |
| 86 | + |
| 87 | +const styles = StyleSheet.create({ |
| 88 | + container: { |
| 89 | + flexGrow: 1, |
| 90 | + overflow: 'hidden', |
| 91 | + }, |
| 92 | +}); |
0 commit comments