import { View, Text, TouchableOpacity, TextInput, StyleSheet, NativeSyntheticEvent, TextInputKeyPressEventData } from 'react-native' import React, {LegacyRef, MutableRefObject, useEffect, useRef, useState} from 'react' import { SIZES } from '../../constants/theme'; import { useTheme } from '../../app/contexts/ThemeContext'; const formatDecimal = (value: string)=>{ switch(value.length){ case 0: return ""; case 1: return "0.0"+value case 2: return "0."+value default: return value.substring(0, value.length - 2) + "." + value.substring(value.length - 2, value.length) } } interface AutoDecimalInputProps{ onValueChange?: (formattedValue: string) => void | undefined label: string, initialValue? : number } const AutoDecimalInput: React.FC = ({onValueChange, label, initialValue}) => { const { colors } = useTheme(); const inputRef = useRef(null); const [pressedNumbers, setPressedNumbers] = useState(""); const init = () => { if(initialValue){ const pressedNumber = initialValue.toFixed(2).replace(".", "") update(pressedNumber); } } const update = (newValues : string) => { if(onValueChange){ onValueChange(formatDecimal(newValues)) } setPressedNumbers(newValues); } useEffect(() => { init() }, [initialValue]) const handleInput = (e: NativeSyntheticEvent)=>{ const pressedKey:string = e.nativeEvent.key if(Number.isInteger(Number.parseInt(pressedKey))){ if(pressedNumbers.length === 0 && pressedKey === "0"){ return } update(pressedNumbers + pressedKey) }else if(pressedKey === "Backspace"){ update(pressedNumbers.substring(0, pressedNumbers.length - 1)) } } return ( { if(inputRef.current) inputRef.current.focus() }}> {label} EUR ) } const styles = StyleSheet.create({ inputContainer: { minHeight: 50, borderRadius: 20, flexDirection: "row", justifyContent: 'space-between', alignItems: "center" }, text:{ fontSize: SIZES.large, marginHorizontal: 15, }, currency: { fontSize: SIZES.normal, color: "#007acc", marginRight: 15, }, currencyWrapper: { flexDirection:"row", justifyContent: 'flex-end', alignItems: "center" } }) export default AutoDecimalInput;