@react-native/virtualized-lists 0.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1944 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ */
10
+
11
+ import type {ScrollResponderType} from 'react-native/Libraries/Components/ScrollView/ScrollView';
12
+ import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
13
+ import type {
14
+ LayoutEvent,
15
+ ScrollEvent,
16
+ } from 'react-native/Libraries/Types/CoreEventTypes';
17
+ import type {ViewToken} from './ViewabilityHelper';
18
+ import type {
19
+ FrameMetricProps,
20
+ Item,
21
+ Props,
22
+ RenderItemProps,
23
+ RenderItemType,
24
+ Separators,
25
+ } from './VirtualizedListProps';
26
+
27
+ import {
28
+ RefreshControl,
29
+ ScrollView,
30
+ View,
31
+ StyleSheet,
32
+ findNodeHandle,
33
+ } from 'react-native';
34
+ import Batchinator from '../Interaction/Batchinator';
35
+ import clamp from '../Utilities/clamp';
36
+ import infoLog from '../Utilities/infoLog';
37
+ import {CellRenderMask} from './CellRenderMask';
38
+ import ChildListCollection from './ChildListCollection';
39
+ import FillRateHelper from './FillRateHelper';
40
+ import StateSafePureComponent from './StateSafePureComponent';
41
+ import ViewabilityHelper from './ViewabilityHelper';
42
+ import CellRenderer from './VirtualizedListCellRenderer';
43
+ import {
44
+ VirtualizedListCellContextProvider,
45
+ VirtualizedListContext,
46
+ VirtualizedListContextProvider,
47
+ } from './VirtualizedListContext.js';
48
+ import {
49
+ computeWindowedRenderLimits,
50
+ keyExtractor as defaultKeyExtractor,
51
+ } from './VirtualizeUtils';
52
+ import invariant from 'invariant';
53
+ import * as React from 'react';
54
+
55
+ export type {RenderItemProps, RenderItemType, Separators};
56
+
57
+ const ON_EDGE_REACHED_EPSILON = 0.001;
58
+
59
+ let _usedIndexForKey = false;
60
+ let _keylessItemComponentName: string = '';
61
+
62
+ type ViewabilityHelperCallbackTuple = {
63
+ viewabilityHelper: ViewabilityHelper,
64
+ onViewableItemsChanged: (info: {
65
+ viewableItems: Array<ViewToken>,
66
+ changed: Array<ViewToken>,
67
+ ...
68
+ }) => void,
69
+ ...
70
+ };
71
+
72
+ type State = {
73
+ renderMask: CellRenderMask,
74
+ cellsAroundViewport: {first: number, last: number},
75
+ };
76
+
77
+ /**
78
+ * Default Props Helper Functions
79
+ * Use the following helper functions for default values
80
+ */
81
+
82
+ // horizontalOrDefault(this.props.horizontal)
83
+ function horizontalOrDefault(horizontal: ?boolean) {
84
+ return horizontal ?? false;
85
+ }
86
+
87
+ // initialNumToRenderOrDefault(this.props.initialNumToRenderOrDefault)
88
+ function initialNumToRenderOrDefault(initialNumToRender: ?number) {
89
+ return initialNumToRender ?? 10;
90
+ }
91
+
92
+ // maxToRenderPerBatchOrDefault(this.props.maxToRenderPerBatch)
93
+ function maxToRenderPerBatchOrDefault(maxToRenderPerBatch: ?number) {
94
+ return maxToRenderPerBatch ?? 10;
95
+ }
96
+
97
+ // onStartReachedThresholdOrDefault(this.props.onStartReachedThreshold)
98
+ function onStartReachedThresholdOrDefault(onStartReachedThreshold: ?number) {
99
+ return onStartReachedThreshold ?? 2;
100
+ }
101
+
102
+ // onEndReachedThresholdOrDefault(this.props.onEndReachedThreshold)
103
+ function onEndReachedThresholdOrDefault(onEndReachedThreshold: ?number) {
104
+ return onEndReachedThreshold ?? 2;
105
+ }
106
+
107
+ // getScrollingThreshold(visibleLength, onEndReachedThreshold)
108
+ function getScrollingThreshold(threshold: number, visibleLength: number) {
109
+ return (threshold * visibleLength) / 2;
110
+ }
111
+
112
+ // scrollEventThrottleOrDefault(this.props.scrollEventThrottle)
113
+ function scrollEventThrottleOrDefault(scrollEventThrottle: ?number) {
114
+ return scrollEventThrottle ?? 50;
115
+ }
116
+
117
+ // windowSizeOrDefault(this.props.windowSize)
118
+ function windowSizeOrDefault(windowSize: ?number) {
119
+ return windowSize ?? 21;
120
+ }
121
+
122
+ function findLastWhere<T>(
123
+ arr: $ReadOnlyArray<T>,
124
+ predicate: (element: T) => boolean,
125
+ ): T | null {
126
+ for (let i = arr.length - 1; i >= 0; i--) {
127
+ if (predicate(arr[i])) {
128
+ return arr[i];
129
+ }
130
+ }
131
+
132
+ return null;
133
+ }
134
+
135
+ /**
136
+ * Base implementation for the more convenient [`<FlatList>`](https://reactnative.dev/docs/flatlist)
137
+ * and [`<SectionList>`](https://reactnative.dev/docs/sectionlist) components, which are also better
138
+ * documented. In general, this should only really be used if you need more flexibility than
139
+ * `FlatList` provides, e.g. for use with immutable data instead of plain arrays.
140
+ *
141
+ * Virtualization massively improves memory consumption and performance of large lists by
142
+ * maintaining a finite render window of active items and replacing all items outside of the render
143
+ * window with appropriately sized blank space. The window adapts to scrolling behavior, and items
144
+ * are rendered incrementally with low-pri (after any running interactions) if they are far from the
145
+ * visible area, or with hi-pri otherwise to minimize the potential of seeing blank space.
146
+ *
147
+ * Some caveats:
148
+ *
149
+ * - Internal state is not preserved when content scrolls out of the render window. Make sure all
150
+ * your data is captured in the item data or external stores like Flux, Redux, or Relay.
151
+ * - This is a `PureComponent` which means that it will not re-render if `props` remain shallow-
152
+ * equal. Make sure that everything your `renderItem` function depends on is passed as a prop
153
+ * (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on
154
+ * changes. This includes the `data` prop and parent component state.
155
+ * - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
156
+ * offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see
157
+ * blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
158
+ * and we are working on improving it behind the scenes.
159
+ * - By default, the list looks for a `key` or `id` prop on each item and uses that for the React key.
160
+ * Alternatively, you can provide a custom `keyExtractor` prop.
161
+ * - As an effort to remove defaultProps, use helper functions when referencing certain props
162
+ *
163
+ */
164
+ class VirtualizedList extends StateSafePureComponent<Props, State> {
165
+ static contextType: typeof VirtualizedListContext = VirtualizedListContext;
166
+
167
+ // scrollToEnd may be janky without getItemLayout prop
168
+ scrollToEnd(params?: ?{animated?: ?boolean, ...}) {
169
+ const animated = params ? params.animated : true;
170
+ const veryLast = this.props.getItemCount(this.props.data) - 1;
171
+ if (veryLast < 0) {
172
+ return;
173
+ }
174
+ const frame = this.__getFrameMetricsApprox(veryLast, this.props);
175
+ const offset = Math.max(
176
+ 0,
177
+ frame.offset +
178
+ frame.length +
179
+ this._footerLength -
180
+ this._scrollMetrics.visibleLength,
181
+ );
182
+
183
+ if (this._scrollRef == null) {
184
+ return;
185
+ }
186
+
187
+ if (this._scrollRef.scrollTo == null) {
188
+ console.warn(
189
+ 'No scrollTo method provided. This may be because you have two nested ' +
190
+ 'VirtualizedLists with the same orientation, or because you are ' +
191
+ 'using a custom component that does not implement scrollTo.',
192
+ );
193
+ return;
194
+ }
195
+
196
+ this._scrollRef.scrollTo(
197
+ horizontalOrDefault(this.props.horizontal)
198
+ ? {x: offset, animated}
199
+ : {y: offset, animated},
200
+ );
201
+ }
202
+
203
+ // scrollToIndex may be janky without getItemLayout prop
204
+ scrollToIndex(params: {
205
+ animated?: ?boolean,
206
+ index: number,
207
+ viewOffset?: number,
208
+ viewPosition?: number,
209
+ ...
210
+ }): $FlowFixMe {
211
+ const {
212
+ data,
213
+ horizontal,
214
+ getItemCount,
215
+ getItemLayout,
216
+ onScrollToIndexFailed,
217
+ } = this.props;
218
+ const {animated, index, viewOffset, viewPosition} = params;
219
+ invariant(
220
+ index >= 0,
221
+ `scrollToIndex out of range: requested index ${index} but minimum is 0`,
222
+ );
223
+ invariant(
224
+ getItemCount(data) >= 1,
225
+ `scrollToIndex out of range: item length ${getItemCount(
226
+ data,
227
+ )} but minimum is 1`,
228
+ );
229
+ invariant(
230
+ index < getItemCount(data),
231
+ `scrollToIndex out of range: requested index ${index} is out of 0 to ${
232
+ getItemCount(data) - 1
233
+ }`,
234
+ );
235
+ if (!getItemLayout && index > this._highestMeasuredFrameIndex) {
236
+ invariant(
237
+ !!onScrollToIndexFailed,
238
+ 'scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, ' +
239
+ 'otherwise there is no way to know the location of offscreen indices or handle failures.',
240
+ );
241
+ onScrollToIndexFailed({
242
+ averageItemLength: this._averageCellLength,
243
+ highestMeasuredFrameIndex: this._highestMeasuredFrameIndex,
244
+ index,
245
+ });
246
+ return;
247
+ }
248
+ const frame = this.__getFrameMetricsApprox(Math.floor(index), this.props);
249
+ const offset =
250
+ Math.max(
251
+ 0,
252
+ this._getOffsetApprox(index, this.props) -
253
+ (viewPosition || 0) *
254
+ (this._scrollMetrics.visibleLength - frame.length),
255
+ ) - (viewOffset || 0);
256
+
257
+ if (this._scrollRef == null) {
258
+ return;
259
+ }
260
+
261
+ if (this._scrollRef.scrollTo == null) {
262
+ console.warn(
263
+ 'No scrollTo method provided. This may be because you have two nested ' +
264
+ 'VirtualizedLists with the same orientation, or because you are ' +
265
+ 'using a custom component that does not implement scrollTo.',
266
+ );
267
+ return;
268
+ }
269
+
270
+ this._scrollRef.scrollTo(
271
+ horizontal ? {x: offset, animated} : {y: offset, animated},
272
+ );
273
+ }
274
+
275
+ // scrollToItem may be janky without getItemLayout prop. Required linear scan through items -
276
+ // use scrollToIndex instead if possible.
277
+ scrollToItem(params: {
278
+ animated?: ?boolean,
279
+ item: Item,
280
+ viewOffset?: number,
281
+ viewPosition?: number,
282
+ ...
283
+ }) {
284
+ const {item} = params;
285
+ const {data, getItem, getItemCount} = this.props;
286
+ const itemCount = getItemCount(data);
287
+ for (let index = 0; index < itemCount; index++) {
288
+ if (getItem(data, index) === item) {
289
+ this.scrollToIndex({...params, index});
290
+ break;
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Scroll to a specific content pixel offset in the list.
297
+ *
298
+ * Param `offset` expects the offset to scroll to.
299
+ * In case of `horizontal` is true, the offset is the x-value,
300
+ * in any other case the offset is the y-value.
301
+ *
302
+ * Param `animated` (`true` by default) defines whether the list
303
+ * should do an animation while scrolling.
304
+ */
305
+ scrollToOffset(params: {animated?: ?boolean, offset: number, ...}) {
306
+ const {animated, offset} = params;
307
+
308
+ if (this._scrollRef == null) {
309
+ return;
310
+ }
311
+
312
+ if (this._scrollRef.scrollTo == null) {
313
+ console.warn(
314
+ 'No scrollTo method provided. This may be because you have two nested ' +
315
+ 'VirtualizedLists with the same orientation, or because you are ' +
316
+ 'using a custom component that does not implement scrollTo.',
317
+ );
318
+ return;
319
+ }
320
+
321
+ this._scrollRef.scrollTo(
322
+ horizontalOrDefault(this.props.horizontal)
323
+ ? {x: offset, animated}
324
+ : {y: offset, animated},
325
+ );
326
+ }
327
+
328
+ recordInteraction() {
329
+ this._nestedChildLists.forEach(childList => {
330
+ childList.recordInteraction();
331
+ });
332
+ this._viewabilityTuples.forEach(t => {
333
+ t.viewabilityHelper.recordInteraction();
334
+ });
335
+ this._updateViewableItems(this.props, this.state.cellsAroundViewport);
336
+ }
337
+
338
+ flashScrollIndicators() {
339
+ if (this._scrollRef == null) {
340
+ return;
341
+ }
342
+
343
+ this._scrollRef.flashScrollIndicators();
344
+ }
345
+
346
+ /**
347
+ * Provides a handle to the underlying scroll responder.
348
+ * Note that `this._scrollRef` might not be a `ScrollView`, so we
349
+ * need to check that it responds to `getScrollResponder` before calling it.
350
+ */
351
+ getScrollResponder(): ?ScrollResponderType {
352
+ if (this._scrollRef && this._scrollRef.getScrollResponder) {
353
+ return this._scrollRef.getScrollResponder();
354
+ }
355
+ }
356
+
357
+ getScrollableNode(): ?number {
358
+ if (this._scrollRef && this._scrollRef.getScrollableNode) {
359
+ return this._scrollRef.getScrollableNode();
360
+ } else {
361
+ return findNodeHandle(this._scrollRef);
362
+ }
363
+ }
364
+
365
+ getScrollRef():
366
+ | ?React.ElementRef<typeof ScrollView>
367
+ | ?React.ElementRef<typeof View> {
368
+ if (this._scrollRef && this._scrollRef.getScrollRef) {
369
+ return this._scrollRef.getScrollRef();
370
+ } else {
371
+ return this._scrollRef;
372
+ }
373
+ }
374
+
375
+ setNativeProps(props: Object) {
376
+ if (this._scrollRef) {
377
+ this._scrollRef.setNativeProps(props);
378
+ }
379
+ }
380
+
381
+ _getCellKey(): string {
382
+ return this.context?.cellKey || 'rootList';
383
+ }
384
+
385
+ // $FlowFixMe[missing-local-annot]
386
+ _getScrollMetrics = () => {
387
+ return this._scrollMetrics;
388
+ };
389
+
390
+ hasMore(): boolean {
391
+ return this._hasMore;
392
+ }
393
+
394
+ // $FlowFixMe[missing-local-annot]
395
+ _getOutermostParentListRef = () => {
396
+ if (this._isNestedWithSameOrientation()) {
397
+ return this.context.getOutermostParentListRef();
398
+ } else {
399
+ return this;
400
+ }
401
+ };
402
+
403
+ _registerAsNestedChild = (childList: {
404
+ cellKey: string,
405
+ ref: React.ElementRef<typeof VirtualizedList>,
406
+ }): void => {
407
+ this._nestedChildLists.add(childList.ref, childList.cellKey);
408
+ if (this._hasInteracted) {
409
+ childList.ref.recordInteraction();
410
+ }
411
+ };
412
+
413
+ _unregisterAsNestedChild = (childList: {
414
+ ref: React.ElementRef<typeof VirtualizedList>,
415
+ }): void => {
416
+ this._nestedChildLists.remove(childList.ref);
417
+ };
418
+
419
+ state: State;
420
+
421
+ constructor(props: Props) {
422
+ super(props);
423
+ invariant(
424
+ // $FlowFixMe[prop-missing]
425
+ !props.onScroll || !props.onScroll.__isNative,
426
+ 'Components based on VirtualizedList must be wrapped with Animated.createAnimatedComponent ' +
427
+ 'to support native onScroll events with useNativeDriver',
428
+ );
429
+ invariant(
430
+ windowSizeOrDefault(props.windowSize) > 0,
431
+ 'VirtualizedList: The windowSize prop must be present and set to a value greater than 0.',
432
+ );
433
+
434
+ invariant(
435
+ props.getItemCount,
436
+ 'VirtualizedList: The "getItemCount" prop must be provided',
437
+ );
438
+
439
+ this._fillRateHelper = new FillRateHelper(this._getFrameMetrics);
440
+ this._updateCellsToRenderBatcher = new Batchinator(
441
+ this._updateCellsToRender,
442
+ this.props.updateCellsBatchingPeriod ?? 50,
443
+ );
444
+
445
+ if (this.props.viewabilityConfigCallbackPairs) {
446
+ this._viewabilityTuples = this.props.viewabilityConfigCallbackPairs.map(
447
+ pair => ({
448
+ viewabilityHelper: new ViewabilityHelper(pair.viewabilityConfig),
449
+ onViewableItemsChanged: pair.onViewableItemsChanged,
450
+ }),
451
+ );
452
+ } else {
453
+ const {onViewableItemsChanged, viewabilityConfig} = this.props;
454
+ if (onViewableItemsChanged) {
455
+ this._viewabilityTuples.push({
456
+ viewabilityHelper: new ViewabilityHelper(viewabilityConfig),
457
+ onViewableItemsChanged: onViewableItemsChanged,
458
+ });
459
+ }
460
+ }
461
+
462
+ invariant(
463
+ !this.context,
464
+ 'Unexpectedly saw VirtualizedListContext available in ctor',
465
+ );
466
+
467
+ const initialRenderRegion = VirtualizedList._initialRenderRegion(props);
468
+
469
+ this.state = {
470
+ cellsAroundViewport: initialRenderRegion,
471
+ renderMask: VirtualizedList._createRenderMask(props, initialRenderRegion),
472
+ };
473
+ }
474
+
475
+ static _createRenderMask(
476
+ props: Props,
477
+ cellsAroundViewport: {first: number, last: number},
478
+ additionalRegions?: ?$ReadOnlyArray<{first: number, last: number}>,
479
+ ): CellRenderMask {
480
+ const itemCount = props.getItemCount(props.data);
481
+
482
+ invariant(
483
+ cellsAroundViewport.first >= 0 &&
484
+ cellsAroundViewport.last >= cellsAroundViewport.first - 1 &&
485
+ cellsAroundViewport.last < itemCount,
486
+ `Invalid cells around viewport "[${cellsAroundViewport.first}, ${cellsAroundViewport.last}]" was passed to VirtualizedList._createRenderMask`,
487
+ );
488
+
489
+ const renderMask = new CellRenderMask(itemCount);
490
+
491
+ if (itemCount > 0) {
492
+ const allRegions = [cellsAroundViewport, ...(additionalRegions ?? [])];
493
+ for (const region of allRegions) {
494
+ renderMask.addCells(region);
495
+ }
496
+
497
+ // The initially rendered cells are retained as part of the
498
+ // "scroll-to-top" optimization
499
+ if (props.initialScrollIndex == null || props.initialScrollIndex <= 0) {
500
+ const initialRegion = VirtualizedList._initialRenderRegion(props);
501
+ renderMask.addCells(initialRegion);
502
+ }
503
+
504
+ // The layout coordinates of sticker headers may be off-screen while the
505
+ // actual header is on-screen. Keep the most recent before the viewport
506
+ // rendered, even if its layout coordinates are not in viewport.
507
+ const stickyIndicesSet = new Set(props.stickyHeaderIndices);
508
+ VirtualizedList._ensureClosestStickyHeader(
509
+ props,
510
+ stickyIndicesSet,
511
+ renderMask,
512
+ cellsAroundViewport.first,
513
+ );
514
+ }
515
+
516
+ return renderMask;
517
+ }
518
+
519
+ static _initialRenderRegion(props: Props): {first: number, last: number} {
520
+ const itemCount = props.getItemCount(props.data);
521
+ const scrollIndex = Math.floor(Math.max(0, props.initialScrollIndex ?? 0));
522
+
523
+ return {
524
+ first: scrollIndex,
525
+ last:
526
+ Math.min(
527
+ itemCount,
528
+ scrollIndex + initialNumToRenderOrDefault(props.initialNumToRender),
529
+ ) - 1,
530
+ };
531
+ }
532
+
533
+ static _ensureClosestStickyHeader(
534
+ props: Props,
535
+ stickyIndicesSet: Set<number>,
536
+ renderMask: CellRenderMask,
537
+ cellIdx: number,
538
+ ) {
539
+ const stickyOffset = props.ListHeaderComponent ? 1 : 0;
540
+
541
+ for (let itemIdx = cellIdx - 1; itemIdx >= 0; itemIdx--) {
542
+ if (stickyIndicesSet.has(itemIdx + stickyOffset)) {
543
+ renderMask.addCells({first: itemIdx, last: itemIdx});
544
+ break;
545
+ }
546
+ }
547
+ }
548
+
549
+ _adjustCellsAroundViewport(
550
+ props: Props,
551
+ cellsAroundViewport: {first: number, last: number},
552
+ ): {first: number, last: number} {
553
+ const {data, getItemCount} = props;
554
+ const onEndReachedThreshold = onEndReachedThresholdOrDefault(
555
+ props.onEndReachedThreshold,
556
+ );
557
+ this._updateViewableItems(props, cellsAroundViewport);
558
+
559
+ const {contentLength, offset, visibleLength} = this._scrollMetrics;
560
+ const distanceFromEnd = contentLength - visibleLength - offset;
561
+
562
+ // Wait until the scroll view metrics have been set up. And until then,
563
+ // we will trust the initialNumToRender suggestion
564
+ if (visibleLength <= 0 || contentLength <= 0) {
565
+ return cellsAroundViewport.last >= getItemCount(data)
566
+ ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props)
567
+ : cellsAroundViewport;
568
+ }
569
+
570
+ let newCellsAroundViewport: {first: number, last: number};
571
+ if (props.disableVirtualization) {
572
+ const renderAhead =
573
+ distanceFromEnd < onEndReachedThreshold * visibleLength
574
+ ? maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch)
575
+ : 0;
576
+
577
+ newCellsAroundViewport = {
578
+ first: 0,
579
+ last: Math.min(
580
+ cellsAroundViewport.last + renderAhead,
581
+ getItemCount(data) - 1,
582
+ ),
583
+ };
584
+ } else {
585
+ // If we have a non-zero initialScrollIndex and run this before we've scrolled,
586
+ // we'll wipe out the initialNumToRender rendered elements starting at initialScrollIndex.
587
+ // So let's wait until we've scrolled the view to the right place. And until then,
588
+ // we will trust the initialScrollIndex suggestion.
589
+
590
+ // Thus, we want to recalculate the windowed render limits if any of the following hold:
591
+ // - initialScrollIndex is undefined or is 0
592
+ // - initialScrollIndex > 0 AND scrolling is complete
593
+ // - initialScrollIndex > 0 AND the end of the list is visible (this handles the case
594
+ // where the list is shorter than the visible area)
595
+ if (
596
+ props.initialScrollIndex &&
597
+ !this._scrollMetrics.offset &&
598
+ Math.abs(distanceFromEnd) >= Number.EPSILON
599
+ ) {
600
+ return cellsAroundViewport.last >= getItemCount(data)
601
+ ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props)
602
+ : cellsAroundViewport;
603
+ }
604
+
605
+ newCellsAroundViewport = computeWindowedRenderLimits(
606
+ props,
607
+ maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch),
608
+ windowSizeOrDefault(props.windowSize),
609
+ cellsAroundViewport,
610
+ this.__getFrameMetricsApprox,
611
+ this._scrollMetrics,
612
+ );
613
+ invariant(
614
+ newCellsAroundViewport.last < getItemCount(data),
615
+ 'computeWindowedRenderLimits() should return range in-bounds',
616
+ );
617
+ }
618
+
619
+ if (this._nestedChildLists.size() > 0) {
620
+ // If some cell in the new state has a child list in it, we should only render
621
+ // up through that item, so that we give that list a chance to render.
622
+ // Otherwise there's churn from multiple child lists mounting and un-mounting
623
+ // their items.
624
+
625
+ // Will this prevent rendering if the nested list doesn't realize the end?
626
+ const childIdx = this._findFirstChildWithMore(
627
+ newCellsAroundViewport.first,
628
+ newCellsAroundViewport.last,
629
+ );
630
+
631
+ newCellsAroundViewport.last = childIdx ?? newCellsAroundViewport.last;
632
+ }
633
+
634
+ return newCellsAroundViewport;
635
+ }
636
+
637
+ _findFirstChildWithMore(first: number, last: number): number | null {
638
+ for (let ii = first; ii <= last; ii++) {
639
+ const cellKeyForIndex = this._indicesToKeys.get(ii);
640
+ if (
641
+ cellKeyForIndex != null &&
642
+ this._nestedChildLists.anyInCell(cellKeyForIndex, childList =>
643
+ childList.hasMore(),
644
+ )
645
+ ) {
646
+ return ii;
647
+ }
648
+ }
649
+
650
+ return null;
651
+ }
652
+
653
+ componentDidMount() {
654
+ if (this._isNestedWithSameOrientation()) {
655
+ this.context.registerAsNestedChild({
656
+ ref: this,
657
+ cellKey: this.context.cellKey,
658
+ });
659
+ }
660
+ }
661
+
662
+ componentWillUnmount() {
663
+ if (this._isNestedWithSameOrientation()) {
664
+ this.context.unregisterAsNestedChild({ref: this});
665
+ }
666
+ this._updateCellsToRenderBatcher.dispose({abort: true});
667
+ this._viewabilityTuples.forEach(tuple => {
668
+ tuple.viewabilityHelper.dispose();
669
+ });
670
+ this._fillRateHelper.deactivateAndFlush();
671
+ }
672
+
673
+ static getDerivedStateFromProps(newProps: Props, prevState: State): State {
674
+ // first and last could be stale (e.g. if a new, shorter items props is passed in), so we make
675
+ // sure we're rendering a reasonable range here.
676
+ const itemCount = newProps.getItemCount(newProps.data);
677
+ if (itemCount === prevState.renderMask.numCells()) {
678
+ return prevState;
679
+ }
680
+
681
+ const constrainedCells = VirtualizedList._constrainToItemCount(
682
+ prevState.cellsAroundViewport,
683
+ newProps,
684
+ );
685
+
686
+ return {
687
+ cellsAroundViewport: constrainedCells,
688
+ renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells),
689
+ };
690
+ }
691
+
692
+ _pushCells(
693
+ cells: Array<Object>,
694
+ stickyHeaderIndices: Array<number>,
695
+ stickyIndicesFromProps: Set<number>,
696
+ first: number,
697
+ last: number,
698
+ inversionStyle: ViewStyleProp,
699
+ ) {
700
+ const {
701
+ CellRendererComponent,
702
+ ItemSeparatorComponent,
703
+ ListHeaderComponent,
704
+ ListItemComponent,
705
+ data,
706
+ debug,
707
+ getItem,
708
+ getItemCount,
709
+ getItemLayout,
710
+ horizontal,
711
+ renderItem,
712
+ } = this.props;
713
+ const stickyOffset = ListHeaderComponent ? 1 : 0;
714
+ const end = getItemCount(data) - 1;
715
+ let prevCellKey;
716
+ last = Math.min(end, last);
717
+ for (let ii = first; ii <= last; ii++) {
718
+ const item = getItem(data, ii);
719
+ const key = this._keyExtractor(item, ii, this.props);
720
+ this._indicesToKeys.set(ii, key);
721
+ if (stickyIndicesFromProps.has(ii + stickyOffset)) {
722
+ stickyHeaderIndices.push(cells.length);
723
+ }
724
+ cells.push(
725
+ <CellRenderer
726
+ CellRendererComponent={CellRendererComponent}
727
+ ItemSeparatorComponent={ii < end ? ItemSeparatorComponent : undefined}
728
+ ListItemComponent={ListItemComponent}
729
+ cellKey={key}
730
+ debug={debug}
731
+ fillRateHelper={this._fillRateHelper}
732
+ getItemLayout={getItemLayout}
733
+ horizontal={horizontal}
734
+ index={ii}
735
+ inversionStyle={inversionStyle}
736
+ item={item}
737
+ key={key}
738
+ prevCellKey={prevCellKey}
739
+ onCellLayout={this._onCellLayout}
740
+ onUpdateSeparators={this._onUpdateSeparators}
741
+ onCellFocusCapture={e => this._onCellFocusCapture(key)}
742
+ onUnmount={this._onCellUnmount}
743
+ ref={ref => {
744
+ this._cellRefs[key] = ref;
745
+ }}
746
+ renderItem={renderItem}
747
+ />,
748
+ );
749
+ prevCellKey = key;
750
+ }
751
+ }
752
+
753
+ static _constrainToItemCount(
754
+ cells: {first: number, last: number},
755
+ props: Props,
756
+ ): {first: number, last: number} {
757
+ const itemCount = props.getItemCount(props.data);
758
+ const last = Math.min(itemCount - 1, cells.last);
759
+
760
+ const maxToRenderPerBatch = maxToRenderPerBatchOrDefault(
761
+ props.maxToRenderPerBatch,
762
+ );
763
+
764
+ return {
765
+ first: clamp(0, itemCount - 1 - maxToRenderPerBatch, cells.first),
766
+ last,
767
+ };
768
+ }
769
+
770
+ _onUpdateSeparators = (keys: Array<?string>, newProps: Object) => {
771
+ keys.forEach(key => {
772
+ const ref = key != null && this._cellRefs[key];
773
+ ref && ref.updateSeparatorProps(newProps);
774
+ });
775
+ };
776
+
777
+ _isNestedWithSameOrientation(): boolean {
778
+ const nestedContext = this.context;
779
+ return !!(
780
+ nestedContext &&
781
+ !!nestedContext.horizontal === horizontalOrDefault(this.props.horizontal)
782
+ );
783
+ }
784
+
785
+ _getSpacerKey = (isVertical: boolean): string =>
786
+ isVertical ? 'height' : 'width';
787
+
788
+ _keyExtractor(
789
+ item: Item,
790
+ index: number,
791
+ props: {
792
+ keyExtractor?: ?(item: Item, index: number) => string,
793
+ ...
794
+ },
795
+ // $FlowFixMe[missing-local-annot]
796
+ ) {
797
+ if (props.keyExtractor != null) {
798
+ return props.keyExtractor(item, index);
799
+ }
800
+
801
+ const key = defaultKeyExtractor(item, index);
802
+ if (key === String(index)) {
803
+ _usedIndexForKey = true;
804
+ if (item.type && item.type.displayName) {
805
+ _keylessItemComponentName = item.type.displayName;
806
+ }
807
+ }
808
+ return key;
809
+ }
810
+
811
+ render(): React.Node {
812
+ if (__DEV__) {
813
+ // $FlowFixMe[underconstrained-implicit-instantiation]
814
+ const flatStyles = StyleSheet.flatten(this.props.contentContainerStyle);
815
+ if (flatStyles != null && flatStyles.flexWrap === 'wrap') {
816
+ console.warn(
817
+ '`flexWrap: `wrap`` is not supported with the `VirtualizedList` components.' +
818
+ 'Consider using `numColumns` with `FlatList` instead.',
819
+ );
820
+ }
821
+ }
822
+ const {ListEmptyComponent, ListFooterComponent, ListHeaderComponent} =
823
+ this.props;
824
+ const {data, horizontal} = this.props;
825
+ const inversionStyle = this.props.inverted
826
+ ? horizontalOrDefault(this.props.horizontal)
827
+ ? styles.horizontallyInverted
828
+ : styles.verticallyInverted
829
+ : null;
830
+ const cells: Array<any | React.Node> = [];
831
+ const stickyIndicesFromProps = new Set(this.props.stickyHeaderIndices);
832
+ const stickyHeaderIndices = [];
833
+
834
+ // 1. Add cell for ListHeaderComponent
835
+ if (ListHeaderComponent) {
836
+ if (stickyIndicesFromProps.has(0)) {
837
+ stickyHeaderIndices.push(0);
838
+ }
839
+ const element = React.isValidElement(ListHeaderComponent) ? (
840
+ ListHeaderComponent
841
+ ) : (
842
+ // $FlowFixMe[not-a-component]
843
+ // $FlowFixMe[incompatible-type-arg]
844
+ <ListHeaderComponent />
845
+ );
846
+ cells.push(
847
+ <VirtualizedListCellContextProvider
848
+ cellKey={this._getCellKey() + '-header'}
849
+ key="$header">
850
+ <View
851
+ onLayout={this._onLayoutHeader}
852
+ style={StyleSheet.compose(
853
+ inversionStyle,
854
+ this.props.ListHeaderComponentStyle,
855
+ )}>
856
+ {
857
+ // $FlowFixMe[incompatible-type] - Typing ReactNativeComponent revealed errors
858
+ element
859
+ }
860
+ </View>
861
+ </VirtualizedListCellContextProvider>,
862
+ );
863
+ }
864
+
865
+ // 2a. Add a cell for ListEmptyComponent if applicable
866
+ const itemCount = this.props.getItemCount(data);
867
+ if (itemCount === 0 && ListEmptyComponent) {
868
+ const element: React.Element<any> = ((React.isValidElement(
869
+ ListEmptyComponent,
870
+ ) ? (
871
+ ListEmptyComponent
872
+ ) : (
873
+ // $FlowFixMe[not-a-component]
874
+ // $FlowFixMe[incompatible-type-arg]
875
+ <ListEmptyComponent />
876
+ )): any);
877
+ cells.push(
878
+ <VirtualizedListCellContextProvider
879
+ cellKey={this._getCellKey() + '-empty'}
880
+ key="$empty">
881
+ {React.cloneElement(element, {
882
+ onLayout: (event: LayoutEvent) => {
883
+ this._onLayoutEmpty(event);
884
+ if (element.props.onLayout) {
885
+ element.props.onLayout(event);
886
+ }
887
+ },
888
+ style: StyleSheet.compose(inversionStyle, element.props.style),
889
+ })}
890
+ </VirtualizedListCellContextProvider>,
891
+ );
892
+ }
893
+
894
+ // 2b. Add cells and spacers for each item
895
+ if (itemCount > 0) {
896
+ _usedIndexForKey = false;
897
+ _keylessItemComponentName = '';
898
+ const spacerKey = this._getSpacerKey(!horizontal);
899
+
900
+ const renderRegions = this.state.renderMask.enumerateRegions();
901
+ const lastSpacer = findLastWhere(renderRegions, r => r.isSpacer);
902
+
903
+ for (const section of renderRegions) {
904
+ if (section.isSpacer) {
905
+ // Legacy behavior is to avoid spacers when virtualization is
906
+ // disabled (including head spacers on initial render).
907
+ if (this.props.disableVirtualization) {
908
+ continue;
909
+ }
910
+
911
+ // Without getItemLayout, we limit our tail spacer to the _highestMeasuredFrameIndex to
912
+ // prevent the user for hyperscrolling into un-measured area because otherwise content will
913
+ // likely jump around as it renders in above the viewport.
914
+ const isLastSpacer = section === lastSpacer;
915
+ const constrainToMeasured = isLastSpacer && !this.props.getItemLayout;
916
+ const last = constrainToMeasured
917
+ ? clamp(
918
+ section.first - 1,
919
+ section.last,
920
+ this._highestMeasuredFrameIndex,
921
+ )
922
+ : section.last;
923
+
924
+ const firstMetrics = this.__getFrameMetricsApprox(
925
+ section.first,
926
+ this.props,
927
+ );
928
+ const lastMetrics = this.__getFrameMetricsApprox(last, this.props);
929
+ const spacerSize =
930
+ lastMetrics.offset + lastMetrics.length - firstMetrics.offset;
931
+ cells.push(
932
+ <View
933
+ key={`$spacer-${section.first}`}
934
+ style={{[spacerKey]: spacerSize}}
935
+ />,
936
+ );
937
+ } else {
938
+ this._pushCells(
939
+ cells,
940
+ stickyHeaderIndices,
941
+ stickyIndicesFromProps,
942
+ section.first,
943
+ section.last,
944
+ inversionStyle,
945
+ );
946
+ }
947
+ }
948
+
949
+ if (!this._hasWarned.keys && _usedIndexForKey) {
950
+ console.warn(
951
+ 'VirtualizedList: missing keys for items, make sure to specify a key or id property on each ' +
952
+ 'item or provide a custom keyExtractor.',
953
+ _keylessItemComponentName,
954
+ );
955
+ this._hasWarned.keys = true;
956
+ }
957
+ }
958
+
959
+ // 3. Add cell for ListFooterComponent
960
+ if (ListFooterComponent) {
961
+ const element = React.isValidElement(ListFooterComponent) ? (
962
+ ListFooterComponent
963
+ ) : (
964
+ // $FlowFixMe[not-a-component]
965
+ // $FlowFixMe[incompatible-type-arg]
966
+ <ListFooterComponent />
967
+ );
968
+ cells.push(
969
+ <VirtualizedListCellContextProvider
970
+ cellKey={this._getFooterCellKey()}
971
+ key="$footer">
972
+ <View
973
+ onLayout={this._onLayoutFooter}
974
+ style={StyleSheet.compose(
975
+ inversionStyle,
976
+ this.props.ListFooterComponentStyle,
977
+ )}>
978
+ {
979
+ // $FlowFixMe[incompatible-type] - Typing ReactNativeComponent revealed errors
980
+ element
981
+ }
982
+ </View>
983
+ </VirtualizedListCellContextProvider>,
984
+ );
985
+ }
986
+
987
+ // 4. Render the ScrollView
988
+ const scrollProps = {
989
+ ...this.props,
990
+ onContentSizeChange: this._onContentSizeChange,
991
+ onLayout: this._onLayout,
992
+ onScroll: this._onScroll,
993
+ onScrollBeginDrag: this._onScrollBeginDrag,
994
+ onScrollEndDrag: this._onScrollEndDrag,
995
+ onMomentumScrollBegin: this._onMomentumScrollBegin,
996
+ onMomentumScrollEnd: this._onMomentumScrollEnd,
997
+ scrollEventThrottle: scrollEventThrottleOrDefault(
998
+ this.props.scrollEventThrottle,
999
+ ), // TODO: Android support
1000
+ invertStickyHeaders:
1001
+ this.props.invertStickyHeaders !== undefined
1002
+ ? this.props.invertStickyHeaders
1003
+ : this.props.inverted,
1004
+ stickyHeaderIndices,
1005
+ style: inversionStyle
1006
+ ? [inversionStyle, this.props.style]
1007
+ : this.props.style,
1008
+ };
1009
+
1010
+ this._hasMore = this.state.cellsAroundViewport.last < itemCount - 1;
1011
+
1012
+ const innerRet = (
1013
+ <VirtualizedListContextProvider
1014
+ value={{
1015
+ cellKey: null,
1016
+ getScrollMetrics: this._getScrollMetrics,
1017
+ horizontal: horizontalOrDefault(this.props.horizontal),
1018
+ getOutermostParentListRef: this._getOutermostParentListRef,
1019
+ registerAsNestedChild: this._registerAsNestedChild,
1020
+ unregisterAsNestedChild: this._unregisterAsNestedChild,
1021
+ }}>
1022
+ {React.cloneElement(
1023
+ (
1024
+ this.props.renderScrollComponent ||
1025
+ this._defaultRenderScrollComponent
1026
+ )(scrollProps),
1027
+ {
1028
+ ref: this._captureScrollRef,
1029
+ },
1030
+ cells,
1031
+ )}
1032
+ </VirtualizedListContextProvider>
1033
+ );
1034
+ let ret: React.Node = innerRet;
1035
+ if (__DEV__) {
1036
+ ret = (
1037
+ <ScrollView.Context.Consumer>
1038
+ {scrollContext => {
1039
+ if (
1040
+ scrollContext != null &&
1041
+ !scrollContext.horizontal ===
1042
+ !horizontalOrDefault(this.props.horizontal) &&
1043
+ !this._hasWarned.nesting &&
1044
+ this.context == null &&
1045
+ this.props.scrollEnabled !== false
1046
+ ) {
1047
+ // TODO (T46547044): use React.warn once 16.9 is sync'd: https://github.com/facebook/react/pull/15170
1048
+ console.error(
1049
+ 'VirtualizedLists should never be nested inside plain ScrollViews with the same ' +
1050
+ 'orientation because it can break windowing and other functionality - use another ' +
1051
+ 'VirtualizedList-backed container instead.',
1052
+ );
1053
+ this._hasWarned.nesting = true;
1054
+ }
1055
+ return innerRet;
1056
+ }}
1057
+ </ScrollView.Context.Consumer>
1058
+ );
1059
+ }
1060
+ if (this.props.debug) {
1061
+ return (
1062
+ <View style={styles.debug}>
1063
+ {ret}
1064
+ {this._renderDebugOverlay()}
1065
+ </View>
1066
+ );
1067
+ } else {
1068
+ return ret;
1069
+ }
1070
+ }
1071
+
1072
+ componentDidUpdate(prevProps: Props) {
1073
+ const {data, extraData} = this.props;
1074
+ if (data !== prevProps.data || extraData !== prevProps.extraData) {
1075
+ // clear the viewableIndices cache to also trigger
1076
+ // the onViewableItemsChanged callback with the new data
1077
+ this._viewabilityTuples.forEach(tuple => {
1078
+ tuple.viewabilityHelper.resetViewableIndices();
1079
+ });
1080
+ }
1081
+ // The `this._hiPriInProgress` is guaranteeing a hiPri cell update will only happen
1082
+ // once per fiber update. The `_scheduleCellsToRenderUpdate` will set it to true
1083
+ // if a hiPri update needs to perform. If `componentDidUpdate` is triggered with
1084
+ // `this._hiPriInProgress=true`, means it's triggered by the hiPri update. The
1085
+ // `_scheduleCellsToRenderUpdate` will check this condition and not perform
1086
+ // another hiPri update.
1087
+ const hiPriInProgress = this._hiPriInProgress;
1088
+ this._scheduleCellsToRenderUpdate();
1089
+ // Make sure setting `this._hiPriInProgress` back to false after `componentDidUpdate`
1090
+ // is triggered with `this._hiPriInProgress = true`
1091
+ if (hiPriInProgress) {
1092
+ this._hiPriInProgress = false;
1093
+ }
1094
+ }
1095
+
1096
+ _averageCellLength = 0;
1097
+ _cellRefs: {[string]: null | CellRenderer<any>} = {};
1098
+ _fillRateHelper: FillRateHelper;
1099
+ _frames: {
1100
+ [string]: {
1101
+ inLayout?: boolean,
1102
+ index: number,
1103
+ length: number,
1104
+ offset: number,
1105
+ },
1106
+ } = {};
1107
+ _footerLength = 0;
1108
+ // Used for preventing scrollToIndex from being called multiple times for initialScrollIndex
1109
+ _hasTriggeredInitialScrollToIndex = false;
1110
+ _hasInteracted = false;
1111
+ _hasMore = false;
1112
+ _hasWarned: {[string]: boolean} = {};
1113
+ _headerLength = 0;
1114
+ _hiPriInProgress: boolean = false; // flag to prevent infinite hiPri cell limit update
1115
+ _highestMeasuredFrameIndex = 0;
1116
+ _indicesToKeys: Map<number, string> = new Map();
1117
+ _lastFocusedCellKey: ?string = null;
1118
+ _nestedChildLists: ChildListCollection<VirtualizedList> =
1119
+ new ChildListCollection();
1120
+ _offsetFromParentVirtualizedList: number = 0;
1121
+ _prevParentOffset: number = 0;
1122
+ // $FlowFixMe[missing-local-annot]
1123
+ _scrollMetrics = {
1124
+ contentLength: 0,
1125
+ dOffset: 0,
1126
+ dt: 10,
1127
+ offset: 0,
1128
+ timestamp: 0,
1129
+ velocity: 0,
1130
+ visibleLength: 0,
1131
+ zoomScale: 1,
1132
+ };
1133
+ _scrollRef: ?React.ElementRef<any> = null;
1134
+ _sentStartForContentLength = 0;
1135
+ _sentEndForContentLength = 0;
1136
+ _totalCellLength = 0;
1137
+ _totalCellsMeasured = 0;
1138
+ _updateCellsToRenderBatcher: Batchinator;
1139
+ _viewabilityTuples: Array<ViewabilityHelperCallbackTuple> = [];
1140
+
1141
+ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
1142
+ * LTI update could not be added via codemod */
1143
+ _captureScrollRef = ref => {
1144
+ this._scrollRef = ref;
1145
+ };
1146
+
1147
+ _computeBlankness() {
1148
+ this._fillRateHelper.computeBlankness(
1149
+ this.props,
1150
+ this.state.cellsAroundViewport,
1151
+ this._scrollMetrics,
1152
+ );
1153
+ }
1154
+
1155
+ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
1156
+ * LTI update could not be added via codemod */
1157
+ _defaultRenderScrollComponent = props => {
1158
+ const onRefresh = props.onRefresh;
1159
+ if (this._isNestedWithSameOrientation()) {
1160
+ // $FlowFixMe[prop-missing] - Typing ReactNativeComponent revealed errors
1161
+ return <View {...props} />;
1162
+ } else if (onRefresh) {
1163
+ invariant(
1164
+ typeof props.refreshing === 'boolean',
1165
+ '`refreshing` prop must be set as a boolean in order to use `onRefresh`, but got `' +
1166
+ JSON.stringify(props.refreshing ?? 'undefined') +
1167
+ '`',
1168
+ );
1169
+ return (
1170
+ // $FlowFixMe[prop-missing] Invalid prop usage
1171
+ // $FlowFixMe[incompatible-use]
1172
+ <ScrollView
1173
+ {...props}
1174
+ refreshControl={
1175
+ props.refreshControl == null ? (
1176
+ <RefreshControl
1177
+ // $FlowFixMe[incompatible-type]
1178
+ refreshing={props.refreshing}
1179
+ onRefresh={onRefresh}
1180
+ progressViewOffset={props.progressViewOffset}
1181
+ />
1182
+ ) : (
1183
+ props.refreshControl
1184
+ )
1185
+ }
1186
+ />
1187
+ );
1188
+ } else {
1189
+ // $FlowFixMe[prop-missing] Invalid prop usage
1190
+ // $FlowFixMe[incompatible-use]
1191
+ return <ScrollView {...props} />;
1192
+ }
1193
+ };
1194
+
1195
+ _onCellLayout = (e: LayoutEvent, cellKey: string, index: number): void => {
1196
+ const layout = e.nativeEvent.layout;
1197
+ const next = {
1198
+ offset: this._selectOffset(layout),
1199
+ length: this._selectLength(layout),
1200
+ index,
1201
+ inLayout: true,
1202
+ };
1203
+ const curr = this._frames[cellKey];
1204
+ if (
1205
+ !curr ||
1206
+ next.offset !== curr.offset ||
1207
+ next.length !== curr.length ||
1208
+ index !== curr.index
1209
+ ) {
1210
+ this._totalCellLength += next.length - (curr ? curr.length : 0);
1211
+ this._totalCellsMeasured += curr ? 0 : 1;
1212
+ this._averageCellLength =
1213
+ this._totalCellLength / this._totalCellsMeasured;
1214
+ this._frames[cellKey] = next;
1215
+ this._highestMeasuredFrameIndex = Math.max(
1216
+ this._highestMeasuredFrameIndex,
1217
+ index,
1218
+ );
1219
+ this._scheduleCellsToRenderUpdate();
1220
+ } else {
1221
+ this._frames[cellKey].inLayout = true;
1222
+ }
1223
+
1224
+ this._triggerRemeasureForChildListsInCell(cellKey);
1225
+
1226
+ this._computeBlankness();
1227
+ this._updateViewableItems(this.props, this.state.cellsAroundViewport);
1228
+ };
1229
+
1230
+ _onCellFocusCapture(cellKey: string) {
1231
+ this._lastFocusedCellKey = cellKey;
1232
+ this._updateCellsToRender();
1233
+ }
1234
+
1235
+ _onCellUnmount = (cellKey: string) => {
1236
+ const curr = this._frames[cellKey];
1237
+ if (curr) {
1238
+ this._frames[cellKey] = {...curr, inLayout: false};
1239
+ }
1240
+ };
1241
+
1242
+ _triggerRemeasureForChildListsInCell(cellKey: string): void {
1243
+ this._nestedChildLists.forEachInCell(cellKey, childList => {
1244
+ childList.measureLayoutRelativeToContainingList();
1245
+ });
1246
+ }
1247
+
1248
+ measureLayoutRelativeToContainingList(): void {
1249
+ // TODO (T35574538): findNodeHandle sometimes crashes with "Unable to find
1250
+ // node on an unmounted component" during scrolling
1251
+ try {
1252
+ if (!this._scrollRef) {
1253
+ return;
1254
+ }
1255
+ // We are assuming that getOutermostParentListRef().getScrollRef()
1256
+ // is a non-null reference to a ScrollView
1257
+ this._scrollRef.measureLayout(
1258
+ this.context.getOutermostParentListRef().getScrollRef(),
1259
+ (x, y, width, height) => {
1260
+ this._offsetFromParentVirtualizedList = this._selectOffset({x, y});
1261
+ this._scrollMetrics.contentLength = this._selectLength({
1262
+ width,
1263
+ height,
1264
+ });
1265
+ const scrollMetrics = this._convertParentScrollMetrics(
1266
+ this.context.getScrollMetrics(),
1267
+ );
1268
+
1269
+ const metricsChanged =
1270
+ this._scrollMetrics.visibleLength !== scrollMetrics.visibleLength ||
1271
+ this._scrollMetrics.offset !== scrollMetrics.offset;
1272
+
1273
+ if (metricsChanged) {
1274
+ this._scrollMetrics.visibleLength = scrollMetrics.visibleLength;
1275
+ this._scrollMetrics.offset = scrollMetrics.offset;
1276
+
1277
+ // If metrics of the scrollView changed, then we triggered remeasure for child list
1278
+ // to ensure VirtualizedList has the right information.
1279
+ this._nestedChildLists.forEach(childList => {
1280
+ childList.measureLayoutRelativeToContainingList();
1281
+ });
1282
+ }
1283
+ },
1284
+ error => {
1285
+ console.warn(
1286
+ "VirtualizedList: Encountered an error while measuring a list's" +
1287
+ ' offset from its containing VirtualizedList.',
1288
+ );
1289
+ },
1290
+ );
1291
+ } catch (error) {
1292
+ console.warn(
1293
+ 'measureLayoutRelativeToContainingList threw an error',
1294
+ error.stack,
1295
+ );
1296
+ }
1297
+ }
1298
+
1299
+ _onLayout = (e: LayoutEvent) => {
1300
+ if (this._isNestedWithSameOrientation()) {
1301
+ // Need to adjust our scroll metrics to be relative to our containing
1302
+ // VirtualizedList before we can make claims about list item viewability
1303
+ this.measureLayoutRelativeToContainingList();
1304
+ } else {
1305
+ this._scrollMetrics.visibleLength = this._selectLength(
1306
+ e.nativeEvent.layout,
1307
+ );
1308
+ }
1309
+ this.props.onLayout && this.props.onLayout(e);
1310
+ this._scheduleCellsToRenderUpdate();
1311
+ this._maybeCallOnEdgeReached();
1312
+ };
1313
+
1314
+ _onLayoutEmpty = (e: LayoutEvent) => {
1315
+ this.props.onLayout && this.props.onLayout(e);
1316
+ };
1317
+
1318
+ _getFooterCellKey(): string {
1319
+ return this._getCellKey() + '-footer';
1320
+ }
1321
+
1322
+ _onLayoutFooter = (e: LayoutEvent) => {
1323
+ this._triggerRemeasureForChildListsInCell(this._getFooterCellKey());
1324
+ this._footerLength = this._selectLength(e.nativeEvent.layout);
1325
+ };
1326
+
1327
+ _onLayoutHeader = (e: LayoutEvent) => {
1328
+ this._headerLength = this._selectLength(e.nativeEvent.layout);
1329
+ };
1330
+
1331
+ // $FlowFixMe[missing-local-annot]
1332
+ _renderDebugOverlay() {
1333
+ const normalize =
1334
+ this._scrollMetrics.visibleLength /
1335
+ (this._scrollMetrics.contentLength || 1);
1336
+ const framesInLayout = [];
1337
+ const itemCount = this.props.getItemCount(this.props.data);
1338
+ for (let ii = 0; ii < itemCount; ii++) {
1339
+ const frame = this.__getFrameMetricsApprox(ii, this.props);
1340
+ /* $FlowFixMe[prop-missing] (>=0.68.0 site=react_native_fb) This comment
1341
+ * suppresses an error found when Flow v0.68 was deployed. To see the
1342
+ * error delete this comment and run Flow. */
1343
+ if (frame.inLayout) {
1344
+ framesInLayout.push(frame);
1345
+ }
1346
+ }
1347
+ const windowTop = this.__getFrameMetricsApprox(
1348
+ this.state.cellsAroundViewport.first,
1349
+ this.props,
1350
+ ).offset;
1351
+ const frameLast = this.__getFrameMetricsApprox(
1352
+ this.state.cellsAroundViewport.last,
1353
+ this.props,
1354
+ );
1355
+ const windowLen = frameLast.offset + frameLast.length - windowTop;
1356
+ const visTop = this._scrollMetrics.offset;
1357
+ const visLen = this._scrollMetrics.visibleLength;
1358
+
1359
+ return (
1360
+ <View style={[styles.debugOverlayBase, styles.debugOverlay]}>
1361
+ {framesInLayout.map((f, ii) => (
1362
+ <View
1363
+ key={'f' + ii}
1364
+ style={[
1365
+ styles.debugOverlayBase,
1366
+ styles.debugOverlayFrame,
1367
+ {
1368
+ top: f.offset * normalize,
1369
+ height: f.length * normalize,
1370
+ },
1371
+ ]}
1372
+ />
1373
+ ))}
1374
+ <View
1375
+ style={[
1376
+ styles.debugOverlayBase,
1377
+ styles.debugOverlayFrameLast,
1378
+ {
1379
+ top: windowTop * normalize,
1380
+ height: windowLen * normalize,
1381
+ },
1382
+ ]}
1383
+ />
1384
+ <View
1385
+ style={[
1386
+ styles.debugOverlayBase,
1387
+ styles.debugOverlayFrameVis,
1388
+ {
1389
+ top: visTop * normalize,
1390
+ height: visLen * normalize,
1391
+ },
1392
+ ]}
1393
+ />
1394
+ </View>
1395
+ );
1396
+ }
1397
+
1398
+ _selectLength(
1399
+ metrics: $ReadOnly<{
1400
+ height: number,
1401
+ width: number,
1402
+ ...
1403
+ }>,
1404
+ ): number {
1405
+ return !horizontalOrDefault(this.props.horizontal)
1406
+ ? metrics.height
1407
+ : metrics.width;
1408
+ }
1409
+
1410
+ _selectOffset(
1411
+ metrics: $ReadOnly<{
1412
+ x: number,
1413
+ y: number,
1414
+ ...
1415
+ }>,
1416
+ ): number {
1417
+ return !horizontalOrDefault(this.props.horizontal) ? metrics.y : metrics.x;
1418
+ }
1419
+
1420
+ _maybeCallOnEdgeReached() {
1421
+ const {
1422
+ data,
1423
+ getItemCount,
1424
+ onStartReached,
1425
+ onStartReachedThreshold,
1426
+ onEndReached,
1427
+ onEndReachedThreshold,
1428
+ initialScrollIndex,
1429
+ } = this.props;
1430
+ const {contentLength, visibleLength, offset} = this._scrollMetrics;
1431
+ let distanceFromStart = offset;
1432
+ let distanceFromEnd = contentLength - visibleLength - offset;
1433
+
1434
+ // Especially when oERT is zero it's necessary to 'floor' very small distance values to be 0
1435
+ // since debouncing causes us to not fire this event for every single "pixel" we scroll and can thus
1436
+ // be at the edge of the list with a distance approximating 0 but not quite there.
1437
+ if (distanceFromStart < ON_EDGE_REACHED_EPSILON) {
1438
+ distanceFromStart = 0;
1439
+ }
1440
+ if (distanceFromEnd < ON_EDGE_REACHED_EPSILON) {
1441
+ distanceFromEnd = 0;
1442
+ }
1443
+
1444
+ // TODO: T121172172 Look into why we're "defaulting" to a threshold of 2px
1445
+ // when oERT is not present (different from 2 viewports used elsewhere)
1446
+ const DEFAULT_THRESHOLD_PX = 2;
1447
+
1448
+ const startThreshold =
1449
+ onStartReachedThreshold != null
1450
+ ? onStartReachedThreshold * visibleLength
1451
+ : DEFAULT_THRESHOLD_PX;
1452
+ const endThreshold =
1453
+ onEndReachedThreshold != null
1454
+ ? onEndReachedThreshold * visibleLength
1455
+ : DEFAULT_THRESHOLD_PX;
1456
+ const isWithinStartThreshold = distanceFromStart <= startThreshold;
1457
+ const isWithinEndThreshold = distanceFromEnd <= endThreshold;
1458
+
1459
+ // First check if the user just scrolled within the end threshold
1460
+ // and call onEndReached only once for a given content length,
1461
+ // and only if onStartReached is not being executed
1462
+ if (
1463
+ onEndReached &&
1464
+ this.state.cellsAroundViewport.last === getItemCount(data) - 1 &&
1465
+ isWithinEndThreshold &&
1466
+ this._scrollMetrics.contentLength !== this._sentEndForContentLength
1467
+ ) {
1468
+ this._sentEndForContentLength = this._scrollMetrics.contentLength;
1469
+ onEndReached({distanceFromEnd});
1470
+ }
1471
+
1472
+ // Next check if the user just scrolled within the start threshold
1473
+ // and call onStartReached only once for a given content length,
1474
+ // and only if onEndReached is not being executed
1475
+ else if (
1476
+ onStartReached != null &&
1477
+ this.state.cellsAroundViewport.first === 0 &&
1478
+ isWithinStartThreshold &&
1479
+ this._scrollMetrics.contentLength !== this._sentStartForContentLength
1480
+ ) {
1481
+ // On initial mount when using initialScrollIndex the offset will be 0 initially
1482
+ // and will trigger an unexpected onStartReached. To avoid this we can use
1483
+ // timestamp to differentiate between the initial scroll metrics and when we actually
1484
+ // received the first scroll event.
1485
+ if (!initialScrollIndex || this._scrollMetrics.timestamp !== 0) {
1486
+ this._sentStartForContentLength = this._scrollMetrics.contentLength;
1487
+ onStartReached({distanceFromStart});
1488
+ }
1489
+ }
1490
+
1491
+ // If the user scrolls away from the start or end and back again,
1492
+ // cause onStartReached or onEndReached to be triggered again
1493
+ else {
1494
+ this._sentStartForContentLength = isWithinStartThreshold
1495
+ ? this._sentStartForContentLength
1496
+ : 0;
1497
+ this._sentEndForContentLength = isWithinEndThreshold
1498
+ ? this._sentEndForContentLength
1499
+ : 0;
1500
+ }
1501
+ }
1502
+
1503
+ _onContentSizeChange = (width: number, height: number) => {
1504
+ if (
1505
+ width > 0 &&
1506
+ height > 0 &&
1507
+ this.props.initialScrollIndex != null &&
1508
+ this.props.initialScrollIndex > 0 &&
1509
+ !this._hasTriggeredInitialScrollToIndex
1510
+ ) {
1511
+ if (this.props.contentOffset == null) {
1512
+ this.scrollToIndex({
1513
+ animated: false,
1514
+ index: this.props.initialScrollIndex,
1515
+ });
1516
+ }
1517
+ this._hasTriggeredInitialScrollToIndex = true;
1518
+ }
1519
+ if (this.props.onContentSizeChange) {
1520
+ this.props.onContentSizeChange(width, height);
1521
+ }
1522
+ this._scrollMetrics.contentLength = this._selectLength({height, width});
1523
+ this._scheduleCellsToRenderUpdate();
1524
+ this._maybeCallOnEdgeReached();
1525
+ };
1526
+
1527
+ /* Translates metrics from a scroll event in a parent VirtualizedList into
1528
+ * coordinates relative to the child list.
1529
+ */
1530
+ _convertParentScrollMetrics = (metrics: {
1531
+ visibleLength: number,
1532
+ offset: number,
1533
+ ...
1534
+ }): $FlowFixMe => {
1535
+ // Offset of the top of the nested list relative to the top of its parent's viewport
1536
+ const offset = metrics.offset - this._offsetFromParentVirtualizedList;
1537
+ // Child's visible length is the same as its parent's
1538
+ const visibleLength = metrics.visibleLength;
1539
+ const dOffset = offset - this._scrollMetrics.offset;
1540
+ const contentLength = this._scrollMetrics.contentLength;
1541
+
1542
+ return {
1543
+ visibleLength,
1544
+ contentLength,
1545
+ offset,
1546
+ dOffset,
1547
+ };
1548
+ };
1549
+
1550
+ _onScroll = (e: Object) => {
1551
+ this._nestedChildLists.forEach(childList => {
1552
+ childList._onScroll(e);
1553
+ });
1554
+ if (this.props.onScroll) {
1555
+ this.props.onScroll(e);
1556
+ }
1557
+ const timestamp = e.timeStamp;
1558
+ let visibleLength = this._selectLength(e.nativeEvent.layoutMeasurement);
1559
+ let contentLength = this._selectLength(e.nativeEvent.contentSize);
1560
+ let offset = this._selectOffset(e.nativeEvent.contentOffset);
1561
+ let dOffset = offset - this._scrollMetrics.offset;
1562
+
1563
+ if (this._isNestedWithSameOrientation()) {
1564
+ if (this._scrollMetrics.contentLength === 0) {
1565
+ // Ignore scroll events until onLayout has been called and we
1566
+ // know our offset from our offset from our parent
1567
+ return;
1568
+ }
1569
+ ({visibleLength, contentLength, offset, dOffset} =
1570
+ this._convertParentScrollMetrics({
1571
+ visibleLength,
1572
+ offset,
1573
+ }));
1574
+ }
1575
+
1576
+ const dt = this._scrollMetrics.timestamp
1577
+ ? Math.max(1, timestamp - this._scrollMetrics.timestamp)
1578
+ : 1;
1579
+ const velocity = dOffset / dt;
1580
+
1581
+ if (
1582
+ dt > 500 &&
1583
+ this._scrollMetrics.dt > 500 &&
1584
+ contentLength > 5 * visibleLength &&
1585
+ !this._hasWarned.perf
1586
+ ) {
1587
+ infoLog(
1588
+ 'VirtualizedList: You have a large list that is slow to update - make sure your ' +
1589
+ 'renderItem function renders components that follow React performance best practices ' +
1590
+ 'like PureComponent, shouldComponentUpdate, etc.',
1591
+ {dt, prevDt: this._scrollMetrics.dt, contentLength},
1592
+ );
1593
+ this._hasWarned.perf = true;
1594
+ }
1595
+
1596
+ // For invalid negative values (w/ RTL), set this to 1.
1597
+ const zoomScale = e.nativeEvent.zoomScale < 0 ? 1 : e.nativeEvent.zoomScale;
1598
+ this._scrollMetrics = {
1599
+ contentLength,
1600
+ dt,
1601
+ dOffset,
1602
+ offset,
1603
+ timestamp,
1604
+ velocity,
1605
+ visibleLength,
1606
+ zoomScale,
1607
+ };
1608
+ this._updateViewableItems(this.props, this.state.cellsAroundViewport);
1609
+ if (!this.props) {
1610
+ return;
1611
+ }
1612
+ this._maybeCallOnEdgeReached();
1613
+ if (velocity !== 0) {
1614
+ this._fillRateHelper.activate();
1615
+ }
1616
+ this._computeBlankness();
1617
+ this._scheduleCellsToRenderUpdate();
1618
+ };
1619
+
1620
+ _scheduleCellsToRenderUpdate() {
1621
+ const {first, last} = this.state.cellsAroundViewport;
1622
+ const {offset, visibleLength, velocity} = this._scrollMetrics;
1623
+ const itemCount = this.props.getItemCount(this.props.data);
1624
+ let hiPri = false;
1625
+ const onStartReachedThreshold = onStartReachedThresholdOrDefault(
1626
+ this.props.onStartReachedThreshold,
1627
+ );
1628
+ const onEndReachedThreshold = onEndReachedThresholdOrDefault(
1629
+ this.props.onEndReachedThreshold,
1630
+ );
1631
+ // Mark as high priority if we're close to the start of the first item
1632
+ // But only if there are items before the first rendered item
1633
+ if (first > 0) {
1634
+ const distTop =
1635
+ offset - this.__getFrameMetricsApprox(first, this.props).offset;
1636
+ hiPri =
1637
+ distTop < 0 ||
1638
+ (velocity < -2 &&
1639
+ distTop <
1640
+ getScrollingThreshold(onStartReachedThreshold, visibleLength));
1641
+ }
1642
+ // Mark as high priority if we're close to the end of the last item
1643
+ // But only if there are items after the last rendered item
1644
+ if (!hiPri && last >= 0 && last < itemCount - 1) {
1645
+ const distBottom =
1646
+ this.__getFrameMetricsApprox(last, this.props).offset -
1647
+ (offset + visibleLength);
1648
+ hiPri =
1649
+ distBottom < 0 ||
1650
+ (velocity > 2 &&
1651
+ distBottom <
1652
+ getScrollingThreshold(onEndReachedThreshold, visibleLength));
1653
+ }
1654
+ // Only trigger high-priority updates if we've actually rendered cells,
1655
+ // and with that size estimate, accurately compute how many cells we should render.
1656
+ // Otherwise, it would just render as many cells as it can (of zero dimension),
1657
+ // each time through attempting to render more (limited by maxToRenderPerBatch),
1658
+ // starving the renderer from actually laying out the objects and computing _averageCellLength.
1659
+ // If this is triggered in an `componentDidUpdate` followed by a hiPri cellToRenderUpdate
1660
+ // We shouldn't do another hipri cellToRenderUpdate
1661
+ if (
1662
+ hiPri &&
1663
+ (this._averageCellLength || this.props.getItemLayout) &&
1664
+ !this._hiPriInProgress
1665
+ ) {
1666
+ this._hiPriInProgress = true;
1667
+ // Don't worry about interactions when scrolling quickly; focus on filling content as fast
1668
+ // as possible.
1669
+ this._updateCellsToRenderBatcher.dispose({abort: true});
1670
+ this._updateCellsToRender();
1671
+ return;
1672
+ } else {
1673
+ this._updateCellsToRenderBatcher.schedule();
1674
+ }
1675
+ }
1676
+
1677
+ _onScrollBeginDrag = (e: ScrollEvent): void => {
1678
+ this._nestedChildLists.forEach(childList => {
1679
+ childList._onScrollBeginDrag(e);
1680
+ });
1681
+ this._viewabilityTuples.forEach(tuple => {
1682
+ tuple.viewabilityHelper.recordInteraction();
1683
+ });
1684
+ this._hasInteracted = true;
1685
+ this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
1686
+ };
1687
+
1688
+ _onScrollEndDrag = (e: ScrollEvent): void => {
1689
+ this._nestedChildLists.forEach(childList => {
1690
+ childList._onScrollEndDrag(e);
1691
+ });
1692
+ const {velocity} = e.nativeEvent;
1693
+ if (velocity) {
1694
+ this._scrollMetrics.velocity = this._selectOffset(velocity);
1695
+ }
1696
+ this._computeBlankness();
1697
+ this.props.onScrollEndDrag && this.props.onScrollEndDrag(e);
1698
+ };
1699
+
1700
+ _onMomentumScrollBegin = (e: ScrollEvent): void => {
1701
+ this._nestedChildLists.forEach(childList => {
1702
+ childList._onMomentumScrollBegin(e);
1703
+ });
1704
+ this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e);
1705
+ };
1706
+
1707
+ _onMomentumScrollEnd = (e: ScrollEvent): void => {
1708
+ this._nestedChildLists.forEach(childList => {
1709
+ childList._onMomentumScrollEnd(e);
1710
+ });
1711
+ this._scrollMetrics.velocity = 0;
1712
+ this._computeBlankness();
1713
+ this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e);
1714
+ };
1715
+
1716
+ _updateCellsToRender = () => {
1717
+ this.setState((state, props) => {
1718
+ const cellsAroundViewport = this._adjustCellsAroundViewport(
1719
+ props,
1720
+ state.cellsAroundViewport,
1721
+ );
1722
+ const renderMask = VirtualizedList._createRenderMask(
1723
+ props,
1724
+ cellsAroundViewport,
1725
+ this._getNonViewportRenderRegions(props),
1726
+ );
1727
+
1728
+ if (
1729
+ cellsAroundViewport.first === state.cellsAroundViewport.first &&
1730
+ cellsAroundViewport.last === state.cellsAroundViewport.last &&
1731
+ renderMask.equals(state.renderMask)
1732
+ ) {
1733
+ return null;
1734
+ }
1735
+
1736
+ return {cellsAroundViewport, renderMask};
1737
+ });
1738
+ };
1739
+
1740
+ _createViewToken = (
1741
+ index: number,
1742
+ isViewable: boolean,
1743
+ props: FrameMetricProps,
1744
+ // $FlowFixMe[missing-local-annot]
1745
+ ) => {
1746
+ const {data, getItem} = props;
1747
+ const item = getItem(data, index);
1748
+ return {
1749
+ index,
1750
+ item,
1751
+ key: this._keyExtractor(item, index, props),
1752
+ isViewable,
1753
+ };
1754
+ };
1755
+
1756
+ /**
1757
+ * Gets an approximate offset to an item at a given index. Supports
1758
+ * fractional indices.
1759
+ */
1760
+ _getOffsetApprox = (index: number, props: FrameMetricProps): number => {
1761
+ if (Number.isInteger(index)) {
1762
+ return this.__getFrameMetricsApprox(index, props).offset;
1763
+ } else {
1764
+ const frameMetrics = this.__getFrameMetricsApprox(
1765
+ Math.floor(index),
1766
+ props,
1767
+ );
1768
+ const remainder = index - Math.floor(index);
1769
+ return frameMetrics.offset + remainder * frameMetrics.length;
1770
+ }
1771
+ };
1772
+
1773
+ __getFrameMetricsApprox: (
1774
+ index: number,
1775
+ props: FrameMetricProps,
1776
+ ) => {
1777
+ length: number,
1778
+ offset: number,
1779
+ ...
1780
+ } = (index, props) => {
1781
+ const frame = this._getFrameMetrics(index, props);
1782
+ if (frame && frame.index === index) {
1783
+ // check for invalid frames due to row re-ordering
1784
+ return frame;
1785
+ } else {
1786
+ const {data, getItemCount, getItemLayout} = props;
1787
+ invariant(
1788
+ index >= 0 && index < getItemCount(data),
1789
+ 'Tried to get frame for out of range index ' + index,
1790
+ );
1791
+ invariant(
1792
+ !getItemLayout,
1793
+ 'Should not have to estimate frames when a measurement metrics function is provided',
1794
+ );
1795
+ return {
1796
+ length: this._averageCellLength,
1797
+ offset: this._averageCellLength * index,
1798
+ };
1799
+ }
1800
+ };
1801
+
1802
+ _getFrameMetrics = (
1803
+ index: number,
1804
+ props: FrameMetricProps,
1805
+ ): ?{
1806
+ length: number,
1807
+ offset: number,
1808
+ index: number,
1809
+ inLayout?: boolean,
1810
+ ...
1811
+ } => {
1812
+ const {data, getItem, getItemCount, getItemLayout} = props;
1813
+ invariant(
1814
+ index >= 0 && index < getItemCount(data),
1815
+ 'Tried to get frame for out of range index ' + index,
1816
+ );
1817
+ const item = getItem(data, index);
1818
+ const frame = this._frames[this._keyExtractor(item, index, props)];
1819
+ if (!frame || frame.index !== index) {
1820
+ if (getItemLayout) {
1821
+ /* $FlowFixMe[prop-missing] (>=0.63.0 site=react_native_fb) This comment
1822
+ * suppresses an error found when Flow v0.63 was deployed. To see the error
1823
+ * delete this comment and run Flow. */
1824
+ return getItemLayout(data, index);
1825
+ }
1826
+ }
1827
+ return frame;
1828
+ };
1829
+
1830
+ _getNonViewportRenderRegions = (
1831
+ props: FrameMetricProps,
1832
+ ): $ReadOnlyArray<{
1833
+ first: number,
1834
+ last: number,
1835
+ }> => {
1836
+ // Keep a viewport's worth of content around the last focused cell to allow
1837
+ // random navigation around it without any blanking. E.g. tabbing from one
1838
+ // focused item out of viewport to another.
1839
+ if (
1840
+ !(this._lastFocusedCellKey && this._cellRefs[this._lastFocusedCellKey])
1841
+ ) {
1842
+ return [];
1843
+ }
1844
+
1845
+ const lastFocusedCellRenderer = this._cellRefs[this._lastFocusedCellKey];
1846
+ const focusedCellIndex = lastFocusedCellRenderer.props.index;
1847
+ const itemCount = props.getItemCount(props.data);
1848
+
1849
+ // The cell may have been unmounted and have a stale index
1850
+ if (
1851
+ focusedCellIndex >= itemCount ||
1852
+ this._indicesToKeys.get(focusedCellIndex) !== this._lastFocusedCellKey
1853
+ ) {
1854
+ return [];
1855
+ }
1856
+
1857
+ let first = focusedCellIndex;
1858
+ let heightOfCellsBeforeFocused = 0;
1859
+ for (
1860
+ let i = first - 1;
1861
+ i >= 0 && heightOfCellsBeforeFocused < this._scrollMetrics.visibleLength;
1862
+ i--
1863
+ ) {
1864
+ first--;
1865
+ heightOfCellsBeforeFocused += this.__getFrameMetricsApprox(
1866
+ i,
1867
+ props,
1868
+ ).length;
1869
+ }
1870
+
1871
+ let last = focusedCellIndex;
1872
+ let heightOfCellsAfterFocused = 0;
1873
+ for (
1874
+ let i = last + 1;
1875
+ i < itemCount &&
1876
+ heightOfCellsAfterFocused < this._scrollMetrics.visibleLength;
1877
+ i++
1878
+ ) {
1879
+ last++;
1880
+ heightOfCellsAfterFocused += this.__getFrameMetricsApprox(
1881
+ i,
1882
+ props,
1883
+ ).length;
1884
+ }
1885
+
1886
+ return [{first, last}];
1887
+ };
1888
+
1889
+ _updateViewableItems(
1890
+ props: FrameMetricProps,
1891
+ cellsAroundViewport: {first: number, last: number},
1892
+ ) {
1893
+ this._viewabilityTuples.forEach(tuple => {
1894
+ tuple.viewabilityHelper.onUpdate(
1895
+ props,
1896
+ this._scrollMetrics.offset,
1897
+ this._scrollMetrics.visibleLength,
1898
+ this._getFrameMetrics,
1899
+ this._createViewToken,
1900
+ tuple.onViewableItemsChanged,
1901
+ cellsAroundViewport,
1902
+ );
1903
+ });
1904
+ }
1905
+ }
1906
+
1907
+ const styles = StyleSheet.create({
1908
+ verticallyInverted: {
1909
+ transform: [{scaleY: -1}],
1910
+ },
1911
+ horizontallyInverted: {
1912
+ transform: [{scaleX: -1}],
1913
+ },
1914
+ debug: {
1915
+ flex: 1,
1916
+ },
1917
+ debugOverlayBase: {
1918
+ position: 'absolute',
1919
+ top: 0,
1920
+ right: 0,
1921
+ },
1922
+ debugOverlay: {
1923
+ bottom: 0,
1924
+ width: 20,
1925
+ borderColor: 'blue',
1926
+ borderWidth: 1,
1927
+ },
1928
+ debugOverlayFrame: {
1929
+ left: 0,
1930
+ backgroundColor: 'orange',
1931
+ },
1932
+ debugOverlayFrameLast: {
1933
+ left: 0,
1934
+ borderColor: 'green',
1935
+ borderWidth: 2,
1936
+ },
1937
+ debugOverlayFrameVis: {
1938
+ left: 0,
1939
+ borderColor: 'red',
1940
+ borderWidth: 2,
1941
+ },
1942
+ });
1943
+
1944
+ module.exports = VirtualizedList;