-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathBasePicker.js
311 lines (263 loc) · 10.7 KB
/
BasePicker.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
import PropTypes from 'prop-types';
import React, {useContext, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import {View} from 'react-native';
import RNPickerSelect from 'react-native-picker-select';
import _ from 'underscore';
import FormHelpMessage from '@components/FormHelpMessage';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import refPropTypes from '@components/refPropTypes';
import {ScrollContext} from '@components/ScrollViewWithContext';
import Text from '@components/Text';
import useTheme from '@styles/themes/useTheme';
import useThemeStyles from '@styles/useThemeStyles';
const propTypes = {
/** A forwarded ref */
forwardedRef: refPropTypes,
/** BasePicker label */
label: PropTypes.string,
/** Should the picker appear disabled? */
isDisabled: PropTypes.bool,
/** Input value */
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/** The items to display in the list of selections */
items: PropTypes.arrayOf(
PropTypes.shape({
/** The value of the item that is being selected */
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
/** The text to display for the item */
label: PropTypes.string.isRequired,
}),
).isRequired,
/** Something to show as the placeholder before something is selected */
placeholder: PropTypes.shape({
/** The value of the placeholder item, usually an empty string */
value: PropTypes.string,
/** The text to be displayed as the placeholder */
label: PropTypes.string,
}),
/** Error text to display */
errorText: PropTypes.string,
/** Customize the BasePicker container */
// eslint-disable-next-line react/forbid-prop-types
containerStyles: PropTypes.arrayOf(PropTypes.object),
/** Customize the BasePicker background color */
backgroundColor: PropTypes.string,
/** The ID used to uniquely identify the input in a Form */
inputID: PropTypes.string,
/** Saves a draft of the input value when used in a form */
// eslint-disable-next-line react/no-unused-prop-types
shouldSaveDraft: PropTypes.bool,
/** A callback method that is called when the value changes and it receives the selected value as an argument */
onInputChange: PropTypes.func.isRequired,
/** Size of a picker component */
size: PropTypes.oneOf(['normal', 'small']),
/** An icon to display with the picker */
icon: PropTypes.func,
/** Whether we should forward the focus/blur calls to the inner picker * */
shouldFocusPicker: PropTypes.bool,
/** Callback called when click or tap out of BasePicker */
onBlur: PropTypes.func,
/** Additional events passed to the core BasePicker for specific platforms such as web */
additionalPickerEvents: PropTypes.func,
/** Hint text that appears below the picker */
hintText: PropTypes.string,
};
const defaultProps = {
forwardedRef: undefined,
label: '',
isDisabled: false,
errorText: '',
hintText: '',
containerStyles: [],
backgroundColor: undefined,
inputID: undefined,
shouldSaveDraft: false,
value: undefined,
placeholder: {},
size: 'normal',
icon: undefined,
shouldFocusPicker: false,
onBlur: () => {},
additionalPickerEvents: () => {},
};
function BasePicker(props) {
const styles = useThemeStyles();
const theme = useTheme();
const [isHighlighted, setIsHighlighted] = useState(false);
// reference to the root View
const root = useRef(null);
// reference to @react-native-picker/picker
const picker = useRef(null);
// Windows will reuse the text color of the select for each one of the options
// so we might need to color accordingly so it doesn't blend with the background.
const placeholder = _.isEmpty(props.placeholder)
? {}
: {
...props.placeholder,
color: theme.pickerOptionsTextColor,
};
useEffect(() => {
if (props.value || !props.items || props.items.length !== 1 || !props.onInputChange) {
return;
}
// When there is only 1 element in the selector, we do the user a favor and automatically select it for them
// so they don't have to spend extra time selecting the only possible value.
props.onInputChange(props.items[0].value, 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.items]);
const context = useContext(ScrollContext);
/**
* Forms use inputID to set values. But BasePicker passes an index as the second parameter to onInputChange
* We are overriding this behavior to make BasePicker work with Form
* @param {String} value
* @param {Number} index
*/
const onInputChange = (value, index) => {
if (props.inputID) {
props.onInputChange(value);
return;
}
props.onInputChange(value, index);
};
const enableHighlight = () => {
setIsHighlighted(true);
};
const disableHighlight = () => {
setIsHighlighted(false);
};
const {icon, size} = props;
const iconToRender = useMemo(() => {
if (icon) {
return () => icon(size);
}
// eslint-disable-next-line react/display-name
return () => (
<Icon
src={Expensicons.DownArrow}
// eslint-disable-next-line react/jsx-props-no-spreading
{...(size === 'small'
? {
width: styles.pickerSmall().icon.width,
height: styles.pickerSmall().icon.height,
}
: {})}
/>
);
}, [icon, size, styles]);
useImperativeHandle(props.forwardedRef, () => ({
/**
* Focuses the picker (if configured to do so)
*
* This method is used by Form
*/
focus() {
if (!props.shouldFocusPicker) {
return;
}
// Defer the focusing to work around a bug on Mobile Safari, where focusing the `select` element in the
// same task when we scrolled to it left that element in a glitched state, where the dropdown list can't
// be opened until the element gets re-focused
_.defer(() => {
picker.current.focus();
});
},
/**
* Like measure(), but measures the view relative to an ancestor
*
* This method is used by Form when scrolling to the input
*
* @param {Object} relativeToNativeComponentRef - reference to an ancestor
* @param {function(x: number, y: number, width: number, height: number): void} onSuccess - callback called on success
* @param {function(): void} onFail - callback called on failure
*/
measureLayout(relativeToNativeComponentRef, onSuccess, onFail) {
if (!root.current) {
return;
}
root.current.measureLayout(relativeToNativeComponentRef, onSuccess, onFail);
},
}));
const hasError = !_.isEmpty(props.errorText);
if (props.isDisabled) {
return (
<View>
{Boolean(props.label) && (
<Text
style={[styles.textLabelSupporting, styles.mb1]}
numberOfLines={1}
>
{props.label}
</Text>
)}
<Text numberOfLines={1}>{props.value}</Text>
{Boolean(props.hintText) && <Text style={[styles.textLabel, styles.colorMuted, styles.mt2]}>{props.hintText}</Text>}
</View>
);
}
return (
<>
<View
ref={root}
style={[
styles.pickerContainer,
props.isDisabled && styles.inputDisabled,
...props.containerStyles,
isHighlighted && styles.borderColorFocus,
hasError && styles.borderColorDanger,
]}
>
{props.label && <Text style={[styles.pickerLabel, styles.textLabelSupporting, styles.pointerEventsNone]}>{props.label}</Text>}
<RNPickerSelect
onValueChange={onInputChange}
// We add a text color to prevent white text on white background dropdown items on Windows
items={_.map(props.items, (item) => ({...item, color: theme.pickerOptionsTextColor}))}
style={size === 'normal' ? styles.picker(props.isDisabled, props.backgroundColor) : styles.pickerSmall(props.backgroundColor)}
useNativeAndroidPickerStyle={false}
placeholder={placeholder}
value={props.value}
Icon={iconToRender}
disabled={props.isDisabled}
fixAndroidTouchableBug
onOpen={enableHighlight}
onClose={disableHighlight}
textInputProps={{
allowFontScaling: false,
}}
pickerProps={{
ref: picker,
tabIndex: -1,
onFocus: enableHighlight,
onBlur: () => {
disableHighlight();
props.onBlur();
},
...props.additionalPickerEvents(enableHighlight, (value, index) => {
onInputChange(value, index);
disableHighlight();
}),
}}
scrollViewRef={context && context.scrollViewRef}
scrollViewContentOffsetY={context && context.contentOffsetY}
/>
</View>
<FormHelpMessage message={props.errorText} />
{Boolean(props.hintText) && <Text style={[styles.textLabel, styles.colorMuted, styles.mt2]}>{props.hintText}</Text>}
</>
);
}
BasePicker.propTypes = propTypes;
BasePicker.defaultProps = defaultProps;
BasePicker.displayName = 'BasePicker';
const BasePickerWithRef = React.forwardRef((props, ref) => (
<BasePicker
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
// Forward the ref to BasePicker, as we implement imperative methods there
forwardedRef={ref}
// eslint-disable-next-line react/prop-types
key={props.inputID}
/>
));
BasePickerWithRef.displayName = 'BasePickerWithRef';
export default BasePickerWithRef;