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