-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReactScrollView.java
1244 lines (1071 loc) · 43.7 KB
/
ReactScrollView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.views.scroll;
import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_CENTER;
import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_DISABLED;
import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_END;
import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_START;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityEvent;
import android.widget.OverScroller;
import android.widget.ScrollView;
import androidx.annotation.Nullable;
import androidx.core.view.AccessibilityDelegateCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.R;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.uimanager.FabricViewStateManager;
import com.facebook.react.uimanager.MeasureSpecAssertions;
import com.facebook.react.uimanager.PointerEvents;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.ReactAccessibilityDelegate;
import com.facebook.react.uimanager.ReactClippingViewGroup;
import com.facebook.react.uimanager.ReactClippingViewGroupHelper;
import com.facebook.react.uimanager.ReactOverflowViewWithInset;
import com.facebook.react.uimanager.ViewProps;
import com.facebook.react.uimanager.events.NativeGestureUtil;
import com.facebook.react.views.scroll.ReactScrollViewHelper.HasFlingAnimator;
import com.facebook.react.views.scroll.ReactScrollViewHelper.HasScrollState;
import com.facebook.react.views.scroll.ReactScrollViewHelper.ReactScrollViewScrollState;
import com.facebook.react.views.view.ReactViewBackgroundManager;
import java.lang.reflect.Field;
import java.util.List;
/**
* A simple subclass of ScrollView that doesn't dispatch measure and layout to its children and has
* a scroll listener to send scroll events to JS.
*
* <p>ReactScrollView only supports vertical scrolling. For horizontal scrolling, use {@link
* ReactHorizontalScrollView}.
*/
public class ReactScrollView extends ScrollView
implements ReactClippingViewGroup,
ViewGroup.OnHierarchyChangeListener,
View.OnLayoutChangeListener,
FabricViewStateManager.HasFabricViewStateManager,
ReactOverflowViewWithInset,
HasScrollState,
HasFlingAnimator {
private static @Nullable Field sScrollerField;
private static boolean sTriedToGetScrollerField = false;
private static final int UNSET_CONTENT_OFFSET = -1;
private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper();
private final @Nullable OverScroller mScroller;
private final VelocityHelper mVelocityHelper = new VelocityHelper();
private final Rect mRect = new Rect(); // for reuse to avoid allocation
private final Rect mOverflowInset = new Rect();
private final Rect mTempRect = new Rect();
private boolean mActivelyScrolling;
private @Nullable Rect mClippingRect;
private @Nullable String mOverflow = ViewProps.HIDDEN;
private boolean mDragging;
private boolean mPagingEnabled = false;
private @Nullable Runnable mPostTouchRunnable;
private boolean mRemoveClippedSubviews;
private boolean mScrollEnabled = true;
private boolean mSendMomentumEvents;
private @Nullable FpsListener mFpsListener = null;
private @Nullable String mScrollPerfTag;
private @Nullable Drawable mEndBackground;
private int mEndFillColor = Color.TRANSPARENT;
private boolean mDisableIntervalMomentum = false;
private int mSnapInterval = 0;
private @Nullable List<Integer> mSnapOffsets;
private boolean mSnapToStart = true;
private boolean mSnapToEnd = true;
private int mSnapToAlignment = SNAP_ALIGNMENT_DISABLED;
private @Nullable View mContentView;
private ReactViewBackgroundManager mReactBackgroundManager;
private int pendingContentOffsetX = UNSET_CONTENT_OFFSET;
private int pendingContentOffsetY = UNSET_CONTENT_OFFSET;
private final FabricViewStateManager mFabricViewStateManager = new FabricViewStateManager();
private final ReactScrollViewScrollState mReactScrollViewScrollState =
new ReactScrollViewScrollState(ViewCompat.LAYOUT_DIRECTION_LTR);
private final ValueAnimator DEFAULT_FLING_ANIMATOR = ObjectAnimator.ofInt(this, "scrollY", 0, 0);
private PointerEvents mPointerEvents = PointerEvents.AUTO;
public ReactScrollView(Context context) {
this(context, null);
}
private View getContentView() {
View contentView = getChildAt(0);
return contentView;
}
public ReactScrollView(Context context, @Nullable FpsListener fpsListener) {
super(context);
mFpsListener = fpsListener;
mReactBackgroundManager = new ReactViewBackgroundManager(this);
mScroller = getOverScrollerFromParent();
setOnHierarchyChangeListener(this);
setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
ViewCompat.setAccessibilityDelegate(
this,
new AccessibilityDelegateCompat() {
@Override
public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(host, event);
event.setScrollable(mScrollEnabled);
final ReadableMap accessibilityCollectionInfo = (ReadableMap) host.getTag(R.id.accessibility_collection_info);
if (accessibilityCollectionInfo != null) {
event.setItemCount(accessibilityCollectionInfo.getInt("itemCount"));
View contentView = getContentView();
Integer firstVisibleIndex = null;
Integer lastVisibleIndex = null;
if (!(contentView instanceof ViewGroup)) {
return;
}
for(int index = 0; index < ((ViewGroup) contentView).getChildCount(); index++) {
View nextChild = ((ViewGroup) contentView).getChildAt(index);
boolean isVisible = isPartiallyScrolledInView(nextChild);
ReadableMap accessibilityCollectionItemInfo = (ReadableMap) nextChild.getTag(R.id.accessibility_collection_item_info);
if (!(nextChild instanceof ViewGroup)) {
return;
}
int childCount = ((ViewGroup) nextChild).getChildCount();
// If this child's accessibilityCollectionItemInfo is null, we'll check one more nested child.
// Happens when getItemLayout is not passed in FlatList which adds an additional View in the hierarchy.
if (childCount > 0 && accessibilityCollectionItemInfo == null) {
View nestedNextChild = ((ViewGroup) nextChild).getChildAt(0);
if (nestedNextChild != null) {
ReadableMap nestedChildAccessibilityInfo = (ReadableMap) nestedNextChild.getTag(R.id.accessibility_collection_item_info);
if (nestedChildAccessibilityInfo != null) {
accessibilityCollectionItemInfo = nestedChildAccessibilityInfo;
}
}
}
if (isVisible == true && accessibilityCollectionItemInfo != null) {
if(firstVisibleIndex == null) {
firstVisibleIndex = accessibilityCollectionItemInfo.getInt("itemIndex");
}
lastVisibleIndex = accessibilityCollectionItemInfo.getInt("itemIndex");;
}
if (firstVisibleIndex != null && lastVisibleIndex != null) {
event.setFromIndex(firstVisibleIndex);
event.setToIndex(lastVisibleIndex);
}
}
}
}
@Override
public void onInitializeAccessibilityNodeInfo(
View host, AccessibilityNodeInfoCompat info) {
super.onInitializeAccessibilityNodeInfo(host, info);
final ReactAccessibilityDelegate.AccessibilityRole accessibilityRole =
(ReactAccessibilityDelegate.AccessibilityRole) host.getTag(R.id.accessibility_role);
if (accessibilityRole != null) {
ReactAccessibilityDelegate.setRole(info, accessibilityRole, host.getContext());
}
final ReadableMap accessibilityCollectionInfo = (ReadableMap) host.getTag(R.id.accessibility_collection_info);
if (accessibilityCollectionInfo != null) {
int rowCount = accessibilityCollectionInfo.getInt("rowCount");
int columnCount = accessibilityCollectionInfo.getInt("columnCount");
boolean hierarchical = accessibilityCollectionInfo.getBoolean("hierarchical");
AccessibilityNodeInfoCompat.CollectionInfoCompat collectionInfoCompat = AccessibilityNodeInfoCompat.CollectionInfoCompat.obtain(rowCount, columnCount, hierarchical);
info.setCollectionInfo(collectionInfoCompat);
}
info.setScrollable(mScrollEnabled);
}
});
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
// Expose the testID prop as the resource-id name of the view. Black-box E2E/UI testing
// frameworks, which interact with the UI through the accessibility framework, do not have
// access to view tags. This allows developers/testers to avoid polluting the
// content-description with test identifiers.
final String testId = (String) this.getTag(R.id.react_test_id);
if (testId != null) {
info.setViewIdResourceName(testId);
}
}
@Nullable
private OverScroller getOverScrollerFromParent() {
OverScroller scroller;
if (!sTriedToGetScrollerField) {
sTriedToGetScrollerField = true;
try {
sScrollerField = ScrollView.class.getDeclaredField("mScroller");
sScrollerField.setAccessible(true);
} catch (NoSuchFieldException e) {
FLog.w(
ReactConstants.TAG,
"Failed to get mScroller field for ScrollView! "
+ "This app will exhibit the bounce-back scrolling bug :(");
}
}
if (sScrollerField != null) {
try {
Object scrollerValue = sScrollerField.get(this);
if (scrollerValue instanceof OverScroller) {
scroller = (OverScroller) scrollerValue;
} else {
FLog.w(
ReactConstants.TAG,
"Failed to cast mScroller field in ScrollView (probably due to OEM changes to AOSP)! "
+ "This app will exhibit the bounce-back scrolling bug :(");
scroller = null;
}
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to get mScroller from ScrollView!", e);
}
} else {
scroller = null;
}
return scroller;
}
public void setDisableIntervalMomentum(boolean disableIntervalMomentum) {
mDisableIntervalMomentum = disableIntervalMomentum;
}
public void setSendMomentumEvents(boolean sendMomentumEvents) {
mSendMomentumEvents = sendMomentumEvents;
}
public void setScrollPerfTag(@Nullable String scrollPerfTag) {
mScrollPerfTag = scrollPerfTag;
}
public void setScrollEnabled(boolean scrollEnabled) {
mScrollEnabled = scrollEnabled;
}
public void setPagingEnabled(boolean pagingEnabled) {
mPagingEnabled = pagingEnabled;
}
public void setDecelerationRate(float decelerationRate) {
getReactScrollViewScrollState().setDecelerationRate(decelerationRate);
if (mScroller != null) {
mScroller.setFriction(1.0f - decelerationRate);
}
}
public void setSnapInterval(int snapInterval) {
mSnapInterval = snapInterval;
}
public void setSnapOffsets(List<Integer> snapOffsets) {
mSnapOffsets = snapOffsets;
}
public void setSnapToStart(boolean snapToStart) {
mSnapToStart = snapToStart;
}
public void setSnapToEnd(boolean snapToEnd) {
mSnapToEnd = snapToEnd;
}
public void setSnapToAlignment(int snapToAlignment) {
mSnapToAlignment = snapToAlignment;
}
public void flashScrollIndicators() {
awakenScrollBars();
}
public void setOverflow(String overflow) {
mOverflow = overflow;
invalidate();
}
@Override
public @Nullable String getOverflow() {
return mOverflow;
}
@Override
public void setOverflowInset(int left, int top, int right, int bottom) {
mOverflowInset.set(left, top, right, bottom);
}
@Override
public Rect getOverflowInset() {
return mOverflowInset;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
MeasureSpecAssertions.assertExplicitMeasureSpec(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(
MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Call with the present values in order to re-layout if necessary
// If a "pending" content offset value has been set, we restore that value.
// Upon call to scrollTo, the "pending" values will be re-set.
int scrollToX =
pendingContentOffsetX != UNSET_CONTENT_OFFSET ? pendingContentOffsetX : getScrollX();
int scrollToY =
pendingContentOffsetY != UNSET_CONTENT_OFFSET ? pendingContentOffsetY : getScrollY();
scrollTo(scrollToX, scrollToY);
ReactScrollViewHelper.emitLayoutEvent(this);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mRemoveClippedSubviews) {
updateClippingRect();
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mRemoveClippedSubviews) {
updateClippingRect();
}
}
/**
* Since ReactScrollView handles layout changes on JS side, it does not call super.onlayout due to
* which mIsLayoutDirty flag in ScrollView remains true and prevents scrolling to child when
* requestChildFocus is called. Overriding this method and scrolling to child without checking any
* layout dirty flag. This will fix focus navigation issue for KeyEvents which are not handled by
* ScrollView, for example: KEYCODE_TAB.
*/
@Override
public void requestChildFocus(View child, View focused) {
if (focused != null) {
scrollToChild(focused);
}
super.requestChildFocus(child, focused);
}
private int getScrollDelta(View descendent) {
descendent.getDrawingRect(mTempRect);
offsetDescendantRectToMyCoords(descendent, mTempRect);
return computeScrollDeltaToGetChildRectOnScreen(mTempRect);
}
/** Returns whether the given descendent is partially scrolled in view */
private boolean isPartiallyScrolledInView(View descendent) {
int scrollDelta = getScrollDelta(descendent);
descendent.getDrawingRect(mTempRect);
return scrollDelta != 0 && Math.abs(scrollDelta) < mTempRect.width();
}
private void scrollToChild(View child) {
Rect tempRect = new Rect();
child.getDrawingRect(tempRect);
/* Offset from child's local coordinates to ScrollView coordinates */
offsetDescendantRectToMyCoords(child, tempRect);
int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(tempRect);
if (scrollDelta != 0) {
scrollBy(0, scrollDelta);
}
}
@Override
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
super.onScrollChanged(x, y, oldX, oldY);
mActivelyScrolling = true;
if (mOnScrollDispatchHelper.onScrollChanged(x, y)) {
if (mRemoveClippedSubviews) {
updateClippingRect();
}
ReactScrollViewHelper.updateStateOnScrollChanged(
this,
mOnScrollDispatchHelper.getXFlingVelocity(),
mOnScrollDispatchHelper.getYFlingVelocity());
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!mScrollEnabled) {
return false;
}
// We intercept the touch event if the children are not supposed to receive it.
if (!PointerEvents.canChildrenBeTouchTarget(mPointerEvents)) {
return true;
}
try {
if (super.onInterceptTouchEvent(ev)) {
NativeGestureUtil.notifyNativeGestureStarted(this, ev);
ReactScrollViewHelper.emitScrollBeginDragEvent(this);
mDragging = true;
enableFpsListener();
getFlingAnimator().cancel();
return true;
}
} catch (IllegalArgumentException e) {
// Log and ignore the error. This seems to be a bug in the android SDK and
// this is the commonly accepted workaround.
// https://tinyurl.com/mw6qkod (Stack Overflow)
FLog.w(ReactConstants.TAG, "Error intercepting touch event.", e);
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mScrollEnabled) {
return false;
}
// We do not accept the touch event if this view is not supposed to receive it.
if (!PointerEvents.canBeTouchTarget(mPointerEvents)) {
return false;
}
mVelocityHelper.calculateVelocity(ev);
int action = ev.getAction() & MotionEvent.ACTION_MASK;
if (action == MotionEvent.ACTION_UP && mDragging) {
ReactScrollViewHelper.updateFabricScrollState(this);
float velocityX = mVelocityHelper.getXVelocity();
float velocityY = mVelocityHelper.getYVelocity();
ReactScrollViewHelper.emitScrollEndDragEvent(this, velocityX, velocityY);
mDragging = false;
// After the touch finishes, we may need to do some scrolling afterwards either as a result
// of a fling or because we need to page align the content
handlePostTouchScrolling(Math.round(velocityX), Math.round(velocityY));
}
return super.onTouchEvent(ev);
}
@Override
public boolean executeKeyEvent(KeyEvent event) {
int eventKeyCode = event.getKeyCode();
if (!mScrollEnabled
&& (eventKeyCode == KeyEvent.KEYCODE_DPAD_UP
|| eventKeyCode == KeyEvent.KEYCODE_DPAD_DOWN)) {
return false;
}
return super.executeKeyEvent(event);
}
@Override
public void setRemoveClippedSubviews(boolean removeClippedSubviews) {
if (removeClippedSubviews && mClippingRect == null) {
mClippingRect = new Rect();
}
mRemoveClippedSubviews = removeClippedSubviews;
updateClippingRect();
}
@Override
public boolean getRemoveClippedSubviews() {
return mRemoveClippedSubviews;
}
@Override
public void updateClippingRect() {
if (!mRemoveClippedSubviews) {
return;
}
Assertions.assertNotNull(mClippingRect);
ReactClippingViewGroupHelper.calculateClippingRect(this, mClippingRect);
View contentView = getChildAt(0);
if (contentView instanceof ReactClippingViewGroup) {
((ReactClippingViewGroup) contentView).updateClippingRect();
}
}
@Override
public void getClippingRect(Rect outClippingRect) {
outClippingRect.set(Assertions.assertNotNull(mClippingRect));
}
@Override
public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
return super.getChildVisibleRect(child, r, offset);
}
@Override
public void fling(int velocityY) {
// Workaround.
// On Android P if a ScrollView is inverted, we will get a wrong sign for
// velocityY (see https://issuetracker.google.com/issues/112385925).
// At the same time, mOnScrollDispatchHelper tracks the correct velocity direction.
//
// Hence, we can use the absolute value from whatever the OS gives
// us and use the sign of what mOnScrollDispatchHelper has tracked.
float signum = Math.signum(mOnScrollDispatchHelper.getYFlingVelocity());
if (signum == 0) {
signum = Math.signum(velocityY);
}
final int correctedVelocityY = (int) (Math.abs(velocityY) * signum);
if (mPagingEnabled) {
flingAndSnap(correctedVelocityY);
} else if (mScroller != null) {
// FB SCROLLVIEW CHANGE
// We provide our own version of fling that uses a different call to the standard OverScroller
// which takes into account the possibility of adding new content while the ScrollView is
// animating. Because we give essentially no max Y for the fling, the fling will continue as
// long
// as there is content. See #onOverScrolled() to see the second part of this change which
// properly
// aborts the scroller animation when we get to the bottom of the ScrollView content.
int scrollWindowHeight = getHeight() - getPaddingBottom() - getPaddingTop();
mScroller.fling(
getScrollX(), // startX
getScrollY(), // startY
0, // velocityX
correctedVelocityY, // velocityY
0, // minX
0, // maxX
0, // minY
Integer.MAX_VALUE, // maxY
0, // overX
scrollWindowHeight / 2 // overY
);
ViewCompat.postInvalidateOnAnimation(this);
// END FB SCROLLVIEW CHANGE
} else {
super.fling(correctedVelocityY);
}
handlePostTouchScrolling(0, correctedVelocityY);
}
private void enableFpsListener() {
if (isScrollPerfLoggingEnabled()) {
Assertions.assertNotNull(mFpsListener);
Assertions.assertNotNull(mScrollPerfTag);
mFpsListener.enable(mScrollPerfTag);
}
}
private void disableFpsListener() {
if (isScrollPerfLoggingEnabled()) {
Assertions.assertNotNull(mFpsListener);
Assertions.assertNotNull(mScrollPerfTag);
mFpsListener.disable(mScrollPerfTag);
}
}
private boolean isScrollPerfLoggingEnabled() {
return mFpsListener != null && mScrollPerfTag != null && !mScrollPerfTag.isEmpty();
}
private int getMaxScrollY() {
int contentHeight = mContentView.getHeight();
int viewportHeight = getHeight() - getPaddingBottom() - getPaddingTop();
return Math.max(0, contentHeight - viewportHeight);
}
@Override
public void draw(Canvas canvas) {
if (mEndFillColor != Color.TRANSPARENT) {
final View content = getChildAt(0);
if (mEndBackground != null && content != null && content.getBottom() < getHeight()) {
mEndBackground.setBounds(0, content.getBottom(), getWidth(), getHeight());
mEndBackground.draw(canvas);
}
}
getDrawingRect(mRect);
switch (mOverflow) {
case ViewProps.VISIBLE:
break;
default:
canvas.clipRect(mRect);
break;
}
super.draw(canvas);
}
/**
* This handles any sort of scrolling that may occur after a touch is finished. This may be
* momentum scrolling (fling) or because you have pagingEnabled on the scroll view. Because we
* don't get any events from Android about this lifecycle, we do all our detection by creating a
* runnable that checks if we scrolled in the last frame and if so assumes we are still scrolling.
*/
private void handlePostTouchScrolling(int velocityX, int velocityY) {
// Check if we are already handling this which may occur if this is called by both the touch up
// and a fling call
if (mPostTouchRunnable != null) {
return;
}
if (mSendMomentumEvents) {
enableFpsListener();
ReactScrollViewHelper.emitScrollMomentumBeginEvent(this, velocityX, velocityY);
}
mActivelyScrolling = false;
mPostTouchRunnable =
new Runnable() {
private boolean mSnappingToPage = false;
private boolean mRunning = true;
private int mStableFrames = 0;
@Override
public void run() {
if (mActivelyScrolling) {
// We are still scrolling.
mActivelyScrolling = false;
mStableFrames = 0;
mRunning = true;
} else {
// There has not been a scroll update since the last time this Runnable executed.
ReactScrollViewHelper.updateFabricScrollState(ReactScrollView.this);
// We keep checking for updates until the ScrollView has "stabilized" and hasn't
// scrolled for N consecutive frames. This number is arbitrary: big enough to catch
// a number of race conditions, but small enough to not cause perf regressions, etc.
// In anecdotal testing, it seemed like a decent number.
// Without this check, sometimes this Runnable stops executing too soon - it will
// fire before the first scroll event of an animated scroll/fling, and stop
// immediately.
mStableFrames++;
mRunning = (mStableFrames < 3);
if (mPagingEnabled && !mSnappingToPage) {
// Only if we have pagingEnabled and we have not snapped to the page do we
// need to continue checking for the scroll. And we cause that scroll by asking for
// it
mSnappingToPage = true;
flingAndSnap(0);
ViewCompat.postOnAnimationDelayed(
ReactScrollView.this, this, ReactScrollViewHelper.MOMENTUM_DELAY);
} else {
if (mSendMomentumEvents) {
ReactScrollViewHelper.emitScrollMomentumEndEvent(ReactScrollView.this);
}
disableFpsListener();
}
}
// We are still scrolling so we just post to check again a frame later
if (mRunning) {
ViewCompat.postOnAnimationDelayed(
ReactScrollView.this, this, ReactScrollViewHelper.MOMENTUM_DELAY);
} else {
mPostTouchRunnable = null;
}
}
};
ViewCompat.postOnAnimationDelayed(
this, mPostTouchRunnable, ReactScrollViewHelper.MOMENTUM_DELAY);
}
private int predictFinalScrollPosition(int velocityY) {
// predict where a fling would end up so we can scroll to the nearest snap offset
// TODO(T106335409): Existing prediction still uses overscroller. Consider change this to use
// fling animator instead.
return getFlingAnimator() == DEFAULT_FLING_ANIMATOR
? ReactScrollViewHelper.predictFinalScrollPosition(this, 0, velocityY, 0, getMaxScrollY()).y
: ReactScrollViewHelper.getNextFlingStartValue(
this,
getScrollY(),
getReactScrollViewScrollState().getFinalAnimatedPositionScroll().y,
velocityY)
+ getFlingExtrapolatedDistance(velocityY);
}
/**
* This will smooth scroll us to the nearest snap offset point It currently just looks at where
* the content is and slides to the nearest point. It is intended to be run after we are done
* scrolling, and handling any momentum scrolling.
*/
private void smoothScrollAndSnap(int velocity) {
double interval = (double) getSnapInterval();
double currentOffset =
(double)
(ReactScrollViewHelper.getNextFlingStartValue(
this,
getScrollY(),
getReactScrollViewScrollState().getFinalAnimatedPositionScroll().y,
velocity));
double targetOffset = (double) predictFinalScrollPosition(velocity);
int previousPage = (int) Math.floor(currentOffset / interval);
int nextPage = (int) Math.ceil(currentOffset / interval);
int currentPage = (int) Math.round(currentOffset / interval);
int targetPage = (int) Math.round(targetOffset / interval);
if (velocity > 0 && nextPage == previousPage) {
nextPage++;
} else if (velocity < 0 && previousPage == nextPage) {
previousPage--;
}
if (
// if scrolling towards next page
velocity > 0
&&
// and the middle of the page hasn't been crossed already
currentPage < nextPage
&&
// and it would have been crossed after flinging
targetPage > previousPage) {
currentPage = nextPage;
} else if (
// if scrolling towards previous page
velocity < 0
&&
// and the middle of the page hasn't been crossed already
currentPage > previousPage
&&
// and it would have been crossed after flinging
targetPage < nextPage) {
currentPage = previousPage;
}
targetOffset = currentPage * interval;
if (targetOffset != currentOffset) {
mActivelyScrolling = true;
reactSmoothScrollTo(getScrollX(), (int) targetOffset);
}
}
private void flingAndSnap(int velocityY) {
if (getChildCount() <= 0) {
return;
}
// pagingEnabled only allows snapping one interval at a time
if (mSnapInterval == 0 && mSnapOffsets == null && mSnapToAlignment == SNAP_ALIGNMENT_DISABLED) {
smoothScrollAndSnap(velocityY);
return;
}
boolean hasCustomizedFlingAnimator = getFlingAnimator() != DEFAULT_FLING_ANIMATOR;
int maximumOffset = getMaxScrollY();
int targetOffset = predictFinalScrollPosition(velocityY);
if (mDisableIntervalMomentum) {
targetOffset = getScrollY();
}
int smallerOffset = 0;
int largerOffset = maximumOffset;
int firstOffset = 0;
int lastOffset = maximumOffset;
int height = getHeight() - getPaddingBottom() - getPaddingTop();
// get the nearest snap points to the target offset
if (mSnapOffsets != null) {
firstOffset = mSnapOffsets.get(0);
lastOffset = mSnapOffsets.get(mSnapOffsets.size() - 1);
for (int i = 0; i < mSnapOffsets.size(); i++) {
int offset = mSnapOffsets.get(i);
if (offset <= targetOffset) {
if (targetOffset - offset < targetOffset - smallerOffset) {
smallerOffset = offset;
}
}
if (offset >= targetOffset) {
if (offset - targetOffset < largerOffset - targetOffset) {
largerOffset = offset;
}
}
}
} else if (mSnapToAlignment != SNAP_ALIGNMENT_DISABLED) {
if (mSnapInterval > 0) {
double ratio = (double) targetOffset / mSnapInterval;
smallerOffset =
Math.max(
getItemStartOffset(
mSnapToAlignment,
(int) (Math.floor(ratio) * mSnapInterval),
mSnapInterval,
height),
0);
largerOffset =
Math.min(
getItemStartOffset(
mSnapToAlignment,
(int) (Math.ceil(ratio) * mSnapInterval),
mSnapInterval,
height),
maximumOffset);
} else {
ViewGroup contentView = (ViewGroup) getContentView();
int smallerChildOffset = largerOffset;
int largerChildOffset = smallerOffset;
for (int i = 0; i < contentView.getChildCount(); i++) {
View item = contentView.getChildAt(i);
int itemStartOffset;
switch (mSnapToAlignment) {
case SNAP_ALIGNMENT_CENTER:
itemStartOffset = item.getTop() - (height - item.getHeight()) / 2;
break;
case SNAP_ALIGNMENT_START:
itemStartOffset = item.getTop();
break;
case SNAP_ALIGNMENT_END:
itemStartOffset = item.getTop() - (height - item.getHeight());
break;
default:
throw new IllegalStateException("Invalid SnapToAlignment value: " + mSnapToAlignment);
}
if (itemStartOffset <= targetOffset) {
if (targetOffset - itemStartOffset < targetOffset - smallerOffset) {
smallerOffset = itemStartOffset;
}
}
if (itemStartOffset >= targetOffset) {
if (itemStartOffset - targetOffset < largerOffset - targetOffset) {
largerOffset = itemStartOffset;
}
}
smallerChildOffset = Math.min(smallerChildOffset, itemStartOffset);
largerChildOffset = Math.max(largerChildOffset, itemStartOffset);
}
// For Recycler ViewGroup, the maximumOffset can be much larger than the total heights of
// items in the layout. In this case snapping is not possible beyond the currently rendered
// children.
smallerOffset = Math.max(smallerOffset, smallerChildOffset);
largerOffset = Math.min(largerOffset, largerChildOffset);
}
} else {
double interval = (double) getSnapInterval();
double ratio = (double) targetOffset / interval;
smallerOffset = (int) (Math.floor(ratio) * interval);
largerOffset = Math.min((int) (Math.ceil(ratio) * interval), maximumOffset);
}
// Calculate the nearest offset
int nearestOffset =
Math.abs(targetOffset - smallerOffset) < Math.abs(largerOffset - targetOffset)
? smallerOffset
: largerOffset;
// if scrolling after the last snap offset and snapping to the
// end of the list is disabled, then we allow free scrolling
if (!mSnapToEnd && targetOffset >= lastOffset) {
if (getScrollY() >= lastOffset) {
// free scrolling
} else {
// snap to end
targetOffset = lastOffset;
}
} else if (!mSnapToStart && targetOffset <= firstOffset) {
if (getScrollY() <= firstOffset) {
// free scrolling
} else {
// snap to beginning
targetOffset = firstOffset;
}
} else if (velocityY > 0) {
if (!hasCustomizedFlingAnimator) {
// The default animator requires boost on initial velocity as when snapping velocity can
// feel sluggish for slow swipes
velocityY += (int) ((largerOffset - targetOffset) * 10.0);
}
targetOffset = largerOffset;
} else if (velocityY < 0) {
if (!hasCustomizedFlingAnimator) {
// The default animator requires boost on initial velocity as when snapping velocity can
// feel sluggish for slow swipes
velocityY -= (int) ((targetOffset - smallerOffset) * 10.0);
}
targetOffset = smallerOffset;
} else {
targetOffset = nearestOffset;
}
// Make sure the new offset isn't out of bounds
targetOffset = Math.min(Math.max(0, targetOffset), maximumOffset);
if (hasCustomizedFlingAnimator || mScroller == null) {
reactSmoothScrollTo(getScrollX(), targetOffset);
} else {
// smoothScrollTo will always scroll over 250ms which is often *waaay*
// too short and will cause the scrolling to feel almost instant
// try to manually interact with OverScroller instead
// if velocity is 0 however, fling() won't work, so we want to use smoothScrollTo
mActivelyScrolling = true;
mScroller.fling(
getScrollX(), // startX
getScrollY(), // startY
// velocity = 0 doesn't work with fling() so we pretend there's a reasonable
// initial velocity going on when a touch is released without any movement
0, // velocityX
velocityY != 0 ? velocityY : targetOffset - getScrollY(), // velocityY
0, // minX
0, // maxX
// setting both minY and maxY to the same value will guarantee that we scroll to it
// but using the standard fling-style easing rather than smoothScrollTo's 250ms animation
targetOffset, // minY
targetOffset, // maxY
0, // overX
// we only want to allow overscrolling if the final offset is at the very edge of the view
(targetOffset == 0 || targetOffset == maximumOffset) ? height / 2 : 0 // overY
);
postInvalidateOnAnimation();
}
}
private int getItemStartOffset(
int snapToAlignment, int itemStartPosition, int itemHeight, int viewPortHeight) {
int itemStartOffset;
switch (snapToAlignment) {
case SNAP_ALIGNMENT_CENTER:
itemStartOffset = itemStartPosition - (viewPortHeight - itemHeight) / 2;
break;
case SNAP_ALIGNMENT_START:
itemStartOffset = itemStartPosition;
break;
case SNAP_ALIGNMENT_END:
itemStartOffset = itemStartPosition - (viewPortHeight - itemHeight);