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