react-native-list 1.0.1 → 2.0.0-alpha.1

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 (190) hide show
  1. package/README.md +188 -32
  2. package/ReactNativeList.podspec +39 -0
  3. package/android/CMakeLists.txt +48 -0
  4. package/android/build.gradle +151 -0
  5. package/android/fix-prefab.gradle +51 -0
  6. package/android/gradle.properties +5 -0
  7. package/android/src/main/AndroidManifest.xml +2 -0
  8. package/android/src/main/cpp/JHybridUiListModule.cpp +192 -0
  9. package/android/src/main/cpp/JHybridUiListModule.h +50 -0
  10. package/android/src/main/cpp/cpp-adapter.cpp +12 -0
  11. package/android/src/main/java/com/hannojg/reactnativelist/ReactNativeListPackage.kt +27 -0
  12. package/android/src/main/java/com/margelo/nitro/reactnativelist/HybridNativeListDataSource.kt +146 -0
  13. package/android/src/main/java/com/margelo/nitro/reactnativelist/HybridNativeListLayout.kt +86 -0
  14. package/android/src/main/java/com/margelo/nitro/reactnativelist/HybridUiListModule.kt +116 -0
  15. package/android/src/main/java/com/margelo/nitro/reactnativelist/HybridUiListView.kt +410 -0
  16. package/android/src/main/java/com/margelo/nitro/reactnativelist/HybridViewHolder.kt +9 -0
  17. package/android/src/main/java/com/margelo/nitro/reactnativelist/NativeListAdapter.kt +217 -0
  18. package/ios/DataSource/HybridNativeListDataSource.swift +213 -0
  19. package/ios/HybridObjects/HybridUiListModule.swift +49 -0
  20. package/ios/HybridObjects/HybridViewHolder.swift +16 -0
  21. package/ios/Layout/HybridNativeListLayout.swift +128 -0
  22. package/ios/Utils/ErrorUtils.h +26 -0
  23. package/ios/Utils/HybridIOSWorkletsModuleProxyHolder.swift +10 -0
  24. package/ios/Utils/SurfaceHelper.h +20 -0
  25. package/ios/Utils/SurfaceHelper.mm +144 -0
  26. package/ios/Utils/SurfacePresenterRegistry.h +17 -0
  27. package/ios/Utils/SurfacePresenterRegistry.m +31 -0
  28. package/ios/Utils/TurboModuleInstaller.h +18 -0
  29. package/ios/Utils/TurboModuleInstaller.mm +267 -0
  30. package/ios/Views/HostCell.swift +216 -0
  31. package/ios/Views/HybridUiListView.swift +695 -0
  32. package/metro/RendererProxyThreadSwitch.js +66 -0
  33. package/metro-config.d.ts +1 -0
  34. package/metro-config.js +52 -0
  35. package/nitro.json +47 -0
  36. package/nitrogen/generated/.gitattributes +1 -0
  37. package/nitrogen/generated/android/ReactNativeList+autolinking.cmake +99 -0
  38. package/nitrogen/generated/android/ReactNativeList+autolinking.gradle +27 -0
  39. package/nitrogen/generated/android/ReactNativeListOnLoad.cpp +156 -0
  40. package/nitrogen/generated/android/ReactNativeListOnLoad.hpp +34 -0
  41. package/nitrogen/generated/android/c++/JFunc_bool_NativeListItem_NativeListItem.hpp +83 -0
  42. package/nitrogen/generated/android/c++/JFunc_bool_double_NativeListItem_double.hpp +83 -0
  43. package/nitrogen/generated/android/c++/JFunc_double_std__string.hpp +78 -0
  44. package/nitrogen/generated/android/c++/JHybridIOSWorkletsModuleProxyHolderSpec.cpp +49 -0
  45. package/nitrogen/generated/android/c++/JHybridIOSWorkletsModuleProxyHolderSpec.hpp +63 -0
  46. package/nitrogen/generated/android/c++/JHybridNativeLinearListLayoutSpec.cpp +63 -0
  47. package/nitrogen/generated/android/c++/JHybridNativeLinearListLayoutSpec.hpp +65 -0
  48. package/nitrogen/generated/android/c++/JHybridNativeListDataSourceSpec.cpp +101 -0
  49. package/nitrogen/generated/android/c++/JHybridNativeListDataSourceSpec.hpp +70 -0
  50. package/nitrogen/generated/android/c++/JHybridNativeListLayoutSpec.cpp +49 -0
  51. package/nitrogen/generated/android/c++/JHybridNativeListLayoutSpec.hpp +63 -0
  52. package/nitrogen/generated/android/c++/JHybridUiListModuleSpec.cpp +65 -0
  53. package/nitrogen/generated/android/c++/JHybridUiListModuleSpec.hpp +64 -0
  54. package/nitrogen/generated/android/c++/JHybridUiListViewSpec.cpp +92 -0
  55. package/nitrogen/generated/android/c++/JHybridUiListViewSpec.hpp +67 -0
  56. package/nitrogen/generated/android/c++/JHybridViewHolderSpec.cpp +49 -0
  57. package/nitrogen/generated/android/c++/JHybridViewHolderSpec.hpp +63 -0
  58. package/nitrogen/generated/android/c++/JNativeItemSizeEstimate.hpp +61 -0
  59. package/nitrogen/generated/android/c++/JNativeLinearListLayoutConfig.hpp +81 -0
  60. package/nitrogen/generated/android/c++/JNativeLinearListLayoutIOSConfig.hpp +59 -0
  61. package/nitrogen/generated/android/c++/JNativeListItem.hpp +76 -0
  62. package/nitrogen/generated/android/c++/JVariant_NullType_HybridIOSWorkletsModuleProxyHolderSpec.cpp +26 -0
  63. package/nitrogen/generated/android/c++/JVariant_NullType_HybridIOSWorkletsModuleProxyHolderSpec.hpp +72 -0
  64. package/nitrogen/generated/android/c++/views/JHybridUiListViewStateUpdater.cpp +53 -0
  65. package/nitrogen/generated/android/c++/views/JHybridUiListViewStateUpdater.hpp +49 -0
  66. package/nitrogen/generated/android/c++/views/JHybridViewHolderStateUpdater.cpp +53 -0
  67. package/nitrogen/generated/android/c++/views/JHybridViewHolderStateUpdater.hpp +49 -0
  68. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/Func_bool_NativeListItem_NativeListItem.kt +80 -0
  69. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/Func_bool_double_NativeListItem_double.kt +80 -0
  70. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/Func_double_std__string.kt +80 -0
  71. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/HybridIOSWorkletsModuleProxyHolderSpec.kt +52 -0
  72. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/HybridNativeLinearListLayoutSpec.kt +54 -0
  73. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/HybridNativeListDataSourceSpec.kt +87 -0
  74. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/HybridNativeListLayoutSpec.kt +52 -0
  75. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/HybridUiListModuleSpec.kt +59 -0
  76. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/HybridUiListViewSpec.kt +76 -0
  77. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/HybridViewHolderSpec.kt +53 -0
  78. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/NativeItemSizeEstimate.kt +56 -0
  79. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/NativeLinearListLayoutConfig.kt +76 -0
  80. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/NativeLinearListLayoutIOSConfig.kt +51 -0
  81. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/NativeListItem.kt +71 -0
  82. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/ReactNativeListOnLoad.kt +35 -0
  83. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/Variant_NullType_HybridIOSWorkletsModuleProxyHolderSpec.kt +62 -0
  84. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/views/HybridUiListViewManager.kt +80 -0
  85. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/views/HybridUiListViewStateUpdater.kt +23 -0
  86. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/views/HybridViewHolderManager.kt +80 -0
  87. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativelist/views/HybridViewHolderStateUpdater.kt +23 -0
  88. package/nitrogen/generated/ios/ReactNativeList+autolinking.rb +62 -0
  89. package/nitrogen/generated/ios/ReactNativeList-Swift-Cxx-Bridge.cpp +162 -0
  90. package/nitrogen/generated/ios/ReactNativeList-Swift-Cxx-Bridge.hpp +368 -0
  91. package/nitrogen/generated/ios/ReactNativeList-Swift-Cxx-Umbrella.hpp +92 -0
  92. package/nitrogen/generated/ios/ReactNativeListAutolinking.mm +83 -0
  93. package/nitrogen/generated/ios/ReactNativeListAutolinking.swift +86 -0
  94. package/nitrogen/generated/ios/c++/HybridIOSWorkletsModuleProxyHolderSpecSwift.cpp +11 -0
  95. package/nitrogen/generated/ios/c++/HybridIOSWorkletsModuleProxyHolderSpecSwift.hpp +75 -0
  96. package/nitrogen/generated/ios/c++/HybridNativeLinearListLayoutSpecSwift.cpp +11 -0
  97. package/nitrogen/generated/ios/c++/HybridNativeLinearListLayoutSpecSwift.hpp +92 -0
  98. package/nitrogen/generated/ios/c++/HybridNativeListDataSourceSpecSwift.cpp +11 -0
  99. package/nitrogen/generated/ios/c++/HybridNativeListDataSourceSpecSwift.hpp +132 -0
  100. package/nitrogen/generated/ios/c++/HybridNativeListLayoutSpecSwift.cpp +11 -0
  101. package/nitrogen/generated/ios/c++/HybridNativeListLayoutSpecSwift.hpp +75 -0
  102. package/nitrogen/generated/ios/c++/HybridUiListModuleSpecSwift.cpp +11 -0
  103. package/nitrogen/generated/ios/c++/HybridUiListModuleSpecSwift.hpp +93 -0
  104. package/nitrogen/generated/ios/c++/HybridUiListViewSpecSwift.cpp +11 -0
  105. package/nitrogen/generated/ios/c++/HybridUiListViewSpecSwift.hpp +121 -0
  106. package/nitrogen/generated/ios/c++/HybridViewHolderSpecSwift.cpp +11 -0
  107. package/nitrogen/generated/ios/c++/HybridViewHolderSpecSwift.hpp +75 -0
  108. package/nitrogen/generated/ios/c++/views/HybridUiListViewComponent.mm +118 -0
  109. package/nitrogen/generated/ios/c++/views/HybridViewHolderComponent.mm +118 -0
  110. package/nitrogen/generated/ios/swift/Func_bool_NativeListItem_NativeListItem.swift +47 -0
  111. package/nitrogen/generated/ios/swift/Func_bool_double_NativeListItem_double.swift +47 -0
  112. package/nitrogen/generated/ios/swift/Func_double_std__string.swift +47 -0
  113. package/nitrogen/generated/ios/swift/HybridIOSWorkletsModuleProxyHolderSpec.swift +55 -0
  114. package/nitrogen/generated/ios/swift/HybridIOSWorkletsModuleProxyHolderSpec_cxx.swift +128 -0
  115. package/nitrogen/generated/ios/swift/HybridNativeLinearListLayoutSpec.swift +55 -0
  116. package/nitrogen/generated/ios/swift/HybridNativeLinearListLayoutSpec_cxx.swift +140 -0
  117. package/nitrogen/generated/ios/swift/HybridNativeListDataSourceSpec.swift +62 -0
  118. package/nitrogen/generated/ios/swift/HybridNativeListDataSourceSpec_cxx.swift +222 -0
  119. package/nitrogen/generated/ios/swift/HybridNativeListLayoutSpec.swift +55 -0
  120. package/nitrogen/generated/ios/swift/HybridNativeListLayoutSpec_cxx.swift +128 -0
  121. package/nitrogen/generated/ios/swift/HybridUiListModuleSpec.swift +56 -0
  122. package/nitrogen/generated/ios/swift/HybridUiListModuleSpec_cxx.swift +175 -0
  123. package/nitrogen/generated/ios/swift/HybridUiListViewSpec.swift +59 -0
  124. package/nitrogen/generated/ios/swift/HybridUiListViewSpec_cxx.swift +227 -0
  125. package/nitrogen/generated/ios/swift/HybridViewHolderSpec.swift +55 -0
  126. package/nitrogen/generated/ios/swift/HybridViewHolderSpec_cxx.swift +147 -0
  127. package/nitrogen/generated/ios/swift/NativeItemSizeEstimate.swift +60 -0
  128. package/nitrogen/generated/ios/swift/NativeLinearListLayoutConfig.swift +60 -0
  129. package/nitrogen/generated/ios/swift/NativeLinearListLayoutIOSConfig.swift +35 -0
  130. package/nitrogen/generated/ios/swift/NativeListItem.swift +75 -0
  131. package/nitrogen/generated/ios/swift/Variant_NullType__any_HybridIOSWorkletsModuleProxyHolderSpec_.swift +30 -0
  132. package/nitrogen/generated/shared/c++/HybridIOSWorkletsModuleProxyHolderSpec.cpp +21 -0
  133. package/nitrogen/generated/shared/c++/HybridIOSWorkletsModuleProxyHolderSpec.hpp +62 -0
  134. package/nitrogen/generated/shared/c++/HybridNativeLinearListLayoutSpec.cpp +22 -0
  135. package/nitrogen/generated/shared/c++/HybridNativeLinearListLayoutSpec.hpp +67 -0
  136. package/nitrogen/generated/shared/c++/HybridNativeListDataSourceSpec.cpp +28 -0
  137. package/nitrogen/generated/shared/c++/HybridNativeListDataSourceSpec.hpp +72 -0
  138. package/nitrogen/generated/shared/c++/HybridNativeListLayoutSpec.cpp +21 -0
  139. package/nitrogen/generated/shared/c++/HybridNativeListLayoutSpec.hpp +62 -0
  140. package/nitrogen/generated/shared/c++/HybridUiListModuleSpec.cpp +22 -0
  141. package/nitrogen/generated/shared/c++/HybridUiListModuleSpec.hpp +68 -0
  142. package/nitrogen/generated/shared/c++/HybridUiListViewSpec.cpp +25 -0
  143. package/nitrogen/generated/shared/c++/HybridUiListViewSpec.hpp +79 -0
  144. package/nitrogen/generated/shared/c++/HybridUiManagerHelperSpec.cpp +23 -0
  145. package/nitrogen/generated/shared/c++/HybridUiManagerHelperSpec.hpp +65 -0
  146. package/nitrogen/generated/shared/c++/HybridViewHolderSpec.cpp +21 -0
  147. package/nitrogen/generated/shared/c++/HybridViewHolderSpec.hpp +62 -0
  148. package/nitrogen/generated/shared/c++/NativeItemSizeEstimate.hpp +87 -0
  149. package/nitrogen/generated/shared/c++/NativeLinearListLayoutConfig.hpp +105 -0
  150. package/nitrogen/generated/shared/c++/NativeLinearListLayoutIOSConfig.hpp +85 -0
  151. package/nitrogen/generated/shared/c++/NativeListItem.hpp +101 -0
  152. package/nitrogen/generated/shared/c++/views/HybridUiListViewComponent.cpp +72 -0
  153. package/nitrogen/generated/shared/c++/views/HybridUiListViewComponent.hpp +109 -0
  154. package/nitrogen/generated/shared/c++/views/HybridViewHolderComponent.cpp +72 -0
  155. package/nitrogen/generated/shared/c++/views/HybridViewHolderComponent.hpp +109 -0
  156. package/nitrogen/generated/shared/json/UiListViewConfig.json +9 -0
  157. package/nitrogen/generated/shared/json/ViewHolderConfig.json +9 -0
  158. package/package.json +152 -5
  159. package/react-native.config.js +16 -0
  160. package/src/ListDataSource.ts +232 -0
  161. package/src/ListLayout.ts +95 -0
  162. package/src/UiListModule.ts +5 -0
  163. package/src/hooks/useChangeEffect.ts +50 -0
  164. package/src/index.tsx +49 -0
  165. package/src/privateGlobals.ts +20 -0
  166. package/src/renderer/fabric/RenderHelper.ts +29 -0
  167. package/src/renderer/fabric/UiManagerHelper.ts +5 -0
  168. package/src/renderer/react/ReactFabricMirror.bundle.js +1984 -0
  169. package/src/renderer/react/ReactFabricMirror.ts +766 -0
  170. package/src/renderer/react/ReactFabricRenderer.ts +11 -0
  171. package/src/specs/IOSWorkletsModuleProxyHolder.nitro.ts +6 -0
  172. package/src/specs/NativeLinearListLayout.nitro.ts +23 -0
  173. package/src/specs/NativeListDataSource.nitro.ts +28 -0
  174. package/src/specs/NativeListLayout.nitro.ts +6 -0
  175. package/src/specs/UIListModule.nitro.ts +13 -0
  176. package/src/specs/UIManagerHelper.nitro.ts +34 -0
  177. package/src/specs/UiListView.nitro.ts +31 -0
  178. package/src/specs/ViewHolder.nitro.ts +11 -0
  179. package/src/views/List.tsx +525 -0
  180. package/src/views/UiListHostComponent.ts +8 -0
  181. package/FillRateHelper.js +0 -179
  182. package/FlatList.js +0 -494
  183. package/LICENSE.md +0 -31
  184. package/MetroListView.js +0 -166
  185. package/SectionList.js +0 -291
  186. package/ViewabilityHelper.js +0 -260
  187. package/VirtualizeUtils.js +0 -163
  188. package/VirtualizedList.js +0 -861
  189. package/VirtualizedSectionList.js +0 -397
  190. package/index.js +0 -5
