-
Notifications
You must be signed in to change notification settings - Fork 3k
/
AmountWithoutCurrencyForm.tsx
66 lines (57 loc) · 2.5 KB
/
AmountWithoutCurrencyForm.tsx
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
import React, {useCallback, useMemo} from 'react';
import type {ForwardedRef} from 'react';
import useLocalize from '@hooks/useLocalize';
import {addLeadingZero, replaceAllDigits, replaceCommasWithPeriod, stripSpacesFromAmount, validateAmount} from '@libs/MoneyRequestUtils';
import CONST from '@src/CONST';
import TextInput from './TextInput';
import type {BaseTextInputProps, BaseTextInputRef} from './TextInput/BaseTextInput/types';
type AmountFormProps = {
/** Amount supplied by the FormProvider */
value?: string;
/** Callback to update the amount in the FormProvider */
onInputChange?: (value: string) => void;
} & Partial<BaseTextInputProps>;
function AmountWithoutCurrencyForm(
{value: amount, onInputChange, inputID, name, defaultValue, accessibilityLabel, role, label, ...rest}: AmountFormProps,
ref: ForwardedRef<BaseTextInputRef>,
) {
const {toLocaleDigit} = useLocalize();
const currentAmount = useMemo(() => (typeof amount === 'string' ? amount : ''), [amount]);
/**
* Sets the selection and the amount accordingly to the value passed to the input
* @param newAmount - Changed amount from user input
*/
const setNewAmount = useCallback(
(newAmount: string) => {
// Remove spaces from the newAmount value because Safari on iOS adds spaces when pasting a copied value
// More info: https://github.com/Expensify/App/issues/16974
const newAmountWithoutSpaces = stripSpacesFromAmount(newAmount);
const replacedCommasAmount = replaceCommasWithPeriod(newAmountWithoutSpaces);
const withLeadingZero = addLeadingZero(replacedCommasAmount);
if (!validateAmount(withLeadingZero, 2)) {
return;
}
onInputChange?.(withLeadingZero);
},
[onInputChange],
);
const formattedAmount = replaceAllDigits(currentAmount, toLocaleDigit);
return (
<TextInput
value={formattedAmount}
onChangeText={setNewAmount}
inputID={inputID}
name={name}
label={label}
defaultValue={defaultValue}
accessibilityLabel={accessibilityLabel}
role={role}
ref={ref}
keyboardType={CONST.KEYBOARD_TYPE.DECIMAL_PAD}
// eslint-disable-next-line react/jsx-props-no-spreading
{...rest}
/>
);
}
AmountWithoutCurrencyForm.displayName = 'AmountWithoutCurrencyForm';
export default React.forwardRef(AmountWithoutCurrencyForm);