react-native-windows 0.77.3 → 0.77.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/Libraries/Components/Button.windows.js +3 -0
  2. package/Libraries/Components/Pressable/Pressable.windows.js +3 -0
  3. package/Libraries/Components/ScrollView/ScrollView.windows.js +1920 -0
  4. package/Libraries/Components/TextInput/TextInput.windows.js +3 -0
  5. package/Libraries/Components/Touchable/TouchableBounce.windows.js +2 -0
  6. package/Libraries/Components/Touchable/TouchableNativeFeedback.windows.js +2 -0
  7. package/Libraries/Components/Touchable/TouchableOpacity.windows.js +2 -0
  8. package/Libraries/Components/Touchable/TouchableWithoutFeedback.windows.js +2 -0
  9. package/Libraries/Components/View/View.windows.js +3 -0
  10. package/Libraries/Components/View/ViewAccessibility.d.ts +7 -2
  11. package/Libraries/Components/View/ViewAccessibility.windows.js +1 -0
  12. package/Libraries/Components/View/ViewPropTypes.windows.js +1 -0
  13. package/Libraries/Core/ReactNativeVersion.js +1 -1
  14. package/Libraries/Core/setUpDeveloperTools.js +2 -3
  15. package/Libraries/Image/Image.windows.js +2 -0
  16. package/Libraries/Text/Text.windows.js +4 -0
  17. package/Libraries/Text/TextProps.windows.js +1 -0
  18. package/Libraries/Utilities/HMRClient.js +0 -28
  19. package/Libraries/Utilities/HMRClientProdShim.js +0 -1
  20. package/Microsoft.ReactNative/Fabric/Composition/CompositionDynamicAutomationProvider.cpp +374 -21
  21. package/Microsoft.ReactNative/Fabric/Composition/CompositionDynamicAutomationProvider.h +21 -0
  22. package/Microsoft.ReactNative/Fabric/Composition/CompositionTextProvider.cpp +115 -0
  23. package/Microsoft.ReactNative/Fabric/Composition/CompositionTextProvider.h +41 -0
  24. package/Microsoft.ReactNative/Fabric/Composition/CompositionTextRangeProvider.cpp +298 -0
  25. package/Microsoft.ReactNative/Fabric/Composition/CompositionTextRangeProvider.h +59 -0
  26. package/Microsoft.ReactNative/Fabric/Composition/CompositionViewComponentView.cpp +1 -2
  27. package/Microsoft.ReactNative/Fabric/Composition/ScrollViewComponentView.cpp +24 -2
  28. package/Microsoft.ReactNative/Fabric/Composition/ScrollViewComponentView.h +5 -0
  29. package/Microsoft.ReactNative/Fabric/Composition/UiaHelpers.cpp +14 -10
  30. package/Microsoft.ReactNative/Fabric/Composition/UiaHelpers.h +3 -2
  31. package/PropertySheets/Generated/PackageVersion.g.props +3 -3
  32. package/ReactCommon/TEMP_UntilReactCommonUpdate/react/renderer/components/view/AccessibilityPrimitives.h +1 -0
  33. package/ReactCommon/TEMP_UntilReactCommonUpdate/react/renderer/components/view/accessibilityPropsConversions.h +4 -0
  34. package/Shared/Networking/WinRTWebSocketResource.cpp +369 -7
  35. package/Shared/Networking/WinRTWebSocketResource.h +118 -0
  36. package/Shared/Shared.vcxitems +6 -0
  37. package/Shared/Shared.vcxitems.filters +8 -0
  38. package/package.json +9 -9
