|
| 1 | +import React, { FC, useEffect, useMemo, useState } from 'react' |
| 2 | +import { StyleSheet, Animated, Easing, Pressable } from 'react-native' |
| 3 | +import { Check } from './icons/Check' |
| 4 | +import { GRAY, PRIMARY, WHITE, DARK } from '../../constants' |
| 5 | + |
| 6 | +export interface CheckBoxProps { |
| 7 | + value: boolean |
| 8 | + isPrimary: boolean |
| 9 | + onToggle: (value: boolean) => void |
| 10 | +} |
| 11 | + |
| 12 | +const animationToggle = (value: boolean) => new Animated.Value(value ? 1 : 0) |
| 13 | + |
| 14 | +export const CheckBox: FC<CheckBoxProps> = (props: CheckBoxProps) => { |
| 15 | + const { value, onToggle, isPrimary } = props |
| 16 | + const [timer] = useState<Animated.Value>(animationToggle(value)) |
| 17 | + const [previousValue, setPreviousValue] = useState<boolean>(value) |
| 18 | + const onToggleHandler = React.useMemo(() => () => onToggle && onToggle(!value), [onToggle, value]) |
| 19 | + const activeColor = isPrimary ? PRIMARY : WHITE |
| 20 | + |
| 21 | + const startAnimation = useMemo( |
| 22 | + () => (value: boolean) => { |
| 23 | + Animated.timing(timer, { |
| 24 | + toValue: value ? 1 : 0, |
| 25 | + duration: 250, |
| 26 | + easing: Easing.out(Easing.circle), |
| 27 | + useNativeDriver: false |
| 28 | + }).start() |
| 29 | + }, |
| 30 | + [timer] |
| 31 | + ) |
| 32 | + |
| 33 | + useEffect(() => { |
| 34 | + if (value !== previousValue) { |
| 35 | + startAnimation(value) |
| 36 | + setPreviousValue(value) |
| 37 | + } |
| 38 | + }, [value, previousValue, startAnimation, setPreviousValue]) |
| 39 | + |
| 40 | + const animatedBgStyle = timer.interpolate({ |
| 41 | + inputRange: [0, 1], |
| 42 | + outputRange: ['transparent', activeColor] |
| 43 | + }) |
| 44 | + const animatedBorderColorStyle = timer.interpolate({ |
| 45 | + inputRange: [0, 1], |
| 46 | + outputRange: [GRAY, 'transparent'] |
| 47 | + }) |
| 48 | + const borderWidth = value ? 0 : 1 |
| 49 | + const iconColor = !value ? 'transparent' : activeColor === PRIMARY ? WHITE : DARK |
| 50 | + |
| 51 | + return ( |
| 52 | + <Pressable onPress={onToggleHandler}> |
| 53 | + <Animated.View |
| 54 | + style={[ |
| 55 | + styles.container, |
| 56 | + { |
| 57 | + backgroundColor: animatedBgStyle, |
| 58 | + borderColor: animatedBorderColorStyle, |
| 59 | + borderWidth |
| 60 | + } |
| 61 | + ]} |
| 62 | + > |
| 63 | + <Check color={iconColor} /> |
| 64 | + </Animated.View> |
| 65 | + </Pressable> |
| 66 | + ) |
| 67 | +} |
| 68 | + |
| 69 | +const styles = StyleSheet.create({ |
| 70 | + container: { |
| 71 | + width: 20, |
| 72 | + height: 20, |
| 73 | + borderRadius: 4, |
| 74 | + alignItems: 'center', |
| 75 | + justifyContent: 'center' |
| 76 | + } |
| 77 | +}) |
0 commit comments