react-native-windows 0.76.11 → 0.76.12

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