UNPKG

@sendbird/uikit-react-native-foundation

Version:

A foundational UI kit for building chat-enabled React Native apps.

102 lines 2.71 kB
import React, { useEffect, useRef } from 'react'; import { Animated, I18nManager, Platform, Pressable } from 'react-native'; import createStyleSheet from '../../styles/createStyleSheet'; import useUIKitTheme from '../../theme/useUIKitTheme'; const Switch = ({ value, onChangeValue, inactiveThumbColor, inactiveTrackColor, trackColor, thumbColor }) => { const { select, palette, colors } = useUIKitTheme(); const position = useRef(new Animated.Value(0)).current; const start = I18nManager.isRTL ? styles.thumbOn.start : styles.thumbOff.start; const end = I18nManager.isRTL ? styles.thumbOff.start : styles.thumbOn.start; useEffect(() => { const animation = Animated.timing(position, { toValue: value ? end : start, duration: 150, useNativeDriver: false }); animation.start(); return () => animation.stop(); }, [value]); const createInterpolate = (offValue, onValue) => { return position.interpolate({ inputRange: [styles.thumbOff.start, styles.thumbOn.start], outputRange: I18nManager.isRTL ? [onValue, offValue] : [offValue, onValue], extrapolate: 'clamp' }); }; const _trackColor = createInterpolate(inactiveTrackColor ?? colors.onBackground04, trackColor ?? palette.primary200); const _thumbColor = createInterpolate(inactiveThumbColor ?? palette.background300, thumbColor ?? select({ light: palette.primary400, dark: palette.primary300 })); return /*#__PURE__*/React.createElement(Pressable, { onPress: () => onChangeValue(!value), style: [styles.container] }, /*#__PURE__*/React.createElement(Animated.View, { style: [styles.track, { backgroundColor: _trackColor }] }), /*#__PURE__*/React.createElement(Animated.View, { style: [styles.thumb, { backgroundColor: _thumbColor, transform: [{ translateX: position }] }] })); }; const OFFSET = { W: 20, H: 16 }; const styles = createStyleSheet({ container: { width: OFFSET.W + OFFSET.H, height: OFFSET.H, alignItems: 'center', justifyContent: 'center' }, track: { width: '100%', height: '100%', borderRadius: OFFSET.H / 2, position: 'absolute' }, thumb: { width: OFFSET.W, height: OFFSET.W, borderRadius: OFFSET.W / 2, ...Platform.select({ android: { elevation: 2 }, ios: { shadowColor: 'black', shadowRadius: 1, shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.4 } }) }, thumbOn: { start: OFFSET.H / 2 }, thumbOff: { start: -OFFSET.H / 2 } }); export default Switch; //# sourceMappingURL=index.js.map