All files / molecules/LimitDeposit/mobile LimitDeposit.native.tsx

89.15% Statements 74/83
72.52% Branches 66/91
92.3% Functions 12/13
90% Lines 72/80

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                                        1x 1x 1x 1x 1x   103x                       1x 92x   92x 92x 92x   92x 92x 92x 92x   92x   92x 54x 22x       92x 27x 3x       92x 55x                 92x 11x     92x 6x                         92x   15x         15x 1x 1x 1x 1x     14x 14x         14x   5x     5x 9x   1x     1x   8x     14x 14x                       92x   21x 21x 21x           92x 3x 3x 3x     3x 2x     3x 3x       92x 2x   2x 2x   2x     2x   2x 2x     92x         92x           92x 92x   92x                                                                                                                                                                                                         1x      
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Text, TextInput, View } from 'react-native';
import { LimitDepositNativeProps } from '../LimitDeposit.types';
import { Input } from '@sb/ui/components/atoms/Input/index.native';
import { RadioInput } from '@sb/ui/components/atoms/RadioInput/index.native';
import { Button } from '@sb/ui/components/atoms/Button/index.native';
import { cn } from '@sb/libs';
 
type TooltipProps = {
  status: 'default' | 'error';
  tooltip: string | undefined;
  tooltipOptions: {
    position: 'bottom';
    status: 'default' | 'error';
    pointerDirection: 'right';
    trigger: 'always';
    className: string;
  };
};
 
const CANCEL_BUTTON_LABEL = 'ABBRECHEN';
const SAVE_BUTTON_LABEL = 'LIMIT SPEICHERN';
const DEFAULT_TOOLTIP_CLASSNAME = 'whitespace-nowrap text-[12px] font-normal w-[200%]';
const DEFAULT_MIN_VALUE = 0;
const DEFAULT_MAX_VALUE = 1000;
 
const createDefaultTooltipProps = (): TooltipProps => ({
  status: 'default',
  tooltip: '',
  tooltipOptions: {
    position: 'bottom',
    status: 'default',
    pointerDirection: 'right',
    trigger: 'always',
    className: DEFAULT_TOOLTIP_CLASSNAME,
  },
});
 
