-
Notifications
You must be signed in to change notification settings - Fork 24.3k
/
VirtualizedList.js
2002 lines (1831 loc) · 63.5 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) Meta Platforms, Inc. and 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
*/
import type {CellMetricProps, ListOrientation} from './ListMetricsAggregator';
import type {ViewToken} from './ViewabilityHelper';
import type {
Item,
Props,
RenderItemProps,
RenderItemType,
Separators,
} from './VirtualizedListProps';
import type {ScrollResponderType} from 'react-native/Libraries/Components/ScrollView/ScrollView';
import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
import type {
LayoutEvent,
ScrollEvent,
} from 'react-native/Libraries/Types/CoreEventTypes';
import Batchinator from '../Interaction/Batchinator';
import clamp from '../Utilities/clamp';
import infoLog from '../Utilities/infoLog';
import {CellRenderMask} from './CellRenderMask';
import ChildListCollection from './ChildListCollection';
import FillRateHelper from './FillRateHelper';
import ListMetricsAggregator from './ListMetricsAggregator';
import StateSafePureComponent from './StateSafePureComponent';
import ViewabilityHelper from './ViewabilityHelper';
import CellRenderer from './VirtualizedListCellRenderer';
import {
VirtualizedListCellContextProvider,
VirtualizedListContext,
VirtualizedListContextProvider,
} from './VirtualizedListContext.js';
import {
horizontalOrDefault,
initialNumToRenderOrDefault,
maxToRenderPerBatchOrDefault,
onEndReachedThresholdOrDefault,
onStartReachedThresholdOrDefault,
windowSizeOrDefault,
} from './VirtualizedListProps';
import {
computeWindowedRenderLimits,
keyExtractor as defaultKeyExtractor,
} from './VirtualizeUtils';
import invariant from 'invariant';
import nullthrows from 'nullthrows';
import * as React from 'react';
import {
I18nManager,
Platform,
RefreshControl,
ScrollView,
StyleSheet,
View,
findNodeHandle,
} from 'react-native';
export type {RenderItemProps, RenderItemType, Separators};
const ON_EDGE_REACHED_EPSILON = 0.001;
let _usedIndexForKey = false;
let _keylessItemComponentName: string = '';
type ViewabilityHelperCallbackTuple = {
viewabilityHelper: ViewabilityHelper,
onViewableItemsChanged: (info: {
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
...
}) => void,
...
};
type State = {
renderMask: CellRenderMask,
cellsAroundViewport: {first: number, last: number},
// Used to track items added at the start of the list for maintainVisibleContentPosition.
firstVisibleItemKey: ?string,
// When > 0 the scroll position available in JS is considered stale and should not be used.
pendingScrollUpdateCount: number,
};
function getScrollingThreshold(threshold: number, visibleLength: number) {
return (threshold * visibleLength) / 2;
}
/**
* Base implementation for the more convenient [`<FlatList>`](https://reactnative.dev/docs/flatlist)
* and [`<SectionList>`](https://reactnative.dev/docs/sectionlist) 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.
* - As an effort to remove defaultProps, use helper functions when referencing certain props
*
*/
class VirtualizedList extends StateSafePureComponent<Props, State> {
static contextType: typeof VirtualizedListContext = VirtualizedListContext;
// 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;
if (veryLast < 0) {
return;
}
const frame = this._listMetrics.getCellMetricsApprox(veryLast, this.props);
const offset = Math.max(
0,
frame.offset +
frame.length +
this._footerLength -
this._scrollMetrics.visibleLength,
);
// TODO: consider using `ref.scrollToEnd` directly
this.scrollToOffset({animated, offset});
}
// scrollToIndex may be janky without getItemLayout prop
scrollToIndex(params: {
animated?: ?boolean,
index: number,
viewOffset?: number,
viewPosition?: number,
...
}): $FlowFixMe {
const {data, getItemCount, getItemLayout, onScrollToIndexFailed} =
this.props;
const {animated, index, viewOffset, viewPosition} = params;
invariant(
index >= 0,
`scrollToIndex out of range: requested index ${index} but minimum is 0`,
);
invariant(
getItemCount(data) >= 1,
`scrollToIndex out of range: item length ${getItemCount(
data,
)} but minimum is 1`,
);
invariant(
index < getItemCount(data),
`scrollToIndex out of range: requested index ${index} is out of 0 to ${
getItemCount(data) - 1
}`,
);
if (
!getItemLayout &&
index > this._listMetrics.getHighestMeasuredCellIndex()
) {
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._listMetrics.getAverageCellLength(),
highestMeasuredFrameIndex:
this._listMetrics.getHighestMeasuredCellIndex(),
index,
});
return;
}
const frame = this._listMetrics.getCellMetricsApprox(
Math.floor(index),
this.props,
);
const offset =
Math.max(
0,
this._listMetrics.getCellOffsetApprox(index, this.props) -
(viewPosition || 0) *
(this._scrollMetrics.visibleLength - frame.length),
) - (viewOffset || 0);
this.scrollToOffset({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,
viewOffset?: number,
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;
const scrollRef = this._scrollRef;
if (scrollRef == null) {
return;
}
if (scrollRef.scrollTo == null) {
console.warn(
'No scrollTo method provided. This may be because you have two nested ' +
'VirtualizedLists with the same orientation, or because you are ' +
'using a custom component that does not implement scrollTo.',
);
return;
}
const {horizontal, rtl} = this._orientation();
if (horizontal && rtl && !this._listMetrics.hasContentLength()) {
console.warn(
'scrollToOffset may not be called in RTL before content is laid out',
);
return;
}
scrollRef.scrollTo({
animated,
...this._scrollToParamsFromOffset(offset),
});
}
_scrollToParamsFromOffset(offset: number): {x?: number, y?: number} {
const {horizontal, rtl} = this._orientation();
if (horizontal && rtl) {
// Add the visible length of the scrollview so that the offset is right-aligned
const cartOffset = this._listMetrics.cartesianOffset(
offset + this._scrollMetrics.visibleLength,
);
return horizontal ? {x: cartOffset} : {y: cartOffset};
} else {
return horizontal ? {x: offset} : {y: offset};
}
}
recordInteraction() {
this._nestedChildLists.forEach(childList => {
childList.recordInteraction();
});
this._viewabilityTuples.forEach(t => {
t.viewabilityHelper.recordInteraction();
});
this._updateViewableItems(this.props, this.state.cellsAroundViewport);
}
flashScrollIndicators() {
if (this._scrollRef == null) {
return;
}
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(): ?ScrollResponderType {
if (this._scrollRef && this._scrollRef.getScrollResponder) {
return this._scrollRef.getScrollResponder();
}
}
getScrollableNode(): ?number {
if (this._scrollRef && this._scrollRef.getScrollableNode) {
return this._scrollRef.getScrollableNode();
} else {
return findNodeHandle(this._scrollRef);
}
}
getScrollRef():
| ?React.ElementRef<typeof ScrollView>
| ?React.ElementRef<typeof View> {
if (this._scrollRef && this._scrollRef.getScrollRef) {
return this._scrollRef.getScrollRef();
} else {
return this._scrollRef;
}
}
setNativeProps(props: Object) {
if (this._scrollRef) {
this._scrollRef.setNativeProps(props);
}
}
_getCellKey(): string {
return this.context?.cellKey || 'rootList';
}
// $FlowFixMe[missing-local-annot]
_getScrollMetrics = () => {
return this._scrollMetrics;
};
hasMore(): boolean {
return this._hasMore;
}
// $FlowFixMe[missing-local-annot]
_getOutermostParentListRef = () => {
if (this._isNestedWithSameOrientation()) {
return this.context.getOutermostParentListRef();
} else {
return this;
}
};
_registerAsNestedChild = (childList: {
cellKey: string,
ref: React.ElementRef<typeof VirtualizedList>,
}): void => {
this._nestedChildLists.add(childList.ref, childList.cellKey);
if (this._hasInteracted) {
childList.ref.recordInteraction();
}
};
_unregisterAsNestedChild = (childList: {
ref: React.ElementRef<typeof VirtualizedList>,
}): void => {
this._nestedChildLists.remove(childList.ref);
};
state: State;
constructor(props: Props) {
super(props);
this._checkProps(props);
this._fillRateHelper = new FillRateHelper(this._listMetrics);
this._updateCellsToRenderBatcher = new Batchinator(
this._updateCellsToRender,
this.props.updateCellsBatchingPeriod ?? 50,
);
if (this.props.viewabilityConfigCallbackPairs) {
this._viewabilityTuples = this.props.viewabilityConfigCallbackPairs.map(
pair => ({
viewabilityHelper: new ViewabilityHelper(pair.viewabilityConfig),
onViewableItemsChanged: pair.onViewableItemsChanged,
}),
);
} else {
const {onViewableItemsChanged, viewabilityConfig} = this.props;
if (onViewableItemsChanged) {
this._viewabilityTuples.push({
viewabilityHelper: new ViewabilityHelper(viewabilityConfig),
onViewableItemsChanged: onViewableItemsChanged,
});
}
}
const initialRenderRegion = VirtualizedList._initialRenderRegion(props);
const minIndexForVisible =
this.props.maintainVisibleContentPosition?.minIndexForVisible ?? 0;
this.state = {
cellsAroundViewport: initialRenderRegion,
renderMask: VirtualizedList._createRenderMask(props, initialRenderRegion),
firstVisibleItemKey:
this.props.getItemCount(this.props.data) > minIndexForVisible
? VirtualizedList._getItemKey(this.props, minIndexForVisible)
: null,
// When we have a non-zero initialScrollIndex, we will receive a
// scroll event later so this will prevent the window from updating
// until we get a valid offset.
pendingScrollUpdateCount:
this.props.initialScrollIndex != null &&
this.props.initialScrollIndex > 0
? 1
: 0,
};
}
_checkProps(props: Props) {
const {onScroll, windowSize, getItemCount, data, initialScrollIndex} =
props;
invariant(
// $FlowFixMe[prop-missing]
!onScroll || !onScroll.__isNative,
'Components based on VirtualizedList must be wrapped with Animated.createAnimatedComponent ' +
'to support native onScroll events with useNativeDriver',
);
invariant(
windowSizeOrDefault(windowSize) > 0,
'VirtualizedList: The windowSize prop must be present and set to a value greater than 0.',
);
invariant(
getItemCount,
'VirtualizedList: The "getItemCount" prop must be provided',
);
const itemCount = getItemCount(data);
if (
initialScrollIndex != null &&
!this._hasTriggeredInitialScrollToIndex &&
(initialScrollIndex < 0 ||
(itemCount > 0 && initialScrollIndex >= itemCount)) &&
!this._hasWarned.initialScrollIndex
) {
console.warn(
`initialScrollIndex "${initialScrollIndex}" is not valid (list has ${itemCount} items)`,
);
this._hasWarned.initialScrollIndex = true;
}
if (__DEV__ && !this._hasWarned.flexWrap) {
// $FlowFixMe[underconstrained-implicit-instantiation]
const flatStyles = StyleSheet.flatten(this.props.contentContainerStyle);
if (flatStyles != null && flatStyles.flexWrap === 'wrap') {
console.warn(
'`flexWrap: `wrap`` is not supported with the `VirtualizedList` components.' +
'Consider using `numColumns` with `FlatList` instead.',
);
this._hasWarned.flexWrap = true;
}
}
}
static _findItemIndexWithKey(
props: Props,
key: string,
hint: ?number,
): ?number {
const itemCount = props.getItemCount(props.data);
if (hint != null && hint >= 0 && hint < itemCount) {
const curKey = VirtualizedList._getItemKey(props, hint);
if (curKey === key) {
return hint;
}
}
for (let ii = 0; ii < itemCount; ii++) {
const curKey = VirtualizedList._getItemKey(props, ii);
if (curKey === key) {
return ii;
}
}
return null;
}
static _getItemKey(
props: {
data: Props['data'],
getItem: Props['getItem'],
keyExtractor: Props['keyExtractor'],
...
},
index: number,
): string {
const item = props.getItem(props.data, index);
return VirtualizedList._keyExtractor(item, index, props);
}
static _createRenderMask(
props: Props,
cellsAroundViewport: {first: number, last: number},
additionalRegions?: ?$ReadOnlyArray<{first: number, last: number}>,
): CellRenderMask {
const itemCount = props.getItemCount(props.data);
invariant(
cellsAroundViewport.first >= 0 &&
cellsAroundViewport.last >= cellsAroundViewport.first - 1 &&
cellsAroundViewport.last < itemCount,
`Invalid cells around viewport "[${cellsAroundViewport.first}, ${cellsAroundViewport.last}]" was passed to VirtualizedList._createRenderMask`,
);
const renderMask = new CellRenderMask(itemCount);
if (itemCount > 0) {
const allRegions = [cellsAroundViewport, ...(additionalRegions ?? [])];
for (const region of allRegions) {
renderMask.addCells(region);
}
// The initially rendered cells are retained as part of the
// "scroll-to-top" optimization
if (props.initialScrollIndex == null || props.initialScrollIndex <= 0) {
const initialRegion = VirtualizedList._initialRenderRegion(props);
renderMask.addCells(initialRegion);
}
// The layout coordinates of sticker headers may be off-screen while the
// actual header is on-screen. Keep the most recent before the viewport
// rendered, even if its layout coordinates are not in viewport.
const stickyIndicesSet = new Set(props.stickyHeaderIndices);
VirtualizedList._ensureClosestStickyHeader(
props,
stickyIndicesSet,
renderMask,
cellsAroundViewport.first,
);
}
return renderMask;
}
static _initialRenderRegion(props: Props): {first: number, last: number} {
const itemCount = props.getItemCount(props.data);
const firstCellIndex = Math.max(
0,
Math.min(itemCount - 1, Math.floor(props.initialScrollIndex ?? 0)),
);
const lastCellIndex =
Math.min(
itemCount,
firstCellIndex + initialNumToRenderOrDefault(props.initialNumToRender),
) - 1;
return {
first: firstCellIndex,
last: lastCellIndex,
};
}
static _ensureClosestStickyHeader(
props: Props,
stickyIndicesSet: Set<number>,
renderMask: CellRenderMask,
cellIdx: number,
) {
const stickyOffset = props.ListHeaderComponent ? 1 : 0;
for (let itemIdx = cellIdx - 1; itemIdx >= 0; itemIdx--) {
if (stickyIndicesSet.has(itemIdx + stickyOffset)) {
renderMask.addCells({first: itemIdx, last: itemIdx});
break;
}
}
}
_adjustCellsAroundViewport(
props: Props,
cellsAroundViewport: {first: number, last: number},
pendingScrollUpdateCount: number,
): {first: number, last: number} {
const {data, getItemCount} = props;
const onEndReachedThreshold = onEndReachedThresholdOrDefault(
props.onEndReachedThreshold,
);
const {offset, visibleLength} = this._scrollMetrics;
const contentLength = this._listMetrics.getContentLength();
const distanceFromEnd = contentLength - visibleLength - offset;
// Wait until the scroll view metrics have been set up. And until then,
// we will trust the initialNumToRender suggestion
if (visibleLength <= 0 || contentLength <= 0) {
return cellsAroundViewport.last >= getItemCount(data)
? VirtualizedList._constrainToItemCount(cellsAroundViewport, props)
: cellsAroundViewport;
}
let newCellsAroundViewport: {first: number, last: number};
if (props.disableVirtualization) {
const renderAhead =
distanceFromEnd < onEndReachedThreshold * visibleLength
? maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch)
: 0;
newCellsAroundViewport = {
first: 0,
last: Math.min(
cellsAroundViewport.last + renderAhead,
getItemCount(data) - 1,
),
};
} else {
// If we have a pending scroll update, we should not adjust the render window as it
// might override the correct window.
if (pendingScrollUpdateCount > 0) {
return cellsAroundViewport.last >= getItemCount(data)
? VirtualizedList._constrainToItemCount(cellsAroundViewport, props)
: cellsAroundViewport;
}
newCellsAroundViewport = computeWindowedRenderLimits(
props,
maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch),
windowSizeOrDefault(props.windowSize),
cellsAroundViewport,
this._listMetrics,
this._scrollMetrics,
);
invariant(
newCellsAroundViewport.last < getItemCount(data),
'computeWindowedRenderLimits() should return range in-bounds',
);
}
if (this._nestedChildLists.size() > 0) {
// If some cell in the new state has a child list in it, we should only render
// up through that item, so that we give that list a chance to render.
// Otherwise there's churn from multiple child lists mounting and un-mounting
// their items.
// Will this prevent rendering if the nested list doesn't realize the end?
const childIdx = this._findFirstChildWithMore(
newCellsAroundViewport.first,
newCellsAroundViewport.last,
);
newCellsAroundViewport.last = childIdx ?? newCellsAroundViewport.last;
}
return newCellsAroundViewport;
}
_findFirstChildWithMore(first: number, last: number): number | null {
for (let ii = first; ii <= last; ii++) {
const cellKeyForIndex = this._indicesToKeys.get(ii);
if (
cellKeyForIndex != null &&
this._nestedChildLists.anyInCell(cellKeyForIndex, childList =>
childList.hasMore(),
)
) {
return ii;
}
}
return null;
}
componentDidMount() {
if (this._isNestedWithSameOrientation()) {
this.context.registerAsNestedChild({
ref: this,
cellKey: this.context.cellKey,
});
}
}
componentWillUnmount() {
if (this._isNestedWithSameOrientation()) {
this.context.unregisterAsNestedChild({ref: this});
}
this._updateCellsToRenderBatcher.dispose({abort: true});
this._viewabilityTuples.forEach(tuple => {
tuple.viewabilityHelper.dispose();
});
this._fillRateHelper.deactivateAndFlush();
}
static getDerivedStateFromProps(newProps: Props, prevState: State): State {
// 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.
const itemCount = newProps.getItemCount(newProps.data);
if (itemCount === prevState.renderMask.numCells()) {
return prevState;
}
let maintainVisibleContentPositionAdjustment: ?number = null;
const prevFirstVisibleItemKey = prevState.firstVisibleItemKey;
const minIndexForVisible =
newProps.maintainVisibleContentPosition?.minIndexForVisible ?? 0;
const newFirstVisibleItemKey =
newProps.getItemCount(newProps.data) > minIndexForVisible
? VirtualizedList._getItemKey(newProps, minIndexForVisible)
: null;
if (
newProps.maintainVisibleContentPosition != null &&
prevFirstVisibleItemKey != null &&
newFirstVisibleItemKey != null
) {
if (newFirstVisibleItemKey !== prevFirstVisibleItemKey) {
// Fast path if items were added at the start of the list.
const hint =
itemCount - prevState.renderMask.numCells() + minIndexForVisible;
const firstVisibleItemIndex = VirtualizedList._findItemIndexWithKey(
newProps,
prevFirstVisibleItemKey,
hint,
);
maintainVisibleContentPositionAdjustment =
firstVisibleItemIndex != null
? firstVisibleItemIndex - minIndexForVisible
: null;
} else {
maintainVisibleContentPositionAdjustment = null;
}
}
const constrainedCells = VirtualizedList._constrainToItemCount(
maintainVisibleContentPositionAdjustment != null
? {
first:
prevState.cellsAroundViewport.first +
maintainVisibleContentPositionAdjustment,
last:
prevState.cellsAroundViewport.last +
maintainVisibleContentPositionAdjustment,
}
: prevState.cellsAroundViewport,
newProps,
);
return {
cellsAroundViewport: constrainedCells,
renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells),
firstVisibleItemKey: newFirstVisibleItemKey,
pendingScrollUpdateCount:
maintainVisibleContentPositionAdjustment != null
? prevState.pendingScrollUpdateCount + 1
: prevState.pendingScrollUpdateCount,
};
}
_pushCells(
cells: Array<Object>,
stickyHeaderIndices: Array<number>,
stickyIndicesFromProps: Set<number>,
first: number,
last: number,
inversionStyle: ViewStyleProp,
) {
const {
CellRendererComponent,
ItemSeparatorComponent,
ListHeaderComponent,
ListItemComponent,
data,
debug,
getItem,
getItemCount,
getItemLayout,
horizontal,
renderItem,
} = this.props;
const stickyOffset = 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 = VirtualizedList._keyExtractor(item, ii, this.props);
this._indicesToKeys.set(ii, key);
if (stickyIndicesFromProps.has(ii + stickyOffset)) {
stickyHeaderIndices.push(cells.length);
}
const shouldListenForLayout =
getItemLayout == null || debug || this._fillRateHelper.enabled();
cells.push(
<CellRenderer
CellRendererComponent={CellRendererComponent}
ItemSeparatorComponent={ii < end ? ItemSeparatorComponent : undefined}
ListItemComponent={ListItemComponent}
cellKey={key}
horizontal={horizontal}
index={ii}
inversionStyle={inversionStyle}
item={item}
key={key}
prevCellKey={prevCellKey}
onUpdateSeparators={this._onUpdateSeparators}
onCellFocusCapture={this._onCellFocusCapture}
onUnmount={this._onCellUnmount}
ref={ref => {
this._cellRefs[key] = ref;
}}
renderItem={renderItem}
{...(shouldListenForLayout && {
onCellLayout: this._onCellLayout,
})}
/>,
);
prevCellKey = key;
}
}
static _constrainToItemCount(
cells: {first: number, last: number},
props: Props,
): {first: number, last: number} {
const itemCount = props.getItemCount(props.data);
const lastPossibleCellIndex = itemCount - 1;
// Constraining `last` may significantly shrink the window. Adjust `first`
// to expand the window if the new `last` results in a new window smaller
// than the number of cells rendered per batch.
const maxToRenderPerBatch = maxToRenderPerBatchOrDefault(
props.maxToRenderPerBatch,
);
const maxFirst = Math.max(0, lastPossibleCellIndex - maxToRenderPerBatch);
return {
first: clamp(0, cells.first, maxFirst),
last: Math.min(lastPossibleCellIndex, cells.last),
};
}
_onUpdateSeparators = (keys: Array<?string>, newProps: Object) => {
keys.forEach(key => {
const ref = key != null && this._cellRefs[key];
ref && ref.updateSeparatorProps(newProps);
});
};
_isNestedWithSameOrientation(): boolean {
const nestedContext = this.context;
return !!(
nestedContext &&
!!nestedContext.horizontal === horizontalOrDefault(this.props.horizontal)
);
}
_getSpacerKey = (isVertical: boolean): string =>
isVertical ? 'height' : 'width';
static _keyExtractor(
item: Item,
index: number,
props: {
keyExtractor?: ?(item: Item, index: number) => string,
...
},
): string {
if (props.keyExtractor != null) {
return props.keyExtractor(item, index);
}
const key = defaultKeyExtractor(item, index);
if (key === String(index)) {
_usedIndexForKey = true;
if (item.type && item.type.displayName) {
_keylessItemComponentName = item.type.displayName;
}
}
return key;
}
render(): React.Node {
this._checkProps(this.props);
const {ListEmptyComponent, ListFooterComponent, ListHeaderComponent} =
this.props;
const {data, horizontal} = this.props;
const inversionStyle = this.props.inverted
? horizontalOrDefault(this.props.horizontal)
? styles.horizontallyInverted
: styles.verticallyInverted
: null;
const cells: Array<any | React.Node> = [];
const stickyIndicesFromProps = new Set(this.props.stickyHeaderIndices);
const stickyHeaderIndices = [];
// 1. Add cell for ListHeaderComponent
if (ListHeaderComponent) {
if (stickyIndicesFromProps.has(0)) {
stickyHeaderIndices.push(0);
}
const element = React.isValidElement(ListHeaderComponent) ? (
ListHeaderComponent
) : (
// $FlowFixMe[not-a-component]
// $FlowFixMe[incompatible-type-arg]
<ListHeaderComponent />
);
cells.push(
<VirtualizedListCellContextProvider
cellKey={this._getCellKey() + '-header'}
key="$header">
<View
// We expect that header component will be a single native view so make it
// not collapsable to avoid this view being flattened and make this assumption
// no longer true.
collapsable={false}
onLayout={this._onLayoutHeader}
style={StyleSheet.compose(
inversionStyle,
this.props.ListHeaderComponentStyle,
)}>
{
// $FlowFixMe[incompatible-type] - Typing ReactNativeComponent revealed errors
element
}
</View>
</VirtualizedListCellContextProvider>,
);
}
// 2a. Add a cell for ListEmptyComponent if applicable
const itemCount = this.props.getItemCount(data);
if (itemCount === 0 && ListEmptyComponent) {
const element: React.Element<any> = ((React.isValidElement(
ListEmptyComponent,
) ? (
ListEmptyComponent
) : (
// $FlowFixMe[not-a-component]
// $FlowFixMe[incompatible-type-arg]
<ListEmptyComponent />
)): any);
cells.push(
<VirtualizedListCellContextProvider
cellKey={this._getCellKey() + '-empty'}
key="$empty">
{React.cloneElement(element, {
onLayout: (event: LayoutEvent) => {
this._onLayoutEmpty(event);
// $FlowFixMe[prop-missing] React.Element internal inspection
if (element.props.onLayout) {
element.props.onLayout(event);
}
},
// $FlowFixMe[prop-missing] React.Element internal inspection
style: StyleSheet.compose(inversionStyle, element.props.style),
})}
</VirtualizedListCellContextProvider>,
);
}
// 2b. Add cells and spacers for each item
if (itemCount > 0) {
_usedIndexForKey = false;
_keylessItemComponentName = '';
const spacerKey = this._getSpacerKey(!horizontal);
const renderRegions = this.state.renderMask.enumerateRegions();
const lastRegion = renderRegions[renderRegions.length - 1];
const lastSpacer = lastRegion?.isSpacer ? lastRegion : null;
for (const section of renderRegions) {
if (section.isSpacer) {
// Legacy behavior is to avoid spacers when virtualization is
// disabled (including head spacers on initial render).
if (this.props.disableVirtualization) {
continue;
}
// 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 isLastSpacer = section === lastSpacer;
const constrainToMeasured = isLastSpacer && !this.props.getItemLayout;
const last = constrainToMeasured
? clamp(
section.first - 1,
section.last,
this._listMetrics.getHighestMeasuredCellIndex(),
)
: section.last;