-
Notifications
You must be signed in to change notification settings - Fork 3k
/
MoneyRequestAmountForm.js
270 lines (244 loc) · 11.1 KB
/
MoneyRequestAmountForm.js
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
import React, {useEffect, useState, useCallback, useRef} from 'react';
import {ScrollView, View} from 'react-native';
import PropTypes from 'prop-types';
import lodashGet from 'lodash/get';
import _ from 'underscore';
import styles from '../../../styles/styles';
import BigNumberPad from '../../../components/BigNumberPad';
import * as CurrencyUtils from '../../../libs/CurrencyUtils';
import * as MoneyRequestUtils from '../../../libs/MoneyRequestUtils';
import Button from '../../../components/Button';
import * as DeviceCapabilities from '../../../libs/DeviceCapabilities';
import TextInputWithCurrencySymbol from '../../../components/TextInputWithCurrencySymbol';
import useLocalize from '../../../hooks/useLocalize';
import CONST from '../../../CONST';
import refPropTypes from '../../../components/refPropTypes';
import getOperatingSystem from '../../../libs/getOperatingSystem';
import * as Browser from '../../../libs/Browser';
import useWindowDimensions from '../../../hooks/useWindowDimensions';
const propTypes = {
/** IOU amount saved in Onyx */
amount: PropTypes.number,
/** Currency chosen by user or saved in Onyx */
currency: PropTypes.string,
/** Whether the amount is being edited or not */
isEditing: PropTypes.bool,
/** Refs forwarded to the TextInputWithCurrencySymbol */
forwardedRef: refPropTypes,
/** Fired when back button pressed, navigates to currency selection page */
onCurrencyButtonPress: PropTypes.func.isRequired,
/** Fired when submit button pressed, saves the given amount and navigates to the next page */
onSubmitButtonPress: PropTypes.func.isRequired,
};
const defaultProps = {
amount: 0,
currency: CONST.CURRENCY.USD,
forwardedRef: null,
isEditing: false,
};
/**
* Returns the new selection object based on the updated amount's length
*
* @param {Object} oldSelection
* @param {Number} prevLength
* @param {Number} newLength
* @returns {Object}
*/
const getNewSelection = (oldSelection, prevLength, newLength) => {
const cursorPosition = oldSelection.end + (newLength - prevLength);
return {start: cursorPosition, end: cursorPosition};
};
const AMOUNT_VIEW_ID = 'amountView';
const NUM_PAD_CONTAINER_VIEW_ID = 'numPadContainerView';
const NUM_PAD_VIEW_ID = 'numPadView';
function MoneyRequestAmountForm({amount, currency, isEditing, forwardedRef, onCurrencyButtonPress, onSubmitButtonPress}) {
const {isExtraSmallScreenHeight} = useWindowDimensions();
const {translate, toLocaleDigit, numberFormat} = useLocalize();
const textInput = useRef(null);
const selectedAmountAsString = amount ? CurrencyUtils.convertToFrontendAmount(amount).toString() : '';
const [currentAmount, setCurrentAmount] = useState(selectedAmountAsString);
const [shouldUpdateSelection, setShouldUpdateSelection] = useState(true);
const [selection, setSelection] = useState({
start: selectedAmountAsString.length,
end: selectedAmountAsString.length,
});
const forwardDeletePressedRef = useRef(false);
/**
* Event occurs when a user presses a mouse button over an DOM element.
*
* @param {Event} event
* @param {Array<string>} nativeIds
*/
const onMouseDown = (event, nativeIds) => {
const relatedTargetId = lodashGet(event, 'nativeEvent.target.id');
if (!_.contains(nativeIds, relatedTargetId)) {
return;
}
event.preventDefault();
if (!textInput.current) {
return;
}
if (!textInput.current.isFocused()) {
textInput.current.focus();
}
};
useEffect(() => {
if (!currency || !amount) {
return;
}
const amountAsStringForState = CurrencyUtils.convertToFrontendAmount(amount).toString();
setCurrentAmount(amountAsStringForState);
setSelection({
start: amountAsStringForState.length,
end: amountAsStringForState.length,
});
// we want to update the state only when the amount is changed
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [amount]);
/**
* Sets the selection and the amount accordingly to the value passed to the input
* @param {String} newAmount - Changed amount from user input
*/
const setNewAmount = (newAmount) => {
// 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.validateAmount(newAmountWithoutSpaces)) {
setSelection((prevSelection) => ({...prevSelection}));
return;
}
setCurrentAmount((prevAmount) => {
const strippedAmount = MoneyRequestUtils.stripCommaFromAmount(newAmountWithoutSpaces);
const isForwardDelete = prevAmount.length > strippedAmount.length && forwardDeletePressedRef.current;
setSelection((prevSelection) => getNewSelection(prevSelection, isForwardDelete ? strippedAmount.length : prevAmount.length, strippedAmount.length));
return strippedAmount;
});
};
/**
* Update amount with number or Backspace pressed for BigNumberPad.
* Validate new amount with decimal number regex up to 6 digits and 2 decimal digit to enable Next button
*
* @param {String} key
*/
const updateAmountNumberPad = useCallback(
(key) => {
if (shouldUpdateSelection && !textInput.current.isFocused()) {
textInput.current.focus();
}
// Backspace button is pressed
if (key === '<' || key === 'Backspace') {
if (currentAmount.length > 0) {
const selectionStart = selection.start === selection.end ? selection.start - 1 : selection.start;
const newAmount = `${currentAmount.substring(0, selectionStart)}${currentAmount.substring(selection.end)}`;
setNewAmount(newAmount);
}
return;
}
const newAmount = MoneyRequestUtils.addLeadingZero(`${currentAmount.substring(0, selection.start)}${key}${currentAmount.substring(selection.end)}`);
setNewAmount(newAmount);
},
[currentAmount, selection, shouldUpdateSelection],
);
/**
* Update long press value, to remove items pressing on <
*
* @param {Boolean} value - Changed text from user input
*/
const updateLongPressHandlerState = useCallback((value) => {
setShouldUpdateSelection(!value);
if (!value && !textInput.current.isFocused()) {
textInput.current.focus();
}
}, []);
/**
* Submit amount and navigate to a proper page
*/
const submitAndNavigateToNextPage = useCallback(() => {
onSubmitButtonPress(currentAmount);
}, [onSubmitButtonPress, currentAmount]);
/**
* Input handler to check for a forward-delete key (or keyboard shortcut) press.
*/
const textInputKeyPress = ({nativeEvent}) => {
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.
forwardDeletePressedRef.current = key === 'delete' || (_.contains([CONST.OS.MAC_OS, CONST.OS.IOS], getOperatingSystem()) && nativeEvent.ctrlKey && key === 'd');
};
const formattedAmount = MoneyRequestUtils.replaceAllDigits(currentAmount, toLocaleDigit);
const buttonText = isEditing ? translate('common.save') : translate('common.next');
return (
<ScrollView contentContainerStyle={styles.flexGrow1}>
<View
nativeID={AMOUNT_VIEW_ID}
onMouseDown={(event) => onMouseDown(event, [AMOUNT_VIEW_ID])}
style={[styles.flex1, styles.flexRow, styles.w100, styles.alignItemsCenter, styles.justifyContentCenter]}
>
<TextInputWithCurrencySymbol
formattedAmount={formattedAmount}
onChangeAmount={setNewAmount}
onCurrencyButtonPress={onCurrencyButtonPress}
placeholder={numberFormat(0)}
ref={(ref) => {
if (typeof forwardedRef === 'function') {
forwardedRef(ref);
} else if (forwardedRef && _.has(forwardedRef, 'current')) {
// eslint-disable-next-line no-param-reassign
forwardedRef.current = ref;
}
textInput.current = ref;
}}
selectedCurrencyCode={currency}
selection={selection}
onSelectionChange={(e) => {
if (!shouldUpdateSelection) {
return;
}
setSelection(e.nativeEvent.selection);
}}
onKeyPress={textInputKeyPress}
/>
</View>
<View
onMouseDown={(event) => onMouseDown(event, [NUM_PAD_CONTAINER_VIEW_ID, NUM_PAD_VIEW_ID])}
style={[styles.w100, styles.justifyContentEnd, styles.pageWrapper]}
nativeID={NUM_PAD_CONTAINER_VIEW_ID}
>
{DeviceCapabilities.canUseTouchScreen() ? (
<BigNumberPad
nativeID={NUM_PAD_VIEW_ID}
numberPressed={updateAmountNumberPad}
longPressHandlerStateChanged={updateLongPressHandlerState}
/>
) : null}
<Button
success
medium={isExtraSmallScreenHeight}
style={[styles.w100, styles.mt5]}
onPress={submitAndNavigateToNextPage}
pressOnEnter
isDisabled={!currentAmount.length || parseFloat(currentAmount) < 0.01}
text={buttonText}
/>
</View>
</ScrollView>
);
}
MoneyRequestAmountForm.propTypes = propTypes;
MoneyRequestAmountForm.defaultProps = defaultProps;
MoneyRequestAmountForm.displayName = 'MoneyRequestAmountForm';
export default React.forwardRef((props, ref) => (
<MoneyRequestAmountForm
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
forwardedRef={ref}
/>
));