-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathMoneyRequestAmountInput.tsx
295 lines (251 loc) · 12 KB
/
MoneyRequestAmountInput.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import type {ForwardedRef} from 'react';
import React, {useCallback, useEffect, useImperativeHandle, useRef, useState} from 'react';
import type {NativeSyntheticEvent, StyleProp, TextInputSelectionChangeEventData, TextStyle, ViewStyle} from 'react-native';
import useLocalize from '@hooks/useLocalize';
import * as Browser from '@libs/Browser';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import getOperatingSystem from '@libs/getOperatingSystem';
import * as MoneyRequestUtils from '@libs/MoneyRequestUtils';
import CONST from '@src/CONST';
import type {BaseTextInputRef} from './TextInput/BaseTextInput/types';
import TextInputWithCurrencySymbol from './TextInputWithCurrencySymbol';
type CurrentMoney = {amount: string; currency: string};
type MoneyRequestAmountInputRef = {
setNewAmount: (amountValue: string) => void;
changeSelection: (newSelection: Selection) => void;
changeAmount: (newAmount: string) => void;
getAmount: () => string;
getSelection: () => Selection;
};
type MoneyRequestAmountInputProps = {
/** IOU amount saved in Onyx */
amount?: number;
/** Currency chosen by user or saved in Onyx */
currency?: string;
/** Whether the currency symbol is pressable */
isCurrencyPressable?: boolean;
/** Fired when back button pressed, navigates to currency selection page */
onCurrencyButtonPress?: () => void;
/** Function to call when the amount changes */
onAmountChange?: (amount: string) => void;
/** Whether to update the selection */
shouldUpdateSelection?: boolean;
/** Style for the input */
inputStyle?: StyleProp<TextStyle>;
/** Style for the container */
containerStyle?: StyleProp<ViewStyle>;
/** Reference to moneyRequestAmountInputRef */
moneyRequestAmountInputRef?: ForwardedRef<MoneyRequestAmountInputRef>;
/** Character to be shown before the amount */
prefixCharacter?: string;
/** Whether to hide the currency symbol */
hideCurrencySymbol?: boolean;
/** Whether to disable native keyboard on mobile */
disableKeyboard?: boolean;
/** Style for the prefix */
prefixStyle?: StyleProp<TextStyle>;
/** Style for the prefix container */
prefixContainerStyle?: StyleProp<ViewStyle>;
/** Style for the touchable input wrapper */
touchableInputWrapperStyle?: StyleProp<ViewStyle>;
/** Whether we want to format the display amount on blur */
formatAmountOnBlur?: boolean;
/** Max length for the amount input */
maxLength?: number;
/** Hide the focus styles on TextInput */
hideFocusedState?: boolean;
};
type Selection = {
start: number;
end: number;
};
/**
* Returns the new selection object based on the updated amount's length
*/
const getNewSelection = (oldSelection: Selection, prevLength: number, newLength: number): Selection => {
const cursorPosition = oldSelection.end + (newLength - prevLength);
return {start: cursorPosition, end: cursorPosition};
};
function MoneyRequestAmountInput(
{
amount = 0,
currency = CONST.CURRENCY.USD,
isCurrencyPressable = true,
onCurrencyButtonPress,
onAmountChange,
prefixCharacter = '',
hideCurrencySymbol = false,
shouldUpdateSelection = true,
moneyRequestAmountInputRef,
disableKeyboard = true,
formatAmountOnBlur,
maxLength,
hideFocusedState = true,
...props
}: MoneyRequestAmountInputProps,
forwardedRef: ForwardedRef<BaseTextInputRef>,
) {
const {toLocaleDigit, numberFormat} = useLocalize();
const textInput = useRef<BaseTextInputRef | null>(null);
const decimals = CurrencyUtils.getCurrencyDecimals(currency);
const selectedAmountAsString = amount ? CurrencyUtils.convertToFrontendAmount(amount).toString() : '';
const [currentAmount, setCurrentAmount] = useState(selectedAmountAsString);
const [selection, setSelection] = useState({
start: selectedAmountAsString.length,
end: selectedAmountAsString.length,
});
const forwardDeletePressedRef = useRef(false);
/**
* Sets the selection and the amount accordingly to the value passed to the input
* @param {String} 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);
const finalAmount = newAmountWithoutSpaces.includes('.')
? MoneyRequestUtils.stripCommaFromAmount(newAmountWithoutSpaces)
: MoneyRequestUtils.replaceCommasWithPeriod(newAmountWithoutSpaces);
// Use a shallow copy of selection to trigger setSelection
// More info: https://github.com/Expensify/App/issues/16385
if (!MoneyRequestUtils.validateAmount(finalAmount, decimals)) {
setSelection((prevSelection) => ({...prevSelection}));
return;
}
// setCurrentAmount contains another setState(setSelection) making it error-prone since it is leading to setSelection being called twice for a single setCurrentAmount call. This solution introducing the hasSelectionBeenSet flag was chosen for its simplicity and lower risk of future errors https://github.com/Expensify/App/issues/23300#issuecomment-1766314724.
let hasSelectionBeenSet = false;
setCurrentAmount((prevAmount) => {
const strippedAmount = MoneyRequestUtils.stripCommaFromAmount(finalAmount);
const isForwardDelete = prevAmount.length > strippedAmount.length && forwardDeletePressedRef.current;
if (!hasSelectionBeenSet) {
hasSelectionBeenSet = true;
setSelection((prevSelection) => getNewSelection(prevSelection, isForwardDelete ? strippedAmount.length : prevAmount.length, strippedAmount.length));
}
onAmountChange?.(strippedAmount);
return strippedAmount;
});
},
[decimals, onAmountChange],
);
useImperativeHandle(moneyRequestAmountInputRef, () => ({
setNewAmount(amountValue: string) {
setNewAmount(amountValue);
},
changeSelection(newSelection: Selection) {
setSelection(newSelection);
},
changeAmount(newAmount: string) {
setCurrentAmount(newAmount);
},
getAmount() {
return currentAmount;
},
getSelection() {
return selection;
},
}));
useEffect(() => {
if (!currency || typeof amount !== 'number' || (formatAmountOnBlur && textInput.current?.isFocused())) {
return;
}
const frontendAmount = formatAmountOnBlur ? CurrencyUtils.convertToDisplayStringWithoutCurrency(amount, currency) : CurrencyUtils.convertToFrontendAmount(amount).toString();
setCurrentAmount(frontendAmount);
// Only update selection if the amount prop was changed from the outside and is not the same as the current amount we just computed
// In the line below the currentAmount is not immediately updated, it should still hold the previous value.
if (frontendAmount !== currentAmount) {
setSelection({
start: frontendAmount.length,
end: frontendAmount.length,
});
}
// we want to re-initialize the state only when the amount changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [amount]);
// Modifies the amount to match the decimals for changed currency.
useEffect(() => {
// If the changed currency supports decimals, we can return
if (MoneyRequestUtils.validateAmount(currentAmount, decimals)) {
return;
}
// If the changed currency doesn't support decimals, we can strip the decimals
setNewAmount(MoneyRequestUtils.stripDecimalsFromAmount(currentAmount));
// we want to update only when decimals change (setNewAmount also changes when decimals change).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [setNewAmount]);
/**
* Input handler to check for a forward-delete key (or keyboard shortcut) press.
*/
const textInputKeyPress = ({nativeEvent}: NativeSyntheticEvent<KeyboardEvent>) => {
const key = nativeEvent?.key.toLowerCase();
if (Browser.isMobileSafari() && key === CONST.PLATFORM_SPECIFIC_KEYS.CTRL.DEFAULT) {
// Optimistically anticipate forward-delete on iOS Safari (in cases where the Mac Accessiblity keyboard is being
// used for input). If the Control-D shortcut doesn't get sent, the ref will still be reset on the next key press.
forwardDeletePressedRef.current = true;
return;
}
// Control-D on Mac is a keyboard shortcut for forward-delete. See https://support.apple.com/en-us/HT201236 for Mac keyboard shortcuts.
// Also check for the keyboard shortcut on iOS in cases where a hardware keyboard may be connected to the device.
const operatingSystem = getOperatingSystem();
forwardDeletePressedRef.current = key === 'delete' || ((operatingSystem === CONST.OS.MAC_OS || operatingSystem === CONST.OS.IOS) && nativeEvent?.ctrlKey && key === 'd');
};
const formatAmount = useCallback(() => {
if (!formatAmountOnBlur) {
return;
}
const formattedAmount = CurrencyUtils.convertToDisplayStringWithoutCurrency(amount, currency);
if (maxLength && formattedAmount.length > maxLength) {
return;
}
setCurrentAmount(formattedAmount);
setSelection({
start: formattedAmount.length,
end: formattedAmount.length,
});
}, [amount, currency, formatAmountOnBlur, maxLength]);
const formattedAmount = MoneyRequestUtils.replaceAllDigits(currentAmount, toLocaleDigit);
return (
<TextInputWithCurrencySymbol
disableKeyboard={disableKeyboard}
formattedAmount={formattedAmount}
onChangeAmount={setNewAmount}
onCurrencyButtonPress={onCurrencyButtonPress}
onBlur={formatAmount}
placeholder={numberFormat(0)}
ref={(ref) => {
if (typeof forwardedRef === 'function') {
forwardedRef(ref);
} else if (forwardedRef?.current) {
// eslint-disable-next-line no-param-reassign
forwardedRef.current = ref;
}
textInput.current = ref;
}}
selectedCurrencyCode={currency}
selection={selection}
onSelectionChange={(e: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
if (!shouldUpdateSelection) {
return;
}
const maxSelection = formattedAmount.length;
const start = Math.min(e.nativeEvent.selection.start, maxSelection);
const end = Math.min(e.nativeEvent.selection.end, maxSelection);
setSelection({start, end});
}}
onKeyPress={textInputKeyPress}
hideCurrencySymbol={hideCurrencySymbol}
prefixCharacter={prefixCharacter}
isCurrencyPressable={isCurrencyPressable}
style={props.inputStyle}
containerStyle={props.containerStyle}
prefixStyle={props.prefixStyle}
prefixContainerStyle={props.prefixContainerStyle}
touchableInputWrapperStyle={props.touchableInputWrapperStyle}
maxLength={maxLength}
hideFocusedState={hideFocusedState}
/>
);
}
MoneyRequestAmountInput.displayName = 'MoneyRequestAmountInput';
export default React.forwardRef(MoneyRequestAmountInput);
export type {CurrentMoney, MoneyRequestAmountInputProps, MoneyRequestAmountInputRef};