All files / atoms/Input/mobile/Components/Hook useInputText.ts

27.18% Statements 28/103
14.15% Branches 15/106
60% Functions 6/10
27.55% Lines 27/98

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                                                              2x                       23x 23x     23x 23x 23x 23x   23x     23x         23x 18x                                       23x 18x                   18x             18x 18x           23x 18x 18x       23x       23x                                                                                                                                 23x 3x                                           3x     3x     23x               23x                            
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { TextInput } from 'react-native';
import { InputMode, InputType } from '../../../Input.types';
 
interface UseInputTextProps {
  value?: string;
  defaultValue?: string;
  onChangeText?: (text: string) => void;
  onInvalid?: () => void;
  disabled?: boolean;
  type?: InputType;
  min?: string | number;
  max?: string | number;
  mode?: InputMode;
  required?: boolean;
}
 
interface UseInputTextReturn {
  text: string;
  isFocused: boolean;
  inputRef: React.RefObject<TextInput>;
  handleChange: (val: string) => void;
  handleFocus: () => void;
  handleBlur: () => void;
  handleContainerPress: () => void;
  setText: (text: string) => void;
  isEmpty: boolean;
  isValidNumber: boolean;
  isValidationPending: boolean;
}
 
export const useInputText = ({
  value,
  defaultValue,
  onChangeText,
  onInvalid,
  disabled = false,
  type,
  min,
  max,
  mode,
  required = false,
}: UseInputTextProps): UseInputTextReturn => {
  const isControlled = value !== undefined;
  const [text, setText] = useState(
    isControlled ? value?.toString() || '' : defaultValue?.toString() || ''
  );
  const [isFocused, setIsFocused] = useState(false);
  const [isValidationPending, setIsValidationPending] = useState(false);
  const inputRef = useRef<TextInput>(null);
  const validationTimeoutRef = useRef<NodeJS.Timeout | null>(null);
 
  const isEmpty = text.length === 0;
 
  // Debounced validation function
  const debouncedValidation = useCallback(() => {
    setIsValidationPending(false);
  }, []);
 
  // Validate number input against min/max constraints (only when not pending)
  const isValidNumber = useMemo(() => {
    Eif (type !== 'number' || isEmpty || isValidationPending) return true;
 
    // Replace comma with dot for parsing
    const normalizedText = text.replace(',', '.');
    const numValue = parseFloat(normalizedText);
    if (isNaN(numValue)) return false;
 
    if (min !== undefined) {
      const minValue = typeof min === 'string' ? parseFloat(min) : min;
      if (numValue < minValue) return false;
    }
 
    if (max !== undefined) {
      const maxValue = typeof max === 'string' ? parseFloat(max) : max;
      if (numValue > maxValue) return false;
    }
 
    return true;
  }, [text, type, min, max, isEmpty, isValidationPending]);
 
  useEffect(() => {
    Iif (type === 'number' && !isEmpty && text.trim() !== '') {
      if (validationTimeoutRef.current) {
        clearTimeout(validationTimeoutRef.current);
      }
 
      if (!isValidationPending) {
        setIsValidationPending(true);
      }
 
      validationTimeoutRef.current = setTimeout(debouncedValidation, 500);
    } else Iif (type === 'number' && isEmpty) {
      setIsValidationPending(false);
      if (validationTimeoutRef.current) {
        clearTimeout(validationTimeoutRef.current);
      }
    }
 
    return () => {
      Iif (validationTimeoutRef.current) {
        clearTimeout(validationTimeoutRef.current);
      }
    };
  }, [text, type, isEmpty, debouncedValidation, isValidationPending]);
 
  useEffect(() => {
    Eif (isControlled) {
      setText(value?.toString() || '');
    }
  }, [value, isControlled]);
 
  const handleFocus = () => {
    setIsFocused(true);
  };
 
  const handleBlur = () => {
    setIsFocused(false);
 
    // Validate required fields
    if (required && isEmpty) {
      onInvalid?.();
      return;
    }
 
    // Validate email format
    if (type === 'email' && !isEmpty) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(text)) {
        onInvalid?.();
        return;
      }
    }
 
    // Format currency values with ,00 on blur
    if (type === 'number' && mode === 'currency' && !isEmpty) {
      // Replace comma with dot for parsing
      const normalizedText = text.replace(',', '.');
      const numValue = parseFloat(normalizedText);
 
      if (!isNaN(numValue)) {
        // Format as currency with comma and 2 decimal places
        const formattedValue = numValue.toFixed(2).replace('.', ',');
 
        // Adjust value to max if it exceeds the maximum
        if (max !== undefined) {
          const maxValue = typeof max === 'string' ? parseFloat(max) : max;
          if (numValue > maxValue) {
            const adjustedValue = maxValue.toFixed(2).replace('.', ',');
            if (!isControlled) {
              setText(adjustedValue);
            }
            onChangeText?.(adjustedValue);
            return;
          }
        }
 
        if (!isControlled) {
          setText(formattedValue);
        }
        onChangeText?.(formattedValue);
        return;
      }
    }
 
    // Adjust value to max if it exceeds the maximum (for non-currency numbers)
    if (type === 'number' && max !== undefined && !isEmpty) {
      const normalizedText = text.replace(',', '.');
      const numValue = parseFloat(normalizedText);
      const maxValue = typeof max === 'string' ? parseFloat(max) : max;
 
      if (!isNaN(numValue) && numValue > maxValue) {
        const adjustedValue = maxValue.toString();
        if (!isControlled) {
          setText(adjustedValue);
        }
        onChangeText?.(adjustedValue);
      }
    }
  };
 
  const handleChange = (val: string) => {
    Iif (type === 'number') {
      // Allow empty string to clear the input
      if (val === '') {
        if (!isControlled) setText(val);
        onChangeText?.(val);
        return;
      }
      let regex: RegExp;
      if (mode === 'currency') {
        // Currency mode: require at least one digit before comma, up to 2 decimals
        regex = /^-?\d+(,\d{0,2})?$/;
      } else if (mode === 'decimal') {
        // Decimal mode: require at least one digit before comma, any decimals
        regex = /^-?\d+(,\d*)?$/;
      } else {
        // Default number mode: allow integers only
        regex = /^-?\d*$/;
      }
      if (!regex.test(val)) {
        return;
      }
    }
    Iif (!isControlled) {
      setText(val);
    }
    onChangeText?.(val);
  };
 
  const handleContainerPress = () => {
    // Focus the TextInput when container is pressed
    if (inputRef.current && !disabled) {
      inputRef.current.focus();
      setIsFocused(true);
    }
  };
 
  return {
    text,
    isFocused,
    inputRef,
    handleChange,
    handleFocus,
    handleBlur,
    handleContainerPress,
    setText,
    isEmpty,
    isValidNumber,
    isValidationPending,
  };
};