97 lines
No EOL
2.8 KiB
TypeScript
97 lines
No EOL
2.8 KiB
TypeScript
import { View, Text, TouchableOpacity, TextInput, StyleSheet, NativeSyntheticEvent, TextInputKeyPressEventData } from 'react-native'
|
|
import React, {LegacyRef, MutableRefObject, useRef, useState} from 'react'
|
|
import colors from '../../constants/colors';
|
|
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,
|
|
}
|
|
|
|
const AutoDecimalInput: React.FC<AutoDecimalInputProps> = ({onValueChange, label}) => {
|
|
const { colors } = useTheme();
|
|
const inputRef = useRef<TextInput>(null);
|
|
const [pressedNumbers, setPressedNumbers] = useState<string>("");
|
|
|
|
const update = (newValues : string) => {
|
|
if(onValueChange){
|
|
onValueChange(formatDecimal(newValues))
|
|
}
|
|
setPressedNumbers(newValues);
|
|
}
|
|
|
|
const handleInput = (e: NativeSyntheticEvent<TextInputKeyPressEventData>)=>{
|
|
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 (
|
|
<TouchableOpacity activeOpacity={1} style={[styles.inputContainer, {backgroundColor: colors.elementDefaultColor}]} onPress={()=>{
|
|
if(inputRef.current)
|
|
inputRef.current.focus()
|
|
}}>
|
|
<Text style={[styles.text, {color: colors.primaryText}]}>{label}</Text>
|
|
<View style={styles.currencyWrapper}>
|
|
<TextInput
|
|
style={[styles.text, {color: colors.primaryText}]}
|
|
keyboardType='number-pad'
|
|
ref={inputRef}
|
|
onKeyPress={handleInput}
|
|
placeholder='0.00'
|
|
textAlign='right'
|
|
placeholderTextColor={colors.secondaryText}
|
|
value={formatDecimal(pressedNumbers)}
|
|
/>
|
|
<Text style={styles.currency}>EUR</Text>
|
|
</View>
|
|
</TouchableOpacity>
|
|
)
|
|
}
|
|
|
|
const styles = StyleSheet.create({
|
|
container: {
|
|
margin: SIZES.normal,
|
|
},
|
|
inputContainer: {
|
|
borderRadius: 20,
|
|
flexDirection: "row",
|
|
justifyContent: 'space-between'
|
|
},
|
|
text:{
|
|
fontSize: SIZES.large,
|
|
marginVertical: 12,
|
|
marginHorizontal: 15,
|
|
},
|
|
currency: {
|
|
fontSize: SIZES.normal,
|
|
color: "#007acc",
|
|
marginRight: 15,
|
|
},
|
|
currencyWrapper: {
|
|
flexDirection:"row",
|
|
justifyContent: 'flex-end',
|
|
alignItems: "center"
|
|
}
|
|
})
|
|
|
|
export default AutoDecimalInput; |