-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathBaseTextInput.js
405 lines (363 loc) · 18 KB
/
BaseTextInput.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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import _ from 'underscore';
import React, {useState, useRef, useEffect, useCallback} from 'react';
import {Animated, View, AppState, Keyboard, StyleSheet} from 'react-native';
import Str from 'expensify-common/lib/str';
import RNTextInput from '../RNTextInput';
import TextInputLabel from './TextInputLabel';
import * as baseTextInputPropTypes from './baseTextInputPropTypes';
import themeColors from '../../styles/themes/default';
import styles from '../../styles/styles';
import Icon from '../Icon';
import * as Expensicons from '../Icon/Expensicons';
import Text from '../Text';
import * as styleConst from './styleConst';
import * as StyleUtils from '../../styles/StyleUtils';
import variables from '../../styles/variables';
import Checkbox from '../Checkbox';
import getSecureEntryKeyboardType from '../../libs/getSecureEntryKeyboardType';
import CONST from '../../CONST';
import FormHelpMessage from '../FormHelpMessage';
import isInputAutoFilled from '../../libs/isInputAutoFilled';
import PressableWithoutFeedback from '../Pressable/PressableWithoutFeedback';
import withLocalize from '../withLocalize';
function BaseTextInput(props) {
const inputValue = props.value || props.defaultValue || '';
const initialActiveLabel = props.forceActiveLabel || inputValue.length > 0 || Boolean(props.prefixCharacter);
const [isFocused, setIsFocused] = useState(false);
const [passwordHidden, setPasswordHidden] = useState(props.secureTextEntry);
const [textInputWidth, setTextInputWidth] = useState(0);
const [textInputHeight, setTextInputHeight] = useState(0);
const [prefixWidth, setPrefixWidth] = useState(0);
const [height, setHeight] = useState(variables.componentSizeLarge);
const [width, setWidth] = useState();
const labelScale = useRef(new Animated.Value(initialActiveLabel ? styleConst.ACTIVE_LABEL_SCALE : styleConst.INACTIVE_LABEL_SCALE)).current;
const labelTranslateY = useRef(new Animated.Value(initialActiveLabel ? styleConst.ACTIVE_LABEL_TRANSLATE_Y : styleConst.INACTIVE_LABEL_TRANSLATE_Y)).current;
const input = useRef(null);
const isLabelActive = useRef(initialActiveLabel);
useEffect(() => {
if (!props.disableKeyboard) {
return;
}
const appStateSubscription = AppState.addEventListener('change', (nextAppState) => {
if (!nextAppState.match(/inactive|background/)) {
return;
}
Keyboard.dismiss();
});
return () => {
appStateSubscription.remove();
};
}, [props.disableKeyboard]);
// AutoFocus which only works on mount:
useEffect(() => {
// We are manually managing focus to prevent this issue: https://github.com/Expensify/App/issues/4514
if (!props.autoFocus || !input.current) {
return;
}
let focusTimeout;
if (props.shouldDelayFocus) {
focusTimeout = setTimeout(() => input.current.focus(), CONST.ANIMATED_TRANSITION);
return;
}
input.current.focus();
return () => {
if (!focusTimeout) {
return;
}
clearTimeout(focusTimeout);
};
// We only want this to run on mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const animateLabel = useCallback(
(translateY, scale) => {
Animated.parallel([
Animated.spring(labelTranslateY, {
toValue: translateY,
duration: styleConst.LABEL_ANIMATION_DURATION,
useNativeDriver: true,
}),
Animated.spring(labelScale, {
toValue: scale,
duration: styleConst.LABEL_ANIMATION_DURATION,
useNativeDriver: true,
}),
]).start();
},
[labelScale, labelTranslateY],
);
const activateLabel = useCallback(() => {
const value = props.value || '';
if (value.length < 0 || isLabelActive.current) {
return;
}
animateLabel(styleConst.ACTIVE_LABEL_TRANSLATE_Y, styleConst.ACTIVE_LABEL_SCALE);
isLabelActive.current = true;
}, [animateLabel, props.value]);
const deactivateLabel = useCallback(() => {
const value = props.value || '';
if (props.forceActiveLabel || value.length !== 0 || props.prefixCharacter) {
return;
}
animateLabel(styleConst.INACTIVE_LABEL_TRANSLATE_Y, styleConst.INACTIVE_LABEL_SCALE);
isLabelActive.current = false;
}, [animateLabel, props.forceActiveLabel, props.prefixCharacter, props.value]);
const onFocus = (event) => {
if (props.onFocus) {
props.onFocus(event);
}
setIsFocused(true);
};
const onBlur = (event) => {
if (props.onBlur) {
props.onBlur(event);
}
setIsFocused(false);
// If the text has been supplied by Chrome autofill, the value state is not synced with the value
// as Chrome doesn't trigger a change event. When there is autofill text, don't deactivate label.
if (!isInputAutoFilled(input.current)) {
deactivateLabel();
}
};
const onPress = (event) => {
if (props.disabled) {
return;
}
if (props.onPress) {
props.onPress(event);
}
if (!event.isDefaultPrevented()) {
input.current.focus();
}
};
const onLayout = useCallback(
(event) => {
if (!props.autoGrowHeight && props.multiline) {
return;
}
const layout = event.nativeEvent.layout;
setWidth((prevWidth) => (props.autoGrowHeight ? layout.width : prevWidth));
setHeight((prevHeight) => (!props.multiline ? layout.height : prevHeight));
},
[props.autoGrowHeight, props.multiline],
);
useEffect(() => {
// Handle side effects when the value gets changed programatically from the outside
// In some cases, When the value prop is empty, it is not properly updated on the TextInput due to its uncontrolled nature, thus manually clearing the TextInput.
if (inputValue === '') {
input.current.clear();
}
if (inputValue) {
activateLabel();
}
}, [activateLabel, inputValue]);
// We capture whether the input has a value or not in a ref.
// It gets updated when the text gets changed.
const hasValueRef = useRef(inputValue.length > 0);
// Activate or deactivate the label when the focus changes:
useEffect(() => {
// We can't use inputValue here directly, as it might contain
// the defaultValue, which doesn't get updated when the text changes.
// We can't use props.value either, as it might be undefined.
if (hasValueRef.current || isFocused) {
activateLabel();
} else if (!hasValueRef.current && !isFocused) {
deactivateLabel();
}
}, [activateLabel, deactivateLabel, inputValue, isFocused]);
/**
* Set Value & activateLabel
*
* @param {String} value
* @memberof BaseTextInput
*/
const setValue = (value) => {
if (props.onInputChange) {
props.onInputChange(value);
}
Str.result(props.onChangeText, value);
if (value && value.length > 0) {
hasValueRef.current = true;
activateLabel();
} else {
hasValueRef.current = false;
}
};
const togglePasswordVisibility = useCallback(() => {
setPasswordHidden((prevPasswordHidden) => !prevPasswordHidden);
}, []);
const storePrefixLayoutDimensions = useCallback((event) => {
setPrefixWidth(Math.abs(event.nativeEvent.layout.width));
}, []);
// eslint-disable-next-line react/forbid-foreign-prop-types
const inputProps = _.omit(props, _.keys(baseTextInputPropTypes.propTypes));
const hasLabel = Boolean(props.label.length);
const isEditable = _.isUndefined(props.editable) ? !props.disabled : props.editable;
const inputHelpText = props.errorText || props.hint;
const placeholder = props.prefixCharacter || isFocused || !hasLabel || (hasLabel && props.forceActiveLabel) ? props.placeholder : null;
const maxHeight = StyleSheet.flatten(props.containerStyles).maxHeight;
const textInputContainerStyles = StyleSheet.flatten([
styles.textInputContainer,
...props.textInputContainerStyles,
props.autoGrow && StyleUtils.getWidthStyle(textInputWidth),
!props.hideFocusedState && isFocused && styles.borderColorFocus,
(props.hasError || props.errorText) && styles.borderColorDanger,
props.autoGrowHeight && {scrollPaddingTop: 2 * maxHeight},
]);
const isMultiline = props.multiline || props.autoGrowHeight;
return (
<>
<View>
<PressableWithoutFeedback
onPress={onPress}
focusable={false}
accessibilityLabel={props.label}
style={[props.autoGrowHeight && styles.autoGrowHeightInputContainer(textInputHeight, maxHeight), !isMultiline && styles.componentHeightLarge, ...props.containerStyles]}
>
<View
// When autoGrowHeight is true we calculate the width for the textInput, so it will break lines properly
// or if multiline is not supplied we calculate the textinput height, using onLayout.
onLayout={onLayout}
style={[
textInputContainerStyles,
// When autoGrow is on and minWidth is not supplied, add a minWidth to allow the input to be focusable.
props.autoGrow && !textInputContainerStyles.minWidth && styles.mnw2,
]}
>
{hasLabel ? (
<>
{/* Adding this background to the label only for multiline text input,
to prevent text overlapping with label when scrolling */}
{isMultiline && (
<View
style={styles.textInputLabelBackground}
pointerEvents="none"
/>
)}
<TextInputLabel
isLabelActive={isLabelActive.current}
label={props.label}
labelTranslateY={labelTranslateY}
labelScale={labelScale}
for={props.nativeID}
/>
</>
) : null}
<View
style={[styles.textInputAndIconContainer, isMultiline && hasLabel && styles.textInputMultilineContainer]}
pointerEvents="box-none"
>
{Boolean(props.prefixCharacter) && (
<View style={styles.textInputPrefixWrapper}>
<Text
pointerEvents="none"
selectable={false}
style={[styles.textInputPrefix, !hasLabel && styles.pv0]}
onLayout={storePrefixLayoutDimensions}
>
{props.prefixCharacter}
</Text>
</View>
)}
<RNTextInput
ref={(ref) => {
if (typeof props.innerRef === 'function') {
props.innerRef(ref);
} else if (props.innerRef && _.has(props.innerRef, 'current')) {
// eslint-disable-next-line no-param-reassign
props.innerRef.current = ref;
}
input.current = ref;
}}
// eslint-disable-next-line
{...inputProps}
autoCorrect={props.secureTextEntry ? false : props.autoCorrect}
placeholder={placeholder}
placeholderTextColor={themeColors.placeholderText}
underlineColorAndroid="transparent"
style={[
styles.flex1,
styles.w100,
props.inputStyle,
(!hasLabel || isMultiline) && styles.pv0,
props.prefixCharacter && StyleUtils.getPaddingLeft(prefixWidth + styles.pl1.paddingLeft),
props.secureTextEntry && styles.secureInput,
// Explicitly remove `lineHeight` from single line inputs so that long text doesn't disappear
// once it exceeds the input space (See https://github.com/Expensify/App/issues/13802)
!isMultiline && {height, lineHeight: undefined},
// Stop scrollbar flashing when breaking lines with autoGrowHeight enabled.
props.autoGrowHeight && StyleUtils.getAutoGrowHeightInputStyle(textInputHeight, maxHeight),
]}
multiline={isMultiline}
maxLength={props.maxLength}
onFocus={onFocus}
onBlur={onBlur}
onChangeText={setValue}
secureTextEntry={passwordHidden}
onPressOut={props.onPress}
showSoftInputOnFocus={!props.disableKeyboard}
keyboardType={getSecureEntryKeyboardType(props.keyboardType, props.secureTextEntry, passwordHidden)}
value={props.value}
selection={props.selection}
editable={isEditable}
defaultValue={props.defaultValue}
// FormSubmit Enter key handler does not have access to direct props.
// `dataset.submitOnEnter` is used to indicate that pressing Enter on this input should call the submit callback.
dataSet={{submitOnEnter: isMultiline && props.submitOnEnter}}
/>
{Boolean(props.secureTextEntry) && (
<Checkbox
style={[styles.flex1, styles.textInputIconContainer]}
onPress={togglePasswordVisibility}
onMouseDown={(e) => e.preventDefault()}
accessibilityLabel={props.translate('common.visible')}
>
<Icon
src={passwordHidden ? Expensicons.Eye : Expensicons.EyeDisabled}
fill={themeColors.icon}
/>
</Checkbox>
)}
{!props.secureTextEntry && Boolean(props.icon) && (
<View style={[styles.textInputIconContainer, isEditable ? styles.cursorPointer : styles.pointerEventsNone]}>
<Icon
src={props.icon}
fill={themeColors.icon}
/>
</View>
)}
</View>
</View>
</PressableWithoutFeedback>
{!_.isEmpty(inputHelpText) && (
<FormHelpMessage
isError={!_.isEmpty(props.errorText)}
message={inputHelpText}
/>
)}
</View>
{/*
Text input component doesn't support auto grow by default.
We're using a hidden text input to achieve that.
This text view is used to calculate width or height of the input value given textStyle in this component.
This Text component is intentionally positioned out of the screen.
*/}
{(props.autoGrow || props.autoGrowHeight) && (
// Add +2 to width so that the first digit of amount do not cut off on mWeb - https://github.com/Expensify/App/issues/8158.
<Text
style={[...props.inputStyle, props.autoGrowHeight && styles.autoGrowHeightHiddenInput(width, maxHeight), styles.hiddenElementOutsideOfWindow, styles.visibilityHidden]}
onLayout={(e) => {
setTextInputWidth(e.nativeEvent.layout.width + 2);
setTextInputHeight(e.nativeEvent.layout.height);
}}
>
{props.value || props.placeholder}
</Text>
)}
</>
);
}
BaseTextInput.displayName = 'BaseTextInput';
BaseTextInput.propTypes = baseTextInputPropTypes.propTypes;
BaseTextInput.defaultProps = baseTextInputPropTypes.defaultProps;
export default withLocalize(BaseTextInput);