@@ -0,0 +1,1920 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @format
8
+ * @flow strict-local
9
+ */
10
+
11
+ import type {HostInstance} from '../../Renderer/shims/ReactNativeTypes';
12
+ import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType';
13
+ import type {PointProp} from '../../StyleSheet/PointPropType';
14
+ import type {ViewStyleProp} from '../../StyleSheet/StyleSheet';
15
+ import type {ColorValue} from '../../StyleSheet/StyleSheet';
16
+ import type {
17
+ LayoutEvent,
18
+ PressEvent,
19
+ ScrollEvent,
20
+ } from '../../Types/CoreEventTypes';
21
+ import type {EventSubscription} from '../../vendor/emitter/EventEmitter';
22
+ import type {KeyboardEvent, KeyboardMetrics} from '../Keyboard/Keyboard';
23
+ import typeof View from '../View/View';
24
+ import type {ViewProps} from '../View/ViewPropTypes';
25
+ import type {Props as ScrollViewStickyHeaderProps} from './ScrollViewStickyHeader';
26
+
27
+ import {
28
+ HScrollContentViewNativeComponent,
29
+ HScrollViewNativeComponent,
30
+ } from '../../../src/private/components/HScrollViewNativeComponents';
31
+ import {
32
+ VScrollContentViewNativeComponent,
33
+ VScrollViewNativeComponent,
34
+ } from '../../../src/private/components/VScrollViewNativeComponents';
35
+ import AnimatedImplementation from '../../Animated/AnimatedImplementation';
36
+ import FrameRateLogger from '../../Interaction/FrameRateLogger';
37
+ import {findNodeHandle} from '../../ReactNative/RendererProxy';
38
+ import UIManager from '../../ReactNative/UIManager';
39
+ import flattenStyle from '../../StyleSheet/flattenStyle';
40
+ import splitLayoutProps from '../../StyleSheet/splitLayoutProps';
41
+ import StyleSheet from '../../StyleSheet/StyleSheet';
42
+ import Dimensions from '../../Utilities/Dimensions';
43
+ import dismissKeyboard from '../../Utilities/dismissKeyboard';
44
+ import Platform from '../../Utilities/Platform';
45
+ import Keyboard from '../Keyboard/Keyboard';
46
+ import TextInputState from '../TextInput/TextInputState';
47
+ import processDecelerationRate from './processDecelerationRate';
48
+ import Commands from './ScrollViewCommands';
49
+ import ScrollViewContext, {HORIZONTAL, VERTICAL} from './ScrollViewContext';
50
+ import ScrollViewStickyHeader from './ScrollViewStickyHeader';
51
+ import invariant from 'invariant';
52
+ import memoize from 'memoize-one';
53
+ import nullthrows from 'nullthrows';
54
+ import * as React from 'react';
55
+
56
+ /*
57
+ * iOS scroll event timing nuances:
58
+ * ===============================
59
+ *
60
+ *
61
+ * Scrolling without bouncing, if you touch down:
62
+ * -------------------------------
63
+ *
64
+ * 1. `onMomentumScrollBegin` (when animation begins after letting up)
65
+ * ... physical touch starts ...
66
+ * 2. `onTouchStartCapture` (when you press down to stop the scroll)
67
+ * 3. `onTouchStart` (same, but bubble phase)
68
+ * 4. `onResponderRelease` (when lifting up - you could pause forever before * lifting)
69
+ * 5. `onMomentumScrollEnd`
70
+ *
71
+ *
72
+ * Scrolling with bouncing, if you touch down:
73
+ * -------------------------------
74
+ *
75
+ * 1. `onMomentumScrollBegin` (when animation begins after letting up)
76
+ * ... bounce begins ...
77
+ * ... some time elapses ...
78
+ * ... physical touch during bounce ...
79
+ * 2. `onMomentumScrollEnd` (Makes no sense why this occurs first during bounce)
80
+ * 3. `onTouchStartCapture` (immediately after `onMomentumScrollEnd`)
81
+ * 4. `onTouchStart` (same, but bubble phase)
82
+ * 5. `onTouchEnd` (You could hold the touch start for a long time)
83
+ * 6. `onMomentumScrollBegin` (When releasing the view starts bouncing back)
84
+ *
85
+ * So when we receive an `onTouchStart`, how can we tell if we are touching
86
+ * *during* an animation (which then causes the animation to stop)? The only way
87
+ * to tell is if the `touchStart` occurred immediately after the
88
+ * `onMomentumScrollEnd`.
89
+ *
90
+ * This is abstracted out for you, so you can just call this.scrollResponderIsAnimating() if
91
+ * necessary
92
+ *
93
+ * `ScrollView` also includes logic for blurring a currently focused input
94
+ * if one is focused while scrolling. This is a natural place
95
+ * to put this logic since it can support not dismissing the keyboard while
96
+ * scrolling, unless a recognized "tap"-like gesture has occurred.
97
+ *
98
+ * The public lifecycle API includes events for keyboard interaction, responder
99
+ * interaction, and scrolling (among others). The keyboard callbacks
100
+ * `onKeyboardWill/Did/*` are *global* events, but are invoked on scroll
101
+ * responder's props so that you can guarantee that the scroll responder's
102
+ * internal state has been updated accordingly (and deterministically) by
103
+ * the time the props callbacks are invoke. Otherwise, you would always wonder
104
+ * if the scroll responder is currently in a state where it recognizes new
105
+ * keyboard positions etc. If coordinating scrolling with keyboard movement,
106
+ * *always* use these hooks instead of listening to your own global keyboard
107
+ * events.
108
+ *
109
+ * Public keyboard lifecycle API: (props callbacks)
110
+ *
111
+ * Standard Keyboard Appearance Sequence:
112
+ *
113
+ * this.props.onKeyboardWillShow
114
+ * this.props.onKeyboardDidShow
115
+ *
116
+ * `onScrollResponderKeyboardDismissed` will be invoked if an appropriate
117
+ * tap inside the scroll responder's scrollable region was responsible
118
+ * for the dismissal of the keyboard. There are other reasons why the
119
+ * keyboard could be dismissed.
120
+ *
121
+ * this.props.onScrollResponderKeyboardDismissed
122
+ *
123
+ * Standard Keyboard Hide Sequence:
124
+ *
125
+ * this.props.onKeyboardWillHide
126
+ * this.props.onKeyboardDidHide
127
+ */
128
+
129
+ // Public methods for ScrollView
130
+ export type ScrollViewImperativeMethods = $ReadOnly<{|
131
+ getScrollResponder: $PropertyType<ScrollView, 'getScrollResponder'>,
132
+ getScrollableNode: $PropertyType<ScrollView, 'getScrollableNode'>,
133
+ getInnerViewNode: $PropertyType<ScrollView, 'getInnerViewNode'>,
134
+ getInnerViewRef: $PropertyType<ScrollView, 'getInnerViewRef'>,
135
+ getNativeScrollRef: $PropertyType<ScrollView, 'getNativeScrollRef'>,
136
+ scrollTo: $PropertyType<ScrollView, 'scrollTo'>,
137
+ scrollToEnd: $PropertyType<ScrollView, 'scrollToEnd'>,
138
+ flashScrollIndicators: $PropertyType<ScrollView, 'flashScrollIndicators'>,
139
+ scrollResponderZoomTo: $PropertyType<ScrollView, 'scrollResponderZoomTo'>,
140
+ scrollResponderScrollNativeHandleToKeyboard: $PropertyType<
141
+ ScrollView,
142
+ 'scrollResponderScrollNativeHandleToKeyboard',
143
+ >,
144
+ |}>;
145
+
146
+ export type DecelerationRateType = 'fast' | 'normal' | number;
147
+ export type ScrollResponderType = ScrollViewImperativeMethods;
148
+
149
+ type PublicScrollViewInstance = $ReadOnly<{|
150
+ ...HostInstance,
151
+ ...ScrollViewImperativeMethods,
152
+ |}>;
153
+
154
+ type InnerViewInstance = React.ElementRef<View>;
155
+
156
+ type IOSProps = $ReadOnly<{|
157
+ /**
158
+ * Controls whether iOS should automatically adjust the content inset
159
+ * for scroll views that are placed behind a navigation bar or
160
+ * tab bar/ toolbar. The default value is true.
161
+ * @platform ios
162
+ */
163
+ automaticallyAdjustContentInsets?: ?boolean,
164
+ /**
165
+ * Controls whether the ScrollView should automatically adjust its `contentInset`
166
+ * and `scrollViewInsets` when the Keyboard changes its size. The default value is false.
167
+ * @platform ios
168
+ */
169
+ automaticallyAdjustKeyboardInsets?: ?boolean,
170
+ /**
171
+ * Controls whether iOS should automatically adjust the scroll indicator
172
+ * insets. The default value is true. Available on iOS 13 and later.
173
+ * @platform ios
174
+ */
175
+ automaticallyAdjustsScrollIndicatorInsets?: ?boolean,
176
+ /**
177
+ * The amount by which the scroll view content is inset from the edges
178
+ * of the scroll view. Defaults to `{top: 0, left: 0, bottom: 0, right: 0}`.
179
+ * @platform ios
180
+ */
181
+ contentInset?: ?EdgeInsetsProp,
182
+ /**
183
+ * When true, the scroll view bounces when it reaches the end of the
184
+ * content if the content is larger then the scroll view along the axis of
185
+ * the scroll direction. When false, it disables all bouncing even if
186
+ * the `alwaysBounce*` props are true. The default value is true.
187
+ * @platform ios
188
+ */
189
+ bounces?: ?boolean,
190
+ /**
191
+ * By default, ScrollView has an active pan responder that hijacks panresponders
192
+ * deeper in the render tree in order to prevent accidental touches while scrolling.
193
+ * However, in certain occasions (such as when using snapToInterval) in a vertical scrollview
194
+ * You may want to disable this behavior in order to prevent the ScrollView from blocking touches
195
+ */
196
+ disableScrollViewPanResponder?: ?boolean,
197
+ /**
198
+ * When true, gestures can drive zoom past min/max and the zoom will animate
199
+ * to the min/max value at gesture end, otherwise the zoom will not exceed
200
+ * the limits.
201
+ * @platform ios
202
+ */
203
+ bouncesZoom?: ?boolean,
204
+ /**
205
+ * When true, the scroll view bounces horizontally when it reaches the end
206
+ * even if the content is smaller than the scroll view itself. The default
207
+ * value is true when `horizontal={true}` and false otherwise.
208
+ * @platform ios
209
+ */
210
+ alwaysBounceHorizontal?: ?boolean,
211
+ /**
212
+ * When true, the scroll view bounces vertically when it reaches the end
213
+ * even if the content is smaller than the scroll view itself. The default
214
+ * value is false when `horizontal={true}` and true otherwise.
215
+ * @platform ios
216
+ */
217
+ alwaysBounceVertical?: ?boolean,
218
+ /**
219
+ * When true, the scroll view automatically centers the content when the
220
+ * content is smaller than the scroll view bounds; when the content is
221
+ * larger than the scroll view, this property has no effect. The default
222
+ * value is false.
223
+ * @platform ios
224
+ */
225
+ centerContent?: ?boolean,
226
+ /**
227
+ * The style of the scroll indicators.
228
+ *
229
+ * - `'default'` (the default), same as `black`.
230
+ * - `'black'`, scroll indicator is black. This style is good against a light background.
231
+ * - `'white'`, scroll indicator is white. This style is good against a dark background.
232
+ *
233
+ * @platform ios
234
+ */
235
+ indicatorStyle?: ?('default' | 'black' | 'white'),
236
+ /**
237
+ * When true, the ScrollView will try to lock to only vertical or horizontal
238
+ * scrolling while dragging. The default value is false.
239
+ * @platform ios
240
+ */
241
+ directionalLockEnabled?: ?boolean,
242
+ /**
243
+ * When false, once tracking starts, won't try to drag if the touch moves.
244
+ * The default value is true.
245
+ * @platform ios
246
+ */
247
+ canCancelContentTouches?: ?boolean,
248
+ /**
249
+ * The maximum allowed zoom scale. The default value is 1.0.
250
+ * @platform ios
251
+ */
252
+ maximumZoomScale?: ?number,
253
+ /**
254
+ * The minimum allowed zoom scale. The default value is 1.0.
255
+ * @platform ios
256
+ */
257
+ minimumZoomScale?: ?number,
258
+ /**
259
+ * When true, ScrollView allows use of pinch gestures to zoom in and out.
260
+ * The default value is true.
261
+ * @platform ios
262
+ */
263
+ pinchGestureEnabled?: ?boolean,
264
+ /**
265
+ * The amount by which the scroll view indicators are inset from the edges
266
+ * of the scroll view. This should normally be set to the same value as
267
+ * the `contentInset`. Defaults to `{0, 0, 0, 0}`.
268
+ * @platform ios
269
+ */
270
+ scrollIndicatorInsets?: ?EdgeInsetsProp,
271
+ /**
272
+ * When true, the scroll view can be programmatically scrolled beyond its
273
+ * content size. The default value is false.
274
+ * @platform ios
275
+ */
276
+ scrollToOverflowEnabled?: ?boolean,
277
+ /**
278
+ * When true, the scroll view scrolls to top when the status bar is tapped.
279
+ * The default value is true.
280
+ * @platform ios
281
+ */
282
+ scrollsToTop?: ?boolean,
283
+ /**
284
+ * Fires when the scroll view scrolls to top after the status bar has been tapped
285
+ * @platform ios
286
+ */
287
+ onScrollToTop?: (event: ScrollEvent) => void,
288
+ /**
289
+ * When true, shows a horizontal scroll indicator.
290
+ * The default value is true.
291
+ */
292
+ showsHorizontalScrollIndicator?: ?boolean,
293
+ /**
294
+ * The current scale of the scroll view content. The default value is 1.0.
295
+ * @platform ios
296
+ */
297
+ zoomScale?: ?number,
298
+ /**
299
+ * This property specifies how the safe area insets are used to modify the
300
+ * content area of the scroll view. The default value of this property is
301
+ * "never". Available on iOS 11 and later.
302
+ * @platform ios
303
+ */
304
+ contentInsetAdjustmentBehavior?: ?(
305
+ | 'automatic'
306
+ | 'scrollableAxes'
307
+ | 'never'
308
+ | 'always'
309
+ ),
310
+ |}>;
311
+
312
+ type AndroidProps = $ReadOnly<{|
313
+ /**
314
+ * Enables nested scrolling for Android API level 21+.
315
+ * Nested scrolling is supported by default on iOS
316
+ * @platform android
317
+ */
318
+ nestedScrollEnabled?: ?boolean,
319
+ /**
320
+ * Sometimes a scrollview takes up more space than its content fills. When this is
321
+ * the case, this prop will fill the rest of the scrollview with a color to avoid setting
322
+ * a background and creating unnecessary overdraw. This is an advanced optimization
323
+ * that is not needed in the general case.
324
+ * @platform android
325
+ */
326
+ endFillColor?: ?ColorValue,
327
+ /**
328
+ * Tag used to log scroll performance on this scroll view. Will force
329
+ * momentum events to be turned on (see sendMomentumEvents). This doesn't do
330
+ * anything out of the box and you need to implement a custom native
331
+ * FpsListener for it to be useful.
332
+ * @platform android
333
+ */
334
+ scrollPerfTag?: ?string,
335
+ /**
336
+ * Used to override default value of overScroll mode.
337
+ *
338
+ * Possible values:
339
+ *
340
+ * - `'auto'` - Default value, allow a user to over-scroll
341
+ * this view only if the content is large enough to meaningfully scroll.
342
+ * - `'always'` - Always allow a user to over-scroll this view.
343
+ * - `'never'` - Never allow a user to over-scroll this view.
344
+ *
345
+ * @platform android
346
+ */
347
+ overScrollMode?: ?('auto' | 'always' | 'never'),
348
+ /**
349
+ * Causes the scrollbars not to turn transparent when they are not in use.
350
+ * The default value is false.
351
+ *
352
+ * @platform android
353
+ */
354
+ persistentScrollbar?: ?boolean,
355
+ /**
356
+ * Fades out the edges of the scroll content.
357
+ *
358
+ * If the value is greater than 0, the fading edges will be set accordingly
359
+ * to the current scroll direction and position,
360
+ * indicating if there is more content to show.
361
+ *
362
+ * The default value is 0.
363
+ *
364
+ * @platform android
365
+ */
366
+ fadingEdgeLength?: ?number,
367
+ |}>;
368
+
369
+ type StickyHeaderComponentType = component(
370
+ ref?: React.RefSetter<$ReadOnly<interface {setNextHeaderY: number => void}>>,
371
+ ...ScrollViewStickyHeaderProps
372
+ );
373
+
374
+ export type Props = $ReadOnly<{|
375
+ ...ViewProps,
376
+ ...IOSProps,
377
+ ...AndroidProps,
378
+
379
+ /**
380
+ * These styles will be applied to the scroll view content container which
381
+ * wraps all of the child views. Example:
382
+ *
383
+ * ```
384
+ * return (
385
+ * <ScrollView contentContainerStyle={styles.contentContainer}>
386
+ * </ScrollView>
387
+ * );
388
+ * ...
389
+ * const styles = StyleSheet.create({
390
+ * contentContainer: {
391
+ * paddingVertical: 20
392
+ * }
393
+ * });
394
+ * ```
395
+ */
396
+ contentContainerStyle?: ?ViewStyleProp,
397
+ /**
398
+ * Used to manually set the starting scroll offset.
399
+ * The default value is `{x: 0, y: 0}`.
400
+ */
401
+ contentOffset?: ?PointProp,
402
+ /**
403
+ * When true, the scroll view stops on the next index (in relation to scroll
404
+ * position at release) regardless of how fast the gesture is. This can be
405
+ * used for pagination when the page is less than the width of the
406
+ * horizontal ScrollView or the height of the vertical ScrollView. The default value is false.
407
+ */
408
+ disableIntervalMomentum?: ?boolean,
409
+ /**
410
+ * A floating-point number that determines how quickly the scroll view
411
+ * decelerates after the user lifts their finger. You may also use string
412
+ * shortcuts `"normal"` and `"fast"` which match the underlying iOS settings
413
+ * for `UIScrollViewDecelerationRateNormal` and
414
+ * `UIScrollViewDecelerationRateFast` respectively.
415
+ *
416
+ * - `'normal'`: 0.998 on iOS, 0.985 on Android (the default)
417
+ * - `'fast'`: 0.99 on iOS, 0.9 on Android
418
+ */
419
+ decelerationRate?: ?DecelerationRateType,
420
+
421
+ /**
422
+ * *Experimental, iOS Only*. The API is experimental and will change in future releases.
423
+ *
424
+ * Controls how much distance is travelled after user stops scrolling.
425
+ * Value greater than 1 will increase the distance travelled.
426
+ * Value less than 1 will decrease the distance travelled.
427
+ *
428
+ * @deprecated
429
+ *
430
+ * The default value is 1.
431
+ */
432
+ experimental_endDraggingSensitivityMultiplier?: ?number,
433
+
434
+ /**
435
+ * When true, the scroll view's children are arranged horizontally in a row
436
+ * instead of vertically in a column. The default value is false.
437
+ */
438
+ horizontal?: ?boolean,
439
+ /**
440
+ * If sticky headers should stick at the bottom instead of the top of the
441
+ * ScrollView. This is usually used with inverted ScrollViews.
442
+ */
443
+ invertStickyHeaders?: ?boolean,
444
+ /**
445
+ * Determines whether the keyboard gets dismissed in response to a drag.
446
+ *
447
+ * *Cross platform*
448
+ *
449
+ * - `'none'` (the default), drags do not dismiss the keyboard.
450
+ * - `'on-drag'`, the keyboard is dismissed when a drag begins.
451
+ *
452
+ * *iOS Only*
453
+ *
454
+ * - `'interactive'`, the keyboard is dismissed interactively with the drag and moves in
455
+ * synchrony with the touch; dragging upwards cancels the dismissal.
456
+ * On android this is not supported and it will have the same behavior as 'none'.
457
+ */
458
+ keyboardDismissMode?: ?// default
459
+ // cross-platform
460
+ ('none' | 'on-drag' | 'interactive'), // ios only
461
+ /**
462
+ * Determines when the keyboard should stay visible after a tap.
463
+ *
464
+ * - `'never'` (the default), tapping outside of the focused text input when the keyboard
465
+ * is up dismisses the keyboard. When this happens, children won't receive the tap.
466
+ * - `'always'`, the keyboard will not dismiss automatically, and the scroll view will not
467
+ * catch taps, but children of the scroll view can catch taps.
468
+ * - `'handled'`, the keyboard will not dismiss automatically when the tap was handled by
469
+ * a children, (or captured by an ancestor).
470
+ * - `false`, deprecated, use 'never' instead
471
+ * - `true`, deprecated, use 'always' instead
472
+ */
473
+ keyboardShouldPersistTaps?: ?('always' | 'never' | 'handled' | true | false),
474
+ /**
475
+ * When set, the scroll view will adjust the scroll position so that the first child that is
476
+ * partially or fully visible and at or beyond `minIndexForVisible` will not change position.
477
+ * This is useful for lists that are loading content in both directions, e.g. a chat thread,
478
+ * where new messages coming in might otherwise cause the scroll position to jump. A value of 0
479
+ * is common, but other values such as 1 can be used to skip loading spinners or other content
480
+ * that should not maintain position.
481
+ *
482
+ * The optional `autoscrollToTopThreshold` can be used to make the content automatically scroll
483
+ * to the top after making the adjustment if the user was within the threshold of the top before
484
+ * the adjustment was made. This is also useful for chat-like applications where you want to see
485
+ * new messages scroll into place, but not if the user has scrolled up a ways and it would be
486
+ * disruptive to scroll a bunch.
487
+ *
488
+ * Caveat 1: Reordering elements in the scrollview with this enabled will probably cause
489
+ * jumpiness and jank. It can be fixed, but there are currently no plans to do so. For now,
490
+ * don't re-order the content of any ScrollViews or Lists that use this feature.
491
+ *
492
+ * Caveat 2: This simply uses `contentOffset` and `frame.origin` in native code to compute
493
+ * visibility. Occlusion, transforms, and other complexity won't be taken into account as to
494
+ * whether content is "visible" or not.
495
+ *
496
+ */
497
+ maintainVisibleContentPosition?: ?$ReadOnly<{|
498
+ minIndexForVisible: number,
499
+ autoscrollToTopThreshold?: ?number,
500
+ |}>,
501
+ /**
502
+ * Called when the momentum scroll starts (scroll which occurs as the ScrollView glides to a stop).
503
+ */
504
+ onMomentumScrollBegin?: ?(event: ScrollEvent) => void,
505
+ /**
506
+ * Called when the momentum scroll ends (scroll which occurs as the ScrollView glides to a stop).
507
+ */
508
+ onMomentumScrollEnd?: ?(event: ScrollEvent) => void,
509
+
510
+ /**
511
+ * Fires at most once per frame during scrolling.
512
+ */
513
+ onScroll?: ?(event: ScrollEvent) => void,
514
+ /**
515
+ * Called when the user begins to drag the scroll view.
516
+ */
517
+ onScrollBeginDrag?: ?(event: ScrollEvent) => void,
518
+ /**
519
+ * Called when the user stops dragging the scroll view and it either stops
520
+ * or begins to glide.
521
+ */
522
+ onScrollEndDrag?: ?(event: ScrollEvent) => void,
523
+ /**
524
+ * Called when scrollable content view of the ScrollView changes.
525
+ *
526
+ * Handler function is passed the content width and content height as parameters:
527
+ * `(contentWidth, contentHeight)`
528
+ *
529
+ * It's implemented using onLayout handler attached to the content container
530
+ * which this ScrollView renders.
531
+ */
532
+ onContentSizeChange?: (contentWidth: number, contentHeight: number) => void,
533
+ onKeyboardDidShow?: (event: KeyboardEvent) => void,
534
+ onKeyboardDidHide?: (event: KeyboardEvent) => void,
535
+ onKeyboardWillShow?: (event: KeyboardEvent) => void,
536
+ onKeyboardWillHide?: (event: KeyboardEvent) => void,
537
+ /**
538
+ * When true, the scroll view stops on multiples of the scroll view's size
539
+ * when scrolling. This can be used for horizontal pagination. The default
540
+ * value is false.
541
+ */
542
+ pagingEnabled?: ?boolean,
543
+ /**
544
+ * When false, the view cannot be scrolled via touch interaction.
545
+ * The default value is true.
546
+ *
547
+ * Note that the view can always be scrolled by calling `scrollTo`.
548
+ */
549
+ scrollEnabled?: ?boolean,
550
+ /**
551
+ * Limits how often scroll events will be fired while scrolling, specified as
552
+ * a time interval in ms. This may be useful when expensive work is performed
553
+ * in response to scrolling. Values <= `16` will disable throttling,
554
+ * regardless of the refresh rate of the device.
555
+ */
556
+ scrollEventThrottle?: ?number,
557
+ /**
558
+ * When true, shows a vertical scroll indicator.
559
+ * The default value is true.
560
+ */
561
+ showsVerticalScrollIndicator?: ?boolean,
562
+ /**
563
+ * When true, Sticky header is hidden when scrolling down, and dock at the top
564
+ * when scrolling up
565
+ */
566
+ stickyHeaderHiddenOnScroll?: ?boolean,
567
+ /**
568
+ * An array of child indices determining which children get docked to the
569
+ * top of the screen when scrolling. For example, passing
570
+ * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the
571
+ * top of the scroll view. This property is not supported in conjunction
572
+ * with `horizontal={true}`.
573
+ */
574
+ stickyHeaderIndices?: ?$ReadOnlyArray<number>,
575
+ /**
576
+ * A React Component that will be used to render sticky headers.
577
+ * To be used together with `stickyHeaderIndices` or with `SectionList`, defaults to `ScrollViewStickyHeader`.
578
+ * You may need to set this if your sticky header uses custom transforms (eg. translation),
579
+ * for example when you want your list to have an animated hidable header.
580
+ */
581
+ StickyHeaderComponent?: StickyHeaderComponentType,
582
+ /**
583
+ * When `snapToInterval` is set, `snapToAlignment` will define the relationship
584
+ * of the snapping to the scroll view.
585
+ *
586
+ * - `'start'` (the default) will align the snap at the left (horizontal) or top (vertical)
587
+ * - `'center'` will align the snap in the center
588
+ * - `'end'` will align the snap at the right (horizontal) or bottom (vertical)
589
+ */
590
+ snapToAlignment?: ?('start' | 'center' | 'end'),
591
+ /**
592
+ * When set, causes the scroll view to stop at multiples of the value of
593
+ * `snapToInterval`. This can be used for paginating through children
594
+ * that have lengths smaller than the scroll view. Typically used in
595
+ * combination with `snapToAlignment` and `decelerationRate="fast"`.
596
+ *
597
+ * Overrides less configurable `pagingEnabled` prop.
598
+ */
599
+ snapToInterval?: ?number,
600
+ /**
601
+ * When set, causes the scroll view to stop at the defined offsets.
602
+ * This can be used for paginating through variously sized children
603
+ * that have lengths smaller than the scroll view. Typically used in
604
+ * combination with `decelerationRate="fast"`.
605
+ *
606
+ * Overrides less configurable `pagingEnabled` and `snapToInterval` props.
607
+ */
608
+ snapToOffsets?: ?$ReadOnlyArray<number>,
609
+ /**
610
+ * Use in conjunction with `snapToOffsets`. By default, the beginning
611
+ * of the list counts as a snap offset. Set `snapToStart` to false to disable
612
+ * this behavior and allow the list to scroll freely between its start and
613
+ * the first `snapToOffsets` offset.
614
+ * The default value is true.
615
+ */
616
+ snapToStart?: ?boolean,
617
+ /**
618
+ * Use in conjunction with `snapToOffsets`. By default, the end
619
+ * of the list counts as a snap offset. Set `snapToEnd` to false to disable
620
+ * this behavior and allow the list to scroll freely between its end and
621
+ * the last `snapToOffsets` offset.
622
+ * The default value is true.
623
+ */
624
+ snapToEnd?: ?boolean,
625
+ /**
626
+ * Experimental: When true, offscreen child views (whose `overflow` value is
627
+ * `hidden`) are removed from their native backing superview when offscreen.
628
+ * This can improve scrolling performance on long lists. The default value is
629
+ * true.
630
+ */
631
+ removeClippedSubviews?: ?boolean,
632
+ /**
633
+ * A RefreshControl component, used to provide pull-to-refresh
634
+ * functionality for the ScrollView. Only works for vertical ScrollViews
635
+ * (`horizontal` prop must be `false`).
636
+ *
637
+ * See [RefreshControl](docs/refreshcontrol.html).
638
+ */
639
+ /* $FlowFixMe[unclear-type] - how to handle generic type without existential
640
+ * operator? */
641
+ refreshControl?: ?ExactReactElement_DEPRECATED<any>,
642
+ children?: React.Node,
643
+ /**
644
+ * A ref to the inner View element of the ScrollView. This should be used
645
+ * instead of calling `getInnerViewRef`.
646
+ */
647
+ innerViewRef?: React.RefSetter<InnerViewInstance>,
648
+ /**
649
+ * A ref to the Native ScrollView component. This ref can be used to call
650
+ * all of ScrollView's public methods, in addition to native methods like
651
+ * measure, measureLayout, etc.
652
+ */
653
+ scrollViewRef?: React.RefSetter<PublicScrollViewInstance>,
654
+ |}>;
655
+
656
+ type State = {|
657
+ layoutHeight: ?number,
658
+ |};
659
+
660
+ const IS_ANIMATING_TOUCH_START_THRESHOLD_MS = 16;
661
+
662
+ export type ScrollViewComponentStatics = $ReadOnly<{|
663
+ Context: typeof ScrollViewContext,
664
+ |}>;
665
+
666
+ /**
667
+ * Component that wraps platform ScrollView while providing
668
+ * integration with touch locking "responder" system.
669
+ *
670
+ * Keep in mind that ScrollViews must have a bounded height in order to work,
671
+ * since they contain unbounded-height children into a bounded container (via
672
+ * a scroll interaction). In order to bound the height of a ScrollView, either
673
+ * set the height of the view directly (discouraged) or make sure all parent
674
+ * views have bounded height. Forgetting to transfer `{flex: 1}` down the
675
+ * view stack can lead to errors here, which the element inspector makes
676
+ * easy to debug.
677
+ *
678
+ * Doesn't yet support other contained responders from blocking this scroll
679
+ * view from becoming the responder.
680
+ *
681
+ *
682
+ * `<ScrollView>` vs [`<FlatList>`](https://reactnative.dev/docs/flatlist) - which one to use?
683
+ *
684
+ * `ScrollView` simply renders all its react child components at once. That
685
+ * makes it very easy to understand and use.
686
+ *
687
+ * On the other hand, this has a performance downside. Imagine you have a very
688
+ * long list of items you want to display, maybe several screens worth of
689
+ * content. Creating JS components and native views for everything all at once,
690
+ * much of which may not even be shown, will contribute to slow rendering and
691
+ * increased memory usage.
692
+ *
693
+ * This is where `FlatList` comes into play. `FlatList` renders items lazily,
694
+ * just when they are about to appear, and removes items that scroll way off
695
+ * screen to save memory and processing time.
696
+ *
697
+ * `FlatList` is also handy if you want to render separators between your items,
698
+ * multiple columns, infinite scroll loading, or any number of other features it
699
+ * supports out of the box.
700
+ */
701
+ class ScrollView extends React.Component<Props, State> {
702
+ static Context: typeof ScrollViewContext = ScrollViewContext;
703
+
704
+ constructor(props: Props) {
705
+ super(props);
706
+
707
+ this._scrollAnimatedValue = new AnimatedImplementation.Value(
708
+ this.props.contentOffset?.y ?? 0,
709
+ );
710
+ this._scrollAnimatedValue.setOffset(this.props.contentInset?.top ?? 0);
711
+ }
712
+
713
+ _scrollAnimatedValue: AnimatedImplementation.Value;
714
+ _scrollAnimatedValueAttachment: ?{detach: () => void, ...} = null;
715
+ _stickyHeaderRefs: Map<string, React.ElementRef<StickyHeaderComponentType>> =
716
+ new Map();
717
+ _headerLayoutYs: Map<string, number> = new Map();
718
+
719
+ _keyboardMetrics: ?KeyboardMetrics = null;
720
+ _additionalScrollOffset: number = 0;
721
+ _isTouching: boolean = false;
722
+ _lastMomentumScrollBeginTime: number = 0;
723
+ _lastMomentumScrollEndTime: number = 0;
724
+
725
+ // Reset to false every time becomes responder. This is used to:
726
+ // - Determine if the scroll view has been scrolled and therefore should
727
+ // refuse to give up its responder lock.
728
+ // - Determine if releasing should dismiss the keyboard when we are in
729
+ // tap-to-dismiss mode (this.props.keyboardShouldPersistTaps !== 'always').
730
+ _observedScrollSinceBecomingResponder: boolean = false;
731
+ _becameResponderWhileAnimating: boolean = false;
732
+ _preventNegativeScrollOffset: ?boolean = null;
733
+
734
+ _animated: ?boolean = null;
735
+
736
+ _subscriptionKeyboardWillShow: ?EventSubscription = null;
737
+ _subscriptionKeyboardWillHide: ?EventSubscription = null;
738
+ _subscriptionKeyboardDidShow: ?EventSubscription = null;
739
+ _subscriptionKeyboardDidHide: ?EventSubscription = null;
740
+
741
+ state: State = {
742
+ layoutHeight: null,
743
+ };
744
+
745
+ componentDidMount() {
746
+ if (typeof this.props.keyboardShouldPersistTaps === 'boolean') {
747
+ console.warn(
748
+ `'keyboardShouldPersistTaps={${
749
+ this.props.keyboardShouldPersistTaps === true ? 'true' : 'false'
750
+ }}' is deprecated. ` +
751
+ `Use 'keyboardShouldPersistTaps="${
752
+ this.props.keyboardShouldPersistTaps ? 'always' : 'never'
753
+ }"' instead`,
754
+ );
755
+ }
756
+
757
+ this._keyboardMetrics = Keyboard.metrics();
758
+ this._additionalScrollOffset = 0;
759
+
760
+ this._subscriptionKeyboardWillShow = Keyboard.addListener(
761
+ 'keyboardWillShow',
762
+ this.scrollResponderKeyboardWillShow,
763
+ );
764
+ this._subscriptionKeyboardWillHide = Keyboard.addListener(
765
+ 'keyboardWillHide',
766
+ this.scrollResponderKeyboardWillHide,
767
+ );
768
+ this._subscriptionKeyboardDidShow = Keyboard.addListener(
769
+ 'keyboardDidShow',
770
+ this.scrollResponderKeyboardDidShow,
771
+ );
772
+ this._subscriptionKeyboardDidHide = Keyboard.addListener(
773
+ 'keyboardDidHide',
774
+ this.scrollResponderKeyboardDidHide,
775
+ );
776
+
777
+ this._updateAnimatedNodeAttachment();
778
+ }
779
+
780
+ componentDidUpdate(prevProps: Props) {
781
+ const prevContentInsetTop = prevProps.contentInset
782
+ ? prevProps.contentInset.top
783
+ : 0;
784
+ const newContentInsetTop = this.props.contentInset
785
+ ? this.props.contentInset.top
786
+ : 0;
787
+ if (prevContentInsetTop !== newContentInsetTop) {
788
+ this._scrollAnimatedValue.setOffset(newContentInsetTop || 0);
789
+ }
790
+
791
+ this._updateAnimatedNodeAttachment();
792
+ }
793
+
794
+ componentWillUnmount() {
795
+ if (this._subscriptionKeyboardWillShow != null) {
796
+ this._subscriptionKeyboardWillShow.remove();
797
+ }
798
+ if (this._subscriptionKeyboardWillHide != null) {
799
+ this._subscriptionKeyboardWillHide.remove();
800
+ }
801
+ if (this._subscriptionKeyboardDidShow != null) {
802
+ this._subscriptionKeyboardDidShow.remove();
803
+ }
804
+ if (this._subscriptionKeyboardDidHide != null) {
805
+ this._subscriptionKeyboardDidHide.remove();
806
+ }
807
+
808
+ if (this._scrollAnimatedValueAttachment) {
809
+ this._scrollAnimatedValueAttachment.detach();
810
+ }
811
+ }
812
+
813
+ /**
814
+ * Returns a reference to the underlying scroll responder, which supports
815
+ * operations like `scrollTo`. All ScrollView-like components should
816
+ * implement this method so that they can be composed while providing access
817
+ * to the underlying scroll responder's methods.
818
+ */
819
+ getScrollResponder: () => ScrollResponderType = () => {
820
+ // $FlowFixMe[unclear-type]
821
+ return ((this: any): ScrollResponderType);
822
+ };
823
+
824
+ getScrollableNode: () => ?number = () => {
825
+ return findNodeHandle(this.getNativeScrollRef());
826
+ };
827
+
828
+ getInnerViewNode: () => ?number = () => {
829
+ return findNodeHandle(this._innerView.nativeInstance);
830
+ };
831
+
832
+ getInnerViewRef: () => InnerViewInstance | null = () => {
833
+ return this._innerView.nativeInstance;
834
+ };
835
+
836
+ getNativeScrollRef: () => HostInstance | null = () => {
837
+ return this._scrollView.nativeInstance;
838
+ };
839
+
840
+ /**
841
+ * Scrolls to a given x, y offset, either immediately or with a smooth animation.
842
+ *
843
+ * Example:
844
+ *
845
+ * `scrollTo({x: 0, y: 0, animated: true})`
846
+ *
847
+ * Note: The weird function signature is due to the fact that, for historical reasons,
848
+ * the function also accepts separate arguments as an alternative to the options object.
849
+ * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
850
+ */
851
+ scrollTo: (
852
+ options?:
853
+ | {
854
+ x?: number,
855
+ y?: number,
856
+ animated?: boolean,
857
+ ...
858
+ }
859
+ | number,
860
+ deprecatedX?: number,
861
+ deprecatedAnimated?: boolean,
862
+ ) => void = (
863
+ options?:
864
+ | {
865
+ x?: number,
866
+ y?: number,
867
+ animated?: boolean,
868
+ ...
869
+ }
870
+ | number,
871
+ deprecatedX?: number,
872
+ deprecatedAnimated?: boolean,
873
+ ) => {
874
+ let x, y, animated;
875
+ if (typeof options === 'number') {
876
+ console.warn(
877
+ '`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, ' +
878
+ 'animated: true})` instead.',
879
+ );
880
+ y = options;
881
+ x = deprecatedX;
882
+ animated = deprecatedAnimated;
883
+ } else if (options) {
884
+ y = options.y;
885
+ x = options.x;
886
+ animated = options.animated;
887
+ }
888
+ const component = this.getNativeScrollRef();
889
+ if (component == null) {
890
+ return;
891
+ }
892
+ Commands.scrollTo(component, x || 0, y || 0, animated !== false);
893
+ };
894
+
895
+ /**
896
+ * If this is a vertical ScrollView scrolls to the bottom.
897
+ * If this is a horizontal ScrollView scrolls to the right.
898
+ *
899
+ * Use `scrollToEnd({animated: true})` for smooth animated scrolling,
900
+ * `scrollToEnd({animated: false})` for immediate scrolling.
901
+ * If no options are passed, `animated` defaults to true.
902
+ */
903
+ scrollToEnd: (options?: ?{animated?: boolean, ...}) => void = (
904
+ options?: ?{animated?: boolean, ...},
905
+ ) => {
906
+ // Default to true
907
+ const animated = (options && options.animated) !== false;
908
+ const component = this.getNativeScrollRef();
909
+ if (component == null) {
910
+ return;
911
+ }
912
+ Commands.scrollToEnd(component, animated);
913
+ };
914
+
915
+ /**
916
+ * Displays the scroll indicators momentarily.
917
+ *
918
+ * @platform ios
919
+ */
920
+ flashScrollIndicators: () => void = () => {
921
+ const component = this.getNativeScrollRef();
922
+ if (component == null) {
923
+ return;
924
+ }
925
+ Commands.flashScrollIndicators(component);
926
+ };
927
+
928
+ /**
929
+ * This method should be used as the callback to onFocus in a TextInputs'
930
+ * parent view. Note that any module using this mixin needs to return
931
+ * the parent view's ref in getScrollViewRef() in order to use this method.
932
+ * @param {number} nodeHandle The TextInput node handle
933
+ * @param {number} additionalOffset The scroll view's bottom "contentInset".
934
+ * Default is 0.
935
+ * @param {bool} preventNegativeScrolling Whether to allow pulling the content
936
+ * down to make it meet the keyboard's top. Default is false.
937
+ */
938
+ scrollResponderScrollNativeHandleToKeyboard: (
939
+ nodeHandle: number | HostInstance,
940
+ additionalOffset?: number,
941
+ preventNegativeScrollOffset?: boolean,
942
+ ) => void = (
943
+ nodeHandle: number | HostInstance,
944
+ additionalOffset?: number,
945
+ preventNegativeScrollOffset?: boolean,
946
+ ) => {
947
+ this._additionalScrollOffset = additionalOffset || 0;
948
+ this._preventNegativeScrollOffset = !!preventNegativeScrollOffset;
949
+
950
+ if (this._innerView.nativeInstance == null) {
951
+ return;
952
+ }
953
+
954
+ if (typeof nodeHandle === 'number') {
955
+ UIManager.measureLayout(
956
+ nodeHandle,
957
+ nullthrows(findNodeHandle(this)),
958
+ // $FlowFixMe[method-unbinding] added when improving typing for this parameters
959
+ this._textInputFocusError,
960
+ this._inputMeasureAndScrollToKeyboard,
961
+ );
962
+ } else {
963
+ nodeHandle.measureLayout(
964
+ this._innerView.nativeInstance,
965
+ this._inputMeasureAndScrollToKeyboard,
966
+ // $FlowFixMe[method-unbinding] added when improving typing for this parameters
967
+ this._textInputFocusError,
968
+ );
969
+ }
970
+ };
971
+
972
+ /**
973
+ * A helper function to zoom to a specific rect in the scrollview. The argument has the shape
974
+ * {x: number; y: number; width: number; height: number; animated: boolean = true}
975
+ *
976
+ * @platform ios
977
+ */
978
+ scrollResponderZoomTo: (
979
+ rect: {|
980
+ x: number,
981
+ y: number,
982
+ width: number,
983
+ height: number,
984
+ animated?: boolean,
985
+ |},
986
+ animated?: boolean, // deprecated, put this inside the rect argument instead
987
+ ) => void = (
988
+ rect: {|
989
+ x: number,
990
+ y: number,
991
+ width: number,
992
+ height: number,
993
+ animated?: boolean,
994
+ |},
995
+ animated?: boolean, // deprecated, put this inside the rect argument instead
996
+ ) => {
997
+ invariant(Platform.OS === 'ios', 'zoomToRect is not implemented');
998
+ if ('animated' in rect) {
999
+ this._animated = rect.animated;
1000
+ delete rect.animated;
1001
+ } else if (typeof animated !== 'undefined') {
1002
+ console.warn(
1003
+ '`scrollResponderZoomTo` `animated` argument is deprecated. Use `options.animated` instead',
1004
+ );
1005
+ }
1006
+
1007
+ const component = this.getNativeScrollRef();
1008
+ if (component == null) {
1009
+ return;
1010
+ }
1011
+ Commands.zoomToRect(component, rect, animated !== false);
1012
+ };
1013
+
1014
+ _textInputFocusError() {
1015
+ console.warn('Error measuring text field.');
1016
+ }
1017
+
1018
+ /**
1019
+ * The calculations performed here assume the scroll view takes up the entire
1020
+ * screen - even if has some content inset. We then measure the offsets of the
1021
+ * keyboard, and compensate both for the scroll view's "contentInset".
1022
+ *
1023
+ * @param {number} left Position of input w.r.t. table view.
1024
+ * @param {number} top Position of input w.r.t. table view.
1025
+ * @param {number} width Width of the text input.
1026
+ * @param {number} height Height of the text input.
1027
+ */
1028
+ _inputMeasureAndScrollToKeyboard: (
1029
+ left: number,
1030
+ top: number,
1031
+ width: number,
1032
+ height: number,
1033
+ ) => void = (left: number, top: number, width: number, height: number) => {
1034
+ let keyboardScreenY = Dimensions.get('window').height;
1035
+
1036
+ const scrollTextInputIntoVisibleRect = () => {
1037
+ if (this._keyboardMetrics != null) {
1038
+ keyboardScreenY = this._keyboardMetrics.screenY;
1039
+ }
1040
+ let scrollOffsetY =
1041
+ top - keyboardScreenY + height + this._additionalScrollOffset;
1042
+
1043
+ // By default, this can scroll with negative offset, pulling the content
1044
+ // down so that the target component's bottom meets the keyboard's top.
1045
+ // If requested otherwise, cap the offset at 0 minimum to avoid content
1046
+ // shifting down.
1047
+ if (this._preventNegativeScrollOffset === true) {
1048
+ scrollOffsetY = Math.max(0, scrollOffsetY);
1049
+ }
1050
+ this.scrollTo({x: 0, y: scrollOffsetY, animated: true});
1051
+
1052
+ this._additionalScrollOffset = 0;
1053
+ this._preventNegativeScrollOffset = false;
1054
+ };
1055
+
1056
+ if (this._keyboardMetrics == null) {
1057
+ // `_keyboardMetrics` is set inside `scrollResponderKeyboardWillShow` which
1058
+ // is not guaranteed to be called before `_inputMeasureAndScrollToKeyboard` but native has already scheduled it.
1059
+ // In case it was not called before `_inputMeasureAndScrollToKeyboard`, we postpone scrolling to
1060
+ // text input.
1061
+ setTimeout(() => {
1062
+ scrollTextInputIntoVisibleRect();
1063
+ }, 0);
1064
+ } else {
1065
+ scrollTextInputIntoVisibleRect();
1066
+ }
1067
+ };
1068
+
1069
+ _getKeyForIndex(index: $FlowFixMe, childArray: $FlowFixMe): $FlowFixMe {
1070
+ const child = childArray[index];
1071
+ return child && child.key;
1072
+ }
1073
+
1074
+ _updateAnimatedNodeAttachment() {
1075
+ if (this._scrollAnimatedValueAttachment) {
1076
+ this._scrollAnimatedValueAttachment.detach();
1077
+ }
1078
+ if (
1079
+ this.props.stickyHeaderIndices &&
1080
+ this.props.stickyHeaderIndices.length > 0
1081
+ ) {
1082
+ this._scrollAnimatedValueAttachment =
1083
+ AnimatedImplementation.attachNativeEvent(
1084
+ this.getNativeScrollRef(),
1085
+ 'onScroll',
1086
+ [{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}],
1087
+ );
1088
+ }
1089
+ }
1090
+
1091
+ _setStickyHeaderRef(
1092
+ key: string,
1093
+ ref: ?React.ElementRef<StickyHeaderComponentType>,
1094
+ ) {
1095
+ if (ref) {
1096
+ this._stickyHeaderRefs.set(key, ref);
1097
+ } else {
1098
+ this._stickyHeaderRefs.delete(key);
1099
+ }
1100
+ }
1101
+
1102
+ _onStickyHeaderLayout(index: $FlowFixMe, event: $FlowFixMe, key: $FlowFixMe) {
1103
+ const {stickyHeaderIndices} = this.props;
1104
+ if (!stickyHeaderIndices) {
1105
+ return;
1106
+ }
1107
+ const childArray = React.Children.toArray<$FlowFixMe>(this.props.children);
1108
+ if (key !== this._getKeyForIndex(index, childArray)) {
1109
+ // ignore stale layout update
1110
+ return;
1111
+ }
1112
+
1113
+ const layoutY = event.nativeEvent.layout.y;
1114
+ this._headerLayoutYs.set(key, layoutY);
1115
+
1116
+ const indexOfIndex = stickyHeaderIndices.indexOf(index);
1117
+ const previousHeaderIndex = stickyHeaderIndices[indexOfIndex - 1];
1118
+ if (previousHeaderIndex != null) {
1119
+ const previousHeader = this._stickyHeaderRefs.get(
1120
+ this._getKeyForIndex(previousHeaderIndex, childArray),
1121
+ );
1122
+ previousHeader &&
1123
+ previousHeader.setNextHeaderY &&
1124
+ previousHeader.setNextHeaderY(layoutY);
1125
+ }
1126
+ }
1127
+
1128
+ _handleScroll = (e: ScrollEvent) => {
1129
+ this._observedScrollSinceBecomingResponder = true;
1130
+ this.props.onScroll && this.props.onScroll(e);
1131
+ };
1132
+
1133
+ _handleLayout = (e: LayoutEvent) => {
1134
+ if (this.props.invertStickyHeaders === true) {
1135
+ this.setState({layoutHeight: e.nativeEvent.layout.height});
1136
+ }
1137
+ if (this.props.onLayout) {
1138
+ this.props.onLayout(e);
1139
+ }
1140
+ };
1141
+
1142
+ _handleContentOnLayout = (e: LayoutEvent) => {
1143
+ const {width, height} = e.nativeEvent.layout;
1144
+ this.props.onContentSizeChange &&
1145
+ this.props.onContentSizeChange(width, height);
1146
+ };
1147
+
1148
+ _innerView: RefForwarder<InnerViewInstance, InnerViewInstance> =
1149
+ createRefForwarder(
1150
+ (instance: InnerViewInstance): InnerViewInstance => instance,
1151
+ );
1152
+
1153
+ _scrollView: RefForwarder<HostInstance, PublicScrollViewInstance | null> =
1154
+ createRefForwarder(nativeInstance => {
1155
+ // This is a hack. Ideally we would forwardRef to the underlying
1156
+ // host component. However, since ScrollView has it's own methods that can be
1157
+ // called as well, if we used the standard forwardRef then these
1158
+ // methods wouldn't be accessible and thus be a breaking change.
1159
+ //
1160
+ // Therefore we edit ref to include ScrollView's public methods so that
1161
+ // they are callable from the ref.
1162
+
1163
+ // $FlowFixMe[prop-missing] - Known issue with appending custom methods.
1164
+ const publicInstance: PublicScrollViewInstance = Object.assign(
1165
+ nativeInstance,
1166
+ {
1167
+ getScrollResponder: this.getScrollResponder,
1168
+ getScrollableNode: this.getScrollableNode,
1169
+ getInnerViewNode: this.getInnerViewNode,
1170
+ getInnerViewRef: this.getInnerViewRef,
1171
+ getNativeScrollRef: this.getNativeScrollRef,
1172
+ scrollTo: this.scrollTo,
1173
+ scrollToEnd: this.scrollToEnd,
1174
+ flashScrollIndicators: this.flashScrollIndicators,
1175
+ scrollResponderZoomTo: this.scrollResponderZoomTo,
1176
+ scrollResponderScrollNativeHandleToKeyboard:
1177
+ this.scrollResponderScrollNativeHandleToKeyboard,
1178
+ },
1179
+ );
1180
+
1181
+ return publicInstance;
1182
+ });
1183
+
1184
+ /**
1185
+ * Warning, this may be called several times for a single keyboard opening.
1186
+ * It's best to store the information in this method and then take any action
1187
+ * at a later point (either in `keyboardDidShow` or other).
1188
+ *
1189
+ * Here's the order that events occur in:
1190
+ * - focus
1191
+ * - willShow {startCoordinates, endCoordinates} several times
1192
+ * - didShow several times
1193
+ * - blur
1194
+ * - willHide {startCoordinates, endCoordinates} several times
1195
+ * - didHide several times
1196
+ *
1197
+ * The `ScrollResponder` module callbacks for each of these events.
1198
+ * Even though any user could have easily listened to keyboard events
1199
+ * themselves, using these `props` callbacks ensures that ordering of events
1200
+ * is consistent - and not dependent on the order that the keyboard events are
1201
+ * subscribed to. This matters when telling the scroll view to scroll to where
1202
+ * the keyboard is headed - the scroll responder better have been notified of
1203
+ * the keyboard destination before being instructed to scroll to where the
1204
+ * keyboard will be. Stick to the `ScrollResponder` callbacks, and everything
1205
+ * will work.
1206
+ *
1207
+ * WARNING: These callbacks will fire even if a keyboard is displayed in a
1208
+ * different navigation pane. Filter out the events to determine if they are
1209
+ * relevant to you. (For example, only if you receive these callbacks after
1210
+ * you had explicitly focused a node etc).
1211
+ */
1212
+
1213
+ scrollResponderKeyboardWillShow: (e: KeyboardEvent) => void = (
1214
+ e: KeyboardEvent,
1215
+ ) => {
1216
+ this._keyboardMetrics = e.endCoordinates;
1217
+ this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e);
1218
+ };
1219
+
1220
+ scrollResponderKeyboardWillHide: (e: KeyboardEvent) => void = (
1221
+ e: KeyboardEvent,
1222
+ ) => {
1223
+ this._keyboardMetrics = null;
1224
+ this.props.onKeyboardWillHide && this.props.onKeyboardWillHide(e);
1225
+ };
1226
+
1227
+ scrollResponderKeyboardDidShow: (e: KeyboardEvent) => void = (
1228
+ e: KeyboardEvent,
1229
+ ) => {
1230
+ this._keyboardMetrics = e.endCoordinates;
1231
+ this.props.onKeyboardDidShow && this.props.onKeyboardDidShow(e);
1232
+ };
1233
+
1234
+ scrollResponderKeyboardDidHide: (e: KeyboardEvent) => void = (
1235
+ e: KeyboardEvent,
1236
+ ) => {
1237
+ this._keyboardMetrics = null;
1238
+ this.props.onKeyboardDidHide && this.props.onKeyboardDidHide(e);
1239
+ };
1240
+
1241
+ /**
1242
+ * Invoke this from an `onMomentumScrollBegin` event.
1243
+ */
1244
+ _handleMomentumScrollBegin: (e: ScrollEvent) => void = (e: ScrollEvent) => {
1245
+ this._lastMomentumScrollBeginTime = global.performance.now();
1246
+ this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e);
1247
+ };
1248
+
1249
+ /**
1250
+ * Invoke this from an `onMomentumScrollEnd` event.
1251
+ */
1252
+ _handleMomentumScrollEnd: (e: ScrollEvent) => void = (e: ScrollEvent) => {
1253
+ FrameRateLogger.endScroll();
1254
+ this._lastMomentumScrollEndTime = global.performance.now();
1255
+ this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e);
1256
+ };
1257
+
1258
+ /**
1259
+ * Unfortunately, `onScrollBeginDrag` also fires when *stopping* the scroll
1260
+ * animation, and there's not an easy way to distinguish a drag vs. stopping
1261
+ * momentum.
1262
+ *
1263
+ * Invoke this from an `onScrollBeginDrag` event.
1264
+ */
1265
+ _handleScrollBeginDrag: (e: ScrollEvent) => void = (e: ScrollEvent) => {
1266
+ FrameRateLogger.beginScroll(); // TODO: track all scrolls after implementing onScrollEndAnimation
1267
+
1268
+ if (
1269
+ Platform.OS === 'android' &&
1270
+ this.props.keyboardDismissMode === 'on-drag'
1271
+ ) {
1272
+ dismissKeyboard();
1273
+ }
1274
+
1275
+ this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
1276
+ };
1277
+
1278
+ /**
1279
+ * Invoke this from an `onScrollEndDrag` event.
1280
+ */
1281
+ _handleScrollEndDrag: (e: ScrollEvent) => void = (e: ScrollEvent) => {
1282
+ const {velocity} = e.nativeEvent;
1283
+ // - If we are animating, then this is a "drag" that is stopping the scrollview and momentum end
1284
+ // will fire.
1285
+ // - If velocity is non-zero, then the interaction will stop when momentum scroll ends or
1286
+ // another drag starts and ends.
1287
+ // - If we don't get velocity, better to stop the interaction twice than not stop it.
1288
+ if (
1289
+ !this._isAnimating() &&
1290
+ (!velocity || (velocity.x === 0 && velocity.y === 0))
1291
+ ) {
1292
+ FrameRateLogger.endScroll();
1293
+ }
1294
+ this.props.onScrollEndDrag && this.props.onScrollEndDrag(e);
1295
+ };
1296
+
1297
+ /**
1298
+ * A helper function for this class that lets us quickly determine if the
1299
+ * view is currently animating. This is particularly useful to know when
1300
+ * a touch has just started or ended.
1301
+ */
1302
+ _isAnimating: () => boolean = () => {
1303
+ const now = global.performance.now();
1304
+ const timeSinceLastMomentumScrollEnd =
1305
+ now - this._lastMomentumScrollEndTime;
1306
+ const isAnimating =
1307
+ timeSinceLastMomentumScrollEnd < IS_ANIMATING_TOUCH_START_THRESHOLD_MS ||
1308
+ this._lastMomentumScrollEndTime < this._lastMomentumScrollBeginTime;
1309
+ return isAnimating;
1310
+ };
1311
+
1312
+ /**
1313
+ * Invoke this from an `onResponderGrant` event.
1314
+ */
1315
+ _handleResponderGrant: (e: PressEvent) => void = (e: PressEvent) => {
1316
+ this._observedScrollSinceBecomingResponder = false;
1317
+ this.props.onResponderGrant && this.props.onResponderGrant(e);
1318
+ this._becameResponderWhileAnimating = this._isAnimating();
1319
+ };
1320
+
1321
+ /**
1322
+ * Invoke this from an `onResponderReject` event.
1323
+ *
1324
+ * Some other element is not yielding its role as responder. Normally, we'd
1325
+ * just disable the `UIScrollView`, but a touch has already began on it, the
1326
+ * `UIScrollView` will not accept being disabled after that. The easiest
1327
+ * solution for now is to accept the limitation of disallowing this
1328
+ * altogether. To improve this, find a way to disable the `UIScrollView` after
1329
+ * a touch has already started.
1330
+ */
1331
+ _handleResponderReject: () => void = () => {};
1332
+
1333
+ /**
1334
+ * Invoke this from an `onResponderRelease` event.
1335
+ */
1336
+ _handleResponderRelease: (e: PressEvent) => void = (e: PressEvent) => {
1337
+ this._isTouching = e.nativeEvent.touches.length !== 0;
1338
+ this.props.onResponderRelease && this.props.onResponderRelease(e);
1339
+
1340
+ if (typeof e.target === 'number') {
1341
+ if (__DEV__) {
1342
+ console.error(
1343
+ 'Did not expect event target to be a number. Should have been a native component',
1344
+ );
1345
+ }
1346
+
1347
+ return;
1348
+ }
1349
+
1350
+ // By default scroll views will unfocus a textField
1351
+ // if another touch occurs outside of it
1352
+ const currentlyFocusedTextInput = TextInputState.currentlyFocusedInput();
1353
+ if (
1354
+ currentlyFocusedTextInput != null &&
1355
+ this.props.keyboardShouldPersistTaps !== true &&
1356
+ this.props.keyboardShouldPersistTaps !== 'always' &&
1357
+ this._keyboardIsDismissible() &&
1358
+ e.target !== currentlyFocusedTextInput &&
1359
+ !this._observedScrollSinceBecomingResponder &&
1360
+ !this._becameResponderWhileAnimating
1361
+ ) {
1362
+ TextInputState.blurTextInput(currentlyFocusedTextInput);
1363
+ }
1364
+ };
1365
+
1366
+ /**
1367
+ * We will allow the scroll view to give up its lock iff it acquired the lock
1368
+ * during an animation. This is a very useful default that happens to satisfy
1369
+ * many common user experiences.
1370
+ *
1371
+ * - Stop a scroll on the left edge, then turn that into an outer view's
1372
+ * backswipe.
1373
+ * - Stop a scroll mid-bounce at the top, continue pulling to have the outer
1374
+ * view dismiss.
1375
+ * - However, without catching the scroll view mid-bounce (while it is
1376
+ * motionless), if you drag far enough for the scroll view to become
1377
+ * responder (and therefore drag the scroll view a bit), any backswipe
1378
+ * navigation of a swipe gesture higher in the view hierarchy, should be
1379
+ * rejected.
1380
+ */
1381
+ _handleResponderTerminationRequest: () => boolean = () => {
1382
+ return !this._observedScrollSinceBecomingResponder;
1383
+ };
1384
+
1385
+ /**
1386
+ * Invoke this from an `onScroll` event.
1387
+ */
1388
+ _handleScrollShouldSetResponder: () => boolean = () => {
1389
+ // Allow any event touch pass through if the default pan responder is disabled
1390
+ if (this.props.disableScrollViewPanResponder === true) {
1391
+ return false;
1392
+ }
1393
+ return this._isTouching;
1394
+ };
1395
+
1396
+ /**
1397
+ * Merely touch starting is not sufficient for a scroll view to become the
1398
+ * responder. Being the "responder" means that the very next touch move/end
1399
+ * event will result in an action/movement.
1400
+ *
1401
+ * Invoke this from an `onStartShouldSetResponder` event.
1402
+ *
1403
+ * `onStartShouldSetResponder` is used when the next move/end will trigger
1404
+ * some UI movement/action, but when you want to yield priority to views
1405
+ * nested inside of the view.
1406
+ *
1407
+ * There may be some cases where scroll views actually should return `true`
1408
+ * from `onStartShouldSetResponder`: Any time we are detecting a standard tap
1409
+ * that gives priority to nested views.
1410
+ *
1411
+ * - If a single tap on the scroll view triggers an action such as
1412
+ * recentering a map style view yet wants to give priority to interaction
1413
+ * views inside (such as dropped pins or labels), then we would return true
1414
+ * from this method when there is a single touch.
1415
+ *
1416
+ * - Similar to the previous case, if a two finger "tap" should trigger a
1417
+ * zoom, we would check the `touches` count, and if `>= 2`, we would return
1418
+ * true.
1419
+ *
1420
+ */
1421
+ _handleStartShouldSetResponder: (e: PressEvent) => boolean = (
1422
+ e: PressEvent,
1423
+ ) => {
1424
+ // Allow any event touch pass through if the default pan responder is disabled
1425
+ if (this.props.disableScrollViewPanResponder === true) {
1426
+ return false;
1427
+ }
1428
+
1429
+ const currentlyFocusedInput = TextInputState.currentlyFocusedInput();
1430
+ if (
1431
+ this.props.keyboardShouldPersistTaps === 'handled' &&
1432
+ this._keyboardIsDismissible() &&
1433
+ e.target !== currentlyFocusedInput
1434
+ ) {
1435
+ return true;
1436
+ }
1437
+ return false;
1438
+ };
1439
+
1440
+ /**
1441
+ * There are times when the scroll view wants to become the responder
1442
+ * (meaning respond to the next immediate `touchStart/touchEnd`), in a way
1443
+ * that *doesn't* give priority to nested views (hence the capture phase):
1444
+ *
1445
+ * - Currently animating.
1446
+ * - Tapping anywhere that is not a text input, while the keyboard is
1447
+ * up (which should dismiss the keyboard).
1448
+ *
1449
+ * Invoke this from an `onStartShouldSetResponderCapture` event.
1450
+ */
1451
+ _handleStartShouldSetResponderCapture: (e: PressEvent) => boolean = (
1452
+ e: PressEvent,
1453
+ ) => {
1454
+ // The scroll view should receive taps instead of its descendants if:
1455
+ // * it is already animating/decelerating
1456
+ if (this._isAnimating()) {
1457
+ return true;
1458
+ }
1459
+
1460
+ // Allow any event touch pass through if the default pan responder is disabled
1461
+ if (this.props.disableScrollViewPanResponder === true) {
1462
+ return false;
1463
+ }
1464
+
1465
+ // * the keyboard is up, keyboardShouldPersistTaps is 'never' (the default),
1466
+ // and a new touch starts with a non-textinput target (in which case the
1467
+ // first tap should be sent to the scroll view and dismiss the keyboard,
1468
+ // then the second tap goes to the actual interior view)
1469
+ const {keyboardShouldPersistTaps} = this.props;
1470
+ const keyboardNeverPersistTaps =
1471
+ !keyboardShouldPersistTaps || keyboardShouldPersistTaps === 'never';
1472
+
1473
+ if (typeof e.target === 'number') {
1474
+ if (__DEV__) {
1475
+ console.error(
1476
+ 'Did not expect event target to be a number. Should have been a native component',
1477
+ );
1478
+ }
1479
+
1480
+ return false;
1481
+ }
1482
+
1483
+ // Let presses through if the soft keyboard is detached from the viewport
1484
+ if (this._softKeyboardIsDetached()) {
1485
+ return false;
1486
+ }
1487
+
1488
+ if (
1489
+ keyboardNeverPersistTaps &&
1490
+ this._keyboardIsDismissible() &&
1491
+ e.target != null &&
1492
+ // $FlowFixMe[incompatible-call]
1493
+ !TextInputState.isTextInput(e.target)
1494
+ ) {
1495
+ return true;
1496
+ }
1497
+
1498
+ return false;
1499
+ };
1500
+
1501
+ /**
1502
+ * Do we consider there to be a dismissible soft-keyboard open?
1503
+ */
1504
+ _keyboardIsDismissible: () => boolean = () => {
1505
+ const currentlyFocusedInput = TextInputState.currentlyFocusedInput();
1506
+
1507
+ // We cannot dismiss the keyboard without an input to blur, even if a soft
1508
+ // keyboard is open (e.g. when keyboard is open due to a native component
1509
+ // not participating in TextInputState). It's also possible that the
1510
+ // currently focused input isn't a TextInput (such as by calling ref.focus
1511
+ // on a non-TextInput).
1512
+ const hasFocusedTextInput =
1513
+ currentlyFocusedInput != null &&
1514
+ TextInputState.isTextInput(currentlyFocusedInput);
1515
+
1516
+ // Even if an input is focused, we may not have a keyboard to dismiss. E.g
1517
+ // when using a physical keyboard. Ensure we have an event for an opened
1518
+ // keyboard.
1519
+ const softKeyboardMayBeOpen =
1520
+ this._keyboardMetrics != null || this._keyboardEventsAreUnreliable();
1521
+
1522
+ return hasFocusedTextInput && softKeyboardMayBeOpen;
1523
+ };
1524
+
1525
+ /**
1526
+ * Whether an open soft keyboard is present which does not overlap the
1527
+ * viewport. E.g. for a VR soft-keyboard which is detached from the app
1528
+ * viewport.
1529
+ */
1530
+ _softKeyboardIsDetached: () => boolean = () => {
1531
+ return this._keyboardMetrics != null && this._keyboardMetrics.height === 0;
1532
+ };
1533
+
1534
+ _keyboardEventsAreUnreliable: () => boolean = () => {
1535
+ // Android versions prior to API 30 rely on observing layout changes when
1536
+ // `android:windowSoftInputMode` is set to `adjustResize` or `adjustPan`.
1537
+ return Platform.OS === 'android' && Platform.Version < 30;
1538
+ };
1539
+
1540
+ /**
1541
+ * Invoke this from an `onTouchEnd` event.
1542
+ *
1543
+ * @param {PressEvent} e Event.
1544
+ */
1545
+ _handleTouchEnd: (e: PressEvent) => void = (e: PressEvent) => {
1546
+ const nativeEvent = e.nativeEvent;
1547
+ this._isTouching = nativeEvent.touches.length !== 0;
1548
+
1549
+ const {keyboardShouldPersistTaps} = this.props;
1550
+ const keyboardNeverPersistsTaps =
1551
+ !keyboardShouldPersistTaps || keyboardShouldPersistTaps === 'never';
1552
+
1553
+ // Dismiss the keyboard now if we didn't become responder in capture phase
1554
+ // to eat presses, but still want to dismiss on interaction.
1555
+ // Don't do anything if the target of the touch event is the current input.
1556
+ const currentlyFocusedTextInput = TextInputState.currentlyFocusedInput();
1557
+ if (
1558
+ currentlyFocusedTextInput != null &&
1559
+ e.target !== currentlyFocusedTextInput &&
1560
+ this._softKeyboardIsDetached() &&
1561
+ this._keyboardIsDismissible() &&
1562
+ keyboardNeverPersistsTaps
1563
+ ) {
1564
+ TextInputState.blurTextInput(currentlyFocusedTextInput);
1565
+ }
1566
+
1567
+ this.props.onTouchEnd && this.props.onTouchEnd(e);
1568
+ };
1569
+
1570
+ /**
1571
+ * Invoke this from an `onTouchCancel` event.
1572
+ *
1573
+ * @param {PressEvent} e Event.
1574
+ */
1575
+ _handleTouchCancel: (e: PressEvent) => void = (e: PressEvent) => {
1576
+ this._isTouching = false;
1577
+ this.props.onTouchCancel && this.props.onTouchCancel(e);
1578
+ };
1579
+
1580
+ /**
1581
+ * Invoke this from an `onTouchStart` event.
1582
+ *
1583
+ * Since we know that the `SimpleEventPlugin` occurs later in the plugin
1584
+ * order, after `ResponderEventPlugin`, we can detect that we were *not*
1585
+ * permitted to be the responder (presumably because a contained view became
1586
+ * responder). The `onResponderReject` won't fire in that case - it only
1587
+ * fires when a *current* responder rejects our request.
1588
+ *
1589
+ * @param {PressEvent} e Touch Start event.
1590
+ */
1591
+ _handleTouchStart: (e: PressEvent) => void = (e: PressEvent) => {
1592
+ this._isTouching = true;
1593
+ this.props.onTouchStart && this.props.onTouchStart(e);
1594
+ };
1595
+
1596
+ /**
1597
+ * Invoke this from an `onTouchMove` event.
1598
+ *
1599
+ * Since we know that the `SimpleEventPlugin` occurs later in the plugin
1600
+ * order, after `ResponderEventPlugin`, we can detect that we were *not*
1601
+ * permitted to be the responder (presumably because a contained view became
1602
+ * responder). The `onResponderReject` won't fire in that case - it only
1603
+ * fires when a *current* responder rejects our request.
1604
+ *
1605
+ * @param {PressEvent} e Touch Start event.
1606
+ */
1607
+ _handleTouchMove: (e: PressEvent) => void = (e: PressEvent) => {
1608
+ this.props.onTouchMove && this.props.onTouchMove(e);
1609
+ };
1610
+
1611
+ render(): React.Node {
1612
+ const horizontal = this.props.horizontal === true;
1613
+
1614
+ const NativeScrollView = horizontal
1615
+ ? HScrollViewNativeComponent
1616
+ : VScrollViewNativeComponent;
1617
+
1618
+ const NativeScrollContentView = horizontal
1619
+ ? HScrollContentViewNativeComponent
1620
+ : VScrollContentViewNativeComponent;
1621
+
1622
+ const contentContainerStyle = [
1623
+ horizontal && styles.contentContainerHorizontal,
1624
+ this.props.contentContainerStyle,
1625
+ ];
1626
+ if (__DEV__ && this.props.style !== undefined) {
1627
+ // $FlowFixMe[underconstrained-implicit-instantiation]
1628
+ const style = flattenStyle(this.props.style);
1629
+ const childLayoutProps = ['alignItems', 'justifyContent'].filter(
1630
+ // $FlowFixMe[incompatible-use]
1631
+ prop => style && style[prop] !== undefined,
1632
+ );
1633
+ invariant(
1634
+ childLayoutProps.length === 0,
1635
+ 'ScrollView child layout (' +
1636
+ JSON.stringify(childLayoutProps) +
1637
+ ') must be applied through the contentContainerStyle prop.',
1638
+ );
1639
+ }
1640
+
1641
+ const contentSizeChangeProps =
1642
+ this.props.onContentSizeChange == null
1643
+ ? null
1644
+ : {
1645
+ onLayout: this._handleContentOnLayout,
1646
+ };
1647
+
1648
+ const {stickyHeaderIndices} = this.props;
1649
+ let children = this.props.children;
1650
+ /**
1651
+ * This function can cause unnecessary remount when nested in conditionals as it causes remap of children keys.
1652
+ * https://react.dev/reference/react/Children#children-toarray-caveats
1653
+ */
1654
+ children = React.Children.toArray<$FlowFixMe>(children);
1655
+
1656
+ if (stickyHeaderIndices != null && stickyHeaderIndices.length > 0) {
1657
+ children = children.map((child, index) => {
1658
+ const indexOfIndex = child ? stickyHeaderIndices.indexOf(index) : -1;
1659
+ if (indexOfIndex > -1) {
1660
+ const key = child.key;
1661
+ const nextIndex = stickyHeaderIndices[indexOfIndex + 1];
1662
+ const StickyHeaderComponent =
1663
+ this.props.StickyHeaderComponent || ScrollViewStickyHeader;
1664
+ return (
1665
+ <StickyHeaderComponent
1666
+ key={key}
1667
+ ref={ref => this._setStickyHeaderRef(key, ref)}
1668
+ nextHeaderLayoutY={this._headerLayoutYs.get(
1669
+ this._getKeyForIndex(nextIndex, children),
1670
+ )}
1671
+ onLayout={event => this._onStickyHeaderLayout(index, event, key)}
1672
+ scrollAnimatedValue={this._scrollAnimatedValue}
1673
+ inverted={this.props.invertStickyHeaders}
1674
+ hiddenOnScroll={this.props.stickyHeaderHiddenOnScroll}
1675
+ scrollViewHeight={this.state.layoutHeight}>
1676
+ {child}
1677
+ </StickyHeaderComponent>
1678
+ );
1679
+ } else {
1680
+ return child;
1681
+ }
1682
+ });
1683
+ }
1684
+ children = (
1685
+ <ScrollViewContext.Provider value={horizontal ? HORIZONTAL : VERTICAL}>
1686
+ {children}
1687
+ </ScrollViewContext.Provider>
1688
+ );
1689
+
1690
+ const hasStickyHeaders =
1691
+ Array.isArray(stickyHeaderIndices) && stickyHeaderIndices.length > 0;
1692
+
1693
+ // Some ScrollView native component behaviors rely on using the metrics
1694
+ // of mounted views for anchoring. Make sure not to flatten children if
1695
+ // this is the case.
1696
+ const preserveChildren =
1697
+ this.props.maintainVisibleContentPosition != null ||
1698
+ (Platform.OS === 'android' && this.props.snapToAlignment != null);
1699
+
1700
+ const contentContainer = (
1701
+ <NativeScrollContentView
1702
+ {...contentSizeChangeProps}
1703
+ ref={this._innerView.getForwardingRef(this.props.innerViewRef)}
1704
+ style={contentContainerStyle}
1705
+ removeClippedSubviews={
1706
+ // Subview clipping causes issues with sticky headers on Android and
1707
+ // would be hard to fix properly in a performant way.
1708
+ Platform.OS === 'android' && hasStickyHeaders
1709
+ ? false
1710
+ : this.props.removeClippedSubviews
1711
+ }
1712
+ collapsable={false}
1713
+ collapsableChildren={!preserveChildren}>
1714
+ {children}
1715
+ </NativeScrollContentView>
1716
+ );
1717
+
1718
+ const alwaysBounceHorizontal =
1719
+ this.props.alwaysBounceHorizontal !== undefined
1720
+ ? this.props.alwaysBounceHorizontal
1721
+ : this.props.horizontal;
1722
+
1723
+ const alwaysBounceVertical =
1724
+ this.props.alwaysBounceVertical !== undefined
1725
+ ? this.props.alwaysBounceVertical
1726
+ : !this.props.horizontal;
1727
+
1728
+ const accessible = this.props.accessible !== false; // [Windows]
1729
+
1730
+ const baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical;
1731
+
1732
+ const {experimental_endDraggingSensitivityMultiplier, ...otherProps} =
1733
+ this.props;
1734
+ const props = {
1735
+ ...otherProps,
1736
+ accessible, // [Windows]
1737
+ alwaysBounceHorizontal,
1738
+ alwaysBounceVertical,
1739
+ style: StyleSheet.compose(baseStyle, this.props.style),
1740
+ // Override the onContentSizeChange from props, since this event can
1741
+ // bubble up from TextInputs
1742
+ onContentSizeChange: null,
1743
+ onLayout: this._handleLayout,
1744
+ onMomentumScrollBegin: this._handleMomentumScrollBegin,
1745
+ onMomentumScrollEnd: this._handleMomentumScrollEnd,
1746
+ onResponderGrant: this._handleResponderGrant,
1747
+ onResponderReject: this._handleResponderReject,
1748
+ onResponderRelease: this._handleResponderRelease,
1749
+ onResponderTerminationRequest: this._handleResponderTerminationRequest,
1750
+ onScrollBeginDrag: this._handleScrollBeginDrag,
1751
+ onScrollEndDrag: this._handleScrollEndDrag,
1752
+ onScrollShouldSetResponder: this._handleScrollShouldSetResponder,
1753
+ onStartShouldSetResponder: this._handleStartShouldSetResponder,
1754
+ onStartShouldSetResponderCapture:
1755
+ this._handleStartShouldSetResponderCapture,
1756
+ onTouchEnd: this._handleTouchEnd,
1757
+ onTouchMove: this._handleTouchMove,
1758
+ onTouchStart: this._handleTouchStart,
1759
+ onTouchCancel: this._handleTouchCancel,
1760
+ onScroll: this._handleScroll,
1761
+ endDraggingSensitivityMultiplier:
1762
+ experimental_endDraggingSensitivityMultiplier,
1763
+ scrollEventThrottle: hasStickyHeaders
1764
+ ? 1
1765
+ : this.props.scrollEventThrottle,
1766
+ sendMomentumEvents:
1767
+ this.props.onMomentumScrollBegin || this.props.onMomentumScrollEnd
1768
+ ? true
1769
+ : false,
1770
+ // default to true
1771
+ snapToStart: this.props.snapToStart !== false,
1772
+ // default to true
1773
+ snapToEnd: this.props.snapToEnd !== false,
1774
+ // pagingEnabled is overridden by snapToInterval / snapToOffsets
1775
+ pagingEnabled: Platform.select({
1776
+ // on iOS, pagingEnabled must be set to false to have snapToInterval / snapToOffsets work
1777
+ ios:
1778
+ this.props.pagingEnabled === true &&
1779
+ this.props.snapToInterval == null &&
1780
+ this.props.snapToOffsets == null,
1781
+ // on Android, pagingEnabled must be set to true to have snapToInterval / snapToOffsets work
1782
+ android:
1783
+ this.props.pagingEnabled === true ||
1784
+ this.props.snapToInterval != null ||
1785
+ this.props.snapToOffsets != null,
1786
+ }),
1787
+ };
1788
+
1789
+ const {decelerationRate} = this.props;
1790
+ if (decelerationRate != null) {
1791
+ props.decelerationRate = processDecelerationRate(decelerationRate);
1792
+ }
1793
+
1794
+ const refreshControl = this.props.refreshControl;
1795
+ const scrollViewRef = this._scrollView.getForwardingRef(
1796
+ this.props.scrollViewRef,
1797
+ );
1798
+
1799
+ if (refreshControl) {
1800
+ if (Platform.OS === 'ios') {
1801
+ // On iOS the RefreshControl is a child of the ScrollView.
1802
+ return (
1803
+ // $FlowFixMe[incompatible-type] - Flow only knows element refs.
1804
+ <NativeScrollView {...props} ref={scrollViewRef}>
1805
+ {refreshControl}
1806
+ {contentContainer}
1807
+ </NativeScrollView>
1808
+ );
1809
+ } else if (Platform.OS === 'android') {
1810
+ // On Android wrap the ScrollView with a AndroidSwipeRefreshLayout.
1811
+ // Since the ScrollView is wrapped add the style props to the
1812
+ // AndroidSwipeRefreshLayout and use flex: 1 for the ScrollView.
1813
+ // Note: we should split props.style on the inner and outer props
1814
+ // however, the ScrollView still needs the baseStyle to be scrollable
1815
+ // $FlowFixMe[underconstrained-implicit-instantiation]
1816
+ // $FlowFixMe[incompatible-call]
1817
+ const {outer, inner} = splitLayoutProps(flattenStyle(props.style));
1818
+ return React.cloneElement(
1819
+ refreshControl,
1820
+ {style: StyleSheet.compose(baseStyle, outer)},
1821
+ <NativeScrollView
1822
+ {...props}
1823
+ style={StyleSheet.compose(baseStyle, inner)}
1824
+ // $FlowFixMe[incompatible-type] - Flow only knows element refs.
1825
+ ref={scrollViewRef}>
1826
+ {contentContainer}
1827
+ </NativeScrollView>,
1828
+ );
1829
+ }
1830
+ }
1831
+ return (
1832
+ // $FlowFixMe[incompatible-type] - Flow only knows element refs.
1833
+ <NativeScrollView {...props} ref={scrollViewRef}>
1834
+ {contentContainer}
1835
+ </NativeScrollView>
1836
+ );
1837
+ }
1838
+ }
1839
+
1840
+ const styles = StyleSheet.create({
1841
+ baseVertical: {
1842
+ flexGrow: 1,
1843
+ flexShrink: 1,
1844
+ flexDirection: 'column',
1845
+ overflow: 'scroll',
1846
+ },
1847
+ baseHorizontal: {
1848
+ flexGrow: 1,
1849
+ flexShrink: 1,
1850
+ flexDirection: 'row',
1851
+ overflow: 'scroll',
1852
+ },
1853
+ contentContainerHorizontal: {
1854
+ flexDirection: 'row',
1855
+ },
1856
+ });
1857
+
1858
+ type RefForwarder<TNativeInstance, TPublicInstance> = {
1859
+ getForwardingRef: (
1860
+ ?React.RefSetter<TPublicInstance>,
1861
+ ) => (TNativeInstance | null) => void,
1862
+ nativeInstance: TNativeInstance | null,
1863
+ publicInstance: TPublicInstance | null,
1864
+ };
1865
+
1866
+ /**
1867
+ * Helper function that should be replaced with `useCallback` and `useMergeRefs`
1868
+ * once `ScrollView` is reimplemented as a functional component.
1869
+ */
1870
+ function createRefForwarder<TNativeInstance, TPublicInstance>(
1871
+ mutator: TNativeInstance => TPublicInstance,
1872
+ ): RefForwarder<TNativeInstance, TPublicInstance> {
1873
+ const state: RefForwarder<TNativeInstance, TPublicInstance> = {
1874
+ getForwardingRef: memoize(forwardedRef => {
1875
+ return (nativeInstance: TNativeInstance | null): void => {
1876
+ const publicInstance =
1877
+ nativeInstance == null ? null : mutator(nativeInstance);
1878
+
1879
+ state.nativeInstance = nativeInstance;
1880
+ state.publicInstance = publicInstance;
1881
+
1882
+ if (forwardedRef != null) {
1883
+ if (typeof forwardedRef === 'function') {
1884
+ forwardedRef(publicInstance);
1885
+ } else {
1886
+ forwardedRef.current = publicInstance;
1887
+ }
1888
+ }
1889
+ };
1890
+ }),
1891
+ nativeInstance: null,
1892
+ publicInstance: null,
1893
+ };
1894
+
1895
+ return state;
1896
+ }
1897
+
1898
+ // TODO: After upgrading to React 19, remove `forwardRef` from this component.
1899
+ // NOTE: This wrapper component is necessary because `ScrollView` is a class
1900
+ // component and we need to map `ref` to a differently named prop. This can be
1901
+ // removed when `ScrollView` is a functional component.
1902
+ const Wrapper: component(
1903
+ ref: React.RefSetter<PublicScrollViewInstance>,
1904
+ ...props: Props
1905
+ ) = React.forwardRef(function Wrapper(
1906
+ props: Props,
1907
+ ref: ?React.RefSetter<PublicScrollViewInstance>,
1908
+ ): React.Node {
1909
+ return ref == null ? (
1910
+ <ScrollView {...props} />
1911
+ ) : (
1912
+ <ScrollView {...props} scrollViewRef={ref} />
1913
+ );
1914
+ });
1915
+ Wrapper.displayName = 'ScrollView';
1916
+ // $FlowExpectedError[prop-missing]
1917
+ Wrapper.Context = ScrollViewContext;
1918
+
1919
+ module.exports = ((Wrapper: $FlowFixMe): typeof Wrapper &
1920
+ ScrollViewComponentStatics);