const LimitDeposit: React.FC<LimitDepositNativeProps> = (props) => {
  Iif (!props.id) return null
 
  const minValue = props.minValue || DEFAULT_MIN_VALUE;
  const maxValue = props.maxValue || DEFAULT_MAX_VALUE;
  const inputRef = useRef<TextInput>(null);
 
  const [isActive, setIsActive] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [displaySaveFeedback, setDisplaySaveFeedback] = useState(false);
  const [tooltipProps, setTooltipProps] = useState<TooltipProps>(createDefaultTooltipProps());
 
  const isControlled = props.radioInputProps?.checked !== undefined;
 
  useEffect(() => {
    if (isActive) {
      setDisplaySaveFeedback(false);
    }
  }, [isActive]);
 
  useEffect(() => {
    if (props.radioInputProps?.checked !== undefined) {
      setIsActive(props.radioInputProps.checked);
    }
  }, [props.radioInputProps?.checked]);
 
  React.useEffect(() => {
    Iif (props.initialValue !== undefined && props.initialValue !== null) {
      const active = isControlled ? !!props.radioInputProps?.checked : isActive;
      if (!active) {
        setInputValue(String(props.initialValue));
        resetTooltipProps();
      }
    }
  }, [props.initialValue, isActive, props.radioInputProps?.checked, isControlled]);
 
  const resetTooltipProps = useCallback(() => {
    setTooltipProps(createDefaultTooltipProps());
  }, []);
 
  const setErrorTooltip = useCallback((message: string) => {
    setTooltipProps({
      status: 'error',
      tooltip: message,
      tooltipOptions: {
        position: 'bottom',
        status: 'error',
        pointerDirection: 'right',
        trigger: 'always',
        className: DEFAULT_TOOLTIP_CLASSNAME,
      },
    });
  }, []);
 
  const handleInputChange = useCallback(
    (text: string) => {
      const normalizedText = text
        .replace(',', '.')
        .replace(/[^0-9.]/g, '')
        .replace(/(\..*)\./g, '$1');
 
      if (normalizedText === '') {
        setInputValue(normalizedText);
        resetTooltipProps();
        props.onInputValueChange?.(0);
        return;
      }
 
      const numericValue = Number(normalizedText);
      Iif (isNaN(numericValue)) {
        setInputValue(normalizedText);
        return;
      }
 
      if (numericValue >= maxValue) {
        const errorMessage =
          typeof props.tooltipErrorMessage === 'string'
            ? props.tooltipErrorMessage
            : props.tooltipErrorMessage?.max || `Value cannot exceed ${maxValue}`;
        setErrorTooltip(errorMessage);
      } else if (numericValue <= minValue && normalizedText !== '') {
        const errorMessage =
          typeof props.tooltipErrorMessage === 'string'
            ? props.tooltipErrorMessage
            : props.tooltipErrorMessage?.min || `Value cannot be less than ${minValue}`;
        setErrorTooltip(errorMessage);
      } else {
        resetTooltipProps();
      }
 
      setInputValue(normalizedText);
      props.onInputValueChange?.(numericValue);
    },
    [
      minValue,
      maxValue,
      props.onInputValueChange,
      props.tooltipErrorMessage,
      resetTooltipProps,
      setErrorTooltip,
    ]
  );
 
  const handleRadioClick = useCallback(
    (value: string | number) => {
      props.onRadioClick?.(String(value));
      Eif (!isControlled) {
        setIsActive((prev) => !prev);
      }
    },
    [props.onRadioClick, isControlled]
  );
 
  const handleLimitSave = useCallback(() => {
    const numericValue = Number(inputValue);
    Eif (!isNaN(numericValue)) {
      props.onLimitSave?.(numericValue);
    }
 
    if (props.onSaveFeedback) {
      setDisplaySaveFeedback(true);
    }
 
    Eif (!isControlled) {
      setIsActive(false);
    }
  }, [inputValue, props.onLimitSave, props.onSaveFeedback, isControlled]);
 
  const handleCancel = useCallback(() => {
    props.onCancel?.();
 
    Eif (!isControlled) {
      setIsActive(false);
    }
    Iif (props.initialValue !== undefined && props.initialValue !== null) {
      setInputValue(String(props.initialValue));
    } else {
      setInputValue('');
    }
    setDisplaySaveFeedback(false);
    resetTooltipProps();
  }, [props.onCancel, isControlled, resetTooltipProps]);
 
  const handleInputFocus = useCallback(() => {
    props.onInputFocus?.();
  }, [props.onInputFocus]);
 
  const isSaveDisabled =
    tooltipProps.status === 'error' ||
    inputValue === '' ||
    isNaN(Number(inputValue)) ||
    Number(inputValue) < minValue ||
    Number(inputValue) > maxValue;
 
  const shouldShowDescription = props.description && isActive;
  const shouldShowButtons = props.showButtons || isActive;
 
  return (
    <View
      className={cn('limit-deposit w-full bg-transparent', props.className)}
      testID="test-limit-deposit-container"
    >
      <View
        className={cn('flex w-full flex-row justify-between gap-2', {
          'pb-2': displaySaveFeedback,
          'pb-8': tooltipProps.status === 'error' && !displaySaveFeedback,
        })}
      >
        <View
          className="flex items-baseline justify-center"
          testID="test-radio-input-limit-deposit"
        >
          <View className="flex flex-row items-center justify-center gap-3">
            <RadioInput
              id={`${props.id}-radio`}
              value={props.radioInputProps?.value || ''}
              label={''}
              variant={props.radioInputProps?.variant || 'primary'}
              classNames={props.radioInputProps?.className}
              labelPosition={props.radioInputProps?.labelPosition || 'left'}
              checked={isControlled ? props.radioInputProps?.checked : isActive}
              onChange={handleRadioClick}
            />
            <Text className="text-text-main text-[16px] font-normal">
              {props.radioInputProps?.label || ''}
            </Text>
          </View>
        </View>
 
        <View className="flex justify-end basis-1/2" testID="test-input-limit-deposit">
          <Input
            ref={inputRef}
            id={`${props.id}-input`}
            name={`${props.id}-input`}
            mode="currency"
            currency={inputValue === '' ? undefined : props.currency || '€'}
            direction="rtl"
            value={inputValue || ''}
            onChangeText={handleInputChange}
            onFocus={handleInputFocus}
            disabled={!(props.radioInputProps?.checked ?? isActive)}
            className="w-full"
            status={tooltipProps.status}
            keyboardType="decimal-pad"
            accessibilityLabel="Input for deposit limit amount"
            {...(tooltipProps.tooltip && tooltipProps.tooltip.trim() !== ''
              ? {
                  tooltip: tooltipProps.tooltip,
                  tooltipOptions: tooltipProps.tooltipOptions,
                }
              : {})}
          />
        </View>
      </View>
 
      {displaySaveFeedback && (
        <View className="flex flex-col gap-1 pb-2">
          <Text className="text-sm text-text-main">{props.onSaveFeedback}</Text>
        </View>
      )}
 
      {shouldShowButtons && (
        <View className="flex flex-col gap-1 pt-2">
          {shouldShowDescription && (
            <View
              className={cn('', { 'pb-2': !props.showButtons })}
              testID="test-description-limit-deposit"
            >
              {typeof props.description === 'string' ? (
                <Text className="text-text-main">{props.description}</Text>
              ) : (
                props.description
              )}
            </View>
          )}
 
          <View className="flex flex-row gap-4 px-1 py-2 justify-evenly">
            <Button
              className="w-1/2 rounded-[4px] px-2 py-4"
              variant="ghost"
              onPress={handleCancel}
              label={CANCEL_BUTTON_LABEL}
              accessibilityLabel={CANCEL_BUTTON_LABEL}
            />
            <Button
              className="w-1/2 rounded-[4px] px-2 py-4"
              onPress={handleLimitSave}
              label={SAVE_BUTTON_LABEL}
              disabled={isSaveDisabled}
              accessibilityLabel={SAVE_BUTTON_LABEL}
            />
          </View>
        </View>
      )}
    </View>
  );
};
 
LimitDeposit.displayName = 'LimitDeposit';
 
export default LimitDeposit;