-
Notifications
You must be signed in to change notification settings - Fork 249
/
RecyclerFlatList.tsx
431 lines (390 loc) · 13.6 KB
/
RecyclerFlatList.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
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
import React from "react";
import {
StyleProp,
View,
ViewStyle,
RefreshControl,
FlatListProps,
LayoutChangeEvent,
} from "react-native";
import {
DataProvider,
ProgressiveListView,
RecyclerListView,
RecyclerListViewProps,
} from "recyclerlistview";
import AutoLayoutView, { BlankAreaEventHandler } from "./AutoLayoutView";
import ItemContainer from "./CellContainer";
import WrapperComponent from "./WrapperComponent";
import GridLayoutProviderWithProps from "./GridLayoutProviderWithProps";
import CustomError from "./errors/CustomError";
import ExceptionList from "./errors/ExceptionList";
export interface RecyclerFlatListProps<T> extends FlatListProps<T> {
// TODO: This is to make eslint silent. Out prettier and lint rules are conflicting.
/**
* Average or median size for elements in the list. Doesn't have to be very accurate but a good estimate can work better.
* For vertical lists provide average height and for horizontal average width.
*/
estimatedItemSize: number;
/**
* Visible height and width of the list. This is not the scroll content size.
*/
estimatedListSize?: { height: number; width: number };
/**
* Draw distance for advanced rendering (in dp/px)
*/
drawDistance?: number;
/**
* Allows developers to override type of items. This will improve recycling if you have different types of items in the list
* Right type will be used for the right item. Default type is 0
* If you don't want to change for an indexes just return undefined.
* Performance: This method is called very frequently. Keep it fast.
*/
overrideItemType?: (
item: T,
index: number,
extraData?: any
) => string | number | undefined;
/**
* with numColumns > 1 you can choose to increase span of some of the items. You can also modify estimated height for some items.
* Modify the given layout. Do not return.
* Performance: This method is called very frequently. Keep it fast.
*/
overrideItemLayout?: (
layout: { span?: number; size?: number },
item: T,
index: number,
maxColumns: number,
extraData?: any
) => void;
/**
* For debugging and exception use cases, internal props will be overriden with these values if used
*/
overrideProps?: object;
/**
* Computes blank space that is visible to the user during scroll or list load. If list doesn't have enough items to fill the screen even then this will be raised.
* Values reported: {
* offsetStart -> visible blank space on top of the screen (while going up). If value is greater than 0 then it's visible to user.
* offsetEnd -> visible blank space at the end of the screen (while going down). If value is greater than 0 then it's visible to user.
* blankArea -> max(offsetStart, offsetEnd) use this directly and look for values > 0
* }
* Please note that this event isn't synced with onScroll event but works with native onDraw/layoutSubviews. Events with values > 0 are blanks.
* This event is raised even when there is no visible blank with negative values for extensibility however, for most use cases check blankArea > 0 and use the value.
*/
onBlankArea?: BlankAreaEventHandler;
}
export interface RecyclerFlatListState<T> {
dataProvider: DataProvider;
numColumns: number;
layoutProvider: GridLayoutProviderWithProps<RecyclerFlatListProps<T>>;
data?: ReadonlyArray<T> | null;
extraData?: ExtraData<unknown>;
}
interface ExtraData<T> {
value?: T;
}
// eslint-disable-next-line @shopify/react-initialize-state
class RecyclerFlatList<T> extends React.PureComponent<
RecyclerFlatListProps<T>,
RecyclerFlatListState<T>
> {
private rlvRef?: RecyclerListView<RecyclerListViewProps, any>;
private listFixedDimensionSize = 0;
static defaultProps = {
data: [],
numColumns: 1,
};
constructor(props) {
super(props);
this.validateProps();
if (props.estimatedListSize) {
if (props.horizontal) {
this.listFixedDimensionSize = props.estimatedListSize.height;
} else {
this.listFixedDimensionSize = props.estimatedListSize.width;
}
}
}
private validateProps() {
if (this.props.onRefresh && typeof this.props.refreshing !== "boolean") {
throw new CustomError(ExceptionList.refreshBooleanMissing);
}
if (!(this.props.estimatedItemSize > 0)) {
throw new CustomError(ExceptionList.estimatedItemSizeMissing);
}
}
// Some of the state variables need to update when props change
static getDerivedStateFromProps<T>(
nextProps: RecyclerFlatListProps<T>,
prevState: RecyclerFlatListState<T> | undefined
): RecyclerFlatListState<T> {
const oldState = prevState || RecyclerFlatList.getInitialMutableState();
const newState = { ...oldState };
if (oldState.numColumns !== nextProps.numColumns) {
newState.numColumns = nextProps.numColumns || 1;
newState.layoutProvider = RecyclerFlatList.getLayoutProvider<T>(
newState.numColumns,
nextProps
);
}
if (nextProps.data !== oldState.data) {
newState.data = nextProps.data;
newState.dataProvider = oldState.dataProvider.cloneWithRows(
nextProps.data as any[]
);
newState.extraData = { ...oldState.extraData };
}
if (nextProps.extraData !== oldState.extraData?.value) {
newState.extraData = { value: nextProps.extraData };
}
newState.layoutProvider.updateProps(nextProps);
return newState;
}
private static getInitialMutableState<T>(): RecyclerFlatListState<T> {
return {
data: null,
layoutProvider: null!!,
dataProvider: new DataProvider((r1, r2) => {
return r1 !== r2;
}),
numColumns: 0,
};
}
// Using only grid layout provider as it can also act as a listview, sizeProvider is a function to support future overrides
private static getLayoutProvider<T>(
numColumns: number,
props: RecyclerFlatListProps<T>
) {
return new GridLayoutProviderWithProps<RecyclerFlatListProps<T>>(
// max span or, total columns
numColumns,
(index, props) => {
// type of the item for given index
const type = props.overrideItemType?.(
props.data!![index],
index,
props.extraData
);
return type || 0;
},
(index, props, mutableLayout) => {
// span of the item at given index, item can choose to span more than one column
props.overrideItemLayout?.(
mutableLayout,
props.data!![index],
index,
numColumns,
props.extraData
);
return mutableLayout?.span || 1;
},
(index, props, mutableLayout) => {
// estimated size of the item an given index
props.overrideItemLayout?.(
mutableLayout,
props.data!![index],
index,
numColumns,
props.extraData
);
return mutableLayout?.size || props.estimatedItemSize;
},
props
);
}
private onEndReached = () => {
// known issue: RLV doesn't report distanceFromEnd
this.props.onEndReached?.({ distanceFromEnd: 0 });
};
render() {
if (this.state.dataProvider.getSize() === 0) {
return this.props.ListEmptyComponent || null;
} else {
let style = this.props.style ?? {};
if (this.props.inverted === true) {
style = [style, { transform: [{ scaleY: -1 }] }];
}
let scrollViewProps: object = {
style,
onLayout: this.handleSizeChange,
removeClippedSubviews: false,
};
if (this.props.onRefresh) {
const refreshControl = (
<RefreshControl
refreshing={this.props.refreshing as boolean}
onRefresh={this.props.onRefresh}
/>
);
scrollViewProps = {
...scrollViewProps,
refreshControl,
};
}
const drawDistance = this.props.drawDistance || 250;
return (
<ProgressiveListView
{...this.props}
ref={this.recyclerRef}
layoutProvider={this.state.layoutProvider}
style={style as object}
dataProvider={this.state.dataProvider}
rowRenderer={this.rowRenderer}
renderFooter={this.footer}
canChangeSize
isHorizontal={Boolean(this.props.horizontal)}
scrollViewProps={scrollViewProps}
forceNonDeterministicRendering
renderItemContainer={this.itemContainer}
renderContentContainer={this.container}
onEndReached={this.onEndReached}
onEndReachedThreshold={this.props.onEndReachedThreshold || undefined}
extendedState={this.state.extraData}
layoutSize={this.props.estimatedListSize}
maxRenderAhead={3 * drawDistance}
finalRenderAheadOffset={drawDistance}
renderAheadStep={drawDistance}
initialRenderIndex={this.props.initialScrollIndex || undefined}
{...this.props.overrideProps}
/>
);
}
}
private handleSizeChange = (event: LayoutChangeEvent) => {
const newSize = this.props.horizontal
? event.nativeEvent.layout.height
: event.nativeEvent.layout.width;
const oldSize = this.listFixedDimensionSize;
this.listFixedDimensionSize = newSize;
// >0 check is to avoid rerender on mount where it would be redundant
if (oldSize > 0 && oldSize !== newSize) {
this.rlvRef?.forceRerender();
}
if (this.props.onLayout) {
this.props.onLayout(event);
}
};
private container = (props, children) => {
return (
<AutoLayoutView {...props} onBlankAreaEvent={this.props.onBlankArea}>
{children}
</AutoLayoutView>
);
};
private itemContainer = (props, parentProps, children) => {
return (
<ItemContainer {...props} index={parentProps.index}>
<WrapperComponent
extendedState={parentProps.extendedState}
internalSnapshot={parentProps.internalSnapshot}
dataHasChanged={parentProps.dataHasChanged}
data={parentProps.data}
>
{children}
</WrapperComponent>
</ItemContainer>
);
};
private separator(index) {
const leadingItem = this.props.data?.[index];
const trailingItem = this.props.data?.[index + 1];
const props = {
leadingItem,
trailingItem,
// TODO: Missing sections as we don't have this feature implemented yet. Implement section, leadingSection and trailingSection.
// https://github.com/facebook/react-native/blob/8bd3edec88148d0ab1f225d2119435681fbbba33/Libraries/Lists/VirtualizedSectionList.js#L285-L294
};
if (this.props.ItemSeparatorComponent != null) {
return <this.props.ItemSeparatorComponent {...props} />;
}
return undefined;
}
private header(index) {
if (index !== 0) return undefined;
const ListHeaderComponent = this.props.ListHeaderComponent;
const style = this.props.ListHeaderComponentStyle || {};
if (React.isValidElement(ListHeaderComponent)) {
ListHeaderComponent.props = { style };
return ListHeaderComponent;
} else if (ListHeaderComponent != null) {
return <ListHeaderComponent style={style} />;
}
}
private footer = () => {
const ListFooterComponent = this.props.ListFooterComponent;
const style = this.props.ListFooterComponentStyle || {};
if (React.isValidElement(ListFooterComponent)) {
ListFooterComponent.props = { style };
return ListFooterComponent;
} else if (ListFooterComponent) {
return <ListFooterComponent style={style} />;
}
return null;
};
private rowRenderer = (type, data, index, extraData) => {
// known issue: expected to pass separators which isn't available in RLV
const elem = this.props.renderItem?.({
item: data,
index,
extraData: extraData?.value,
} as any);
let elements = [this.header(index), elem];
const separator = this.separator(index);
if (separator != null) {
elements.push(separator);
}
let style: StyleProp<ViewStyle> = { flex: 1 };
if (this.props.inverted === true) {
elements = elements.reverse();
style = [style, { transform: [{ scaleY: -1 }] }];
}
return (
<View style={style}>
<>
{elements[0]}
{elements[1]}
{elements[2]}
</>
</View>
);
};
private recyclerRef = (ref: any) => {
this.rlvRef = ref;
};
// eslint-disable-next-line @shopify/react-prefer-private-members
public scrollToEnd(params?: { animated?: boolean | null | undefined }) {
this.rlvRef?.scrollToEnd(Boolean(params?.animated));
}
// eslint-disable-next-line @shopify/react-prefer-private-members
public scrollToIndex(params: {
animated?: boolean | null | undefined;
index: number;
viewOffset?: number | undefined;
viewPosition?: number | undefined;
}) {
// known issue: no support for view offset/position
this.rlvRef?.scrollToIndex(params.index, Boolean(params.animated));
}
// eslint-disable-next-line @shopify/react-prefer-private-members
public scrollToItem(params: {
animated?: boolean | null | undefined;
item: any;
viewPosition?: number | undefined;
}) {
this.rlvRef?.scrollToItem(params.item, Boolean(params.animated));
}
// eslint-disable-next-line @shopify/react-prefer-private-members
public scrollToOffset(params: {
animated?: boolean | null | undefined;
offset: number;
}) {
const x = this.props.horizontal ? params.offset : 0;
const y = this.props.horizontal ? 0 : params.offset;
this.rlvRef?.scrollToOffset(x, y, Boolean(params.animated));
}
// eslint-disable-next-line @shopify/react-prefer-private-members
public getScrollableNode(): number | null {
return this.rlvRef?.getScrollableNode?.() || null;
}
}
export default RecyclerFlatList;