All files / atoms/RadioGroup/mobile RadioGroup.native.tsx

97.36% Statements 37/38
95.77% Branches 68/71
100% Functions 10/10
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                1x                           16x 16x 14x   16x 2x 2x 2x 2x   16x 16x               46x 46x   46x 3x             43x                   46x       9x         3x         34x               15x   1x   1x           1x   1x   11x       16x                 16x             16x                 46x   46x       46x       46x     9x   3x         46x     2x                                                                                            
import { TouchableOpacity, View, ViewStyle } from 'react-native';
import React, { useEffect, useState } from 'react';
import { RadioGroupNativeProps } from '../RadioGroup.types';
import { Label } from '../../Label/mobile/Label.native';
import { cn } from '@sb/libs';
import { useTheme } from '@sb/ui/components/Themes/ThemeProvider';
import { colors } from '@sb/styles/colors';
 
export const RadioGroup: React.FC<RadioGroupNativeProps> = ({
  id,
  style,
  options,
  selectedOption,
  onChange,
  disabled = false,
  horizontal = false,
  variant = 'default',
  labelStyle = {},
  selectContainerStyle = {},
  className,
  labelClassName,
}) => {
  const [internalSelected, setInternalSelected] = useState(selectedOption);
  useEffect(() => {
    setInternalSelected(selectedOption);
  }, [selectedOption]);
  const handleToggle = (option: string) => {
    Iif (disabled) return;
    const newValue = internalSelected === option ? '' : option;
    setInternalSelected(newValue);
    onChange?.(newValue);
  };
  const theme = useTheme();
  const themeColors = colors[theme.theme];
 
  function getItemBorderRadius(
    index: number,
    total: number,
    borderRadius: number,
    horizontal: boolean
  ): ViewStyle {
    const isFirst = index === 0;
    const isLast = index === total - 1;
 
    if (horizontal) {
      return {
        borderTopLeftRadius: isFirst ? borderRadius : 0,
        borderBottomLeftRadius: isFirst ? borderRadius : 0,
        borderTopRightRadius: isLast ? borderRadius : 0,
        borderBottomRightRadius: isLast ? borderRadius : 0,
      };
    } else {
      return {
        borderTopLeftRadius: isFirst ? borderRadius : 0,
        borderTopRightRadius: isFirst ? borderRadius : 0,
        borderBottomLeftRadius: isLast ? borderRadius : 0,
        borderBottomRightRadius: isLast ? borderRadius : 0,
      };
    }
  }
 
  function getContainerStyles(variant: RadioGroupNativeProps['variant'], isActive: boolean) {
    switch (variant) {
      case 'secondary':
      case 'outline':
      case 'ghost':
        return {
          borderWidth: 1,
          borderColor: themeColors.colorLoader_Text,
        };
      case 'primary':
        return {
          borderWidth: 1,
          borderColor: isActive ? themeColors.colorAccent : themeColors.colorLoader_Text,
        };
      default:
        return {
          borderWidth: 1,
          borderColor: themeColors.colorLoader_Text,
        };
    }
  }
 
  function getSelectedStyles(variant: RadioGroupNativeProps['variant']) {
    switch (variant) {
      case 'outline':
        return { backgroundColor: 'transparent' };
      case 'ghost':
        return {
          backgroundColor: themeColors.colorLoader_Text,
          borderWidth: 1,
          borderColor: themeColors.colorLoader_Text,
        };
      case 'primary':
        return { backgroundColor: themeColors.colorAccent };
      case 'secondary':
        return { backgroundColor: themeColors.colorElement_Nuance_Color };
      default:
        return { backgroundColor: themeColors.colorAccent };
    }
  }
 
  const containerClasses = cn(
    'flex',
    'relative',
    'overflow-hidden',
    'rounded',
    horizontal ? 'flex-row' : 'flex-col',
    className
  );
 
  const labelBaseClasses = cn(
    'flex items-center justify-center',
    'p-3 text-center',
    'w-[115px]',
    disabled ? 'opacity-50 cursor-not-allowed' : ''
  );
 
  return (
    <View
      testID={id}
      id={id}
      accessibilityLabel={'radio group'}
      className={containerClasses}
      style={[style as ViewStyle, disabled ? { opacity: 0.8 } : {}]}
    >
      {options.map((option, index) => {
        const isSelected = internalSelected === option;
 
        const dividerClasses = horizontal
          ? 'border-l border-loader-text first:border-none'
          : 'border-t border-loader-text first:border-none';
 
        const itemLabelClasses = cn(labelBaseClasses, dividerClasses);
 
        // Default fallback to 0 if not passed
        const containerRadius =
          (Array.isArray(style)
            ? style
                .filter(
                  (sl): sl is ViewStyle => !!sl && typeof sl === 'object' && 'borderRadius' in sl
                )
                .find((sl) => sl.borderRadius !== undefined)?.borderRadius
            : typeof style === 'object' && style !== null && 'borderRadius' in style
              ? (style as ViewStyle).borderRadius
              : 0) ?? 0;
 
        return (
          <TouchableOpacity
            key={option}
            onPress={() => handleToggle(option)}
            testID={`${id}-${option}`}
            activeOpacity={0.8}
            accessibilityRole="radio"
            accessibilityState={{ selected: isSelected, disabled }}
            accessibilityLabel={`radio option ${option}`}
            disabled={disabled}
            className={cn(itemLabelClasses)}
            style={[
              {
                flex: horizontal ? 1 : undefined,
                width: '100%',
                alignItems: 'center',
                justifyContent: 'center',
              },
              selectContainerStyle &&
                getItemBorderRadius(index, options.length, Number(containerRadius), horizontal),
              selectContainerStyle,
              getContainerStyles(variant, isSelected),
              isSelected && getSelectedStyles(variant),
            ]}
          >
            <Label
              testID={`${id}-label-${option}`}
              size="small"
              variant={variant !== 'ghost' ? 'primary' : 'secondary'}
              accessibilityLabel={`radio option ${option}`}
              className={labelClassName}
              style={[
                labelStyle,
                isSelected
                  ? variant === 'outline'
                    ? { color: themeColors.colorAccent }
                    : { color: themeColors.colorSecondary }
                  : null,
                {},
              ]}
            >
              {option}
            </Label>
          </TouchableOpacity>
        );
      })}
    </View>
  );
};