-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
BaseOptionsSelector.js
executable file
·472 lines (418 loc) · 17.9 KB
/
BaseOptionsSelector.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import _ from 'underscore';
import lodashGet from 'lodash/get';
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {View} from 'react-native';
import Button from '../Button';
import FixedFooter from '../FixedFooter';
import OptionsList from '../OptionsList';
import CONST from '../../CONST';
import styles from '../../styles/styles';
import withLocalize, {withLocalizePropTypes} from '../withLocalize';
import withNavigationFocus, {withNavigationFocusPropTypes} from '../withNavigationFocus';
import TextInput from '../TextInput';
import ArrowKeyFocusManager from '../ArrowKeyFocusManager';
import KeyboardShortcut from '../../libs/KeyboardShortcut';
import {propTypes as optionsSelectorPropTypes, defaultProps as optionsSelectorDefaultProps} from './optionsSelectorPropTypes';
import setSelection from '../../libs/setSelection';
import compose from '../../libs/compose';
import getPlatform from '../../libs/getPlatform';
const propTypes = {
/** padding bottom style of safe area */
safeAreaPaddingBottomStyle: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.object), PropTypes.object]),
/** Content container styles for OptionsList */
contentContainerStyles: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.object), PropTypes.object]),
/** List container styles for OptionsList */
listContainerStyles: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.object), PropTypes.object]),
/** List styles for OptionsList */
listStyles: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.object), PropTypes.object]),
...optionsSelectorPropTypes,
...withLocalizePropTypes,
...withNavigationFocusPropTypes,
};
const defaultProps = {
shouldDelayFocus: false,
safeAreaPaddingBottomStyle: {},
contentContainerStyles: [],
listContainerStyles: [styles.flex1],
listStyles: [],
...optionsSelectorDefaultProps,
};
class BaseOptionsSelector extends Component {
constructor(props) {
super(props);
this.updateFocusedIndex = this.updateFocusedIndex.bind(this);
this.scrollToIndex = this.scrollToIndex.bind(this);
this.selectRow = this.selectRow.bind(this);
this.selectFocusedOption = this.selectFocusedOption.bind(this);
this.addToSelection = this.addToSelection.bind(this);
this.relatedTarget = null;
const allOptions = this.flattenSections();
const focusedIndex = this.getInitiallyFocusedIndex(allOptions);
this.state = {
allOptions,
focusedIndex,
shouldDisableRowSelection: false,
};
}
componentDidMount() {
this.subscribeToKeyboardShortcut();
if (this.props.isFocused && this.props.autoFocus && this.textInput) {
setTimeout(() => {
this.textInput.focus();
}, CONST.ANIMATED_TRANSITION);
}
this.scrollToIndex(this.props.selectedOptions.length ? 0 : this.state.focusedIndex, false);
}
componentDidUpdate(prevProps) {
if (prevProps.isFocused !== this.props.isFocused) {
if (this.props.isFocused) {
this.subscribeToKeyboardShortcut();
} else {
this.unSubscribeFromKeyboardShortcut();
}
}
// Screen coming back into focus, for example
// when doing Cmd+Shift+K, then Cmd+K, then Cmd+Shift+K.
// Only applies to platforms that support keyboard shortcuts
if ([CONST.PLATFORM.DESKTOP, CONST.PLATFORM.WEB].includes(getPlatform()) && !prevProps.isFocused && this.props.isFocused && this.props.autoFocus && this.textInput) {
setTimeout(() => {
this.textInput.focus();
}, CONST.ANIMATED_TRANSITION);
}
if (_.isEqual(this.props.sections, prevProps.sections)) {
return;
}
const newOptions = this.flattenSections();
if (prevProps.preferredLocale !== this.props.preferredLocale) {
this.setState({
allOptions: newOptions,
});
return;
}
const newFocusedIndex = this.props.selectedOptions.length;
const isNewFocusedIndex = newFocusedIndex !== this.state.focusedIndex;
// eslint-disable-next-line react/no-did-update-set-state
this.setState(
{
allOptions: newOptions,
focusedIndex: _.isNumber(this.props.initialFocusedIndex) ? this.props.initialFocusedIndex : newFocusedIndex,
},
() => {
// If we just toggled an option on a multi-selection page or cleared the search input, scroll to top
if (this.props.selectedOptions.length !== prevProps.selectedOptions.length || (!!prevProps.value && !this.props.value)) {
this.scrollToIndex(0);
return;
}
// Otherwise, scroll to the focused index (as long as it's in range)
if (this.state.allOptions.length <= this.state.focusedIndex || !isNewFocusedIndex) {
return;
}
this.scrollToIndex(this.state.focusedIndex);
},
);
}
componentWillUnmount() {
if (this.focusTimeout) {
clearTimeout(this.focusTimeout);
}
this.unSubscribeFromKeyboardShortcut();
}
/**
* @param {Array<Object>} allOptions
* @returns {Number}
*/
getInitiallyFocusedIndex(allOptions) {
if (_.isNumber(this.props.initialFocusedIndex)) {
return this.props.initialFocusedIndex;
}
if (this.props.selectedOptions.length > 0) {
return this.props.selectedOptions.length;
}
const defaultIndex = this.props.shouldTextInputAppearBelowOptions ? allOptions.length : 0;
if (_.isUndefined(this.props.initiallyFocusedOptionKey)) {
return defaultIndex;
}
const indexOfInitiallyFocusedOption = _.findIndex(allOptions, (option) => option.keyForList === this.props.initiallyFocusedOptionKey);
if (indexOfInitiallyFocusedOption >= 0) {
return indexOfInitiallyFocusedOption;
}
return defaultIndex;
}
subscribeToKeyboardShortcut() {
const enterConfig = CONST.KEYBOARD_SHORTCUTS.ENTER;
this.unsubscribeEnter = KeyboardShortcut.subscribe(
enterConfig.shortcutKey,
this.selectFocusedOption,
enterConfig.descriptionKey,
enterConfig.modifiers,
true,
() => !this.state.allOptions[this.state.focusedIndex],
);
const CTRLEnterConfig = CONST.KEYBOARD_SHORTCUTS.CTRL_ENTER;
this.unsubscribeCTRLEnter = KeyboardShortcut.subscribe(
CTRLEnterConfig.shortcutKey,
() => {
if (this.props.canSelectMultipleOptions) {
this.props.onConfirmSelection();
return;
}
const focusedOption = this.state.allOptions[this.state.focusedIndex];
if (!focusedOption) {
return;
}
this.selectRow(focusedOption);
},
CTRLEnterConfig.descriptionKey,
CTRLEnterConfig.modifiers,
true,
);
}
unSubscribeFromKeyboardShortcut() {
if (this.unsubscribeEnter) {
this.unsubscribeEnter();
}
if (this.unsubscribeCTRLEnter) {
this.unsubscribeCTRLEnter();
}
}
selectFocusedOption() {
const focusedOption = this.state.allOptions[this.state.focusedIndex];
if (!focusedOption || !this.props.isFocused) {
return;
}
if (this.props.canSelectMultipleOptions) {
this.selectRow(focusedOption);
} else if (!this.state.shouldDisableRowSelection) {
this.setState({shouldDisableRowSelection: true});
let result = this.selectRow(focusedOption);
if (!(result instanceof Promise)) {
result = Promise.resolve();
}
setTimeout(() => {
result.finally(() => {
this.setState({shouldDisableRowSelection: false});
});
}, 500);
}
}
focus() {
if (!this.textInput) {
return;
}
this.textInput.focus();
}
/**
* Flattens the sections into a single array of options.
* Each object in this array is enhanced to have:
*
* 1. A `sectionIndex`, which represents the index of the section it came from
* 2. An `index`, which represents the index of the option within the section it came from.
*
* @returns {Array<Object>}
*/
flattenSections() {
const allOptions = [];
this.disabledOptionsIndexes = [];
let index = 0;
_.each(this.props.sections, (section, sectionIndex) => {
_.each(section.data, (option, optionIndex) => {
allOptions.push({
...option,
sectionIndex,
index: optionIndex,
});
if (section.isDisabled || option.isDisabled) {
this.disabledOptionsIndexes.push(index);
}
index += 1;
});
});
return allOptions;
}
/**
* @param {Number} index
*/
updateFocusedIndex(index) {
this.setState({focusedIndex: index}, () => this.scrollToIndex(index));
}
/**
* Scrolls to the focused index within the SectionList
*
* @param {Number} index
* @param {Boolean} animated
*/
scrollToIndex(index, animated = true) {
const option = this.state.allOptions[index];
if (!this.list || !option) {
return;
}
const itemIndex = option.index;
const sectionIndex = option.sectionIndex;
// Note: react-native's SectionList automatically strips out any empty sections.
// So we need to reduce the sectionIndex to remove any empty sections in front of the one we're trying to scroll to.
// Otherwise, it will cause an index-out-of-bounds error and crash the app.
let adjustedSectionIndex = sectionIndex;
for (let i = 0; i < sectionIndex; i++) {
if (_.isEmpty(lodashGet(this.props.sections, `[${i}].data`))) {
adjustedSectionIndex--;
}
}
this.list.scrollToLocation({sectionIndex: adjustedSectionIndex, itemIndex, animated});
}
/**
* Completes the follow-up actions after a row is selected
*
* @param {Object} option
* @param {Object} ref
* @returns {Promise}
*/
selectRow(option, ref) {
return new Promise((resolve) => {
if (this.props.shouldShowTextInput && this.props.shouldFocusOnSelectRow) {
if (this.relatedTarget && ref === this.relatedTarget) {
this.textInput.focus();
this.relatedTarget = null;
}
if (this.textInput.isFocused()) {
setSelection(this.textInput, 0, this.props.value.length);
}
}
const selectedOption = this.props.onSelectRow(option);
resolve(selectedOption);
if (!this.props.canSelectMultipleOptions) {
return;
}
// Focus the first unselected item from the list (i.e: the best result according to the current search term)
this.setState({
focusedIndex: this.props.selectedOptions.length,
});
});
}
/**
* Completes the follow-up action after clicking on multiple select button
* @param {Object} option
*/
addToSelection(option) {
if (this.props.shouldShowTextInput && this.props.shouldFocusOnSelectRow) {
this.textInput.focus();
if (this.textInput.isFocused()) {
setSelection(this.textInput, 0, this.props.value.length);
}
}
this.props.onAddToSelection(option);
}
render() {
const shouldShowFooter =
!this.props.isReadOnly && (this.props.shouldShowConfirmButton || this.props.footerContent) && !(this.props.canSelectMultipleOptions && _.isEmpty(this.props.selectedOptions));
const defaultConfirmButtonText = _.isUndefined(this.props.confirmButtonText) ? this.props.translate('common.confirm') : this.props.confirmButtonText;
const shouldShowDefaultConfirmButton = !this.props.footerContent && defaultConfirmButtonText;
const safeAreaPaddingBottomStyle = shouldShowFooter ? undefined : this.props.safeAreaPaddingBottomStyle;
const textInput = (
<TextInput
ref={(el) => (this.textInput = el)}
value={this.props.value}
label={this.props.textInputLabel}
accessibilityLabel={this.props.textInputLabel}
accessibilityRole={CONST.ACCESSIBILITY_ROLE.TEXT}
onChangeText={this.props.onChangeText}
onSubmitEditing={this.selectFocusedOption}
placeholder={this.props.placeholderText}
maxLength={this.props.maxLength}
keyboardType={this.props.keyboardType}
onBlur={(e) => {
if (!this.props.shouldFocusOnSelectRow) {
return;
}
this.relatedTarget = e.relatedTarget;
}}
selectTextOnFocus
blurOnSubmit={Boolean(this.state.allOptions.length)}
spellCheck={false}
shouldInterceptSwipe={this.props.shouldTextInputInterceptSwipe}
/>
);
const optionsList = (
<OptionsList
ref={(el) => (this.list = el)}
optionHoveredStyle={this.props.optionHoveredStyle}
onSelectRow={this.props.onSelectRow ? this.selectRow : undefined}
sections={this.props.sections}
focusedIndex={this.state.focusedIndex}
selectedOptions={this.props.selectedOptions}
canSelectMultipleOptions={this.props.canSelectMultipleOptions}
shouldShowMultipleOptionSelectorAsButton={this.props.shouldShowMultipleOptionSelectorAsButton}
multipleOptionSelectorButtonText={this.props.multipleOptionSelectorButtonText}
onAddToSelection={this.addToSelection}
hideSectionHeaders={this.props.hideSectionHeaders}
headerMessage={this.props.headerMessage}
boldStyle={this.props.boldStyle}
showTitleTooltip={this.props.showTitleTooltip}
isDisabled={this.props.isDisabled}
shouldHaveOptionSeparator={this.props.shouldHaveOptionSeparator}
highlightSelectedOptions={this.props.highlightSelectedOptions}
onLayout={() => {
if (this.props.selectedOptions.length === 0) {
this.scrollToIndex(this.state.focusedIndex, false);
}
if (this.props.onLayout) {
this.props.onLayout();
}
}}
contentContainerStyles={[safeAreaPaddingBottomStyle, ...this.props.contentContainerStyles]}
listContainerStyles={this.props.listContainerStyles}
listStyles={this.props.listStyles}
isLoading={!this.props.shouldShowOptions}
showScrollIndicator={this.props.showScrollIndicator}
isRowMultilineSupported={this.props.isRowMultilineSupported}
/>
);
return (
<ArrowKeyFocusManager
disabledIndexes={this.disabledOptionsIndexes}
focusedIndex={this.state.focusedIndex}
maxIndex={this.state.allOptions.length - 1}
onFocusedIndexChanged={this.props.disableArrowKeysActions ? () => {} : this.updateFocusedIndex}
shouldResetIndexOnEndReached={false}
>
<View style={[styles.flexGrow1, styles.flexShrink1, styles.flexBasisAuto]}>
{this.props.shouldTextInputAppearBelowOptions ? (
<>
<View style={[styles.flexGrow0, styles.flexShrink1, styles.flexBasisAuto, styles.w100, styles.flexRow]}>{optionsList}</View>
<View style={this.props.shouldUseStyleForChildren ? [styles.ph5, styles.pv5, styles.flexGrow1, styles.flexShrink0] : []}>
{this.props.children}
{this.props.shouldShowTextInput && textInput}
</View>
</>
) : (
<>
<View style={this.props.shouldUseStyleForChildren ? [styles.ph5, styles.pb3] : []}>
{this.props.children}
{this.props.shouldShowTextInput && textInput}
</View>
{optionsList}
</>
)}
</View>
{shouldShowFooter && (
<FixedFooter>
{shouldShowDefaultConfirmButton && (
<Button
success
style={[styles.w100]}
text={defaultConfirmButtonText}
onPress={this.props.onConfirmSelection}
pressOnEnter
enterKeyEventListenerPriority={1}
/>
)}
{this.props.footerContent}
</FixedFooter>
)}
</ArrowKeyFocusManager>
);
}
}
BaseOptionsSelector.defaultProps = defaultProps;
BaseOptionsSelector.propTypes = propTypes;
export default compose(withLocalize, withNavigationFocus)(BaseOptionsSelector);