-
Notifications
You must be signed in to change notification settings - Fork 24.4k
/
VirtualizedList.js
1940 lines (1827 loc) · 62.1 KB
/
VirtualizedList.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const Batchinator = require('../Interaction/Batchinator');
const FillRateHelper = require('./FillRateHelper');
const PropTypes = require('prop-types');
const React = require('react');
const ReactNative = require('../Renderer/shims/ReactNative');
const RefreshControl = require('../Components/RefreshControl/RefreshControl');
const ScrollView = require('../Components/ScrollView/ScrollView');
const StyleSheet = require('../StyleSheet/StyleSheet');
const View = require('../Components/View/View');
const ViewabilityHelper = require('./ViewabilityHelper');
const flattenStyle = require('../StyleSheet/flattenStyle');
const infoLog = require('../Utilities/infoLog');
const invariant = require('invariant');
const warning = require('fbjs/lib/warning');
const {computeWindowedRenderLimits} = require('./VirtualizeUtils');
import type {ViewStyleProp} from '../StyleSheet/StyleSheet';
import type {
ViewabilityConfig,
ViewToken,
ViewabilityConfigCallbackPair,
} from './ViewabilityHelper';
type Item = any;
export type Separators = {
highlight: () => void,
unhighlight: () => void,
updateProps: (select: 'leading' | 'trailing', newProps: Object) => void,
};
export type RenderItemProps<ItemT> = {
item: ItemT,
index: number,
separators: Separators,
};
export type RenderItemType<ItemT> = (
info: RenderItemProps<ItemT>,
) => React.Node;
type ViewabilityHelperCallbackTuple = {
viewabilityHelper: ViewabilityHelper,
onViewableItemsChanged: (info: {
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
}) => void,
};
type RequiredProps = {
/**
* The default accessor functions assume this is an Array<{key: string} | {id: string}> but you can override
* getItem, getItemCount, and keyExtractor to handle any type of index-based data.
*/
data?: any,
/**
* A generic accessor for extracting an item from any sort of data blob.
*/
getItem: (data: any, index: number) => ?Item,
/**
* Determines how many items are in the data blob.
*/
getItemCount: (data: any) => number,
};
type OptionalProps = {
// TODO: Conflicts with the optional `renderItem` in
// `VirtualizedSectionList`'s props.
renderItem?: $FlowFixMe<?RenderItemType<Item>>,
/**
* `debug` will turn on extra logging and visual overlays to aid with debugging both usage and
* implementation, but with a significant perf hit.
*/
debug?: ?boolean,
/**
* DEPRECATED: Virtualization provides significant performance and memory optimizations, but fully
* unmounts react instances that are outside of the render window. You should only need to disable
* this for debugging purposes.
*/
disableVirtualization?: ?boolean,
/**
* A marker property for telling the list to re-render (since it implements `PureComponent`). If
* any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the
* `data` prop, stick it here and treat it immutably.
*/
extraData?: any,
getItemLayout?: (
data: any,
index: number,
) => {length: number, offset: number, index: number}, // e.g. height, y
horizontal?: ?boolean,
/**
* How many items to render in the initial batch. This should be enough to fill the screen but not
* much more. Note these items will never be unmounted as part of the windowed rendering in order
* to improve perceived performance of scroll-to-top actions.
*/
initialNumToRender: number,
/**
* Instead of starting at the top with the first item, start at `initialScrollIndex`. This
* disables the "scroll to top" optimization that keeps the first `initialNumToRender` items
* always rendered and immediately renders the items starting at this initial index. Requires
* `getItemLayout` to be implemented.
*/
initialScrollIndex?: ?number,
/**
* Reverses the direction of scroll. Uses scale transforms of -1.
*/
inverted?: ?boolean,
keyExtractor: (item: Item, index: number) => string,
/**
* Each cell is rendered using this element. Can be a React Component Class,
* or a render function. Defaults to using View.
*/
CellRendererComponent?: ?React.ComponentType<any>,
/**
* Each data item is rendered using this element. Can be a React Component Class,
* or a render function.
*/
ListItemComponent?: ?React.ComponentType<any>,
/**
* Rendered when the list is empty. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListEmptyComponent?: ?(React.ComponentType<any> | React.Element<any>),
/**
* Rendered at the bottom of all the items. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListFooterComponent?: ?(React.ComponentType<any> | React.Element<any>),
/**
* Styling for internal View for ListFooterComponent
*/
ListFooterComponentStyle?: ViewStyleProp,
/**
* Rendered at the top of all the items. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListHeaderComponent?: ?(React.ComponentType<any> | React.Element<any>),
/**
* Styling for internal View for ListHeaderComponent
*/
ListHeaderComponentStyle?: ViewStyleProp,
/**
* A unique identifier for this list. If there are multiple VirtualizedLists at the same level of
* nesting within another VirtualizedList, this key is necessary for virtualization to
* work properly.
*/
listKey?: string,
/**
* The maximum number of items to render in each incremental render batch. The more rendered at
* once, the better the fill rate, but responsiveness my suffer because rendering content may
* interfere with responding to button taps or other interactions.
*/
maxToRenderPerBatch: number,
onEndReached?: ?(info: {distanceFromEnd: number}) => void,
onEndReachedThreshold?: ?number, // units of visible length
onLayout?: ?Function,
/**
* If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make
* sure to also set the `refreshing` prop correctly.
*/
onRefresh?: ?Function,
/**
* Used to handle failures when scrolling to an index that has not been measured yet. Recommended
* action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and
* then try again after more items have been rendered.
*/
onScrollToIndexFailed?: ?(info: {
index: number,
highestMeasuredFrameIndex: number,
averageItemLength: number,
}) => void,
/**
* Called when the viewability of rows changes, as defined by the
* `viewabilityConfig` prop.
*/
onViewableItemsChanged?: ?(info: {
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
}) => void,
persistentScrollbar?: ?boolean,
/**
* Set this when offset is needed for the loading indicator to show correctly.
* @platform android
*/
progressViewOffset?: number,
/**
* A custom refresh control element. When set, it overrides the default
* <RefreshControl> component built internally. The onRefresh and refreshing
* props are also ignored. Only works for vertical VirtualizedList.
*/
refreshControl?: ?React.Element<any>,
/**
* Set this true while waiting for new data from a refresh.
*/
refreshing?: ?boolean,
/**
* Note: may have bugs (missing content) in some circumstances - use at your own risk.
*
* This may improve scroll performance for large lists.
*/
removeClippedSubviews?: boolean,
/**
* Render a custom scroll component, e.g. with a differently styled `RefreshControl`.
*/
renderScrollComponent?: (props: Object) => React.Element<any>,
/**
* Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off
* screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`.
*/
updateCellsBatchingPeriod: number,
viewabilityConfig?: ViewabilityConfig,
/**
* List of ViewabilityConfig/onViewableItemsChanged pairs. A specific onViewableItemsChanged
* will be called when its corresponding ViewabilityConfig's conditions are met.
*/
viewabilityConfigCallbackPairs?: Array<ViewabilityConfigCallbackPair>,
/**
* Determines the maximum number of items rendered outside of the visible area, in units of
* visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will
* render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing
* this number will reduce memory consumption and may improve performance, but will increase the
* chance that fast scrolling may reveal momentary blank areas of unrendered content.
*/
windowSize: number,
};
/* $FlowFixMe - this Props seems to be missing a bunch of stuff. Remove this
* comment to see the errors */
export type Props = RequiredProps & OptionalProps;
let _usedIndexForKey = false;
let _keylessItemComponentName: string = '';
type Frame = {
offset: number,
length: number,
index: number,
inLayout: boolean,
};
type ChildListState = {
first: number,
last: number,
frames: {[key: number]: Frame},
};
type State = {first: number, last: number};
/**
* Base implementation for the more convenient [`<FlatList>`](/react-native/docs/flatlist.html)
* and [`<SectionList>`](/react-native/docs/sectionlist.html) components, which are also better
* documented. In general, this should only really be used if you need more flexibility than
* `FlatList` provides, e.g. for use with immutable data instead of plain arrays.
*
* Virtualization massively improves memory consumption and performance of large lists by
* maintaining a finite render window of active items and replacing all items outside of the render
* window with appropriately sized blank space. The window adapts to scrolling behavior, and items
* are rendered incrementally with low-pri (after any running interactions) if they are far from the
* visible area, or with hi-pri otherwise to minimize the potential of seeing blank space.
*
* Some caveats:
*
* - Internal state is not preserved when content scrolls out of the render window. Make sure all
* your data is captured in the item data or external stores like Flux, Redux, or Relay.
* - This is a `PureComponent` which means that it will not re-render if `props` remain shallow-
* equal. Make sure that everything your `renderItem` function depends on is passed as a prop
* (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on
* changes. This includes the `data` prop and parent component state.
* - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
* offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see
* blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
* and we are working on improving it behind the scenes.
* - By default, the list looks for a `key` or `id` prop on each item and uses that for the React key.
* Alternatively, you can provide a custom `keyExtractor` prop.
*
*/
class VirtualizedList extends React.PureComponent<Props, State> {
props: Props;
// scrollToEnd may be janky without getItemLayout prop
scrollToEnd(params?: ?{animated?: ?boolean}) {
const animated = params ? params.animated : true;
const veryLast = this.props.getItemCount(this.props.data) - 1;
const frame = this._getFrameMetricsApprox(veryLast);
const offset = Math.max(
0,
frame.offset +
frame.length +
this._footerLength -
this._scrollMetrics.visibleLength,
);
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error when upgrading Flow's support for React. To see the
* error delete this comment and run Flow. */
this._scrollRef.scrollTo(
this.props.horizontal ? {x: offset, animated} : {y: offset, animated},
);
}
// scrollToIndex may be janky without getItemLayout prop
scrollToIndex(params: {
animated?: ?boolean,
index: number,
viewOffset?: number,
viewPosition?: number,
}) {
const {
data,
horizontal,
getItemCount,
getItemLayout,
onScrollToIndexFailed,
} = this.props;
const {animated, index, viewOffset, viewPosition} = params;
invariant(
index >= 0 && index < getItemCount(data),
`scrollToIndex out of range: ${index} vs ${getItemCount(data) - 1}`,
);
if (!getItemLayout && index > this._highestMeasuredFrameIndex) {
invariant(
!!onScrollToIndexFailed,
'scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, ' +
'otherwise there is no way to know the location of offscreen indices or handle failures.',
);
onScrollToIndexFailed({
averageItemLength: this._averageCellLength,
highestMeasuredFrameIndex: this._highestMeasuredFrameIndex,
index,
});
return;
}
const frame = this._getFrameMetricsApprox(index);
const offset =
Math.max(
0,
frame.offset -
(viewPosition || 0) *
(this._scrollMetrics.visibleLength - frame.length),
) - (viewOffset || 0);
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error when upgrading Flow's support for React. To see the
* error delete this comment and run Flow. */
this._scrollRef.scrollTo(
horizontal ? {x: offset, animated} : {y: offset, animated},
);
}
// scrollToItem may be janky without getItemLayout prop. Required linear scan through items -
// use scrollToIndex instead if possible.
scrollToItem(params: {
animated?: ?boolean,
item: Item,
viewPosition?: number,
}) {
const {item} = params;
const {data, getItem, getItemCount} = this.props;
const itemCount = getItemCount(data);
for (let index = 0; index < itemCount; index++) {
if (getItem(data, index) === item) {
this.scrollToIndex({...params, index});
break;
}
}
}
/**
* Scroll to a specific content pixel offset in the list.
*
* Param `offset` expects the offset to scroll to.
* In case of `horizontal` is true, the offset is the x-value,
* in any other case the offset is the y-value.
*
* Param `animated` (`true` by default) defines whether the list
* should do an animation while scrolling.
*/
scrollToOffset(params: {animated?: ?boolean, offset: number}) {
const {animated, offset} = params;
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error when upgrading Flow's support for React. To see the
* error delete this comment and run Flow. */
this._scrollRef.scrollTo(
this.props.horizontal ? {x: offset, animated} : {y: offset, animated},
);
}
recordInteraction() {
this._nestedChildLists.forEach(childList => {
childList.ref && childList.ref.recordInteraction();
});
this._viewabilityTuples.forEach(t => {
t.viewabilityHelper.recordInteraction();
});
this._updateViewableItems(this.props.data);
}
flashScrollIndicators() {
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error when upgrading Flow's support for React. To see the
* error delete this comment and run Flow. */
this._scrollRef.flashScrollIndicators();
}
/**
* Provides a handle to the underlying scroll responder.
* Note that `this._scrollRef` might not be a `ScrollView`, so we
* need to check that it responds to `getScrollResponder` before calling it.
*/
getScrollResponder() {
if (this._scrollRef && this._scrollRef.getScrollResponder) {
return this._scrollRef.getScrollResponder();
}
}
getScrollableNode() {
if (this._scrollRef && this._scrollRef.getScrollableNode) {
return this._scrollRef.getScrollableNode();
} else {
return ReactNative.findNodeHandle(this._scrollRef);
}
}
getScrollRef() {
if (this._scrollRef && this._scrollRef.getScrollRef) {
return this._scrollRef.getScrollRef();
} else {
return this._scrollRef;
}
}
setNativeProps(props: Object) {
if (this._scrollRef) {
this._scrollRef.setNativeProps(props);
}
}
static defaultProps = {
disableVirtualization: false,
horizontal: false,
initialNumToRender: 10,
keyExtractor: (item: Item, index: number) => {
if (item.key != null) {
return item.key;
}
if (item.id != null) {
return item.id;
}
_usedIndexForKey = true;
if (item.type && item.type.displayName) {
_keylessItemComponentName = item.type.displayName;
}
return String(index);
},
maxToRenderPerBatch: 10,
onEndReachedThreshold: 2, // multiples of length
scrollEventThrottle: 50,
updateCellsBatchingPeriod: 50,
windowSize: 21, // multiples of length
};
static contextTypes = {
virtualizedCell: PropTypes.shape({
cellKey: PropTypes.string,
}),
virtualizedList: PropTypes.shape({
getScrollMetrics: PropTypes.func,
horizontal: PropTypes.bool,
getOutermostParentListRef: PropTypes.func,
getNestedChildState: PropTypes.func,
registerAsNestedChild: PropTypes.func,
unregisterAsNestedChild: PropTypes.func,
}),
};
static childContextTypes = {
virtualizedList: PropTypes.shape({
getScrollMetrics: PropTypes.func,
horizontal: PropTypes.bool,
getOutermostParentListRef: PropTypes.func,
getNestedChildState: PropTypes.func,
registerAsNestedChild: PropTypes.func,
unregisterAsNestedChild: PropTypes.func,
}),
};
getChildContext() {
return {
virtualizedList: {
getScrollMetrics: this._getScrollMetrics,
horizontal: this.props.horizontal,
getOutermostParentListRef: this._getOutermostParentListRef,
getNestedChildState: this._getNestedChildState,
registerAsNestedChild: this._registerAsNestedChild,
unregisterAsNestedChild: this._unregisterAsNestedChild,
},
};
}
_getCellKey(): string {
return (
(this.context.virtualizedCell && this.context.virtualizedCell.cellKey) ||
'rootList'
);
}
_getScrollMetrics = () => {
return this._scrollMetrics;
};
hasMore(): boolean {
return this._hasMore;
}
_getOutermostParentListRef = () => {
if (this._isNestedWithSameOrientation()) {
return this.context.virtualizedList.getOutermostParentListRef();
} else {
return this;
}
};
_getNestedChildState = (key: string): ?ChildListState => {
const existingChildData = this._nestedChildLists.get(key);
return existingChildData && existingChildData.state;
};
_registerAsNestedChild = (childList: {
cellKey: string,
key: string,
ref: VirtualizedList,
}): ?ChildListState => {
// Register the mapping between this child key and the cellKey for its cell
const childListsInCell =
this._cellKeysToChildListKeys.get(childList.cellKey) || new Set();
childListsInCell.add(childList.key);
this._cellKeysToChildListKeys.set(childList.cellKey, childListsInCell);
const existingChildData = this._nestedChildLists.get(childList.key);
if (existingChildData && existingChildData.ref !== null) {
console.error(
'A VirtualizedList contains a cell which itself contains ' +
'more than one VirtualizedList of the same orientation as the parent ' +
'list. You must pass a unique listKey prop to each sibling list.',
);
}
this._nestedChildLists.set(childList.key, {
ref: childList.ref,
state: null,
});
if (this._hasInteracted) {
childList.ref.recordInteraction();
}
};
_unregisterAsNestedChild = (childList: {
key: string,
state: ChildListState,
}): void => {
this._nestedChildLists.set(childList.key, {
ref: null,
state: childList.state,
});
};
state: State;
constructor(props: Props, context: Object) {
super(props, context);
invariant(
!props.onScroll || !props.onScroll.__isNative,
'Components based on VirtualizedList must be wrapped with Animated.createAnimatedComponent ' +
'to support native onScroll events with useNativeDriver',
);
invariant(
props.windowSize > 0,
'VirtualizedList: The windowSize prop must be present and set to a value greater than 0.',
);
this._fillRateHelper = new FillRateHelper(this._getFrameMetrics);
this._updateCellsToRenderBatcher = new Batchinator(
this._updateCellsToRender,
this.props.updateCellsBatchingPeriod,
);
if (this.props.viewabilityConfigCallbackPairs) {
this._viewabilityTuples = this.props.viewabilityConfigCallbackPairs.map(
pair => ({
viewabilityHelper: new ViewabilityHelper(pair.viewabilityConfig),
onViewableItemsChanged: pair.onViewableItemsChanged,
}),
);
} else if (this.props.onViewableItemsChanged) {
this._viewabilityTuples.push({
viewabilityHelper: new ViewabilityHelper(this.props.viewabilityConfig),
onViewableItemsChanged: this.props.onViewableItemsChanged,
});
}
let initialState = {
first: this.props.initialScrollIndex || 0,
last:
Math.min(
this.props.getItemCount(this.props.data),
(this.props.initialScrollIndex || 0) + this.props.initialNumToRender,
) - 1,
};
if (this._isNestedWithSameOrientation()) {
const storedState = this.context.virtualizedList.getNestedChildState(
this.props.listKey || this._getCellKey(),
);
if (storedState) {
initialState = storedState;
this.state = storedState;
this._frames = storedState.frames;
}
}
this.state = initialState;
}
componentDidMount() {
if (this._isNestedWithSameOrientation()) {
this.context.virtualizedList.registerAsNestedChild({
cellKey: this._getCellKey(),
key: this.props.listKey || this._getCellKey(),
ref: this,
});
}
}
componentWillUnmount() {
if (this._isNestedWithSameOrientation()) {
this.context.virtualizedList.unregisterAsNestedChild({
key: this.props.listKey || this._getCellKey(),
state: {
first: this.state.first,
last: this.state.last,
frames: this._frames,
},
});
}
this._updateViewableItems(null);
this._updateCellsToRenderBatcher.dispose({abort: true});
this._viewabilityTuples.forEach(tuple => {
tuple.viewabilityHelper.dispose();
});
this._fillRateHelper.deactivateAndFlush();
}
static getDerivedStateFromProps(newProps: Props, prevState: State) {
const {data, getItemCount, maxToRenderPerBatch} = newProps;
// first and last could be stale (e.g. if a new, shorter items props is passed in), so we make
// sure we're rendering a reasonable range here.
return {
first: Math.max(
0,
Math.min(prevState.first, getItemCount(data) - 1 - maxToRenderPerBatch),
),
last: Math.max(0, Math.min(prevState.last, getItemCount(data) - 1)),
};
}
_pushCells(
cells: Array<Object>,
stickyHeaderIndices: Array<number>,
stickyIndicesFromProps: Set<number>,
first: number,
last: number,
inversionStyle: ViewStyleProp,
) {
const {
CellRendererComponent,
ItemSeparatorComponent,
data,
getItem,
getItemCount,
horizontal,
keyExtractor,
} = this.props;
const stickyOffset = this.props.ListHeaderComponent ? 1 : 0;
const end = getItemCount(data) - 1;
let prevCellKey;
last = Math.min(end, last);
for (let ii = first; ii <= last; ii++) {
const item = getItem(data, ii);
const key = keyExtractor(item, ii);
this._indicesToKeys.set(ii, key);
if (stickyIndicesFromProps.has(ii + stickyOffset)) {
stickyHeaderIndices.push(cells.length);
}
cells.push(
<CellRenderer
CellRendererComponent={CellRendererComponent}
ItemSeparatorComponent={ii < end ? ItemSeparatorComponent : undefined}
cellKey={key}
fillRateHelper={this._fillRateHelper}
horizontal={horizontal}
index={ii}
inversionStyle={inversionStyle}
item={item}
key={key}
prevCellKey={prevCellKey}
onUpdateSeparators={this._onUpdateSeparators}
onLayout={e => this._onCellLayout(e, key, ii)}
onUnmount={this._onCellUnmount}
parentProps={this.props}
ref={ref => {
this._cellRefs[key] = ref;
}}
/>,
);
prevCellKey = key;
}
}
_onUpdateSeparators = (keys: Array<?string>, newProps: Object) => {
keys.forEach(key => {
const ref = key != null && this._cellRefs[key];
ref && ref.updateSeparatorProps(newProps);
});
};
_isVirtualizationDisabled(): boolean {
return this.props.disableVirtualization || false;
}
_isNestedWithSameOrientation(): boolean {
const nestedContext = this.context.virtualizedList;
return !!(
nestedContext && !!nestedContext.horizontal === !!this.props.horizontal
);
}
render() {
if (__DEV__) {
const flatStyles = flattenStyle(this.props.contentContainerStyle);
warning(
flatStyles == null || flatStyles.flexWrap !== 'wrap',
'`flexWrap: `wrap`` is not supported with the `VirtualizedList` components.' +
'Consider using `numColumns` with `FlatList` instead.',
);
}
const {
ListEmptyComponent,
ListFooterComponent,
ListHeaderComponent,
} = this.props;
const {data, horizontal} = this.props;
const isVirtualizationDisabled = this._isVirtualizationDisabled();
const inversionStyle = this.props.inverted
? this.props.horizontal
? styles.horizontallyInverted
: styles.verticallyInverted
: null;
const cells = [];
const stickyIndicesFromProps = new Set(this.props.stickyHeaderIndices);
const stickyHeaderIndices = [];
if (ListHeaderComponent) {
if (stickyIndicesFromProps.has(0)) {
stickyHeaderIndices.push(0);
}
const element = React.isValidElement(ListHeaderComponent) ? (
ListHeaderComponent
) : (
// $FlowFixMe
<ListHeaderComponent />
);
cells.push(
<VirtualizedCellWrapper
cellKey={this._getCellKey() + '-header'}
key="$header">
<View
onLayout={this._onLayoutHeader}
style={StyleSheet.compose(
inversionStyle,
this.props.ListHeaderComponentStyle,
)}>
{
// $FlowFixMe - Typing ReactNativeComponent revealed errors
element
}
</View>
</VirtualizedCellWrapper>,
);
}
const itemCount = this.props.getItemCount(data);
if (itemCount > 0) {
_usedIndexForKey = false;
_keylessItemComponentName = '';
const spacerKey = !horizontal ? 'height' : 'width';
const lastInitialIndex = this.props.initialScrollIndex
? -1
: this.props.initialNumToRender - 1;
const {first, last} = this.state;
this._pushCells(
cells,
stickyHeaderIndices,
stickyIndicesFromProps,
0,
lastInitialIndex,
inversionStyle,
);
const firstAfterInitial = Math.max(lastInitialIndex + 1, first);
if (!isVirtualizationDisabled && first > lastInitialIndex + 1) {
let insertedStickySpacer = false;
if (stickyIndicesFromProps.size > 0) {
const stickyOffset = ListHeaderComponent ? 1 : 0;
// See if there are any sticky headers in the virtualized space that we need to render.
for (let ii = firstAfterInitial - 1; ii > lastInitialIndex; ii--) {
if (stickyIndicesFromProps.has(ii + stickyOffset)) {
const initBlock = this._getFrameMetricsApprox(lastInitialIndex);
const stickyBlock = this._getFrameMetricsApprox(ii);
const leadSpace =
stickyBlock.offset -
initBlock.offset -
(this.props.initialScrollIndex ? 0 : initBlock.length);
cells.push(
<View key="$sticky_lead" style={{[spacerKey]: leadSpace}} />,
);
this._pushCells(
cells,
stickyHeaderIndices,
stickyIndicesFromProps,
ii,
ii,
inversionStyle,
);
const trailSpace =
this._getFrameMetricsApprox(first).offset -
(stickyBlock.offset + stickyBlock.length);
cells.push(
<View key="$sticky_trail" style={{[spacerKey]: trailSpace}} />,
);
insertedStickySpacer = true;
break;
}
}
}
if (!insertedStickySpacer) {
const initBlock = this._getFrameMetricsApprox(lastInitialIndex);
const firstSpace =
this._getFrameMetricsApprox(first).offset -
(initBlock.offset + initBlock.length);
cells.push(
<View key="$lead_spacer" style={{[spacerKey]: firstSpace}} />,
);
}
}
this._pushCells(
cells,
stickyHeaderIndices,
stickyIndicesFromProps,
firstAfterInitial,
last,
inversionStyle,
);
if (!this._hasWarned.keys && _usedIndexForKey) {
console.warn(
'VirtualizedList: missing keys for items, make sure to specify a key or id property on each ' +
'item or provide a custom keyExtractor.',
_keylessItemComponentName,
);
this._hasWarned.keys = true;
}
if (!isVirtualizationDisabled && last < itemCount - 1) {
const lastFrame = this._getFrameMetricsApprox(last);
// Without getItemLayout, we limit our tail spacer to the _highestMeasuredFrameIndex to
// prevent the user for hyperscrolling into un-measured area because otherwise content will
// likely jump around as it renders in above the viewport.
const end = this.props.getItemLayout
? itemCount - 1
: Math.min(itemCount - 1, this._highestMeasuredFrameIndex);
const endFrame = this._getFrameMetricsApprox(end);
const tailSpacerLength =
endFrame.offset +
endFrame.length -
(lastFrame.offset + lastFrame.length);
cells.push(
<View key="$tail_spacer" style={{[spacerKey]: tailSpacerLength}} />,
);
}
} else if (ListEmptyComponent) {
const element: React.Element<any> = ((React.isValidElement(
ListEmptyComponent,
) ? (
ListEmptyComponent
) : (
// $FlowFixMe
<ListEmptyComponent />
)): any);
cells.push(
React.cloneElement(element, {
key: '$empty',
onLayout: event => {
this._onLayoutEmpty(event);
if (element.props.onLayout) {
element.props.onLayout(event);
}
},
style: StyleSheet.compose(
inversionStyle,
element.props.style,
),
}),
);
}
if (ListFooterComponent) {
const element = React.isValidElement(ListFooterComponent) ? (
ListFooterComponent
) : (
// $FlowFixMe
<ListFooterComponent />
);
cells.push(
<VirtualizedCellWrapper
cellKey={this._getCellKey() + '-footer'}
key="$footer">
<View
onLayout={this._onLayoutFooter}
style={StyleSheet.compose(
inversionStyle,
this.props.ListFooterComponentStyle,
)}>
{
// $FlowFixMe - Typing ReactNativeComponent revealed errors
element
}
</View>
</VirtualizedCellWrapper>,
);
}
const scrollProps = {
...this.props,
onContentSizeChange: this._onContentSizeChange,
onLayout: this._onLayout,
onScroll: this._onScroll,
onScrollBeginDrag: this._onScrollBeginDrag,
onScrollEndDrag: this._onScrollEndDrag,
onMomentumScrollEnd: this._onMomentumScrollEnd,
scrollEventThrottle: this.props.scrollEventThrottle, // TODO: Android support
invertStickyHeaders:
this.props.invertStickyHeaders !== undefined
? this.props.invertStickyHeaders
: this.props.inverted,
stickyHeaderIndices,
};
if (inversionStyle) {
/* $FlowFixMe(>=0.70.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.70 was deployed. To see the error delete
* this comment and run Flow. */
scrollProps.style = [inversionStyle, this.props.style];
}
this._hasMore =
this.state.last < this.props.getItemCount(this.props.data) - 1;
const innerRet = React.cloneElement(
(this.props.renderScrollComponent || this._defaultRenderScrollComponent)(
scrollProps,
),
{
ref: this._captureScrollRef,
},
cells,
);
let ret = innerRet;
if (__DEV__) {
ret = (
<ScrollView.Context.Consumer>
{scrollContext => {
if (
scrollContext != null &&
!this._hasWarned.nesting &&
this.context.virtualizedList == null
) {
// TODO (T46547044): use React.warn once 16.9 is sync'd: https://github.com/facebook/react/pull/15170
console.warn(
'VirtualizedLists should never be nested inside a plain ScrollView - use another VirtualizedList-backed container instead.',
);
this._hasWarned.nesting = true;
}
return innerRet;
}}
</ScrollView.Context.Consumer>
);
}