@@ -1,861 +0,0 @@
1
- /**
2
- * Copyright (c) 2015-present, Facebook, Inc.
3
- * All rights reserved.
4
- *
5
- * This source code is licensed under the BSD-style license found in the
6
- * LICENSE file in the root directory of this source tree. An additional grant
7
- * of patent rights can be found in the PATENTS file in the same directory.
8
- *
9
- * @providesModule VirtualizedList
10
- * @flow
11
- */
12
- 'use strict';
13
-
14
- const Batchinator = require('Batchinator');
15
- const FillRateHelper = require('FillRateHelper');
16
- const React = require('React');
17
- const ReactNative = require('ReactNative');
18
- const RefreshControl = require('RefreshControl');
19
- const ScrollView = require('ScrollView');
20
- const View = require('View');
21
- const ViewabilityHelper = require('./ViewabilityHelper');
22
-
23
- const infoLog = require('infoLog');
24
- const invariant = require('fbjs/lib/invariant');
25
-
26
- const {computeWindowedRenderLimits} = require('VirtualizeUtils');
27
-
28
- import type {ViewabilityConfig, ViewToken} from './ViewabilityHelper';
29
-
30
- type Item = any;
31
-
32
- type renderItemType = (info: {
33
- item: Item,
34
- index: number,
35
- separators: {
36
- highlight: () => void,
37
- unhighlight: () => void,
38
- updateProps: (select: 'leading' | 'trailing', newProps: Object) => void,
39
- },
40
- }) => ?React.Element<any>;
41
-
42
- type RequiredProps = {
43
- renderItem: renderItemType,
44
- /**
45
- * The default accessor functions assume this is an Array<{key: string}> but you can override
46
- * getItem, getItemCount, and keyExtractor to handle any type of index-based data.
47
- */
48
- data?: any,
49
- };
50
- type OptionalProps = {
51
- /**
52
- * `debug` will turn on extra logging and visual overlays to aid with debugging both usage and
53
- * implementation, but with a significant perf hit.
54
- */
55
- debug?: ?boolean,
56
- /**
57
- * DEPRECATED: Virtualization provides significant performance and memory optimizations, but fully
58
- * unmounts react instances that are outside of the render window. You should only need to disable
59
- * this for debugging purposes.
60
- */
61
- disableVirtualization: boolean,
62
- /**
63
- * A marker property for telling the list to re-render (since it implements `PureComponent`). If
64
- * any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the
65
- * `data` prop, stick it here and treat it immutably.
66
- */
67
- extraData?: any,
68
- /**
69
- * A generic accessor for extracting an item from any sort of data blob.
70
- */
71
- getItem: (data: any, index: number) => ?Item,
72
- /**
73
- * Determines how many items are in the data blob.
74
- */
75
- getItemCount: (data: any) => number,
76
- getItemLayout?: (data: any, index: number) =>
77
- {length: number, offset: number, index: number}, // e.g. height, y
78
- horizontal?: ?boolean,
79
- /**
80
- * How many items to render in the initial batch. This should be enough to fill the screen but not
81
- * much more. Note these items will never be unmounted as part of the windowed rendering in order
82
- * to improve perceived performance of scroll-to-top actions.
83
- */
84
- initialNumToRender: number,
85
- keyExtractor: (item: Item, index: number) => string,
86
- /**
87
- * The maximum number of items to render in each incremental render batch. The more rendered at
88
- * once, the better the fill rate, but responsiveness my suffer because rendering content may
89
- * interfere with responding to button taps or other interactions.
90
- */
91
- maxToRenderPerBatch: number,
92
- onEndReached?: ?(info: {distanceFromEnd: number}) => void,
93
- onEndReachedThreshold?: ?number, // units of visible length
94
- onLayout?: ?Function,
95
- /**
96
- * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make
97
- * sure to also set the `refreshing` prop correctly.
98
- */
99
- onRefresh?: ?Function,
100
- /**
101
- * Called when the viewability of rows changes, as defined by the
102
- * `viewabilityConfig` prop.
103
- */
104
- onViewableItemsChanged?: ?(info: {
105
- viewableItems: Array<ViewToken>,
106
- changed: Array<ViewToken>,
107
- }) => void,
108
- /**
109
- * Set this true while waiting for new data from a refresh.
110
- */
111
- refreshing?: ?boolean,
112
- /**
113
- * Note: may have bugs (missing content) in some circumstances - use at your own risk.
114
- *
115
- * This may improve scroll performance for large lists.
116
- */
117
- removeClippedSubviews?: boolean,
118
- /**
119
- * Render a custom scroll component, e.g. with a differently styled `RefreshControl`.
120
- */
121
- renderScrollComponent: (props: Object) => React.Element<any>,
122
- /**
123
- * Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off
124
- * screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`.
125
- */
126
- updateCellsBatchingPeriod: number,
127
- viewabilityConfig?: ViewabilityConfig,
128
- /**
129
- * Determines the maximum number of items rendered outside of the visible area, in units of
130
- * visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will
131
- * render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing
132
- * this number will reduce memory consumption and may improve performance, but will increase the
133
- * chance that fast scrolling may reveal momentary blank areas of unrendered content.
134
- */
135
- windowSize: number,
136
- };
137
- /* $FlowFixMe - this Props seems to be missing a bunch of stuff. Remove this
138
- * comment to see the errors */
139
- export type Props = RequiredProps & OptionalProps;
140
-
141
- let _usedIndexForKey = false;
142
-
143
- type State = {first: number, last: number};
144
-
145
- /**
146
- * Base implementation for the more convenient [`<FlatList>`](/react-native/docs/flatlist.html)
147
- * and [`<SectionList>`](/react-native/docs/sectionlist.html) components, which are also better
148
- * documented. In general, this should only really be used if you need more flexibility than
149
- * `FlatList` provides, e.g. for use with immutable data instead of plain arrays.
150
- *
151
- * Virtualization massively improves memory consumption and performance of large lists by
152
- * maintaining a finite render window of active items and replacing all items outside of the render
153
- * window with appropriately sized blank space. The window adapts to scrolling behavior, and items
154
- * are rendered incrementally with low-pri (after any running interactions) if they are far from the
155
- * visible area, or with hi-pri otherwise to minimize the potential of seeing blank space.
156
- *
157
- * Some caveats:
158
- *
159
- * - Internal state is not preserved when content scrolls out of the render window. Make sure all
160
- * your data is captured in the item data or external stores like Flux, Redux, or Relay.
161
- * - This is a `PureComponent` which means that it will not re-render if `props` remain shallow-
162
- * equal. Make sure that everything your `renderItem` function depends on is passed as a prop
163
- * (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on
164
- * changes. This includes the `data` prop and parent component state.
165
- * - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
166
- * offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see
167
- * blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
168
- * and we are working on improving it behind the scenes.
169
- * - By default, the list looks for a `key` prop on each item and uses that for the React key.
170
- * Alternatively, you can provide a custom `keyExtractor` prop.
171
- *
172
- */
173
- class VirtualizedList extends React.PureComponent<OptionalProps, Props, State> {
174
- props: Props;
175
-
176
- // scrollToEnd may be janky without getItemLayout prop
177
- scrollToEnd(params?: ?{animated?: ?boolean}) {
178
- const animated = params ? params.animated : true;
179
- const veryLast = this.props.getItemCount(this.props.data) - 1;
180
- const frame = this._getFrameMetricsApprox(veryLast);
181
- const offset = frame.offset + frame.length + this._footerLength -
182
- this._scrollMetrics.visibleLength;
183
- this._scrollRef.scrollTo(
184
- this.props.horizontal ? {x: offset, animated} : {y: offset, animated}
185
- );
186
- }
187
-
188
- // scrollToIndex may be janky without getItemLayout prop
189
- scrollToIndex(params: {
190
- animated?: ?boolean, index: number, viewOffset?: number, viewPosition?: number
191
- }) {
192
- const {data, horizontal, getItemCount, getItemLayout} = this.props;
193
- const {animated, index, viewOffset, viewPosition} = params;
194
- invariant(
195
- index >= 0 && index < getItemCount(data),
196
- `scrollToIndex out of range: ${index} vs ${getItemCount(data) - 1}`,
197
- );
198
- invariant(
199
- getItemLayout || index < this._highestMeasuredFrameIndex,
200
- 'scrollToIndex should be used in conjunction with getItemLayout, ' +
201
- 'otherwise there is no way to know the location of an arbitrary index.',
202
- );
203
- const frame = this._getFrameMetricsApprox(index);
204
- const offset = Math.max(
205
- 0,
206
- frame.offset - (viewPosition || 0) * (this._scrollMetrics.visibleLength - frame.length),
207
- ) - (viewOffset || 0);
208
- this._scrollRef.scrollTo(horizontal ? {x: offset, animated} : {y: offset, animated});
209
- }
210
-
211
- // scrollToItem may be janky without getItemLayout prop. Required linear scan through items -
212
- // use scrollToIndex instead if possible.
213
- scrollToItem(params: {animated?: ?boolean, item: Item, viewPosition?: number}) {
214
- const {item} = params;
215
- const {data, getItem, getItemCount} = this.props;
216
- const itemCount = getItemCount(data);
217
- for (let index = 0; index < itemCount; index++) {
218
- if (getItem(data, index) === item) {
219
- this.scrollToIndex({...params, index});
220
- break;
221
- }
222
- }
223
- }
224
-
225
- scrollToOffset(params: {animated?: ?boolean, offset: number}) {
226
- const {animated, offset} = params;
227
- this._scrollRef.scrollTo(
228
- this.props.horizontal ? {x: offset, animated} : {y: offset, animated}
229
- );
230
- }
231
-
232
- recordInteraction() {
233
- this._viewabilityHelper.recordInteraction();
234
- this._updateViewableItems(this.props.data);
235
- }
236
-
237
- /**
238
- * Provides a handle to the underlying scroll responder.
239
- * Note that `this._scrollRef` might not be a `ScrollView`, so we
240
- * need to check that it responds to `getScrollResponder` before calling it.
241
- */
242
- getScrollResponder() {
243
- if (this._scrollRef && this._scrollRef.getScrollResponder) {
244
- return this._scrollRef.getScrollResponder();
245
- }
246
- }
247
-
248
- getScrollableNode() {
249
- if (this._scrollRef && this._scrollRef.getScrollableNode) {
250
- return this._scrollRef.getScrollableNode();
251
- } else {
252
- return ReactNative.findNodeHandle(this._scrollRef);
253
- }
254
- }
255
-
256
- static defaultProps = {
257
- disableVirtualization: false,
258
- getItem: (data: any, index: number) => data[index],
259
- getItemCount: (data: any) => data ? data.length : 0,
260
- horizontal: false,
261
- initialNumToRender: 10,
262
- keyExtractor: (item: Item, index: number) => {
263
- if (item.key != null) {
264
- return item.key;
265
- }
266
- _usedIndexForKey = true;
267
- return String(index);
268
- },
269
- maxToRenderPerBatch: 10,
270
- onEndReachedThreshold: 2, // multiples of length
271
- renderScrollComponent: (props: Props) => {
272
- if (props.onRefresh) {
273
- invariant(
274
- typeof props.refreshing === 'boolean',
275
- '`refreshing` prop must be set as a boolean in order to use `onRefresh`, but got `' +
276
- JSON.stringify(props.refreshing) + '`',
277
- );
278
- return (
279
- <ScrollView
280
- {...props}
281
- refreshControl={
282
- <RefreshControl
283
- refreshing={props.refreshing}
284
- onRefresh={props.onRefresh}
285
- />
286
- }
287
- />
288
- );
289
- } else {
290
- return <ScrollView {...props} />;
291
- }
292
- },
293
- scrollEventThrottle: 50,
294
- updateCellsBatchingPeriod: 50,
295
- windowSize: 21, // multiples of length
296
- };
297
-
298
- state: State;
299
-
300
- constructor(props: Props, context: Object) {
301
- super(props, context);
302
- invariant(
303
- !props.onScroll || !props.onScroll.__isNative,
304
- 'Components based on VirtualizedList must be wrapped with Animated.createAnimatedComponent ' +
305
- 'to support native onScroll events with useNativeDriver',
306
- );
307
-
308
- this._fillRateHelper = new FillRateHelper(this._getFrameMetrics);
309
- this._updateCellsToRenderBatcher = new Batchinator(
310
- this._updateCellsToRender,
311
- this.props.updateCellsBatchingPeriod,
312
- );
313
- this._viewabilityHelper = new ViewabilityHelper(this.props.viewabilityConfig);
314
- this.state = {
315
- first: 0,
316
- last: Math.min(this.props.getItemCount(this.props.data), this.props.initialNumToRender) - 1,
317
- };
318
- }
319
-
320
- componentWillUnmount() {
321
- this._updateViewableItems(null);
322
- this._updateCellsToRenderBatcher.dispose();
323
- this._viewabilityHelper.dispose();
324
- }
325
-
326
- componentWillReceiveProps(newProps: Props) {
327
- const {data, extraData, getItemCount, maxToRenderPerBatch} = newProps;
328
- // first and last could be stale (e.g. if a new, shorter items props is passed in), so we make
329
- // sure we're rendering a reasonable range here.
330
- this.setState({
331
- first: Math.max(0, Math.min(this.state.first, getItemCount(data) - 1 - maxToRenderPerBatch)),
332
- last: Math.max(0, Math.min(this.state.last, getItemCount(data) - 1)),
333
- });
334
- if (data !== this.props.data || extraData !== this.props.extraData) {
335
- this._hasDataChangedSinceEndReached = true;
336
- }
337
- this._updateCellsToRenderBatcher.schedule();
338
- }
339
-
340
- _pushCells(
341
- cells: Array<Object>,
342
- stickyHeaderIndices: Array<number>,
343
- stickyIndicesFromProps: Set<number>,
344
- first: number,
345
- last: number,
346
- ) {
347
- const {ItemSeparatorComponent, data, getItem, getItemCount, keyExtractor} = this.props;
348
- const stickyOffset = this.props.ListHeaderComponent ? 1 : 0;
349
- const end = getItemCount(data) - 1;
350
- let prevCellKey;
351
- last = Math.min(end, last);
352
- for (let ii = first; ii <= last; ii++) {
353
- const item = getItem(data, ii);
354
- invariant(item, 'No item for index ' + ii);
355
- const key = keyExtractor(item, ii);
356
- if (stickyIndicesFromProps.has(ii + stickyOffset)) {
357
- stickyHeaderIndices.push(cells.length);
358
- }
359
- cells.push(
360
- <CellRenderer
361
- cellKey={key}
362
- ItemSeparatorComponent={ii < end ? ItemSeparatorComponent : undefined}
363
- index={ii}
364
- item={item}
365
- key={key}
366
- prevCellKey={prevCellKey}
367
- onUpdateSeparators={this._onUpdateSeparators}
368
- onLayout={(e) => this._onCellLayout(e, key, ii)}
369
- onUnmount={this._onCellUnmount}
370
- parentProps={this.props}
371
- ref={(ref) => {this._cellRefs[key] = ref;}}
372
- />
373
- );
374
- prevCellKey = key;
375
- }
376
- }
377
-
378
- _onUpdateSeparators = (keys: Array<?string>, newProps: Object) => {
379
- keys.forEach((key) => {
380
- const ref = key != null && this._cellRefs[key];
381
- ref && ref.updateSeparatorProps(newProps);
382
- });
383
- };
384
-
385
- render() {
386
- const {ListFooterComponent, ListHeaderComponent} = this.props;
387
- const {data, disableVirtualization, horizontal} = this.props;
388
- const cells = [];
389
- const stickyIndicesFromProps = new Set(this.props.stickyHeaderIndices);
390
- const stickyHeaderIndices = [];
391
- if (ListHeaderComponent) {
392
- const element = React.isValidElement(ListHeaderComponent)
393
- ? ListHeaderComponent
394
- : <ListHeaderComponent />;
395
- cells.push(
396
- <View key="$header" onLayout={this._onLayoutHeader}>
397
- {element}
398
- </View>
399
- );
400
- }
401
- const itemCount = this.props.getItemCount(data);
402
- if (itemCount > 0) {
403
- _usedIndexForKey = false;
404
- const spacerKey = !horizontal ? 'height' : 'width';
405
- const lastInitialIndex = this.props.initialNumToRender - 1;
406
- const {first, last} = this.state;
407
- this._pushCells(cells, stickyHeaderIndices, stickyIndicesFromProps, 0, lastInitialIndex);
408
- const firstAfterInitial = Math.max(lastInitialIndex + 1, first);
409
- if (!disableVirtualization && first > lastInitialIndex + 1) {
410
- let insertedStickySpacer = false;
411
- if (stickyIndicesFromProps.size > 0) {
412
- const stickyOffset = ListHeaderComponent ? 1 : 0;
413
- // See if there are any sticky headers in the virtualized space that we need to render.
414
- for (let ii = firstAfterInitial - 1; ii > lastInitialIndex; ii--) {
415
- if (stickyIndicesFromProps.has(ii + stickyOffset)) {
416
- const initBlock = this._getFrameMetricsApprox(lastInitialIndex);
417
- const stickyBlock = this._getFrameMetricsApprox(ii);
418
- const leadSpace = stickyBlock.offset - (initBlock.offset + initBlock.length);
419
- cells.push(
420
- <View key="$sticky_lead" style={{[spacerKey]: leadSpace}} />
421
- );
422
- this._pushCells(cells, stickyHeaderIndices, stickyIndicesFromProps, ii, ii);
423
- const trailSpace = this._getFrameMetricsApprox(first).offset -
424
- (stickyBlock.offset + stickyBlock.length);
425
- cells.push(
426
- <View key="$sticky_trail" style={{[spacerKey]: trailSpace}} />
427
- );
428
- insertedStickySpacer = true;
429
- break;
430
- }
431
- }
432
- }
433
- if (!insertedStickySpacer) {
434
- const initBlock = this._getFrameMetricsApprox(lastInitialIndex);
435
- const firstSpace = this._getFrameMetricsApprox(first).offset -
436
- (initBlock.offset + initBlock.length);
437
- cells.push(
438
- <View key="$lead_spacer" style={{[spacerKey]: firstSpace}} />
439
- );
440
- }
441
- }
442
- this._pushCells(cells, stickyHeaderIndices, stickyIndicesFromProps, firstAfterInitial, last);
443
- if (!this._hasWarned.keys && _usedIndexForKey) {
444
- console.warn(
445
- 'VirtualizedList: missing keys for items, make sure to specify a key property on each ' +
446
- 'item or provide a custom keyExtractor.'
447
- );
448
- this._hasWarned.keys = true;
449
- }
450
- if (!disableVirtualization && last < itemCount - 1) {
451
- const lastFrame = this._getFrameMetricsApprox(last);
452
- // Without getItemLayout, we limit our tail spacer to the _highestMeasuredFrameIndex to
453
- // prevent the user for hyperscrolling into un-measured area because otherwise content will
454
- // likely jump around as it renders in above the viewport.
455
- const end = this.props.getItemLayout ?
456
- itemCount - 1 :
457
- Math.min(itemCount - 1, this._highestMeasuredFrameIndex);
458
- const endFrame = this._getFrameMetricsApprox(end);
459
- const tailSpacerLength =
460
- (endFrame.offset + endFrame.length) -
461
- (lastFrame.offset + lastFrame.length);
462
- cells.push(
463
- <View key="$tail_spacer" style={{[spacerKey]: tailSpacerLength}} />
464
- );
465
- }
466
- }
467
- if (ListFooterComponent) {
468
- const element = React.isValidElement(ListFooterComponent)
469
- ? ListFooterComponent
470
- : <ListFooterComponent />;
471
- cells.push(
472
- <View key="$footer" onLayout={this._onLayoutFooter}>
473
- {element}
474
- </View>
475
- );
476
- }
477
- const ret = React.cloneElement(
478
- this.props.renderScrollComponent(this.props),
479
- {
480
- onContentSizeChange: this._onContentSizeChange,
481
- onLayout: this._onLayout,
482
- onScroll: this._onScroll,
483
- onScrollBeginDrag: this._onScrollBeginDrag,
484
- ref: this._captureScrollRef,
485
- scrollEventThrottle: this.props.scrollEventThrottle, // TODO: Android support
486
- stickyHeaderIndices,
487
- },
488
- cells,
489
- );
490
- if (this.props.debug) {
491
- return <View style={{flex: 1}}>{ret}{this._renderDebugOverlay()}</View>;
492
- } else {
493
- return ret;
494
- }
495
- }
496
-
497
- componentDidUpdate() {
498
- this._updateCellsToRenderBatcher.schedule();
499
- }
500
-
501
- _averageCellLength = 0;
502
- _cellRefs = {};
503
- _hasDataChangedSinceEndReached = true;
504
- _hasWarned = {};
505
- _highestMeasuredFrameIndex = 0;
506
- _headerLength = 0;
507
- _fillRateHelper: FillRateHelper;
508
- _frames = {};
509
- _footerLength = 0;
510
- _scrollMetrics = {
511
- visibleLength: 0, contentLength: 0, offset: 0, dt: 10, velocity: 0, timestamp: 0,
512
- };
513
- _scrollRef = (null: any);
514
- _sentEndForContentLength = 0;
515
- _totalCellLength = 0;
516
- _totalCellsMeasured = 0;
517
- _updateCellsToRenderBatcher: Batchinator;
518
- _viewabilityHelper: ViewabilityHelper;
519
-
520
- _captureScrollRef = (ref) => {
521
- this._scrollRef = ref;
522
- };
523
-
524
- _onCellLayout(e, cellKey, index) {
525
- const layout = e.nativeEvent.layout;
526
- const next = {
527
- offset: this._selectOffset(layout),
528
- length: this._selectLength(layout),
529
- index,
530
- inLayout: true,
531
- };
532
- const curr = this._frames[cellKey];
533
- if (!curr ||
534
- next.offset !== curr.offset ||
535
- next.length !== curr.length ||
536
- index !== curr.index
537
- ) {
538
- this._totalCellLength += next.length - (curr ? curr.length : 0);
539
- this._totalCellsMeasured += (curr ? 0 : 1);
540
- this._averageCellLength = this._totalCellLength / this._totalCellsMeasured;
541
- this._frames[cellKey] = next;
542
- this._highestMeasuredFrameIndex = Math.max(this._highestMeasuredFrameIndex, index);
543
- this._updateCellsToRenderBatcher.schedule();
544
- } else {
545
- this._frames[cellKey].inLayout = true;
546
- }
547
- this._sampleFillRate('onCellLayout');
548
- }
549
-
550
- _onCellUnmount = (cellKey: string) => {
551
- const curr = this._frames[cellKey];
552
- if (curr) {
553
- this._frames[cellKey] = {...curr, inLayout: false};
554
- }
555
- };
556
-
557
- _onLayout = (e: Object) => {
558
- this._scrollMetrics.visibleLength = this._selectLength(e.nativeEvent.layout);
559
- this.props.onLayout && this.props.onLayout(e);
560
- this._updateCellsToRenderBatcher.schedule();
561
- };
562
-
563
- _onLayoutFooter = (e) => {
564
- this._footerLength = this._selectLength(e.nativeEvent.layout);
565
- };
566
-
567
- _onLayoutHeader = (e) => {
568
- this._headerLength = this._selectLength(e.nativeEvent.layout);
569
- };
570
-
571
- _renderDebugOverlay() {
572
- const normalize = this._scrollMetrics.visibleLength / this._scrollMetrics.contentLength;
573
- const framesInLayout = [];
574
- const itemCount = this.props.getItemCount(this.props.data);
575
- for (let ii = 0; ii < itemCount; ii++) {
576
- const frame = this._getFrameMetricsApprox(ii);
577
- if (frame.inLayout) {
578
- framesInLayout.push(frame);
579
- }
580
- }
581
- const windowTop = this._getFrameMetricsApprox(this.state.first).offset;
582
- const frameLast = this._getFrameMetricsApprox(this.state.last);
583
- const windowLen = frameLast.offset + frameLast.length - windowTop;
584
- const visTop = this._scrollMetrics.offset;
585
- const visLen = this._scrollMetrics.visibleLength;
586
- const baseStyle = {position: 'absolute', top: 0, right: 0};
587
- return (
588
- <View style={{...baseStyle, bottom: 0, width: 20, borderColor: 'blue', borderWidth: 1}}>
589
- {framesInLayout.map((f, ii) =>
590
- <View key={'f' + ii} style={{
591
- ...baseStyle,
592
- left: 0,
593
- top: f.offset * normalize,
594
- height: f.length * normalize,
595
- backgroundColor: 'orange',
596
- }} />
597
- )}
598
- <View style={{
599
- ...baseStyle,
600
- left: 0,
601
- top: windowTop * normalize,
602
- height: windowLen * normalize,
603
- borderColor: 'green',
604
- borderWidth: 2,
605
- }} />
606
- <View style={{
607
- ...baseStyle,
608
- left: 0,
609
- top: visTop * normalize,
610
- height: visLen * normalize,
611
- borderColor: 'red',
612
- borderWidth: 2,
613
- }} />
614
- </View>
615
- );
616
- }
617
-
618
- _selectLength(metrics: {height: number, width: number}): number {
619
- return !this.props.horizontal ? metrics.height : metrics.width;
620
- }
621
-
622
- _selectOffset(metrics: {x: number, y: number}): number {
623
- return !this.props.horizontal ? metrics.y : metrics.x;
624
- }
625
-
626
- _onContentSizeChange = (width: number, height: number) => {
627
- if (this.props.onContentSizeChange) {
628
- this.props.onContentSizeChange(width, height);
629
- }
630
- this._scrollMetrics.contentLength = this._selectLength({height, width});
631
- this._updateCellsToRenderBatcher.schedule();
632
- };
633
-
634
- _sampleFillRate(sampleType: string) {
635
- this._fillRateHelper.computeInfoSampled(
636
- sampleType,
637
- this.props,
638
- this.state,
639
- this._scrollMetrics,
640
- );
641
- }
642
-
643
- _onScroll = (e: Object) => {
644
- if (this.props.onScroll) {
645
- this.props.onScroll(e);
646
- }
647
- const timestamp = e.timeStamp;
648
- const visibleLength = this._selectLength(e.nativeEvent.layoutMeasurement);
649
- const contentLength = this._selectLength(e.nativeEvent.contentSize);
650
- const offset = this._selectOffset(e.nativeEvent.contentOffset);
651
- const dt = Math.max(1, timestamp - this._scrollMetrics.timestamp);
652
- if (dt > 500 && this._scrollMetrics.dt > 500 && (contentLength > (5 * visibleLength)) &&
653
- !this._hasWarned.perf) {
654
- infoLog(
655
- 'VirtualizedList: You have a large list that is slow to update - make sure your ' +
656
- 'renderItem function renders components that follow React performance best practices ' +
657
- 'like PureComponent, shouldComponentUpdate, etc.',
658
- {dt, prevDt: this._scrollMetrics.dt, contentLength},
659
- );
660
- this._hasWarned.perf = true;
661
- }
662
- const dOffset = offset - this._scrollMetrics.offset;
663
- const velocity = dOffset / dt;
664
- this._scrollMetrics = {contentLength, dt, offset, timestamp, velocity, visibleLength};
665
- const {data, getItemCount, onEndReached, onEndReachedThreshold, windowSize} = this.props;
666
-
667
- this._sampleFillRate('onScroll');
668
-
669
- this._updateViewableItems(data);
670
- if (!data) {
671
- return;
672
- }
673
- const distanceFromEnd = contentLength - visibleLength - offset;
674
- const itemCount = getItemCount(data);
675
- if (onEndReached &&
676
- this.state.last === itemCount - 1 &&
677
- distanceFromEnd < onEndReachedThreshold * visibleLength &&
678
- (this._hasDataChangedSinceEndReached ||
679
- this._scrollMetrics.contentLength !== this._sentEndForContentLength)) {
680
- // Only call onEndReached once for a given dataset + content length.
681
- this._hasDataChangedSinceEndReached = false;
682
- this._sentEndForContentLength = this._scrollMetrics.contentLength;
683
- onEndReached({distanceFromEnd});
684
- }
685
- const {first, last} = this.state;
686
- if ((first > 0 && velocity < 0) || (last < itemCount - 1 && velocity > 0)) {
687
- const distanceToContentEdge = Math.min(
688
- Math.abs(this._getFrameMetricsApprox(first).offset - offset),
689
- Math.abs(this._getFrameMetricsApprox(last).offset - (offset + visibleLength)),
690
- );
691
- const hiPri = distanceToContentEdge < (windowSize * visibleLength / 4);
692
- if (hiPri) {
693
- // Don't worry about interactions when scrolling quickly; focus on filling content as fast
694
- // as possible.
695
- this._updateCellsToRenderBatcher.dispose({abort: true});
696
- this._updateCellsToRender();
697
- return;
698
- }
699
- }
700
- this._updateCellsToRenderBatcher.schedule();
701
- };
702
-
703
- _onScrollBeginDrag = (e): void => {
704
- this._viewabilityHelper.recordInteraction();
705
- this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
706
- };
707
-
708
- _updateCellsToRender = () => {
709
- const {data, disableVirtualization, getItemCount, onEndReachedThreshold} = this.props;
710
- this._updateViewableItems(data);
711
- if (!data) {
712
- return;
713
- }
714
- this.setState((state) => {
715
- let newState;
716
- if (!disableVirtualization) {
717
- newState = computeWindowedRenderLimits(
718
- this.props, state, this._getFrameMetricsApprox, this._scrollMetrics,
719
- );
720
- } else {
721
- const {contentLength, offset, visibleLength} = this._scrollMetrics;
722
- const distanceFromEnd = contentLength - visibleLength - offset;
723
- const renderAhead = distanceFromEnd < onEndReachedThreshold * visibleLength ?
724
- this.props.maxToRenderPerBatch : 0;
725
- newState = {
726
- first: 0,
727
- last: Math.min(state.last + renderAhead, getItemCount(data) - 1),
728
- };
729
- }
730
- return newState;
731
- });
732
- };
733
-
734
- _createViewToken = (index: number, isViewable: boolean) => {
735
- const {data, getItem, keyExtractor} = this.props;
736
- const item = getItem(data, index);
737
- invariant(item, 'Missing item for index ' + index);
738
- return {index, item, key: keyExtractor(item, index), isViewable};
739
- };
740
-
741
- _getFrameMetricsApprox = (index: number): {length: number, offset: number} => {
742
- const frame = this._getFrameMetrics(index);
743
- if (frame && frame.index === index) { // check for invalid frames due to row re-ordering
744
- return frame;
745
- } else {
746
- const {getItemLayout} = this.props;
747
- invariant(
748
- !getItemLayout,
749
- 'Should not have to estimate frames when a measurement metrics function is provided'
750
- );
751
- return {
752
- length: this._averageCellLength,
753
- offset: this._averageCellLength * index,
754
- };
755
- }
756
- };
757
-
758
- _getFrameMetrics = (index: number): ?{
759
- length: number, offset: number, index: number, inLayout?: boolean,
760
- } => {
761
- const {data, getItem, getItemCount, getItemLayout, keyExtractor} = this.props;
762
- invariant(getItemCount(data) > index, 'Tried to get frame for out of range index ' + index);
763
- const item = getItem(data, index);
764
- let frame = item && this._frames[keyExtractor(item, index)];
765
- if (!frame || frame.index !== index) {
766
- if (getItemLayout) {
767
- frame = getItemLayout(data, index);
768
- }
769
- }
770
- return frame;
771
- };
772
-
773
- _updateViewableItems(data: any) {
774
- const {getItemCount, onViewableItemsChanged} = this.props;
775
- if (!onViewableItemsChanged) {
776
- return;
777
- }
778
- this._viewabilityHelper.onUpdate(
779
- getItemCount(data),
780
- this._scrollMetrics.offset,
781
- this._scrollMetrics.visibleLength,
782
- this._getFrameMetrics,
783
- this._createViewToken,
784
- onViewableItemsChanged,
785
- this.state,
786
- );
787
- }
788
- }
789
-
790
- class CellRenderer extends React.Component {
791
- props: {
792
- ItemSeparatorComponent: ?ReactClass<*>,
793
- cellKey: string,
794
- index: number,
795
- item: Item,
796
- onLayout: (event: Object) => void, // This is extracted by ScrollViewStickyHeader
797
- onUnmount: (cellKey: string) => void,
798
- onUpdateSeparators: (cellKeys: Array<?string>, props: Object) => void,
799
- parentProps: {
800
- getItemLayout?: ?Function,
801
- renderItem: renderItemType,
802
- },
803
- prevCellKey: ?string,
804
- };
805
-
806
- state = {
807
- separatorProps: {
808
- highlighted: false,
809
- leadingItem: this.props.item,
810
- },
811
- };
812
-
813
- // TODO: consider factoring separator stuff out of VirtualizedList into FlatList since it's not
814
- // reused by SectionList and we can keep VirtualizedList simpler.
815
- _separators = {
816
- highlight: () => {
817
- const {cellKey, prevCellKey} = this.props;
818
- this.props.onUpdateSeparators([cellKey, prevCellKey], {highlighted: true});
819
- },
820
- unhighlight: () => {
821
- const {cellKey, prevCellKey} = this.props;
822
- this.props.onUpdateSeparators([cellKey, prevCellKey], {highlighted: false});
823
- },
824
- updateProps: (select: 'leading' | 'trailing', newProps: Object) => {
825
- const {cellKey, prevCellKey} = this.props;
826
- this.props.onUpdateSeparators([select === 'leading' ? cellKey : prevCellKey], newProps);
827
- },
828
- };
829
-
830
- updateSeparatorProps(newProps: Object) {
831
- this.setState(state => ({separatorProps: {...state.separatorProps, ...newProps}}));
832
- }
833
-
834
- componentWillUnmount() {
835
- this.props.onUnmount(this.props.cellKey);
836
- }
837
-
838
- render() {
839
- const {ItemSeparatorComponent, item, index, parentProps} = this.props;
840
- const {renderItem, getItemLayout} = parentProps;
841
- invariant(renderItem, 'no renderItem!');
842
- const element = renderItem({
843
- item,
844
- index,
845
- separators: this._separators,
846
- });
847
- const onLayout = (getItemLayout && !parentProps.debug && !FillRateHelper.enabled())
848
- ? undefined
849
- : this.props.onLayout;
850
- // NOTE: that when this is a sticky header, `onLayout` will get automatically extracted and
851
- // called explicitly by `ScrollViewStickyHeader`.
852
- return (
853
- <View onLayout={onLayout}>
854
- {element}
855
- {ItemSeparatorComponent && <ItemSeparatorComponent {...this.state.separatorProps} />}
856
- </View>
857
- );
858
- }
859
- }
860
-
861
- module.exports = VirtualizedList;