ScrollView.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  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. * @format
  8. * @flow strict-local
  9. */
  10. 'use strict';
  11. const AnimatedImplementation = require('../../Animated/src/AnimatedImplementation');
  12. const Platform = require('../../Utilities/Platform');
  13. const React = require('react');
  14. const ReactNative = require('../../Renderer/shims/ReactNative');
  15. require('../../Renderer/shims/ReactNative'); // Force side effects to prevent T55744311
  16. const ScrollResponder = require('../ScrollResponder');
  17. const ScrollViewStickyHeader = require('./ScrollViewStickyHeader');
  18. const StyleSheet = require('../../StyleSheet/StyleSheet');
  19. const View = require('../View/View');
  20. const dismissKeyboard = require('../../Utilities/dismissKeyboard');
  21. const flattenStyle = require('../../StyleSheet/flattenStyle');
  22. const invariant = require('invariant');
  23. const processDecelerationRate = require('./processDecelerationRate');
  24. const resolveAssetSource = require('../../Image/resolveAssetSource');
  25. const splitLayoutProps = require('../../StyleSheet/splitLayoutProps');
  26. const setAndForwardRef = require('../../Utilities/setAndForwardRef');
  27. import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType';
  28. import type {PointProp} from '../../StyleSheet/PointPropType';
  29. import type {ViewStyleProp} from '../../StyleSheet/StyleSheet';
  30. import type {ColorValue} from '../../StyleSheet/StyleSheetTypes';
  31. import type {
  32. PressEvent,
  33. ScrollEvent,
  34. LayoutEvent,
  35. } from '../../Types/CoreEventTypes';
  36. import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
  37. import type {State as ScrollResponderState} from '../ScrollResponder';
  38. import type {ViewProps} from '../View/ViewPropTypes';
  39. import type {Props as ScrollViewStickyHeaderProps} from './ScrollViewStickyHeader';
  40. import ScrollViewNativeComponent from './ScrollViewNativeComponent';
  41. import ScrollContentViewNativeComponent from './ScrollContentViewNativeComponent';
  42. import AndroidHorizontalScrollViewNativeComponent from './AndroidHorizontalScrollViewNativeComponent';
  43. import AndroidHorizontalScrollContentViewNativeComponent from './AndroidHorizontalScrollContentViewNativeComponent';
  44. let AndroidScrollView;
  45. let AndroidHorizontalScrollContentView;
  46. let AndroidHorizontalScrollView;
  47. let RCTScrollView;
  48. let RCTScrollContentView;
  49. if (Platform.OS === 'android') {
  50. AndroidScrollView = ScrollViewNativeComponent;
  51. AndroidHorizontalScrollView = AndroidHorizontalScrollViewNativeComponent;
  52. AndroidHorizontalScrollContentView = AndroidHorizontalScrollContentViewNativeComponent;
  53. } else {
  54. RCTScrollView = ScrollViewNativeComponent;
  55. RCTScrollContentView = ScrollContentViewNativeComponent;
  56. }
  57. // Public methods for ScrollView
  58. export type ScrollViewImperativeMethods = $ReadOnly<{|
  59. getScrollResponder: $PropertyType<ScrollView, 'getScrollResponder'>,
  60. getScrollableNode: $PropertyType<ScrollView, 'getScrollableNode'>,
  61. getInnerViewNode: $PropertyType<ScrollView, 'getInnerViewNode'>,
  62. getInnerViewRef: $PropertyType<ScrollView, 'getInnerViewRef'>,
  63. getNativeScrollRef: $PropertyType<ScrollView, 'getNativeScrollRef'>,
  64. scrollTo: $PropertyType<ScrollView, 'scrollTo'>,
  65. scrollToEnd: $PropertyType<ScrollView, 'scrollToEnd'>,
  66. flashScrollIndicators: $PropertyType<ScrollView, 'flashScrollIndicators'>,
  67. // ScrollResponder.Mixin public methods
  68. scrollResponderZoomTo: $PropertyType<
  69. typeof ScrollResponder.Mixin,
  70. 'scrollResponderZoomTo',
  71. >,
  72. scrollResponderScrollNativeHandleToKeyboard: $PropertyType<
  73. typeof ScrollResponder.Mixin,
  74. 'scrollResponderScrollNativeHandleToKeyboard',
  75. >,
  76. |}>;
  77. export type ScrollResponderType = ScrollViewImperativeMethods;
  78. type IOSProps = $ReadOnly<{|
  79. /**
  80. * Controls whether iOS should automatically adjust the content inset
  81. * for scroll views that are placed behind a navigation bar or
  82. * tab bar/ toolbar. The default value is true.
  83. * @platform ios
  84. */
  85. automaticallyAdjustContentInsets?: ?boolean,
  86. /**
  87. * The amount by which the scroll view content is inset from the edges
  88. * of the scroll view. Defaults to `{top: 0, left: 0, bottom: 0, right: 0}`.
  89. * @platform ios
  90. */
  91. contentInset?: ?EdgeInsetsProp,
  92. /**
  93. * Used to manually set the starting scroll offset.
  94. * The default value is `{x: 0, y: 0}`.
  95. * @platform ios
  96. */
  97. contentOffset?: ?PointProp,
  98. /**
  99. * When true, the scroll view bounces when it reaches the end of the
  100. * content if the content is larger then the scroll view along the axis of
  101. * the scroll direction. When false, it disables all bouncing even if
  102. * the `alwaysBounce*` props are true. The default value is true.
  103. * @platform ios
  104. */
  105. bounces?: ?boolean,
  106. /**
  107. * By default, ScrollView has an active pan responder that hijacks panresponders
  108. * deeper in the render tree in order to prevent accidental touches while scrolling.
  109. * However, in certain occasions (such as when using snapToInterval) in a vertical scrollview
  110. * You may want to disable this behavior in order to prevent the ScrollView from blocking touches
  111. */
  112. disableScrollViewPanResponder?: ?boolean,
  113. /**
  114. * When true, gestures can drive zoom past min/max and the zoom will animate
  115. * to the min/max value at gesture end, otherwise the zoom will not exceed
  116. * the limits.
  117. * @platform ios
  118. */
  119. bouncesZoom?: ?boolean,
  120. /**
  121. * When true, the scroll view bounces horizontally when it reaches the end
  122. * even if the content is smaller than the scroll view itself. The default
  123. * value is true when `horizontal={true}` and false otherwise.
  124. * @platform ios
  125. */
  126. alwaysBounceHorizontal?: ?boolean,
  127. /**
  128. * When true, the scroll view bounces vertically when it reaches the end
  129. * even if the content is smaller than the scroll view itself. The default
  130. * value is false when `horizontal={true}` and true otherwise.
  131. * @platform ios
  132. */
  133. alwaysBounceVertical?: ?boolean,
  134. /**
  135. * When true, the scroll view automatically centers the content when the
  136. * content is smaller than the scroll view bounds; when the content is
  137. * larger than the scroll view, this property has no effect. The default
  138. * value is false.
  139. * @platform ios
  140. */
  141. centerContent?: ?boolean,
  142. /**
  143. * The style of the scroll indicators.
  144. *
  145. * - `'default'` (the default), same as `black`.
  146. * - `'black'`, scroll indicator is black. This style is good against a light background.
  147. * - `'white'`, scroll indicator is white. This style is good against a dark background.
  148. *
  149. * @platform ios
  150. */
  151. indicatorStyle?: ?('default' | 'black' | 'white'),
  152. /**
  153. * When true, the ScrollView will try to lock to only vertical or horizontal
  154. * scrolling while dragging. The default value is false.
  155. * @platform ios
  156. */
  157. directionalLockEnabled?: ?boolean,
  158. /**
  159. * When false, once tracking starts, won't try to drag if the touch moves.
  160. * The default value is true.
  161. * @platform ios
  162. */
  163. canCancelContentTouches?: ?boolean,
  164. /**
  165. * When set, the scroll view will adjust the scroll position so that the first child that is
  166. * currently visible and at or beyond `minIndexForVisible` will not change position. This is
  167. * useful for lists that are loading content in both directions, e.g. a chat thread, where new
  168. * messages coming in might otherwise cause the scroll position to jump. A value of 0 is common,
  169. * but other values such as 1 can be used to skip loading spinners or other content that should
  170. * not maintain position.
  171. *
  172. * The optional `autoscrollToTopThreshold` can be used to make the content automatically scroll
  173. * to the top after making the adjustment if the user was within the threshold of the top before
  174. * the adjustment was made. This is also useful for chat-like applications where you want to see
  175. * new messages scroll into place, but not if the user has scrolled up a ways and it would be
  176. * disruptive to scroll a bunch.
  177. *
  178. * Caveat 1: Reordering elements in the scrollview with this enabled will probably cause
  179. * jumpiness and jank. It can be fixed, but there are currently no plans to do so. For now,
  180. * don't re-order the content of any ScrollViews or Lists that use this feature.
  181. *
  182. * Caveat 2: This simply uses `contentOffset` and `frame.origin` in native code to compute
  183. * visibility. Occlusion, transforms, and other complexity won't be taken into account as to
  184. * whether content is "visible" or not.
  185. *
  186. * @platform ios
  187. */
  188. maintainVisibleContentPosition?: ?$ReadOnly<{|
  189. minIndexForVisible: number,
  190. autoscrollToTopThreshold?: ?number,
  191. |}>,
  192. /**
  193. * The maximum allowed zoom scale. The default value is 1.0.
  194. * @platform ios
  195. */
  196. maximumZoomScale?: ?number,
  197. /**
  198. * The minimum allowed zoom scale. The default value is 1.0.
  199. * @platform ios
  200. */
  201. minimumZoomScale?: ?number,
  202. /**
  203. * When true, ScrollView allows use of pinch gestures to zoom in and out.
  204. * The default value is true.
  205. * @platform ios
  206. */
  207. pinchGestureEnabled?: ?boolean,
  208. /**
  209. * This controls how often the scroll event will be fired while scrolling
  210. * (as a time interval in ms). A lower number yields better accuracy for code
  211. * that is tracking the scroll position, but can lead to scroll performance
  212. * problems due to the volume of information being send over the bridge.
  213. *
  214. * Values between 0 and 17ms indicate 60fps updates are needed and throttling
  215. * will be disabled.
  216. *
  217. * If you do not need precise scroll position tracking, set this value higher
  218. * to limit the information being sent across the bridge.
  219. *
  220. * The default value is zero, which results in the scroll event being sent only
  221. * once each time the view is scrolled.
  222. *
  223. * @platform ios
  224. */
  225. scrollEventThrottle?: ?number,
  226. /**
  227. * The amount by which the scroll view indicators are inset from the edges
  228. * of the scroll view. This should normally be set to the same value as
  229. * the `contentInset`. Defaults to `{0, 0, 0, 0}`.
  230. * @platform ios
  231. */
  232. scrollIndicatorInsets?: ?EdgeInsetsProp,
  233. /**
  234. * When true, the scroll view can be programmatically scrolled beyond its
  235. * content size. The default value is false.
  236. * @platform ios
  237. */
  238. scrollToOverflowEnabled?: ?boolean,
  239. /**
  240. * When true, the scroll view scrolls to top when the status bar is tapped.
  241. * The default value is true.
  242. * @platform ios
  243. */
  244. scrollsToTop?: ?boolean,
  245. /**
  246. * Fires when the scroll view scrolls to top after the status bar has been tapped
  247. * @platform ios
  248. */
  249. onScrollToTop?: (event: ScrollEvent) => void,
  250. /**
  251. * When true, shows a horizontal scroll indicator.
  252. * The default value is true.
  253. */
  254. showsHorizontalScrollIndicator?: ?boolean,
  255. /**
  256. * When `snapToInterval` is set, `snapToAlignment` will define the relationship
  257. * of the snapping to the scroll view.
  258. *
  259. * - `'start'` (the default) will align the snap at the left (horizontal) or top (vertical)
  260. * - `'center'` will align the snap in the center
  261. * - `'end'` will align the snap at the right (horizontal) or bottom (vertical)
  262. *
  263. * @platform ios
  264. */
  265. snapToAlignment?: ?('start' | 'center' | 'end'),
  266. /**
  267. * The current scale of the scroll view content. The default value is 1.0.
  268. * @platform ios
  269. */
  270. zoomScale?: ?number,
  271. /**
  272. * This property specifies how the safe area insets are used to modify the
  273. * content area of the scroll view. The default value of this property is
  274. * "never". Available on iOS 11 and later.
  275. * @platform ios
  276. */
  277. contentInsetAdjustmentBehavior?: ?(
  278. | 'automatic'
  279. | 'scrollableAxes'
  280. | 'never'
  281. | 'always'
  282. ),
  283. /**
  284. * When true, ScrollView will emit updateChildFrames data in scroll events,
  285. * otherwise will not compute or emit child frame data. This only exists
  286. * to support legacy issues, `onLayout` should be used instead to retrieve
  287. * frame data.
  288. * The default value is false.
  289. * @platform ios
  290. */
  291. DEPRECATED_sendUpdatedChildFrames?: ?boolean,
  292. |}>;
  293. type AndroidProps = $ReadOnly<{|
  294. /**
  295. * Enables nested scrolling for Android API level 21+.
  296. * Nested scrolling is supported by default on iOS
  297. * @platform android
  298. */
  299. nestedScrollEnabled?: ?boolean,
  300. /**
  301. * Sometimes a scrollview takes up more space than its content fills. When this is
  302. * the case, this prop will fill the rest of the scrollview with a color to avoid setting
  303. * a background and creating unnecessary overdraw. This is an advanced optimization
  304. * that is not needed in the general case.
  305. * @platform android
  306. */
  307. endFillColor?: ?ColorValue,
  308. /**
  309. * Tag used to log scroll performance on this scroll view. Will force
  310. * momentum events to be turned on (see sendMomentumEvents). This doesn't do
  311. * anything out of the box and you need to implement a custom native
  312. * FpsListener for it to be useful.
  313. * @platform android
  314. */
  315. scrollPerfTag?: ?string,
  316. /**
  317. * Used to override default value of overScroll mode.
  318. *
  319. * Possible values:
  320. *
  321. * - `'auto'` - Default value, allow a user to over-scroll
  322. * this view only if the content is large enough to meaningfully scroll.
  323. * - `'always'` - Always allow a user to over-scroll this view.
  324. * - `'never'` - Never allow a user to over-scroll this view.
  325. *
  326. * @platform android
  327. */
  328. overScrollMode?: ?('auto' | 'always' | 'never'),
  329. /**
  330. * Causes the scrollbars not to turn transparent when they are not in use.
  331. * The default value is false.
  332. *
  333. * @platform android
  334. */
  335. persistentScrollbar?: ?boolean,
  336. /**
  337. * Fades out the edges of the the scroll content.
  338. *
  339. * If the value is greater than 0, the fading edges will be set accordingly
  340. * to the current scroll direction and position,
  341. * indicating if there is more content to show.
  342. *
  343. * The default value is 0.
  344. *
  345. * @platform android
  346. */
  347. fadingEdgeLength?: ?number,
  348. |}>;
  349. type VRProps = $ReadOnly<{|
  350. /**
  351. * Optionally an image can be used for the scroll bar thumb. This will
  352. * override the color. While the image is loading or the image fails to
  353. * load the color will be used instead. Use an alpha of 0 in the color
  354. * to avoid seeing it while the image is loading.
  355. *
  356. * - `uri` - a string representing the resource identifier for the image, which
  357. * should be either a local file path or the name of a static image resource
  358. * - `number` - Opaque type returned by something like
  359. * `import IMAGE from './image.jpg'`.
  360. * @platform vr
  361. */
  362. scrollBarThumbImage?: ?($ReadOnly<{||}> | number), // Opaque type returned by import IMAGE from './image.jpg'
  363. |}>;
  364. type StickyHeaderComponentType = React.AbstractComponent<
  365. ScrollViewStickyHeaderProps,
  366. $ReadOnly<{setNextHeaderY: number => void, ...}>,
  367. >;
  368. export type Props = $ReadOnly<{|
  369. ...ViewProps,
  370. ...IOSProps,
  371. ...AndroidProps,
  372. ...VRProps,
  373. /**
  374. * These styles will be applied to the scroll view content container which
  375. * wraps all of the child views. Example:
  376. *
  377. * ```
  378. * return (
  379. * <ScrollView contentContainerStyle={styles.contentContainer}>
  380. * </ScrollView>
  381. * );
  382. * ...
  383. * const styles = StyleSheet.create({
  384. * contentContainer: {
  385. * paddingVertical: 20
  386. * }
  387. * });
  388. * ```
  389. */
  390. contentContainerStyle?: ?ViewStyleProp,
  391. /**
  392. * When true, the scroll view stops on the next index (in relation to scroll
  393. * position at release) regardless of how fast the gesture is. This can be
  394. * used for pagination when the page is less than the width of the
  395. * horizontal ScrollView or the height of the vertical ScrollView. The default value is false.
  396. */
  397. disableIntervalMomentum?: ?boolean,
  398. /**
  399. * A floating-point number that determines how quickly the scroll view
  400. * decelerates after the user lifts their finger. You may also use string
  401. * shortcuts `"normal"` and `"fast"` which match the underlying iOS settings
  402. * for `UIScrollViewDecelerationRateNormal` and
  403. * `UIScrollViewDecelerationRateFast` respectively.
  404. *
  405. * - `'normal'`: 0.998 on iOS, 0.985 on Android (the default)
  406. * - `'fast'`: 0.99 on iOS, 0.9 on Android
  407. */
  408. decelerationRate?: ?('fast' | 'normal' | number),
  409. /**
  410. * When true, the scroll view's children are arranged horizontally in a row
  411. * instead of vertically in a column. The default value is false.
  412. */
  413. horizontal?: ?boolean,
  414. /**
  415. * If sticky headers should stick at the bottom instead of the top of the
  416. * ScrollView. This is usually used with inverted ScrollViews.
  417. */
  418. invertStickyHeaders?: ?boolean,
  419. /**
  420. * Determines whether the keyboard gets dismissed in response to a drag.
  421. *
  422. * *Cross platform*
  423. *
  424. * - `'none'` (the default), drags do not dismiss the keyboard.
  425. * - `'on-drag'`, the keyboard is dismissed when a drag begins.
  426. *
  427. * *iOS Only*
  428. *
  429. * - `'interactive'`, the keyboard is dismissed interactively with the drag and moves in
  430. * synchrony with the touch; dragging upwards cancels the dismissal.
  431. * On android this is not supported and it will have the same behavior as 'none'.
  432. */
  433. keyboardDismissMode?: ?// default
  434. (| 'none' // cross-platform
  435. | 'on-drag'
  436. | 'interactive'
  437. ), // ios only
  438. /**
  439. * Determines when the keyboard should stay visible after a tap.
  440. *
  441. * - `'never'` (the default), tapping outside of the focused text input when the keyboard
  442. * is up dismisses the keyboard. When this happens, children won't receive the tap.
  443. * - `'always'`, the keyboard will not dismiss automatically, and the scroll view will not
  444. * catch taps, but children of the scroll view can catch taps.
  445. * - `'handled'`, the keyboard will not dismiss automatically when the tap was handled by
  446. * a children, (or captured by an ancestor).
  447. * - `false`, deprecated, use 'never' instead
  448. * - `true`, deprecated, use 'always' instead
  449. */
  450. keyboardShouldPersistTaps?: ?('always' | 'never' | 'handled' | true | false),
  451. /**
  452. * Called when the momentum scroll starts (scroll which occurs as the ScrollView glides to a stop).
  453. */
  454. onMomentumScrollBegin?: ?(event: ScrollEvent) => void,
  455. /**
  456. * Called when the momentum scroll ends (scroll which occurs as the ScrollView glides to a stop).
  457. */
  458. onMomentumScrollEnd?: ?(event: ScrollEvent) => void,
  459. /**
  460. * Fires at most once per frame during scrolling. The frequency of the
  461. * events can be controlled using the `scrollEventThrottle` prop.
  462. */
  463. onScroll?: ?(event: ScrollEvent) => void,
  464. /**
  465. * Called when the user begins to drag the scroll view.
  466. */
  467. onScrollBeginDrag?: ?(event: ScrollEvent) => void,
  468. /**
  469. * Called when the user stops dragging the scroll view and it either stops
  470. * or begins to glide.
  471. */
  472. onScrollEndDrag?: ?(event: ScrollEvent) => void,
  473. /**
  474. * Called when scrollable content view of the ScrollView changes.
  475. *
  476. * Handler function is passed the content width and content height as parameters:
  477. * `(contentWidth, contentHeight)`
  478. *
  479. * It's implemented using onLayout handler attached to the content container
  480. * which this ScrollView renders.
  481. */
  482. onContentSizeChange?: (contentWidth: number, contentHeight: number) => void,
  483. onKeyboardDidShow?: (event: PressEvent) => void,
  484. /**
  485. * When true, the scroll view stops on multiples of the scroll view's size
  486. * when scrolling. This can be used for horizontal pagination. The default
  487. * value is false.
  488. *
  489. * Note: Vertical pagination is not supported on Android.
  490. */
  491. pagingEnabled?: ?boolean,
  492. /**
  493. * When false, the view cannot be scrolled via touch interaction.
  494. * The default value is true.
  495. *
  496. * Note that the view can always be scrolled by calling `scrollTo`.
  497. */
  498. scrollEnabled?: ?boolean,
  499. /**
  500. * When true, shows a vertical scroll indicator.
  501. * The default value is true.
  502. */
  503. showsVerticalScrollIndicator?: ?boolean,
  504. /**
  505. * An array of child indices determining which children get docked to the
  506. * top of the screen when scrolling. For example, passing
  507. * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the
  508. * top of the scroll view. This property is not supported in conjunction
  509. * with `horizontal={true}`.
  510. */
  511. stickyHeaderIndices?: ?$ReadOnlyArray<number>,
  512. /**
  513. * A React Component that will be used to render sticky headers.
  514. * To be used together with `stickyHeaderIndices` or with `SectionList`, defaults to `ScrollViewStickyHeader`.
  515. * You may need to set this if your sticky header uses custom transforms (eg. translation),
  516. * for example when you want your list to have an animated hidable header.
  517. */
  518. StickyHeaderComponent?: StickyHeaderComponentType,
  519. /**
  520. * When set, causes the scroll view to stop at multiples of the value of
  521. * `snapToInterval`. This can be used for paginating through children
  522. * that have lengths smaller than the scroll view. Typically used in
  523. * combination with `snapToAlignment` and `decelerationRate="fast"`.
  524. *
  525. * Overrides less configurable `pagingEnabled` prop.
  526. */
  527. snapToInterval?: ?number,
  528. /**
  529. * When set, causes the scroll view to stop at the defined offsets.
  530. * This can be used for paginating through variously sized children
  531. * that have lengths smaller than the scroll view. Typically used in
  532. * combination with `decelerationRate="fast"`.
  533. *
  534. * Overrides less configurable `pagingEnabled` and `snapToInterval` props.
  535. */
  536. snapToOffsets?: ?$ReadOnlyArray<number>,
  537. /**
  538. * Use in conjunction with `snapToOffsets`. By default, the beginning
  539. * of the list counts as a snap offset. Set `snapToStart` to false to disable
  540. * this behavior and allow the list to scroll freely between its start and
  541. * the first `snapToOffsets` offset.
  542. * The default value is true.
  543. */
  544. snapToStart?: ?boolean,
  545. /**
  546. * Use in conjunction with `snapToOffsets`. By default, the end
  547. * of the list counts as a snap offset. Set `snapToEnd` to false to disable
  548. * this behavior and allow the list to scroll freely between its end and
  549. * the last `snapToOffsets` offset.
  550. * The default value is true.
  551. */
  552. snapToEnd?: ?boolean,
  553. /**
  554. * Experimental: When true, offscreen child views (whose `overflow` value is
  555. * `hidden`) are removed from their native backing superview when offscreen.
  556. * This can improve scrolling performance on long lists. The default value is
  557. * true.
  558. */
  559. removeClippedSubviews?: ?boolean,
  560. /**
  561. * A RefreshControl component, used to provide pull-to-refresh
  562. * functionality for the ScrollView. Only works for vertical ScrollViews
  563. * (`horizontal` prop must be `false`).
  564. *
  565. * See [RefreshControl](docs/refreshcontrol.html).
  566. */
  567. // $FlowFixMe - how to handle generic type without existential operator?
  568. refreshControl?: ?React.Element<any>,
  569. children?: React.Node,
  570. /**
  571. * A ref to the inner View element of the ScrollView. This should be used
  572. * instead of calling `getInnerViewRef`.
  573. */
  574. innerViewRef?: React.Ref<typeof View>,
  575. /**
  576. * A ref to the Native ScrollView component. This ref can be used to call
  577. * all of ScrollView's public methods, in addition to native methods like
  578. * measure, measureLayout, etc.
  579. */
  580. scrollViewRef?: React.Ref<
  581. typeof ScrollViewNativeComponent & ScrollViewImperativeMethods,
  582. >,
  583. |}>;
  584. type State = {|
  585. layoutHeight: ?number,
  586. ...ScrollResponderState,
  587. |};
  588. function createScrollResponder(
  589. node: React.ElementRef<typeof ScrollView>,
  590. ): typeof ScrollResponder.Mixin {
  591. const scrollResponder = {...ScrollResponder.Mixin};
  592. for (const key in scrollResponder) {
  593. if (typeof scrollResponder[key] === 'function') {
  594. scrollResponder[key] = scrollResponder[key].bind(node);
  595. }
  596. }
  597. return scrollResponder;
  598. }
  599. type ContextType = {|horizontal: boolean|} | null;
  600. const Context: React.Context<ContextType> = React.createContext(null);
  601. const standardHorizontalContext: ContextType = Object.freeze({
  602. horizontal: true,
  603. });
  604. const standardVerticalContext: ContextType = Object.freeze({horizontal: false});
  605. type ScrollViewComponentStatics = $ReadOnly<{|
  606. Context: typeof Context,
  607. |}>;
  608. /**
  609. * Component that wraps platform ScrollView while providing
  610. * integration with touch locking "responder" system.
  611. *
  612. * Keep in mind that ScrollViews must have a bounded height in order to work,
  613. * since they contain unbounded-height children into a bounded container (via
  614. * a scroll interaction). In order to bound the height of a ScrollView, either
  615. * set the height of the view directly (discouraged) or make sure all parent
  616. * views have bounded height. Forgetting to transfer `{flex: 1}` down the
  617. * view stack can lead to errors here, which the element inspector makes
  618. * easy to debug.
  619. *
  620. * Doesn't yet support other contained responders from blocking this scroll
  621. * view from becoming the responder.
  622. *
  623. *
  624. * `<ScrollView>` vs [`<FlatList>`](https://reactnative.dev/docs/flatlist.html) - which one to use?
  625. *
  626. * `ScrollView` simply renders all its react child components at once. That
  627. * makes it very easy to understand and use.
  628. *
  629. * On the other hand, this has a performance downside. Imagine you have a very
  630. * long list of items you want to display, maybe several screens worth of
  631. * content. Creating JS components and native views for everything all at once,
  632. * much of which may not even be shown, will contribute to slow rendering and
  633. * increased memory usage.
  634. *
  635. * This is where `FlatList` comes into play. `FlatList` renders items lazily,
  636. * just when they are about to appear, and removes items that scroll way off
  637. * screen to save memory and processing time.
  638. *
  639. * `FlatList` is also handy if you want to render separators between your items,
  640. * multiple columns, infinite scroll loading, or any number of other features it
  641. * supports out of the box.
  642. */
  643. class ScrollView extends React.Component<Props, State> {
  644. static Context: React$Context<ContextType> = Context;
  645. /**
  646. * Part 1: Removing ScrollResponder.Mixin:
  647. *
  648. * 1. Mixin methods should be flow typed. That's why we create a
  649. * copy of ScrollResponder.Mixin and attach it to this._scrollResponder.
  650. * Otherwise, we'd have to manually declare each method on the component
  651. * class and assign it a flow type.
  652. * 2. Mixin methods can call component methods, and access the component's
  653. * props and state. So, we need to bind all mixin methods to the
  654. * component instance.
  655. * 3. Continued...
  656. */
  657. _scrollResponder: typeof ScrollResponder.Mixin = createScrollResponder(this);
  658. constructor(props: Props) {
  659. super(props);
  660. /**
  661. * Part 2: Removing ScrollResponder.Mixin
  662. *
  663. * 3. Mixin methods access other mixin methods via dynamic dispatch using
  664. * this. Since mixin methods are bound to the component instance, we need
  665. * to copy all mixin methods to the component instance. This is also
  666. * necessary because getScrollResponder() is a public method that returns
  667. * an object that can be used to execute all scrollResponder methods.
  668. * Since the object returned from that method is the ScrollView instance,
  669. * we need to bind all mixin methods to the ScrollView instance.
  670. */
  671. for (const key in ScrollResponder.Mixin) {
  672. if (
  673. typeof ScrollResponder.Mixin[key] === 'function' &&
  674. key.startsWith('scrollResponder')
  675. ) {
  676. // $FlowFixMe - dynamically adding properties to a class
  677. (this: any)[key] = ScrollResponder.Mixin[key].bind(this);
  678. }
  679. }
  680. /**
  681. * Part 3: Removing ScrollResponder.Mixin
  682. *
  683. * 4. Mixins can initialize properties and use properties on the component
  684. * instance.
  685. */
  686. Object.keys(ScrollResponder.Mixin)
  687. .filter(key => typeof ScrollResponder.Mixin[key] !== 'function')
  688. .forEach(key => {
  689. // $FlowFixMe - dynamically adding properties to a class
  690. (this: any)[key] = ScrollResponder.Mixin[key];
  691. });
  692. }
  693. _scrollAnimatedValue: AnimatedImplementation.Value = new AnimatedImplementation.Value(
  694. 0,
  695. );
  696. _scrollAnimatedValueAttachment: ?{detach: () => void, ...} = null;
  697. _stickyHeaderRefs: Map<
  698. string,
  699. React.ElementRef<StickyHeaderComponentType>,
  700. > = new Map();
  701. _headerLayoutYs: Map<string, number> = new Map();
  702. state: State = {
  703. layoutHeight: null,
  704. ...ScrollResponder.Mixin.scrollResponderMixinGetInitialState(),
  705. };
  706. UNSAFE_componentWillMount() {
  707. this._scrollResponder.UNSAFE_componentWillMount();
  708. this._scrollAnimatedValue = new AnimatedImplementation.Value(
  709. this.props.contentOffset?.y ?? 0,
  710. );
  711. this._scrollAnimatedValue.setOffset(this.props.contentInset?.top ?? 0);
  712. this._stickyHeaderRefs = new Map();
  713. this._headerLayoutYs = new Map();
  714. }
  715. UNSAFE_componentWillReceiveProps(nextProps: Props) {
  716. const currentContentInsetTop = this.props.contentInset
  717. ? this.props.contentInset.top
  718. : 0;
  719. const nextContentInsetTop = nextProps.contentInset
  720. ? nextProps.contentInset.top
  721. : 0;
  722. if (currentContentInsetTop !== nextContentInsetTop) {
  723. this._scrollAnimatedValue.setOffset(nextContentInsetTop || 0);
  724. }
  725. }
  726. componentDidMount() {
  727. this._updateAnimatedNodeAttachment();
  728. }
  729. componentDidUpdate() {
  730. this._updateAnimatedNodeAttachment();
  731. }
  732. componentWillUnmount() {
  733. this._scrollResponder.componentWillUnmount();
  734. if (this._scrollAnimatedValueAttachment) {
  735. this._scrollAnimatedValueAttachment.detach();
  736. }
  737. }
  738. _setNativeRef = setAndForwardRef({
  739. getForwardedRef: () => this.props.scrollViewRef,
  740. setLocalRef: ref => {
  741. this._scrollViewRef = ref;
  742. /*
  743. This is a hack. Ideally we would forwardRef to the underlying
  744. host component. However, since ScrollView has it's own methods that can be
  745. called as well, if we used the standard forwardRef then these
  746. methods wouldn't be accessible and thus be a breaking change.
  747. Therefore we edit ref to include ScrollView's public methods so that
  748. they are callable from the ref.
  749. */
  750. if (ref) {
  751. ref.getScrollResponder = this.getScrollResponder;
  752. ref.getScrollableNode = this.getScrollableNode;
  753. ref.getInnerViewNode = this.getInnerViewNode;
  754. ref.getInnerViewRef = this.getInnerViewRef;
  755. ref.getNativeScrollRef = this.getNativeScrollRef;
  756. ref.scrollTo = this.scrollTo;
  757. ref.scrollToEnd = this.scrollToEnd;
  758. ref.flashScrollIndicators = this.flashScrollIndicators;
  759. // $FlowFixMe - This method was manually bound from ScrollResponder.mixin
  760. ref.scrollResponderZoomTo = this.scrollResponderZoomTo;
  761. // $FlowFixMe - This method was manually bound from ScrollResponder.mixin
  762. ref.scrollResponderScrollNativeHandleToKeyboard = this.scrollResponderScrollNativeHandleToKeyboard;
  763. }
  764. },
  765. });
  766. /**
  767. * Returns a reference to the underlying scroll responder, which supports
  768. * operations like `scrollTo`. All ScrollView-like components should
  769. * implement this method so that they can be composed while providing access
  770. * to the underlying scroll responder's methods.
  771. */
  772. getScrollResponder: () => ScrollResponderType = () => {
  773. // $FlowFixMe - overriding type to include ScrollResponder.Mixin
  774. return ((this: any): ScrollResponderType);
  775. };
  776. getScrollableNode: () => ?number = () => {
  777. return ReactNative.findNodeHandle(this._scrollViewRef);
  778. };
  779. getInnerViewNode(): ?number {
  780. return ReactNative.findNodeHandle(this._innerViewRef);
  781. }
  782. getInnerViewRef(): ?React.ElementRef<typeof View> {
  783. return this._innerViewRef;
  784. }
  785. getNativeScrollRef: () => ?React.ElementRef<HostComponent<mixed>> = () => {
  786. return this._scrollViewRef;
  787. };
  788. /**
  789. * Scrolls to a given x, y offset, either immediately or with a smooth animation.
  790. *
  791. * Example:
  792. *
  793. * `scrollTo({x: 0, y: 0, animated: true})`
  794. *
  795. * Note: The weird function signature is due to the fact that, for historical reasons,
  796. * the function also accepts separate arguments as an alternative to the options object.
  797. * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
  798. */
  799. scrollTo: (
  800. options?:
  801. | {
  802. x?: number,
  803. y?: number,
  804. animated?: boolean,
  805. ...
  806. }
  807. | number,
  808. deprecatedX?: number,
  809. deprecatedAnimated?: boolean,
  810. ) => void = (
  811. options?:
  812. | {
  813. x?: number,
  814. y?: number,
  815. animated?: boolean,
  816. ...
  817. }
  818. | number,
  819. deprecatedX?: number,
  820. deprecatedAnimated?: boolean,
  821. ) => {
  822. let x, y, animated;
  823. if (typeof options === 'number') {
  824. console.warn(
  825. '`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, ' +
  826. 'animated: true})` instead.',
  827. );
  828. y = options;
  829. x = deprecatedX;
  830. animated = deprecatedAnimated;
  831. } else if (options) {
  832. y = options.y;
  833. x = options.x;
  834. animated = options.animated;
  835. }
  836. this._scrollResponder.scrollResponderScrollTo({
  837. x: x || 0,
  838. y: y || 0,
  839. animated: animated !== false,
  840. });
  841. };
  842. /**
  843. * If this is a vertical ScrollView scrolls to the bottom.
  844. * If this is a horizontal ScrollView scrolls to the right.
  845. *
  846. * Use `scrollToEnd({animated: true})` for smooth animated scrolling,
  847. * `scrollToEnd({animated: false})` for immediate scrolling.
  848. * If no options are passed, `animated` defaults to true.
  849. */
  850. scrollToEnd: (options?: ?{animated?: boolean, ...}) => void = (
  851. options?: ?{animated?: boolean, ...},
  852. ) => {
  853. // Default to true
  854. const animated = (options && options.animated) !== false;
  855. this._scrollResponder.scrollResponderScrollToEnd({
  856. animated: animated,
  857. });
  858. };
  859. /**
  860. * Displays the scroll indicators momentarily.
  861. *
  862. * @platform ios
  863. */
  864. flashScrollIndicators: () => void = () => {
  865. this._scrollResponder.scrollResponderFlashScrollIndicators();
  866. };
  867. _getKeyForIndex(index, childArray) {
  868. const child = childArray[index];
  869. return child && child.key;
  870. }
  871. _updateAnimatedNodeAttachment() {
  872. if (this._scrollAnimatedValueAttachment) {
  873. this._scrollAnimatedValueAttachment.detach();
  874. }
  875. if (
  876. this.props.stickyHeaderIndices &&
  877. this.props.stickyHeaderIndices.length > 0
  878. ) {
  879. this._scrollAnimatedValueAttachment = AnimatedImplementation.attachNativeEvent(
  880. this._scrollViewRef,
  881. 'onScroll',
  882. [{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}],
  883. );
  884. }
  885. }
  886. _setStickyHeaderRef(
  887. key: string,
  888. ref: ?React.ElementRef<StickyHeaderComponentType>,
  889. ) {
  890. if (ref) {
  891. this._stickyHeaderRefs.set(key, ref);
  892. } else {
  893. this._stickyHeaderRefs.delete(key);
  894. }
  895. }
  896. _onStickyHeaderLayout(index, event, key) {
  897. const {stickyHeaderIndices} = this.props;
  898. if (!stickyHeaderIndices) {
  899. return;
  900. }
  901. const childArray = React.Children.toArray(this.props.children);
  902. if (key !== this._getKeyForIndex(index, childArray)) {
  903. // ignore stale layout update
  904. return;
  905. }
  906. const layoutY = event.nativeEvent.layout.y;
  907. this._headerLayoutYs.set(key, layoutY);
  908. const indexOfIndex = stickyHeaderIndices.indexOf(index);
  909. const previousHeaderIndex = stickyHeaderIndices[indexOfIndex - 1];
  910. if (previousHeaderIndex != null) {
  911. const previousHeader = this._stickyHeaderRefs.get(
  912. this._getKeyForIndex(previousHeaderIndex, childArray),
  913. );
  914. previousHeader &&
  915. previousHeader.setNextHeaderY &&
  916. previousHeader.setNextHeaderY(layoutY);
  917. }
  918. }
  919. _handleScroll = (e: ScrollEvent) => {
  920. if (__DEV__) {
  921. if (
  922. this.props.onScroll &&
  923. this.props.scrollEventThrottle == null &&
  924. Platform.OS === 'ios'
  925. ) {
  926. console.log(
  927. 'You specified `onScroll` on a <ScrollView> but not ' +
  928. '`scrollEventThrottle`. You will only receive one event. ' +
  929. 'Using `16` you get all the events but be aware that it may ' +
  930. "cause frame drops, use a bigger number if you don't need as " +
  931. 'much precision.',
  932. );
  933. }
  934. }
  935. if (Platform.OS === 'android') {
  936. if (
  937. this.props.keyboardDismissMode === 'on-drag' &&
  938. this.state.isTouching
  939. ) {
  940. dismissKeyboard();
  941. }
  942. }
  943. this._scrollResponder.scrollResponderHandleScroll(e);
  944. };
  945. _handleLayout = (e: LayoutEvent) => {
  946. if (this.props.invertStickyHeaders === true) {
  947. this.setState({layoutHeight: e.nativeEvent.layout.height});
  948. }
  949. if (this.props.onLayout) {
  950. this.props.onLayout(e);
  951. }
  952. };
  953. _handleContentOnLayout = (e: LayoutEvent) => {
  954. const {width, height} = e.nativeEvent.layout;
  955. this.props.onContentSizeChange &&
  956. this.props.onContentSizeChange(width, height);
  957. };
  958. _scrollViewRef: ?React.ElementRef<HostComponent<mixed>> = null;
  959. _innerViewRef: ?React.ElementRef<typeof View> = null;
  960. _setInnerViewRef = setAndForwardRef({
  961. getForwardedRef: () => this.props.innerViewRef,
  962. setLocalRef: ref => {
  963. this._innerViewRef = ref;
  964. },
  965. });
  966. render(): React.Node | React.Element<string> {
  967. let ScrollViewClass;
  968. let ScrollContentContainerViewClass;
  969. if (Platform.OS === 'android') {
  970. if (this.props.horizontal === true) {
  971. ScrollViewClass = AndroidHorizontalScrollView;
  972. ScrollContentContainerViewClass = AndroidHorizontalScrollContentView;
  973. } else {
  974. ScrollViewClass = AndroidScrollView;
  975. ScrollContentContainerViewClass = View;
  976. }
  977. } else {
  978. ScrollViewClass = RCTScrollView;
  979. ScrollContentContainerViewClass = RCTScrollContentView;
  980. }
  981. invariant(
  982. ScrollViewClass !== undefined,
  983. 'ScrollViewClass must not be undefined',
  984. );
  985. invariant(
  986. ScrollContentContainerViewClass !== undefined,
  987. 'ScrollContentContainerViewClass must not be undefined',
  988. );
  989. const contentContainerStyle = [
  990. this.props.horizontal === true && styles.contentContainerHorizontal,
  991. this.props.contentContainerStyle,
  992. ];
  993. if (__DEV__ && this.props.style !== undefined) {
  994. const style = flattenStyle(this.props.style);
  995. const childLayoutProps = ['alignItems', 'justifyContent'].filter(
  996. prop => style && style[prop] !== undefined,
  997. );
  998. invariant(
  999. childLayoutProps.length === 0,
  1000. 'ScrollView child layout (' +
  1001. JSON.stringify(childLayoutProps) +
  1002. ') must be applied through the contentContainerStyle prop.',
  1003. );
  1004. }
  1005. let contentSizeChangeProps = {};
  1006. if (this.props.onContentSizeChange) {
  1007. contentSizeChangeProps = {
  1008. onLayout: this._handleContentOnLayout,
  1009. };
  1010. }
  1011. const {stickyHeaderIndices} = this.props;
  1012. let children = this.props.children;
  1013. if (stickyHeaderIndices != null && stickyHeaderIndices.length > 0) {
  1014. const childArray = React.Children.toArray(this.props.children);
  1015. children = childArray.map((child, index) => {
  1016. const indexOfIndex = child ? stickyHeaderIndices.indexOf(index) : -1;
  1017. if (indexOfIndex > -1) {
  1018. const key = child.key;
  1019. const nextIndex = stickyHeaderIndices[indexOfIndex + 1];
  1020. const StickyHeaderComponent =
  1021. this.props.StickyHeaderComponent || ScrollViewStickyHeader;
  1022. return (
  1023. <StickyHeaderComponent
  1024. key={key}
  1025. ref={ref => this._setStickyHeaderRef(key, ref)}
  1026. nextHeaderLayoutY={this._headerLayoutYs.get(
  1027. this._getKeyForIndex(nextIndex, childArray),
  1028. )}
  1029. onLayout={event => this._onStickyHeaderLayout(index, event, key)}
  1030. scrollAnimatedValue={this._scrollAnimatedValue}
  1031. inverted={this.props.invertStickyHeaders}
  1032. scrollViewHeight={this.state.layoutHeight}>
  1033. {child}
  1034. </StickyHeaderComponent>
  1035. );
  1036. } else {
  1037. return child;
  1038. }
  1039. });
  1040. }
  1041. children = (
  1042. <Context.Provider
  1043. value={
  1044. this.props.horizontal === true
  1045. ? standardHorizontalContext
  1046. : standardVerticalContext
  1047. }>
  1048. {children}
  1049. </Context.Provider>
  1050. );
  1051. const hasStickyHeaders =
  1052. Array.isArray(stickyHeaderIndices) && stickyHeaderIndices.length > 0;
  1053. const contentContainer = (
  1054. /* $FlowFixMe(>=0.112.0 site=react_native_fb) This comment suppresses an
  1055. * error found when Flow v0.112 was deployed. To see the error, delete
  1056. * this comment and run Flow. */
  1057. <ScrollContentContainerViewClass
  1058. {...contentSizeChangeProps}
  1059. ref={this._setInnerViewRef}
  1060. style={contentContainerStyle}
  1061. removeClippedSubviews={
  1062. // Subview clipping causes issues with sticky headers on Android and
  1063. // would be hard to fix properly in a performant way.
  1064. Platform.OS === 'android' && hasStickyHeaders
  1065. ? false
  1066. : this.props.removeClippedSubviews
  1067. }
  1068. collapsable={false}>
  1069. {children}
  1070. </ScrollContentContainerViewClass>
  1071. );
  1072. const alwaysBounceHorizontal =
  1073. this.props.alwaysBounceHorizontal !== undefined
  1074. ? this.props.alwaysBounceHorizontal
  1075. : this.props.horizontal;
  1076. const alwaysBounceVertical =
  1077. this.props.alwaysBounceVertical !== undefined
  1078. ? this.props.alwaysBounceVertical
  1079. : !this.props.horizontal;
  1080. const DEPRECATED_sendUpdatedChildFrames = !!this.props
  1081. .DEPRECATED_sendUpdatedChildFrames;
  1082. const baseStyle =
  1083. this.props.horizontal === true
  1084. ? styles.baseHorizontal
  1085. : styles.baseVertical;
  1086. const props = {
  1087. ...this.props,
  1088. alwaysBounceHorizontal,
  1089. alwaysBounceVertical,
  1090. style: [baseStyle, this.props.style],
  1091. // Override the onContentSizeChange from props, since this event can
  1092. // bubble up from TextInputs
  1093. onContentSizeChange: null,
  1094. onLayout: this._handleLayout,
  1095. onMomentumScrollBegin: this._scrollResponder
  1096. .scrollResponderHandleMomentumScrollBegin,
  1097. onMomentumScrollEnd: this._scrollResponder
  1098. .scrollResponderHandleMomentumScrollEnd,
  1099. onResponderGrant: this._scrollResponder
  1100. .scrollResponderHandleResponderGrant,
  1101. onResponderReject: this._scrollResponder
  1102. .scrollResponderHandleResponderReject,
  1103. onResponderRelease: this._scrollResponder
  1104. .scrollResponderHandleResponderRelease,
  1105. onResponderTerminationRequest: this._scrollResponder
  1106. .scrollResponderHandleTerminationRequest,
  1107. onScrollBeginDrag: this._scrollResponder
  1108. .scrollResponderHandleScrollBeginDrag,
  1109. onScrollEndDrag: this._scrollResponder.scrollResponderHandleScrollEndDrag,
  1110. onScrollShouldSetResponder: this._scrollResponder
  1111. .scrollResponderHandleScrollShouldSetResponder,
  1112. onStartShouldSetResponder: this._scrollResponder
  1113. .scrollResponderHandleStartShouldSetResponder,
  1114. onStartShouldSetResponderCapture: this._scrollResponder
  1115. .scrollResponderHandleStartShouldSetResponderCapture,
  1116. onTouchEnd: this._scrollResponder.scrollResponderHandleTouchEnd,
  1117. onTouchMove: this._scrollResponder.scrollResponderHandleTouchMove,
  1118. onTouchStart: this._scrollResponder.scrollResponderHandleTouchStart,
  1119. onTouchCancel: this._scrollResponder.scrollResponderHandleTouchCancel,
  1120. onScroll: this._handleScroll,
  1121. scrollBarThumbImage: resolveAssetSource(this.props.scrollBarThumbImage),
  1122. scrollEventThrottle: hasStickyHeaders
  1123. ? 1
  1124. : this.props.scrollEventThrottle,
  1125. sendMomentumEvents:
  1126. this.props.onMomentumScrollBegin || this.props.onMomentumScrollEnd
  1127. ? true
  1128. : false,
  1129. DEPRECATED_sendUpdatedChildFrames,
  1130. // default to true
  1131. snapToStart: this.props.snapToStart !== false,
  1132. // default to true
  1133. snapToEnd: this.props.snapToEnd !== false,
  1134. // pagingEnabled is overridden by snapToInterval / snapToOffsets
  1135. pagingEnabled: Platform.select({
  1136. // on iOS, pagingEnabled must be set to false to have snapToInterval / snapToOffsets work
  1137. ios:
  1138. this.props.pagingEnabled === true &&
  1139. this.props.snapToInterval == null &&
  1140. this.props.snapToOffsets == null,
  1141. // on Android, pagingEnabled must be set to true to have snapToInterval / snapToOffsets work
  1142. android:
  1143. this.props.pagingEnabled === true ||
  1144. this.props.snapToInterval != null ||
  1145. this.props.snapToOffsets != null,
  1146. }),
  1147. };
  1148. const {decelerationRate} = this.props;
  1149. if (decelerationRate != null) {
  1150. props.decelerationRate = processDecelerationRate(decelerationRate);
  1151. }
  1152. const refreshControl = this.props.refreshControl;
  1153. if (refreshControl) {
  1154. if (Platform.OS === 'ios') {
  1155. // On iOS the RefreshControl is a child of the ScrollView.
  1156. // tvOS lacks native support for RefreshControl, so don't include it in that case
  1157. return (
  1158. /* $FlowFixMe(>=0.117.0 site=react_native_fb) This comment suppresses
  1159. * an error found when Flow v0.117 was deployed. To see the error,
  1160. * delete this comment and run Flow. */
  1161. <ScrollViewClass {...props} ref={this._setNativeRef}>
  1162. {Platform.isTV ? null : refreshControl}
  1163. {contentContainer}
  1164. </ScrollViewClass>
  1165. );
  1166. } else if (Platform.OS === 'android') {
  1167. // On Android wrap the ScrollView with a AndroidSwipeRefreshLayout.
  1168. // Since the ScrollView is wrapped add the style props to the
  1169. // AndroidSwipeRefreshLayout and use flex: 1 for the ScrollView.
  1170. // Note: we should split props.style on the inner and outer props
  1171. // however, the ScrollView still needs the baseStyle to be scrollable
  1172. const {outer, inner} = splitLayoutProps(flattenStyle(props.style));
  1173. return React.cloneElement(
  1174. refreshControl,
  1175. {style: [baseStyle, outer]},
  1176. <ScrollViewClass
  1177. {...props}
  1178. style={[baseStyle, inner]}
  1179. ref={this._setNativeRef}>
  1180. {contentContainer}
  1181. </ScrollViewClass>,
  1182. );
  1183. }
  1184. }
  1185. return (
  1186. <ScrollViewClass {...props} ref={this._setNativeRef}>
  1187. {contentContainer}
  1188. </ScrollViewClass>
  1189. );
  1190. }
  1191. }
  1192. const styles = StyleSheet.create({
  1193. baseVertical: {
  1194. flexGrow: 1,
  1195. flexShrink: 1,
  1196. flexDirection: 'column',
  1197. overflow: 'scroll',
  1198. },
  1199. baseHorizontal: {
  1200. flexGrow: 1,
  1201. flexShrink: 1,
  1202. flexDirection: 'row',
  1203. overflow: 'scroll',
  1204. },
  1205. contentContainerHorizontal: {
  1206. flexDirection: 'row',
  1207. },
  1208. });
  1209. function Wrapper(props, ref) {
  1210. return <ScrollView {...props} scrollViewRef={ref} />;
  1211. }
  1212. Wrapper.displayName = 'ScrollView';
  1213. const ForwardedScrollView = React.forwardRef(Wrapper);
  1214. // $FlowFixMe Add static context to ForwardedScrollView
  1215. ForwardedScrollView.Context = Context;
  1216. ForwardedScrollView.displayName = 'ScrollView';
  1217. module.exports = ((ForwardedScrollView: $FlowFixMe): React.AbstractComponent<
  1218. React.ElementConfig<typeof ScrollView>,
  1219. $ReadOnly<{|
  1220. ...$Exact<React.ElementRef<HostComponent<mixed>>>,
  1221. ...ScrollViewImperativeMethods,
  1222. |}>,
  1223. > &
  1224. ScrollViewComponentStatics);