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

92.95% Statements 66/71
83.52% Branches 71/85
100% Functions 8/8
94.2% Lines 65/69

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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310                                                  13x           13x           13x   13x 3x   3x 3x               3x 3x     3x         3x 3x 3x 3x   3x                                                             8x       8x 8x 8x       8x             13x                                           381x 381x   381x   381x   381x   78x         78x     78x 78x   35x       35x 35x 35x   3x           3x 3x 3x   2x           2x 2x 2x   261x       261x 261x 261x   2x       2x 2x 2x                 381x 381x     381x     381x                   381x 1x 1x                 381x 1x 1x                 381x 8x 8x     381x                                                                                                                   13x  
import React, { forwardRef, useEffect, useRef } from 'react';
import {
  AccessibilityState,
  Animated,
  Easing,
  StyleProp,
  Text,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import Svg, { Circle } from 'react-native-svg';
import type { ButtonNativeProps, ButtonSize } from '../Button.types';
import { colors } from '@sb/styles/colors';
import { useTheme } from '@sb/ui/components/Themes/ThemeProvider';
import { cn } from '@sb/libs';
 
type ButtonNativePropsWithIconColor = ButtonNativeProps & {
  iconColor?: string;
  accessibilityRole?: string;
  accessibilityState?: AccessibilityState;
};
 
 
 
const SIZE_CLASSES: Record<ButtonSize, string> = {
  small: 'py-1.5 px-2',
  medium: 'py-2 px-3',
  large: 'py-3 px-4',
};
 
const ICON_SIZES: Record<ButtonSize, number> = {
  small: 16,
  medium: 20,
  large: 24,
};
 
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
 
const LoadingSpinner = ({ size, color }: { size: number; color: string }) => {
  const rotation = useRef(new Animated.Value(0)).current;
 
  useEffect(() => {
    const animation = Animated.loop(
      Animated.timing(rotation, {
        toValue: 1,
        duration: 1000,
        easing: Easing.linear,
        useNativeDriver: true,
      })
    );
    animation.start();
    return () => animation.stop();
  }, [rotation]);
 
  const rotate = rotation.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });
 
  const radius = size / 2;
  const strokeWidth = 2;
  const circumference = 2 * Math.PI * (radius - strokeWidth / 2);
  const strokeDashoffset = circumference * 0.25; // 3/4 of the circle
 
  return (
    <Animated.View
      style={{
        width: size,
        height: size,
        transform: [{ rotate }],
      }}
    >
      <Svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <AnimatedCircle
          cx={radius}
          cy={radius}
          r={radius - strokeWidth / 2}
          fill="transparent"
          stroke={color}
          strokeWidth={strokeWidth}
          strokeDasharray={`${circumference} ${circumference}`}
          strokeDashoffset={strokeDashoffset}
          strokeLinecap="round"
        />
      </Svg>
    </Animated.View>
  );
};
 
function renderIconElement(
  iconNode: React.ReactElement,
  size: ButtonSize,
  iconColor?: string,
  decorative: boolean = true
): React.ReactElement | null {
  Iif (!React.isValidElement(iconNode)) {
    return null;
  }
 
  const iconSize = ICON_SIZES[size];
  const existingStyle = (iconNode.props as { style?: object }).style || {};
  const styleWithColor = iconColor
    ? { width: iconSize, height: iconSize, color: iconColor, ...existingStyle }
    : { width: iconSize, height: iconSize, ...existingStyle };
 
  return React.cloneElement(iconNode as React.ReactElement<{ style?: object; color?: string }>, {
    style: styleWithColor,
    color: iconColor,
    ...(decorative ? { accessibilityRole: 'image', accessibilityLabel: undefined } : {}),
  });
}
 
