import React from 'react'; import { StyleSheet, TouchableHighlight, ImageBackground, View, StyleProp, ViewStyle, } from 'react-native'; import type { Theme } from '../../types'; import { withTheme } from '../../core/theming'; import { buildBorderStyles } from '../../styles/styles'; import { Border } from '../../styles/styleElements'; import { Text, CheckmarkIcon } from '../..'; const checkboxSize = 20; const radioSize = 20; export type SwitchStatus = 'checked' | 'unchecked' | 'indeterminate'; export type SwitchProps = { disabled?: boolean; label?: string; onPress?: () => void; status: SwitchStatus; style?: StyleProp; variant?: 'default' | 'flat'; theme: Theme; }; type Props = SwitchProps & React.ComponentPropsWithRef & { component: 'radio' | 'checkbox'; }; // TODO: see if ref is passed const SwitchBase = ({ component, disabled = false, label = '', variant = 'default', onPress = () => {}, status, style = {}, theme, ...rest }: Props) => { const [isPressed, setIsPressed] = React.useState(false); const isRadio = component === 'radio'; const switchSize = !isRadio ? checkboxSize : radioSize; const boxSize = variant === 'flat' ? switchSize - 4 : switchSize; const borderRadius = isRadio ? boxSize / 2 : 0; const checked = status === 'checked'; const borders = buildBorderStyles(theme); const renderCheckmark = () => { if (checked) { return isRadio ? ( ) : ( ); } if (status === 'indeterminate') { return ( ); } return ; }; const getBackgroundColor = () => { if (variant === 'flat') { return disabled ? theme.flatLight : theme.canvas; } return disabled ? theme.material : theme.canvas; }; /*const getAccessibilityComponentType = () => { if (isRadio) { return checked ? 'radiobutton_checked' : 'radiobutton_unchecked'; } return 'button'; };*/ return ( setIsPressed(false)} onShowUnderlay={() => setIsPressed(true)} // TODO: check if those accessibility properties are correct accessibilityRole={component} accessibilityState={{ disabled, checked }} accessibilityLiveRegion='polite' underlayColor='none' {...rest} > {renderCheckmark()} {Boolean(label) && ( {label} )} ); }; const styles = StyleSheet.create({ wrapper: { width: 'auto', alignSelf: 'flex-start', padding: 4, }, content: { flexDirection: 'row', alignItems: 'center', width: 'auto', }, switchSymbol: { marginRight: 4, alignItems: 'center', justifyContent: 'center', }, labelWrapper: { paddingHorizontal: 4, flexShrink: 1, }, label: { fontSize: 16, }, }); const SwitchBaseWithTheme = withTheme(SwitchBase); export { SwitchBaseWithTheme as SwitchBase };