import React, { useEffect, useRef } from 'react'; import { Animated, Pressable } from 'react-native'; import ReactNativeHapticFeedback from 'react-native-haptic-feedback'; import { Color, SemanticColor } from '../../foundation'; import { ShadowedView, shadowStyle } from 'react-native-fast-shadow'; type ToggleProps = { /** * 토글의 UI 표현을 결정하는 값 (true: 켜짐, false: 꺼짐) */ value: boolean; /** * press 이벤트 핸들러를 전달받을 수 있습니다. * @param value value prop 값의 반대값을 전달받을 수 있습니다. 하지만 value 값은 Toggle 컴포넌트를 사용하는 컴포넌트가 결정하므로 이 인자가 필요하지 않을 수 있습니다. */ onPress: (value: boolean) => void; /** * 비활성 상태로 설정합니다. (기본값: false) * 비활성 상태일때는 onPress 이벤트 핸들러가 호출되지 않습니다. */ disabled?: boolean; }; /** * Toggle 컴포넌트 * * - Stateless 컴포넌트 - value prop 값에 의해 UI 표현이 변경됩니다. */ export function Toggle(props: ToggleProps): React.JSX.Element { const { value, onPress, disabled = false } = props; // Animated.Value 값 1 -> 켜짐, 0 -> 꺼짐 const toggleAnimation = useRef(new Animated.Value(value ? 1 : 0)).current; const backgroundColorAnimation = toggleAnimation.interpolate({ inputRange: [0, 1], outputRange: [SemanticColor.bg_tertiary, SemanticColor.bg_purple_enabled], }); const animatedStyles = { transform: [ { translateX: toggleAnimation.interpolate({ inputRange: [0, 1], outputRange: [0, 20], // 바깥쪽 View의 너비(48px)에서 안쪽 View의 너비(24px)를 뺀 값 }), }, ], }; const toggleBgColor = (() => { if (disabled) { return SemanticColor.bg_senary; } return backgroundColorAnimation; })(); // value prop 값이 변경될 때 애니메이션을 실행합니다. const prevValue = useRef(value); useEffect(() => { if (value === prevValue.current) return; prevValue.current = value; Animated.timing(toggleAnimation, { toValue: value ? 1 : 0, duration: 300, useNativeDriver: false, }).start(); }, [toggleAnimation, value]); const handlePress = () => { // 토글 상태의 반대값을 부모 컴포넌트에게 전달합니다. onPress(!value); // 토글 터치 피드백 // - value 값의 변경에 관계없이 반응합니다. // - value 값은 부모로부터의 변경이 늦을 수 있으므로, 햅틱 피드백으로 즉각적인 반응성을 유저에게 제공합니다. ReactNativeHapticFeedback.trigger('impactLight', { enableVibrateFallback: false, ignoreAndroidSystemSettings: false, }); }; // 피그마 시안은 그림자를 3개 사용함. 복잡하게 구현하고싶지 않고, 그림자가 은근 리소스를 먹어서 그림자 1개로 비슷하게 보이게 눈으로 맞춤 const shadowedViewStyle = shadowStyle({ color: Color.blueGray900, opacity: 0.15, radius: 3, offset: [0, 3], }); return ( ); }