@office-iss/react-native-win32 0.0.0-canary.245 → 0.0.0-canary.247

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