-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
BaseOptionsList.tsx
302 lines (274 loc) · 12.2 KB
/
BaseOptionsList.tsx
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
import isEqual from 'lodash/isEqual';
import type {ForwardedRef} from 'react';
import React, {forwardRef, memo, useEffect, useRef} from 'react';
import type {SectionListRenderItem} from 'react-native';
import {View} from 'react-native';
import OptionRow from '@components/OptionRow';
import OptionsListSkeletonView from '@components/OptionsListSkeletonView';
import SectionList from '@components/SectionList';
import Text from '@components/Text';
import usePrevious from '@hooks/usePrevious';
import useThemeStyles from '@hooks/useThemeStyles';
import Timing from '@libs/actions/Timing';
import Performance from '@libs/Performance';
import type {OptionData} from '@libs/ReportUtils';
import StringUtils from '@libs/StringUtils';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import type {BaseOptionListProps, OptionsList, OptionsListData, Section} from './types';
function BaseOptionsList(
{
keyboardDismissMode = 'none',
onScrollBeginDrag = () => {},
onScroll = () => {},
listStyles,
focusedIndex = 0,
selectedOptions = [],
headerMessage = '',
isLoading = false,
sections = [],
onLayout,
hideSectionHeaders = false,
shouldHaveOptionSeparator = false,
showTitleTooltip = false,
optionHoveredStyle,
contentContainerStyles,
sectionHeaderStyle,
showScrollIndicator = true,
listContainerStyles: listContainerStylesProp,
shouldDisableRowInnerPadding = false,
shouldPreventDefaultFocusOnSelectRow = false,
disableFocusOptions = false,
canSelectMultipleOptions = false,
shouldShowMultipleOptionSelectorAsButton,
multipleOptionSelectorButtonText,
onAddToSelection,
highlightSelectedOptions = false,
onSelectRow,
boldStyle = false,
isDisabled = false,
isRowMultilineSupported = false,
isLoadingNewOptions = false,
nestedScrollEnabled = true,
bounces = true,
renderFooterContent,
}: BaseOptionListProps,
ref: ForwardedRef<OptionsList>,
) {
const styles = useThemeStyles();
const flattenedData = useRef<
Array<{
length: number;
offset: number;
}>
>([]);
const previousSections = usePrevious<OptionsListData[]>(sections);
const didLayout = useRef(false);
const listContainerStyles = listContainerStylesProp ?? [styles.flex1];
/**
* This helper function is used to memoize the computation needed for getItemLayout. It is run whenever section data changes.
*/
const buildFlatSectionArray = () => {
let offset = 0;
// Start with just an empty list header
const flatArray = [{length: 0, offset}];
// Build the flat array
for (const section of sections) {
// Add the section header
const sectionHeaderHeight = section.title && !hideSectionHeaders ? variables.optionsListSectionHeaderHeight : 0;
flatArray.push({length: sectionHeaderHeight, offset});
offset += sectionHeaderHeight;
// Add section items
for (let i = 0; i < section.data.length; i++) {
let fullOptionHeight = variables.optionRowHeight;
if (i > 0 && shouldHaveOptionSeparator) {
fullOptionHeight += variables.borderTopWidth;
}
flatArray.push({length: fullOptionHeight, offset});
offset += fullOptionHeight;
}
// Add the section footer
flatArray.push({length: 0, offset});
}
// Then add the list footer
flatArray.push({length: 0, offset});
return flatArray;
};
useEffect(() => {
if (isEqual(sections, previousSections)) {
return;
}
flattenedData.current = buildFlatSectionArray();
});
useEffect(() => {
if (isLoading) {
return;
}
// Mark the end of the search page load time. This data is collected only for Search page.
Timing.end(CONST.TIMING.OPEN_SEARCH);
Performance.markEnd(CONST.TIMING.OPEN_SEARCH);
}, [isLoading]);
const onViewableItemsChanged = () => {
if (didLayout.current || !onLayout) {
return;
}
didLayout.current = true;
onLayout();
};
/**
* 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 data - This is the same as the data we pass into the component
* @param 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}]
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
const getItemLayout = (_data: OptionsListData[] | null, flatDataArrayIndex: number) => {
if (!flattenedData.current[flatDataArrayIndex]) {
flattenedData.current = buildFlatSectionArray();
}
const targetItem = flattenedData.current[flatDataArrayIndex];
return {
length: targetItem.length,
offset: targetItem.offset,
index: flatDataArrayIndex,
};
};
/**
* Returns the key used by the list
*/
const extractKey = (option: OptionData) => option.keyForList ?? '';
/**
* Function which renders a row in the list
*
* @param {Object} params
* @param {Object} params.item
* @param {Number} params.index
* @param {Object} params.section
*
* @return {Component}
*/
const renderItem: SectionListRenderItem<OptionData, Section> = ({item, index, section}) => {
const isItemDisabled = isDisabled || !!section.isDisabled || !!item.isDisabled;
const isSelected = selectedOptions?.some((option) => {
if (option.accountID && option.accountID === item.accountID) {
return true;
}
if (option.reportID && option.reportID === item.reportID) {
return true;
}
if (option.policyID && option.policyID === item.policyID) {
return true;
}
if (!option.name || StringUtils.isEmptyString(option.name)) {
return false;
}
return option.name === item.searchText;
});
return (
<OptionRow
keyForList={item.keyForList ?? ''}
option={item}
showTitleTooltip={showTitleTooltip}
hoverStyle={optionHoveredStyle}
optionIsFocused={!disableFocusOptions && !isItemDisabled && focusedIndex === index + section.indexOffset}
onSelectRow={onSelectRow}
isSelected={isSelected}
showSelectedState={canSelectMultipleOptions}
shouldShowSelectedStateAsButton={shouldShowMultipleOptionSelectorAsButton}
selectedStateButtonText={multipleOptionSelectorButtonText}
onSelectedStatePressed={onAddToSelection}
highlightSelected={highlightSelectedOptions}
boldStyle={item.boldStyle ?? boldStyle}
isDisabled={isItemDisabled}
shouldHaveOptionSeparator={index > 0 && shouldHaveOptionSeparator}
shouldDisableRowInnerPadding={shouldDisableRowInnerPadding}
shouldPreventDefaultFocusOnSelectRow={shouldPreventDefaultFocusOnSelectRow}
isMultilineSupported={isRowMultilineSupported}
/>
);
};
/**
* Function which renders a section header component
*/
const renderSectionHeader = ({section: {title, shouldShow}}: {section: OptionsListData}) => {
if (!title && shouldShow && !hideSectionHeaders && sectionHeaderStyle) {
return <View style={sectionHeaderStyle} />;
}
if (title && shouldShow && !hideSectionHeaders) {
return (
// Note: The `optionsListSectionHeader` style provides an explicit height to section headers.
// We do this so that we can reference the height in `getItemLayout` –
// we need to know the heights of all list items up-front in order to synchronously compute the layout of any given list item.
// So be aware that if you adjust the content of the section header (for example, change the font size), you may need to adjust this explicit height as well.
<View style={[styles.optionsListSectionHeader, styles.justifyContentCenter, sectionHeaderStyle]}>
<Text style={[styles.ph5, styles.textLabelSupporting]}>{title}</Text>
</View>
);
}
return <View />;
};
return (
<View style={listContainerStyles}>
{isLoading ? (
<OptionsListSkeletonView shouldAnimate />
) : (
<>
{/* If we are loading new options we will avoid showing any header message. This is mostly because one of the header messages says there are no options. */}
{/* This is misleading because we might be in the process of loading fresh options from the server. */}
{!isLoadingNewOptions && headerMessage ? (
<View style={[styles.ph5, styles.pb5]}>
<Text style={[styles.textLabel, styles.colorMuted]}>{headerMessage}</Text>
</View>
) : null}
<SectionList<OptionData, Section>
ref={ref}
style={listStyles}
indicatorStyle="white"
keyboardShouldPersistTaps="always"
keyboardDismissMode={keyboardDismissMode}
nestedScrollEnabled={nestedScrollEnabled}
scrollEnabled={nestedScrollEnabled}
onScrollBeginDrag={onScrollBeginDrag}
onScroll={onScroll}
contentContainerStyle={contentContainerStyles}
showsVerticalScrollIndicator={showScrollIndicator}
sections={sections}
keyExtractor={extractKey}
stickySectionHeadersEnabled={false}
renderItem={renderItem}
getItemLayout={getItemLayout}
renderSectionHeader={renderSectionHeader}
extraData={focusedIndex}
initialNumToRender={12}
maxToRenderPerBatch={CONST.MAX_TO_RENDER_PER_BATCH.DEFAULT}
windowSize={5}
viewabilityConfig={{viewAreaCoveragePercentThreshold: 95}}
onViewableItemsChanged={onViewableItemsChanged}
bounces={bounces}
ListFooterComponent={renderFooterContent}
testID="options-list"
/>
</>
)}
</View>
);
}
BaseOptionsList.displayName = 'BaseOptionsList';
// using memo to avoid unnecessary rerenders when parents component rerenders (thus causing this component to rerender because shallow comparison is used for some props).
export default memo(
forwardRef(BaseOptionsList),
(prevProps, nextProps) =>
nextProps.focusedIndex === prevProps.focusedIndex &&
nextProps?.selectedOptions?.length === prevProps?.selectedOptions?.length &&
nextProps.headerMessage === prevProps.headerMessage &&
nextProps.isLoading === prevProps.isLoading &&
isEqual(nextProps.sections, prevProps.sections),
);