-
Notifications
You must be signed in to change notification settings - Fork 3k
/
BaseSelectionListRadio.js
277 lines (242 loc) · 11.4 KB
/
BaseSelectionListRadio.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
import React, {useEffect, useRef, useState} from 'react';
import {View} from 'react-native';
import _ from 'underscore';
import lodashGet from 'lodash/get';
import SectionList from '../SectionList';
import Text from '../Text';
import styles from '../../styles/styles';
import TextInput from '../TextInput';
import ArrowKeyFocusManager from '../ArrowKeyFocusManager';
import CONST from '../../CONST';
import variables from '../../styles/variables';
import {propTypes as selectionListRadioPropTypes, defaultProps as selectionListRadioDefaultProps} from './selectionListRadioPropTypes';
import RadioListItem from './RadioListItem';
import useKeyboardShortcut from '../../hooks/useKeyboardShortcut';
import SafeAreaConsumer from '../SafeAreaConsumer';
import withKeyboardState, {keyboardStatePropTypes} from '../withKeyboardState';
const propTypes = {
...keyboardStatePropTypes,
...selectionListRadioPropTypes,
};
function BaseSelectionListRadio(props) {
const firstLayoutRef = useRef(true);
const listRef = useRef(null);
const textInputRef = useRef(null);
const focusTimeoutRef = useRef(null);
const shouldShowTextInput = Boolean(props.textInputLabel);
/**
* Iterates through the sections and items inside each section, and builds 3 arrays along the way:
* - `allOptions`: Contains all the items in the list, flattened, regardless of section
* - `disabledOptionsIndexes`: Contains the indexes of all the disabled items in the list, to be used by the ArrowKeyFocusManager
* - `itemLayouts`: Contains the layout information for each item, header and footer in the list,
* so we can calculate the position of any given item when scrolling programmatically
*
* @return {{itemLayouts: [{offset: number, length: number}], disabledOptionsIndexes: *[], allOptions: *[]}}
*/
const getFlattenedSections = () => {
const allOptions = [];
const disabledOptionsIndexes = [];
let disabledIndex = 0;
let offset = 0;
const itemLayouts = [{length: 0, offset}];
_.each(props.sections, (section, sectionIndex) => {
// We're not rendering any section header, but we need to push to the array
// because React Native accounts for it in getItemLayout
const sectionHeaderHeight = 0;
itemLayouts.push({length: sectionHeaderHeight, offset});
offset += sectionHeaderHeight;
_.each(section.data, (option, optionIndex) => {
// Add item to the general flattened array
allOptions.push({
...option,
sectionIndex,
index: optionIndex,
});
// If disabled, add to the disabled indexes array
if (section.isDisabled || option.isDisabled) {
disabledOptionsIndexes.push(disabledIndex);
}
disabledIndex += 1;
// Account for the height of the item in getItemLayout
const fullItemHeight = variables.optionRowHeight;
itemLayouts.push({length: fullItemHeight, offset});
offset += fullItemHeight;
});
// We're not rendering any section footer, but we need to push to the array
// because React Native accounts for it in getItemLayout
itemLayouts.push({length: 0, offset});
});
// We're not rendering the list footer, but we need to push to the array
// because React Native accounts for it in getItemLayout
itemLayouts.push({length: 0, offset});
return {
allOptions,
disabledOptionsIndexes,
itemLayouts,
};
};
const flattenedSections = getFlattenedSections();
const [focusedIndex, setFocusedIndex] = useState(() => {
const defaultIndex = 0;
const indexOfInitiallyFocusedOption = _.findIndex(flattenedSections.allOptions, (option) => option.keyForList === props.initiallyFocusedOptionKey);
if (indexOfInitiallyFocusedOption >= 0) {
return indexOfInitiallyFocusedOption;
}
return defaultIndex;
});
/**
* Scrolls to the desired item index in the section list
*
* @param {Number} index - the index of the item to scroll to
* @param {Boolean} animated - whether to animate the scroll
*/
const scrollToIndex = (index, animated) => {
const item = flattenedSections.allOptions[index];
if (!listRef.current || !item) {
return;
}
const itemIndex = item.index;
const sectionIndex = item.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(props.sections, `[${i}].data`))) {
adjustedSectionIndex--;
}
}
listRef.current.scrollToLocation({sectionIndex: adjustedSectionIndex, itemIndex, animated});
};
/**
* This function is used to compute the layout of any given item in our list.
* We need to implement it so that we can programmatically scroll to items outside the virtual render window of the SectionList.
*
* @param {Array} data - This is the same as the data we pass into the component
* @param {Number} flatDataArrayIndex - This index is provided by React Native, and refers to a flat array with data from all the sections. This flat array has some quirks:
*
* 1. It ALWAYS includes a list header and a list footer, even if we don't provide/render those.
* 2. Each section includes a header, even if we don't provide/render one.
*
* For example, given a list with two sections, two items in each section, no header, no footer, and no section headers, the flat array might look something like this:
*
* [{header}, {sectionHeader}, {item}, {item}, {sectionHeader}, {item}, {item}, {footer}]
*
* @returns {Object}
*/
const getItemLayout = (data, flatDataArrayIndex) => {
const targetItem = flattenedSections.itemLayouts[flatDataArrayIndex];
return {
length: targetItem.length,
offset: targetItem.offset,
index: flatDataArrayIndex,
};
};
const renderItem = ({item, index, section}) => {
const isFocused = focusedIndex === index + lodashGet(section, 'indexOffset', 0);
return (
<RadioListItem
item={item}
isFocused={isFocused}
onSelectRow={props.onSelectRow}
/>
);
};
/** Focuses the text input when the component mounts. If `props.shouldDelayFocus` is true, we wait for the animation to finish */
useEffect(() => {
if (shouldShowTextInput) {
if (props.shouldDelayFocus) {
focusTimeoutRef.current = setTimeout(() => textInputRef.current.focus(), CONST.ANIMATED_TRANSITION);
} else {
textInputRef.current.focus();
}
}
return () => {
if (!focusTimeoutRef.current) {
return;
}
clearTimeout(focusTimeoutRef.current);
};
}, [props.shouldDelayFocus, shouldShowTextInput]);
const selectFocusedOption = () => {
const focusedOption = flattenedSections.allOptions[focusedIndex];
if (!focusedOption) {
return;
}
props.onSelectRow(focusedOption);
};
useKeyboardShortcut(CONST.KEYBOARD_SHORTCUTS.ENTER, selectFocusedOption, {
captureOnInputs: true,
shouldBubble: () => !flattenedSections.allOptions[focusedIndex],
});
return (
<ArrowKeyFocusManager
disabledIndexes={flattenedSections.disabledOptionsIndexes}
focusedIndex={focusedIndex}
maxIndex={flattenedSections.allOptions.length - 1}
onFocusedIndexChanged={(newFocusedIndex) => {
setFocusedIndex(newFocusedIndex);
scrollToIndex(newFocusedIndex, true);
}}
>
<SafeAreaConsumer>
{({safeAreaPaddingBottomStyle}) => (
<View style={[styles.flex1, !props.isKeyboardShown && safeAreaPaddingBottomStyle]}>
{shouldShowTextInput && (
<View style={[styles.ph5, styles.pb3]}>
<TextInput
ref={textInputRef}
label={props.textInputLabel}
accessibilityLabel={props.textInputLabel}
accessibilityRole={CONST.ACCESSIBILITY_ROLE.TEXT}
value={props.textInputValue}
placeholder={props.textInputPlaceholder}
maxLength={props.textInputMaxLength}
onChangeText={props.onChangeText}
keyboardType={props.keyboardType}
selectTextOnFocus
spellCheck={false}
onSubmitEditing={selectFocusedOption}
/>
</View>
)}
{Boolean(props.headerMessage) && (
<View style={[styles.ph5, styles.pb5]}>
<Text style={[styles.textLabel, styles.colorMuted]}>{props.headerMessage}</Text>
</View>
)}
<SectionList
ref={listRef}
sections={props.sections}
renderItem={renderItem}
getItemLayout={getItemLayout}
onScroll={props.onScroll}
onScrollBeginDrag={props.onScrollBeginDrag}
keyExtractor={(item) => item.keyForList}
extraData={focusedIndex}
indicatorStyle="white"
keyboardShouldPersistTaps="always"
showsVerticalScrollIndicator={false}
OP
initialNumToRender={12}
maxToRenderPerBatch={5}
windowSize={5}
viewabilityConfig={{viewAreaCoveragePercentThreshold: 95}}
onLayout={() => {
if (!firstLayoutRef.current) {
return;
}
scrollToIndex(focusedIndex, false);
firstLayoutRef.current = false;
}}
/>
</View>
)}
</SafeAreaConsumer>
</ArrowKeyFocusManager>
);
}
BaseSelectionListRadio.displayName = 'BaseSelectionListRadio';
BaseSelectionListRadio.propTypes = propTypes;
BaseSelectionListRadio.defaultProps = selectionListRadioDefaultProps;
export default withKeyboardState(BaseSelectionListRadio);