-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
PercentageForm.tsx
79 lines (66 loc) · 2.98 KB
/
PercentageForm.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
67
68
69
70
71
72
73
74
75
76
77
78
79
import type {ForwardedRef} from 'react';
import React, {forwardRef, useCallback, useMemo, useRef} from 'react';
import useLocalize from '@hooks/useLocalize';
import * as MoneyRequestUtils from '@libs/MoneyRequestUtils';
import CONST from '@src/CONST';
import TextInput from './TextInput';
import type {BaseTextInputRef} from './TextInput/BaseTextInput/types';
type PercentageFormProps = {
/** Amount supplied by the FormProvider */
value?: string;
/** Error to display at the bottom of the component */
errorText?: string;
/** Callback to update the amount in the FormProvider */
onInputChange?: (value: string) => void;
/** Custom label for the TextInput */
label?: string;
};
function PercentageForm({value: amount, errorText, onInputChange, label, ...rest}: PercentageFormProps, forwardedRef: ForwardedRef<BaseTextInputRef>) {
const {toLocaleDigit, numberFormat} = useLocalize();
const textInput = useRef<BaseTextInputRef | null>(null);
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 = MoneyRequestUtils.stripSpacesFromAmount(newAmount);
// Use a shallow copy of selection to trigger setSelection
// More info: https://github.com/Expensify/App/issues/16385
if (!MoneyRequestUtils.validatePercentage(newAmountWithoutSpaces)) {
return;
}
const strippedAmount = MoneyRequestUtils.stripCommaFromAmount(newAmountWithoutSpaces);
onInputChange?.(strippedAmount);
},
[onInputChange],
);
const formattedAmount = MoneyRequestUtils.replaceAllDigits(currentAmount, toLocaleDigit);
return (
<TextInput
label={label}
value={formattedAmount}
onChangeText={setNewAmount}
placeholder={numberFormat(0)}
ref={(ref: BaseTextInputRef) => {
if (typeof forwardedRef === 'function') {
forwardedRef(ref);
} else if (forwardedRef && 'current' in forwardedRef) {
// eslint-disable-next-line no-param-reassign
forwardedRef.current = ref;
}
textInput.current = ref;
}}
suffixCharacter="%"
keyboardType={CONST.KEYBOARD_TYPE.DECIMAL_PAD}
// eslint-disable-next-line react/jsx-props-no-spreading
{...rest}
/>
);
}
PercentageForm.displayName = 'PercentageForm';
export default forwardRef(PercentageForm);
export type {PercentageFormProps};