export const Button = forwardRef<TouchableOpacity, ButtonNativePropsWithIconColor>(
  (
    {
      label,
      icon,
      onPress,
      disabled = false,
      variant = 'primary',
      size = 'medium',
      loading = false,
      rounded = true,
      className = '',
      style,
      textStyle,
      accessibilityLabel,
      iconColor,
      accessibilityHint,
      accessibilityRole = 'button',
      ...rest
    },
    ref
  ) => {
    const { theme } = useTheme();
    const themeColors = colors[theme];
 
    let containerStyle: StyleProp<ViewStyle> = {};
    let textColor: string | undefined;
    let textFontClassName = '';
 
    switch (variant) {
      case 'primary':
        containerStyle = {
          backgroundColor: (disabled || loading)
            ? themeColors.colorButton_Main_Disabled_Background_Color
            : themeColors.colorButton_Main_Background_Color,
        };
        textColor = (disabled || loading)
          ? themeColors.colorButton_Main_Disabled_TextColor
          : themeColors.colorButton_Main_TextColor;
        textFontClassName = 'font-Bold';
        break;
      case 'secondary':
        containerStyle = {
          backgroundColor: themeColors.colorButton_Secondary_Background_Color,
          ...(disabled || loading ? { opacity: 0.5 } : {}),
        };
        textColor = themeColors.colorButton_Secondary_Text_Color;
        textFontClassName = 'font-Bold';
        break;
      case 'ghost':
        containerStyle = {
          backgroundColor: 'transparent',
          borderWidth: 1,
          borderColor: themeColors.colorText_Primary,
          ...(disabled || loading ? { opacity: 0.5 } : {}),
        };
        textColor = themeColors.colorText_Primary;
        textFontClassName = 'font-normal';
        break;
      case 'ghostDark':
        containerStyle = {
          backgroundColor: 'transparent',
          borderWidth: 1,
          borderColor: themeColors.colorPrimary,
          ...(disabled || loading ? { opacity: 0.5 } : {}),
        };
        textColor = themeColors.colorPrimary;
        textFontClassName = 'font-normal';
        break;
      case 'cyan':
        containerStyle = {
          backgroundColor: themeColors.colorPrimary_Background,
          ...(disabled || loading ? { opacity: 0.5 } : {}),
        };
        textColor = themeColors.colorText_Primary;
        textFontClassName = 'font-normal';
        break;
      case 'withShadow':
        containerStyle = {
          backgroundColor: themeColors.colorButton_Main_Background_Color,
          ...(disabled || loading ? { opacity: 0.5 } : {}),
        };
        textColor = themeColors.colorButton_Main_TextColor;
        textFontClassName = 'font-Bold';
        break;
      default:
        containerStyle = {
          backgroundColor: themeColors.colorButton_Main_Background_Color,
        };
        textColor = themeColors.colorButton_Main_TextColor;
        textFontClassName = 'font-Bold';
    }
 
    const paddingClass = SIZE_CLASSES[size];
    const scaleAnim = useRef(new Animated.Value(1)).current;
 
    // Icon color follows text color unless explicitly overridden
  const resolvedIconColor = iconColor ?? textColor;
 
    const shadowStyle: StyleProp<ViewStyle> =
      variant === 'withShadow'
        ? {
            elevation: 5,
            shadowColor: themeColors.buttonTop_ShadowShadow,
            shadowOffset: { width: 0, height: -5 },
            shadowOpacity: 0.3,
            shadowRadius: 5,
          }
        : {};
 
    const handlePressIn = () => {
      Eif (!disabled && !loading) {
        Animated.spring(scaleAnim, {
          toValue: 0.95,
          useNativeDriver: true,
          friction: 5,
          tension: 150,
        }).start();
      }
    };
 
    const handlePressOut = () => {
      Eif (!disabled && !loading) {
        Animated.spring(scaleAnim, {
          toValue: 1,
          useNativeDriver: true,
          friction: 5,
          tension: 150,
        }).start();
      }
    };
 
    const renderIcon = () => {
      Iif (!icon || !React.isValidElement(icon)) return null;
      return renderIconElement(icon, size, resolvedIconColor);
    };
 
    return (
      <TouchableOpacity
        testID={'button-test'}
        ref={ref}
        onPress={onPress}
        onPressIn={handlePressIn}
        onPressOut={handlePressOut}
        disabled={disabled || loading}
        accessibilityLabel={accessibilityLabel || (typeof label === 'string' ? label : undefined)}
        accessibilityRole={accessibilityRole}
        accessibilityState={rest.accessibilityState}
        accessibilityHint={accessibilityHint}
        className={cn(
          'flex-row items-center justify-center',
          paddingClass,
          rounded ? 'rounded-[3px]' : 'rounded-none',
          className
        )}
        style={[shadowStyle, containerStyle, style]}
        {...rest}
      >
        <Animated.View
          style={{
            transform: [{ scale: scaleAnim }],
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          {loading ? (
            <LoadingSpinner
              size={ICON_SIZES[size]}
              color={resolvedIconColor || themeColors.colorText_Tertiary}
            />
          ) : (
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              {icon && <View style={{ marginRight: label ? 8 : 0 }}>{renderIcon()}</View>}
              {label && (
                <Text
                  className={cn(textFontClassName, textStyle, 'text-lg')}
                  style={{ color: textColor }}
                >
                  {label}
                </Text>
              )}
            </View>
          )}
        </Animated.View>
      </TouchableOpacity>
    );
  }
);
 
Button.displayName = 'Button';