VirtualizedList.js 70 KB

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