import React, { forwardRef } from 'react'; import { StyleSheet, Animated, TouchableOpacity } from 'react-native'; import useTheme from '../../context/theme/useTheme'; import { HelperText } from '../../utils/HelperText'; import type { SwitchProps } from './types'; import { Box } from '../Box'; import createSxStyle from '../../lib/sx'; export const Switch: React.FC = forwardRef( ( { value, defaultValue, onChange, textError, bordered, styles, isDisabled, type = 'circle', borderColor = 'primary', activeColor = 'input', deactiveColor = 'input', thumbActiveColor = 'primary', thumbDisabledColor = 'border', error = false, size = 'middle', style = {}, icon, sx, ...restSxProps }, ref ) => { const theme = useTheme(); const { activeOpacity, borderWidth } = useTheme(); const [isEnabled, setIsEnabled] = React.useState( defaultValue ?? false ); const onToggleSwitch = () => { if (typeof value === 'boolean') { console.log(onChange); if (onChange) { setIsEnabled(!value); return onChange && onChange(!value); } } else { setIsEnabled(!isEnabled); } }; React.useEffect(() => { if (typeof value === 'boolean') { setIsEnabled(value); } }, [value, onChange]); const { height, width } = sizesStyle[size]; const calcSizeToggle: number = height * (type !== 'square' ? 0.75 : 0.7); const calcSizeIcon: number = height * 0.4; return ( {icon && isEnabled && React.cloneElement(icon.true as any, { size: calcSizeIcon, color: icon.true?.props?.color || 'text' })} {icon && !isEnabled && React.cloneElement(icon.false as any, { size: calcSizeIcon, color: icon.false?.props?.color || 'text' })} {(error || textError) && ( {textError} )} ); } ); const sizesStyle = StyleSheet.create({ small: { width: 32, height: 18 }, middle: { width: 40, height: 22 }, large: { width: 54, height: 30 } });