forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathRCTScrollViewComponentView.mm
More file actions
1253 lines (1055 loc) · 44.7 KB
/
RCTScrollViewComponentView.mm
File metadata and controls
1253 lines (1055 loc) · 44.7 KB
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.
*/
#import "RCTScrollViewComponentView.h"
#import <React/RCTAssert.h>
#import <React/RCTBridge+Private.h>
#import <React/RCTConstants.h>
#import <React/RCTScrollEvent.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
#import <react/renderer/components/scrollview/RCTComponentViewHelpers.h>
#import <react/renderer/components/scrollview/ScrollViewComponentDescriptor.h>
#import <react/renderer/components/scrollview/ScrollViewEventEmitter.h>
#import <react/renderer/components/scrollview/ScrollViewProps.h>
#import <react/renderer/components/scrollview/ScrollViewState.h>
#import <react/renderer/components/scrollview/conversions.h>
#import "RCTConversions.h"
#import "RCTCustomPullToRefreshViewProtocol.h"
#import "RCTEnhancedScrollView.h"
#import "RCTFabricComponentsPlugins.h"
using namespace facebook::react;
static NSString *kOnScrollEvent = @"onScroll";
static NSString *kOnScrollEndEvent = @"onScrollEnded";
static const CGFloat kClippingLeeway = 44.0;
#if TARGET_OS_IOS // [macOS] [visionOS]
static UIScrollViewKeyboardDismissMode RCTUIKeyboardDismissModeFromProps(const ScrollViewProps &props)
{
switch (props.keyboardDismissMode) {
case ScrollViewKeyboardDismissMode::None:
return UIScrollViewKeyboardDismissModeNone;
case ScrollViewKeyboardDismissMode::OnDrag:
return UIScrollViewKeyboardDismissModeOnDrag;
case ScrollViewKeyboardDismissMode::Interactive:
return UIScrollViewKeyboardDismissModeInteractive;
}
}
#endif // [macOS] [visionOS]
#if !TARGET_OS_OSX // [macOS
static UIScrollViewIndicatorStyle RCTUIScrollViewIndicatorStyleFromProps(const ScrollViewProps &props)
{
switch (props.indicatorStyle) {
case ScrollViewIndicatorStyle::Default:
return UIScrollViewIndicatorStyleDefault;
case ScrollViewIndicatorStyle::Black:
return UIScrollViewIndicatorStyleBlack;
case ScrollViewIndicatorStyle::White:
return UIScrollViewIndicatorStyleWhite;
}
}
#endif // [macOS]
// Once Fabric implements proper NativeAnimationDriver, this should be removed.
// This is just a workaround to allow animations based on onScroll event.
// This is only used to animate sticky headers in ScrollViews, and only the contentOffset and tag is used.
// TODO: T116850910 [Fabric][iOS] Make Fabric not use legacy RCTEventDispatcher for native-driven AnimatedEvents
static void
RCTSendScrollEventForNativeAnimations_DEPRECATED(RCTUIScrollView *scrollView, NSInteger tag, NSString *eventName) // [macOS]
{
if (ReactNativeFeatureFlags::cxxNativeAnimatedEnabled()) {
return;
}
static uint16_t coalescingKey = 0;
RCTScrollEvent *scrollEvent = [[RCTScrollEvent alloc] initWithEventName:eventName
reactTag:[NSNumber numberWithInt:tag]
scrollViewContentOffset:scrollView.contentOffset
scrollViewContentInset:scrollView.contentInset
scrollViewContentSize:scrollView.contentSize
scrollViewFrame:scrollView.frame
scrollViewZoomScale:scrollView.zoomScale
userData:nil
coalescingKey:coalescingKey];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:scrollEvent, @"event", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:RCTNotifyEventDispatcherObserversOfEvent_DEPRECATED
object:nil
userInfo:userInfo];
}
@interface RCTScrollViewComponentView () <
#if !TARGET_OS_OSX // [macOS]
UIScrollViewDelegate,
#endif // [macOS]
RCTScrollViewProtocol,
RCTScrollableProtocol,
RCTEnhancedScrollViewOverridingDelegate>
- (void)_preserveContentOffsetIfNeededWithBlock:(void (^)())block;
- (void)_remountChildrenIfNeeded;
- (void)_remountChildren;
- (void)_forceDispatchNextScrollEvent;
- (void)_handleScrollEndIfNeeded;
- (void)_handleFinishedScrolling:(RCTUIScrollView *)scrollView;
- (void)_prepareForMaintainVisibleScrollPosition;
- (void)_adjustForMaintainVisibleContentPosition;
@end
@implementation RCTScrollViewComponentView {
ScrollViewShadowNode::ConcreteState::Shared _state;
CGSize _contentSize;
NSTimeInterval _lastScrollEventDispatchTime;
NSTimeInterval _scrollEventThrottle;
// Flag indicating whether the scrolling that is currently happening
// is triggered by user or not.
// This helps to only update state from `scrollViewDidScroll` in case
// some other part of the system scrolls scroll view.
BOOL _isUserTriggeredScrolling;
BOOL _shouldUpdateContentInsetAdjustmentBehavior;
BOOL _automaticallyAdjustKeyboardInsets;
CGPoint _contentOffsetWhenClipped;
__weak RCTUIView *_contentView; // [macOS]
CGRect _prevFirstVisibleFrame;
__weak RCTPlatformView *_firstVisibleView; // [macOS]
CGFloat _endDraggingSensitivityMultiplier;
}
+ (RCTScrollViewComponentView *_Nullable)findScrollViewComponentViewForView:(RCTPlatformView *)view // [macOS]
{
do {
view = (RCTPlatformView *)view.superview; // [macOS]
} while (view != nil && ![view isKindOfClass:[RCTScrollViewComponentView class]]);
return (RCTScrollViewComponentView *)view;
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
_props = ScrollViewShadowNode::defaultSharedProps();
_scrollView = [[RCTEnhancedScrollView alloc] initWithFrame:self.bounds];
_scrollView.clipsToBounds = _props->getClipsContentToBounds();
_scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
#if !TARGET_OS_OSX // [macOS]
_scrollView.delaysContentTouches = NO;
#endif // [macOS]
((RCTEnhancedScrollView *)_scrollView).overridingDelegate = self;
_isUserTriggeredScrolling = NO;
_shouldUpdateContentInsetAdjustmentBehavior = YES;
_automaticallyAdjustKeyboardInsets = NO;
[self addSubview:_scrollView];
_containerView = [[RCTUIView alloc] initWithFrame:CGRectZero]; // [macOS]
#if !TARGET_OS_OSX // [macOS]
[_scrollView addSubview:_containerView];
#else // [macOS
// Do NOT set autoresizingMask on the documentView. AppKit's autoresizing
// corrupts the documentView frame during tile/resize (adding the clip view's
// size delta to the container, inflating it beyond the actual content size).
// React manages the documentView frame directly via updateState:.
[_scrollView setDocumentView:_containerView];
#endif // macOS]
#if !TARGET_OS_OSX // [macOS]
[self.scrollViewDelegateSplitter addDelegate:self];
#endif // [macOS]
#if TARGET_OS_IOS
[self _registerKeyboardListener];
#endif
_scrollEventThrottle = 0;
_endDraggingSensitivityMultiplier = 1;
}
return self;
}
- (void)dealloc
{
// Removing all delegates from the splitter nils the actual delegate which prevents a crash on UIScrollView
// deallocation.
#if !TARGET_OS_OSX // [macOS]
[self.scrollViewDelegateSplitter removeAllDelegates];
#endif // [macOS]
}
#if TARGET_OS_OSX // [macOS
+ (void)initialize
{
if (self == [RCTScrollViewComponentView class]) {
// Pre-warm the cached scrollbar width at class load time, before any
// layout occurs. This ensures the first Yoga layout pass already knows
// the correct scrollbar dimensions — no state round-trip required.
[self _updateCachedScrollbarWidth];
// Observe system scrollbar style changes so we can update the cached
// value and trigger re-layout when the preference changes.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(_systemScrollerStyleDidChange:)
name:NSPreferredScrollerStyleDidChangeNotification
object:nil];
}
}
+ (void)_updateCachedScrollbarWidth
{
CGFloat width = 0;
if ([NSScroller preferredScrollerStyle] == NSScrollerStyleLegacy) {
width = [NSScroller scrollerWidthForControlSize:NSControlSizeRegular
scrollerStyle:NSScrollerStyleLegacy];
}
ScrollViewShadowNode::setSystemScrollbarWidth(static_cast<Float>(width));
}
+ (void)_systemScrollerStyleDidChange:(NSNotification *)notification
{
[self _updateCachedScrollbarWidth];
}
- (void)_preferredScrollerStyleDidChange:(NSNotification *)notification
{
// Update the native scroll view's scroller style and re-tile so scrollers
// are properly created/removed.
_scrollView.scrollerStyle = [NSScroller preferredScrollerStyle];
[_scrollView tile];
// Force a state update to trigger shadow tree re-clone. The cloned
// ScrollViewShadowNode will read the updated cached scrollbar width
// in applyScrollbarPadding() and re-layout with correct padding.
if (_state) {
_state->updateState(
[](const ScrollViewShadowNode::ConcreteState::Data &oldData)
-> ScrollViewShadowNode::ConcreteState::SharedData {
auto newData = oldData;
// Reset contentBoundingRect to force a state difference
newData.contentBoundingRect = {};
return std::make_shared<const ScrollViewShadowNode::ConcreteState::Data>(newData);
});
}
}
#endif // macOS]
#if TARGET_OS_IOS
- (void)_registerKeyboardListener
{
// According to Apple docs, we don't need to explicitly unregister the observer, it's done automatically.
// See the Apple documentation:
// https://developer.apple.com/documentation/foundation/nsnotificationcenter/1413994-removeobserver?language=objc
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_keyboardWillChangeFrame:)
name:UIKeyboardWillChangeFrameNotification
object:nil];
}
- (void)_keyboardWillChangeFrame:(NSNotification *)notification
{
if (!_automaticallyAdjustKeyboardInsets) {
return;
}
BOOL isHorizontal = _scrollView.contentSize.width > self.frame.size.width;
if (isHorizontal) {
return;
}
bool isInverted = [self isInverted];
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve =
(UIViewAnimationCurve)[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
CGRect keyboardEndFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect keyboardBeginFrame = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGPoint absoluteViewOrigin = [self convertPoint:self.bounds.origin toView:nil];
CGFloat scrollViewLowerY = isInverted ? absoluteViewOrigin.y : absoluteViewOrigin.y + self.bounds.size.height;
UIEdgeInsets newEdgeInsets = _scrollView.contentInset;
CGFloat inset = MAX(scrollViewLowerY - keyboardEndFrame.origin.y, 0);
const auto &props = static_cast<const ScrollViewProps &>(*_props);
if (isInverted) {
newEdgeInsets.top = MAX(inset, props.contentInset.top);
} else {
newEdgeInsets.bottom = MAX(inset, props.contentInset.bottom);
}
CGPoint newContentOffset = _scrollView.contentOffset;
self.firstResponderFocus = CGRectNull;
CGFloat contentDiff = 0;
if ([[UIApplication sharedApplication] sendAction:@selector(reactUpdateResponderOffsetForScrollView:)
to:nil
from:self
forEvent:nil]) {
if (CGRectEqualToRect(_firstResponderFocus, CGRectNull)) {
UIView *inputAccessoryView = _firstResponderViewOutsideScrollView.inputAccessoryView;
if (inputAccessoryView) {
// Text input view is within the inputAccessoryView.
contentDiff = keyboardEndFrame.origin.y - keyboardBeginFrame.origin.y;
}
} else {
// Inner text field focused
CGFloat focusEnd = CGRectGetMaxY(self.firstResponderFocus);
if (focusEnd > keyboardEndFrame.origin.y) {
// Text field active region is below visible area with keyboard - update diff to bring into view
contentDiff = keyboardEndFrame.origin.y - focusEnd;
}
}
}
if (isInverted) {
newContentOffset.y += contentDiff;
} else {
newContentOffset.y -= contentDiff;
}
if (@available(iOS 14.0, *)) {
// On iOS when Prefer Cross-Fade Transitions is enabled, the keyboard position
// & height is reported differently (0 instead of Y position value matching height of frame)
// Fixes similar issue we saw with https://github.com/facebook/react-native/pull/34503
if (UIAccessibilityPrefersCrossFadeTransitions() && keyboardEndFrame.size.height == 0) {
newContentOffset.y = 0;
newEdgeInsets.bottom = 0;
}
}
[UIView animateWithDuration:duration
delay:0.0
options:animationOptionsWithCurve(curve)
animations:^{
self->_scrollView.contentInset = newEdgeInsets;
self->_scrollView.verticalScrollIndicatorInsets = newEdgeInsets;
[self scrollTo:newContentOffset.x y:newContentOffset.y animated:NO];
}
completion:nil];
}
static inline UIViewAnimationOptions animationOptionsWithCurve(UIViewAnimationCurve curve)
{
// UIViewAnimationCurve #7 is used for keyboard and therefore private - so we can't use switch/case here.
// source: https://stackoverflow.com/a/7327374/5281431
RCTAssert(
UIViewAnimationCurveLinear << 16 == UIViewAnimationOptionCurveLinear,
@"Unexpected implementation of UIViewAnimationCurve");
return curve << 16;
}
#endif
#if TARGET_OS_OSX // [macOS
- (void)setContentInset:(UIEdgeInsets)contentInset
{
if (UIEdgeInsetsEqualToEdgeInsets(contentInset, _contentInset)) {
return;
}
_contentInset = contentInset;
_scrollView.contentInset = contentInset;
_scrollView.scrollIndicatorInsets = contentInset;
}
#endif // macOS]
- (RCTGenericDelegateSplitter<id<RCTUIScrollViewDelegate>> *)scrollViewDelegateSplitter
{
return ((RCTEnhancedScrollView *)_scrollView).delegateSplitter;
}
#pragma mark - RCTMountingTransactionObserving
- (void)mountingTransactionWillMount:(const facebook::react::MountingTransaction &)transaction
withSurfaceTelemetry:(const facebook::react::SurfaceTelemetry &)surfaceTelemetry
{
[self _prepareForMaintainVisibleScrollPosition];
}
- (void)mountingTransactionDidMount:(const MountingTransaction &)transaction
withSurfaceTelemetry:(const facebook::react::SurfaceTelemetry &)surfaceTelemetry
{
[self _remountChildren];
[self _adjustForMaintainVisibleContentPosition];
}
#pragma mark - RCTComponentViewProtocol
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<ScrollViewComponentDescriptor>();
}
- (void)updateLayoutMetrics:(const LayoutMetrics &)layoutMetrics
oldLayoutMetrics:(const LayoutMetrics &)oldLayoutMetrics
{
[super updateLayoutMetrics:layoutMetrics oldLayoutMetrics:oldLayoutMetrics];
if (layoutMetrics.layoutDirection != oldLayoutMetrics.layoutDirection) {
CGAffineTransform transform = (layoutMetrics.layoutDirection == LayoutDirection::LeftToRight)
? CGAffineTransformIdentity
: CGAffineTransformMakeScale(-1, 1);
_containerView.transform = transform;
#if !TARGET_OS_OSX // [macOS]
_scrollView.transform = transform;
#endif // [macOS]
}
}
- (bool)isInverted
{
// Look into the entry at position 2,2 to check if scaleY is applied
return self.layer.transform.m22 == -1;
}
- (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &)oldProps
{
const auto &oldScrollViewProps = static_cast<const ScrollViewProps &>(*_props);
const auto &newScrollViewProps = static_cast<const ScrollViewProps &>(*props);
#define REMAP_PROP(reactName, localName, target) \
if (oldScrollViewProps.reactName != newScrollViewProps.reactName) { \
target.localName = newScrollViewProps.reactName; \
}
#define REMAP_VIEW_PROP(reactName, localName) REMAP_PROP(reactName, localName, self)
#define MAP_VIEW_PROP(name) REMAP_VIEW_PROP(name, name)
#define REMAP_SCROLL_VIEW_PROP(reactName, localName) \
REMAP_PROP(reactName, localName, ((RCTEnhancedScrollView *)_scrollView))
#define MAP_SCROLL_VIEW_PROP(name) REMAP_SCROLL_VIEW_PROP(name, name)
// FIXME: Commented props are not supported yet.
MAP_SCROLL_VIEW_PROP(alwaysBounceHorizontal);
MAP_SCROLL_VIEW_PROP(alwaysBounceVertical);
#if !TARGET_OS_OSX // [macOS]
MAP_SCROLL_VIEW_PROP(bounces);
MAP_SCROLL_VIEW_PROP(bouncesZoom);
MAP_SCROLL_VIEW_PROP(canCancelContentTouches);
#endif // [macOS]
MAP_SCROLL_VIEW_PROP(centerContent);
// MAP_SCROLL_VIEW_PROP(automaticallyAdjustContentInsets);
#if !TARGET_OS_OSX // [macOS]
MAP_SCROLL_VIEW_PROP(decelerationRate);
MAP_SCROLL_VIEW_PROP(directionalLockEnabled);
MAP_SCROLL_VIEW_PROP(maximumZoomScale);
MAP_SCROLL_VIEW_PROP(minimumZoomScale);
#endif // [macOS]
MAP_SCROLL_VIEW_PROP(scrollEnabled);
#if !TARGET_OS_OSX // [macOS]
MAP_SCROLL_VIEW_PROP(pagingEnabled);
MAP_SCROLL_VIEW_PROP(pinchGestureEnabled);
MAP_SCROLL_VIEW_PROP(scrollsToTop);
#endif // [macOS]
MAP_SCROLL_VIEW_PROP(showsHorizontalScrollIndicator);
MAP_SCROLL_VIEW_PROP(showsVerticalScrollIndicator);
if (oldScrollViewProps.automaticallyAdjustKeyboardInsets != newScrollViewProps.automaticallyAdjustKeyboardInsets) {
_automaticallyAdjustKeyboardInsets = newScrollViewProps.automaticallyAdjustKeyboardInsets;
}
if (oldScrollViewProps.scrollIndicatorInsets != newScrollViewProps.scrollIndicatorInsets) {
_scrollView.scrollIndicatorInsets = RCTUIEdgeInsetsFromEdgeInsets(newScrollViewProps.scrollIndicatorInsets);
}
if (oldScrollViewProps.indicatorStyle != newScrollViewProps.indicatorStyle) {
#if !TARGET_OS_OSX // [macOS]
_scrollView.indicatorStyle = RCTUIScrollViewIndicatorStyleFromProps(newScrollViewProps);
#endif // [macOS]
}
_endDraggingSensitivityMultiplier = newScrollViewProps.endDraggingSensitivityMultiplier;
if (oldScrollViewProps.scrollEventThrottle != newScrollViewProps.scrollEventThrottle) {
// Zero means "send value only once per significant logical event".
// Prop value is in milliseconds.
// iOS implementation uses `NSTimeInterval` (in seconds).
CGFloat throttleInSeconds = newScrollViewProps.scrollEventThrottle / 1000.0;
CGFloat msPerFrame = 1.0 / 60.0;
if (throttleInSeconds < 0) {
_scrollEventThrottle = INFINITY;
} else if (throttleInSeconds <= msPerFrame) {
_scrollEventThrottle = 0;
} else {
_scrollEventThrottle = throttleInSeconds;
}
}
// Overflow prop
if (oldScrollViewProps.getClipsContentToBounds() != newScrollViewProps.getClipsContentToBounds()) {
_scrollView.clipsToBounds = newScrollViewProps.getClipsContentToBounds();
}
MAP_SCROLL_VIEW_PROP(zoomScale);
if (oldScrollViewProps.contentInset != newScrollViewProps.contentInset) {
#if !TARGET_OS_OSX // [macOS]
_scrollView.contentInset = RCTUIEdgeInsetsFromEdgeInsets(newScrollViewProps.contentInset);
#else // [macOS
self.contentInset = RCTUIEdgeInsetsFromEdgeInsets(newScrollViewProps.contentInset);
#endif // macOS]
}
RCTEnhancedScrollView *scrollView = (RCTEnhancedScrollView *)_scrollView;
if (oldScrollViewProps.contentOffset != newScrollViewProps.contentOffset) {
_scrollView.contentOffset = RCTCGPointFromPoint(newScrollViewProps.contentOffset);
}
if (oldScrollViewProps.snapToAlignment != newScrollViewProps.snapToAlignment) {
scrollView.snapToAlignment = RCTNSStringFromString(toString(newScrollViewProps.snapToAlignment));
}
scrollView.snapToStart = newScrollViewProps.snapToStart;
scrollView.snapToEnd = newScrollViewProps.snapToEnd;
if (oldScrollViewProps.snapToOffsets != newScrollViewProps.snapToOffsets) {
NSMutableArray<NSNumber *> *snapToOffsets = [NSMutableArray array];
for (const auto &snapToOffset : newScrollViewProps.snapToOffsets) {
[snapToOffsets addObject:[NSNumber numberWithFloat:snapToOffset]];
}
scrollView.snapToOffsets = snapToOffsets;
}
#if !TARGET_OS_OSX // [macOS]
if (oldScrollViewProps.automaticallyAdjustsScrollIndicatorInsets !=
newScrollViewProps.automaticallyAdjustsScrollIndicatorInsets) {
scrollView.automaticallyAdjustsScrollIndicatorInsets = newScrollViewProps.automaticallyAdjustsScrollIndicatorInsets;
}
if ((oldScrollViewProps.contentInsetAdjustmentBehavior != newScrollViewProps.contentInsetAdjustmentBehavior) ||
_shouldUpdateContentInsetAdjustmentBehavior) {
const auto contentInsetAdjustmentBehavior = newScrollViewProps.contentInsetAdjustmentBehavior;
if (contentInsetAdjustmentBehavior == ContentInsetAdjustmentBehavior::Never) {
scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else if (contentInsetAdjustmentBehavior == ContentInsetAdjustmentBehavior::Automatic) {
scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
} else if (contentInsetAdjustmentBehavior == ContentInsetAdjustmentBehavior::ScrollableAxes) {
scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentScrollableAxes;
} else if (contentInsetAdjustmentBehavior == ContentInsetAdjustmentBehavior::Always) {
scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
}
_shouldUpdateContentInsetAdjustmentBehavior = NO;
}
#endif // [macOS]
MAP_SCROLL_VIEW_PROP(disableIntervalMomentum);
MAP_SCROLL_VIEW_PROP(snapToInterval);
if (oldScrollViewProps.keyboardDismissMode != newScrollViewProps.keyboardDismissMode) {
#if TARGET_OS_IOS // [macOS] [visionOS]
scrollView.keyboardDismissMode = RCTUIKeyboardDismissModeFromProps(newScrollViewProps);
#endif // [macOS] [visionOS]
}
[super updateProps:props oldProps:oldProps];
}
- (void)updateState:(const State::Shared &)state oldState:(const State::Shared &)oldState
{
assert(std::dynamic_pointer_cast<const ScrollViewShadowNode::ConcreteState>(state));
_state = std::static_pointer_cast<const ScrollViewShadowNode::ConcreteState>(state);
auto &data = _state->getData();
auto contentOffset = RCTCGPointFromPoint(data.contentOffset);
if (!oldState && !CGPointEqualToPoint(contentOffset, CGPointZero)) {
/*
* When <ScrollView /> is suspended, it is removed from view hierarchy and its offset is stored in
* state. We want to restore this offset from the state but it must be snapped to be within UIScrollView's
* content to remove any overscroll.
*
* This can happen, for example, with pull to refresh. The UIScrollView will be overscrolled into negative offset.
* If the offset is not adjusted to be within the content area, it leads to a gap and UIScrollView does not adjust
* its offset until user scrolls.
*/
// Adjusting overscroll on the top.
contentOffset.y = fmax(contentOffset.y, -_scrollView.contentInset.top);
// Adjusting overscroll on the left.
contentOffset.x = fmax(contentOffset.x, -_scrollView.contentInset.left);
// TODO: T190695447 - Protect against over scroll on the bottom and right as well.
// This is not easily done because we need to flip the order of method calls for
// ShadowViewMutation::Insert. updateLayout must come before updateState.
_scrollView.contentOffset = contentOffset;
}
CGSize contentSize = RCTCGSizeFromSize(data.getContentSize());
if (CGSizeEqualToSize(_contentSize, contentSize)) {
return;
}
_contentSize = contentSize;
_containerView.frame = CGRect{RCTCGPointFromPoint(data.contentBoundingRect.origin), contentSize};
[self _preserveContentOffsetIfNeededWithBlock:^{
self->_scrollView.contentSize = contentSize;
}];
#if TARGET_OS_OSX // [macOS
// Force the scroll view to re-evaluate which scrollers should be visible.
[_scrollView tile];
#endif // macOS]
}
- (RCTPlatformView *)betterHitTest:(CGPoint)point withEvent:(UIEvent *)event // [macOS]
{
// This is the same algorithm as in the RCTViewComponentView with the exception of
// skipping the immediate child (_containerView) and checking grandchildren instead.
// This prevents issues with touches outside of _containerView being ignored even
// if they are within the bounds of the _containerView's children.
#if !TARGET_OS_OSX // [macOS]
if (!self.userInteractionEnabled || self.hidden || self.alpha < 0.01) {
#else // [macOS
if (!self.userInteractionEnabled || self.hidden || self.alphaValue < 0.01 ) {
#endif // macOS]
return nil;
}
BOOL isPointInside = [self pointInside:point withEvent:event];
BOOL clipsToBounds = _containerView.clipsToBounds;
clipsToBounds = clipsToBounds || _layoutMetrics.overflowInset == EdgeInsets{};
if (clipsToBounds && !isPointInside) {
return nil;
}
#if TARGET_OS_OSX // [macOS
// Check if the hit lands on a scrollbar (NSScroller) BEFORE checking content
// subviews. Scrollers are subviews of the NSScrollView, not the documentView
// (_containerView). They must be checked first because content views typically
// fill the entire visible area and would otherwise swallow scroller clicks —
// for both overlay and legacy (always-visible) scrollbar styles.
if (isPointInside) {
NSPoint scrollViewPoint = [_scrollView convertPoint:point fromView:self];
NSView *scrollViewHit = [_scrollView hitTest:scrollViewPoint];
if ([scrollViewHit isKindOfClass:[NSScroller class]]) {
return (RCTPlatformView *)scrollViewHit;
}
}
#endif // macOS]
for (RCTPlatformView *subview in [_containerView.subviews reverseObjectEnumerator]) { // [macOS]
RCTPlatformView *hitView = RCTUIViewHitTestWithEvent(subview, point, self, event); // [macOS]
if (hitView) {
return hitView;
}
}
return isPointInside ? self : nil;
}
/*
* Disables programmatical changing of ScrollView's `contentOffset` if a touch gesture is in progress.
*/
- (void)_preserveContentOffsetIfNeededWithBlock:(void (^)())block
{
if (!block) {
return;
}
if (!_isUserTriggeredScrolling) {
return block();
}
[((RCTEnhancedScrollView *)_scrollView) preserveContentOffsetWithBlock:block];
}
- (void)mountChildComponentView:(RCTUIView<RCTComponentViewProtocol> *)childComponentView index:(NSInteger)index // [macOS]
{
[_containerView insertSubview:childComponentView atIndex:index];
if (![childComponentView conformsToProtocol:@protocol(RCTCustomPullToRefreshViewProtocol)]) {
_contentView = childComponentView;
}
}
- (void)unmountChildComponentView:(RCTUIView<RCTComponentViewProtocol> *)childComponentView index:(NSInteger)index // [macOS]
{
[childComponentView removeFromSuperview];
if (![childComponentView conformsToProtocol:@protocol(RCTCustomPullToRefreshViewProtocol)] &&
_contentView == childComponentView) {
_contentView = nil;
}
}
/*
* Returns whether or not the scroll view interaction should be blocked because
* JavaScript was found to be the responder.
*/
- (BOOL)_shouldDisableScrollInteraction
{
RCTUIView *ancestorView = (RCTUIView *)self.superview; // [macOS]
while (ancestorView) {
if ([ancestorView respondsToSelector:@selector(isJSResponder)]) {
BOOL isJSResponder = ((RCTUIView<RCTComponentViewProtocol> *)ancestorView).isJSResponder; // [macOS]
if (isJSResponder) {
return YES;
}
}
ancestorView = (RCTUIView *)ancestorView.superview; // [macOS]
}
return NO;
}
- (ScrollViewEventEmitter::Metrics)_scrollViewMetrics
{
auto metrics = ScrollViewEventEmitter::Metrics{};
metrics.contentSize = RCTSizeFromCGSize(_scrollView.contentSize);
metrics.contentOffset = RCTPointFromCGPoint(_scrollView.contentOffset);
metrics.contentInset = RCTEdgeInsetsFromUIEdgeInsets(_scrollView.contentInset);
metrics.containerSize = RCTSizeFromCGSize(_scrollView.bounds.size);
metrics.zoomScale = _scrollView.zoomScale;
metrics.timestamp = CACurrentMediaTime();
if (_layoutMetrics.layoutDirection == LayoutDirection::RightToLeft) {
metrics.contentOffset.x = metrics.contentSize.width - metrics.containerSize.width - metrics.contentOffset.x;
}
return metrics;
}
- (ScrollViewEventEmitter::EndDragMetrics)_scrollViewMetricsWithVelocity:(CGPoint)velocity
andTargetContentOffset:(CGPoint)targetContentOffset
{
ScrollViewEventEmitter::EndDragMetrics metrics = [self _scrollViewMetrics];
metrics.targetContentOffset.x = targetContentOffset.x;
metrics.targetContentOffset.y = targetContentOffset.y;
metrics.velocity.x = velocity.x;
metrics.velocity.y = velocity.y;
return metrics;
}
- (void)_updateStateWithContentOffset
{
if (!_state) {
return;
}
auto contentOffset = RCTPointFromCGPoint(_scrollView.contentOffset);
_state->updateState(
[contentOffset](
const ScrollViewShadowNode::ConcreteState::Data &oldData) -> ScrollViewShadowNode::ConcreteState::SharedData {
if (oldData.contentOffset == contentOffset) {
// avoid doing a state update if content offset didn't change.
return nullptr;
}
auto newData = oldData;
newData.contentOffset = contentOffset;
return std::make_shared<const ScrollViewShadowNode::ConcreteState::Data>(newData);
});
}
- (void)prepareForRecycle
{
[super prepareForRecycle];
// Must invalidate state before setting contentOffset on ScrollView.
// Otherwise the state will be propagated to shadow tree.
_state.reset();
const auto &props = static_cast<const ScrollViewProps &>(*_props);
_scrollView.contentOffset = RCTCGPointFromPoint(props.contentOffset);
// We set the default behavior to "never" so that iOS
// doesn't do weird things to UIScrollView insets automatically
// and keeps it as an opt-in behavior.
#if !TARGET_OS_OSX // [macOS]
_scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
#endif // [macOS]
_shouldUpdateContentInsetAdjustmentBehavior = YES;
_isUserTriggeredScrolling = NO;
CGRect oldFrame = self.frame;
self.frame = CGRectZero;
self.frame = oldFrame;
_contentView = nil;
_prevFirstVisibleFrame = CGRectZero;
_firstVisibleView = nil;
}
#if TARGET_OS_OSX // [macOS
#pragma mark - NSScrollView scroll notification
- (void)scrollViewDocumentViewBoundsDidChange:(__unused NSNotification *)notification
{
RCTEnhancedScrollView *scrollView = _scrollView;
if (scrollView.centerContent) {
// Update content centering through contentOffset setter
[scrollView setContentOffset:scrollView.contentOffset];
}
[self scrollViewDidScroll:scrollView];
}
#endif // macOS]
#pragma mark - UIScrollViewDelegate
#if !TARGET_OS_OSX // [macOS]
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetContentOffset
{
if (fabs(_endDraggingSensitivityMultiplier - 1) > 0.0001f) {
if (targetContentOffset->y > 0) {
const CGFloat travel = targetContentOffset->y - scrollView.contentOffset.y;
targetContentOffset->y = scrollView.contentOffset.y + travel * _endDraggingSensitivityMultiplier;
}
}
if (!_eventEmitter) {
return;
}
auto metrics = [self _scrollViewMetricsWithVelocity:velocity andTargetContentOffset:*targetContentOffset];
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onScrollEndDrag(metrics);
}
- (BOOL)touchesShouldCancelInContentView:(__unused RCTPlatformView *)view // [macOS]
{
// Historically, `UIScrollView`s in React Native do not cancel touches
// started on `UIControl`-based views (as normal iOS `UIScrollView`s do).
return ![self _shouldDisableScrollInteraction];
}
#endif // [macOS]
- (void)scrollViewDidScroll:(RCTUIScrollView *)scrollView // [macOS]
{
auto scrollMetrics = [self _scrollViewMetrics];
[self _updateStateWithContentOffset];
NSTimeInterval now = CACurrentMediaTime();
if ((_lastScrollEventDispatchTime == 0) || (now - _lastScrollEventDispatchTime > _scrollEventThrottle)) {
_lastScrollEventDispatchTime = now;
if (_eventEmitter) {
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onScroll(scrollMetrics);
}
RCTSendScrollEventForNativeAnimations_DEPRECATED(scrollView, self.tag, kOnScrollEvent);
}
[self _remountChildrenIfNeeded];
}
- (void)scrollViewDidZoom:(RCTUIScrollView *)scrollView // [macOS]
{
[self scrollViewDidScroll:scrollView];
}
- (BOOL)scrollViewShouldScrollToTop:(RCTUIScrollView *)scrollView // [macOS]
{
_isUserTriggeredScrolling = YES;
return YES;
}
- (void)scrollViewDidScrollToTop:(RCTUIScrollView *)scrollView // [macOS]
{
if (!_eventEmitter) {
return;
}
_isUserTriggeredScrolling = NO;
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onScrollToTop([self _scrollViewMetrics]);
[self _updateStateWithContentOffset];
}
- (void)scrollViewWillBeginDragging:(RCTUIScrollView *)scrollView // [macOS]
{
[self _forceDispatchNextScrollEvent];
if (!_eventEmitter) {
return;
}
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onScrollBeginDrag([self _scrollViewMetrics]);
_isUserTriggeredScrolling = YES;
}
- (void)scrollViewDidEndDragging:(RCTUIScrollView *)scrollView willDecelerate:(BOOL)decelerate // [macOS]
{
[self _forceDispatchNextScrollEvent];
if (!_eventEmitter) {
return;
}
[self _updateStateWithContentOffset];
if (!decelerate) {
// ScrollView will not decelerate and `scrollViewDidEndDecelerating` will not be called.
// `_isUserTriggeredScrolling` must be set to NO here.
_isUserTriggeredScrolling = NO;
RCTSendScrollEventForNativeAnimations_DEPRECATED(scrollView, self.tag, kOnScrollEndEvent);
}
}
- (void)scrollViewWillBeginDecelerating:(RCTUIScrollView *)scrollView // [macOS]
{
[self _forceDispatchNextScrollEvent];
if (!_eventEmitter) {
return;
}
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onMomentumScrollBegin([self _scrollViewMetrics]);
}
- (void)scrollViewDidEndDecelerating:(RCTUIScrollView *)scrollView // [macOS]
{
[self _forceDispatchNextScrollEvent];
if (!_eventEmitter) {
return;
}
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onMomentumScrollEnd([self _scrollViewMetrics]);
[self _updateStateWithContentOffset];
_isUserTriggeredScrolling = NO;
RCTSendScrollEventForNativeAnimations_DEPRECATED(scrollView, self.tag, kOnScrollEndEvent);
}
- (void)scrollViewDidEndScrollingAnimation:(RCTUIScrollView *)scrollView // [macOS]
{
[self _handleFinishedScrolling:scrollView];
}
#if !TARGET_OS_OSX // [macOS]
- (void)didMoveToWindow
{
[super didMoveToWindow];
#else // [macOS
- (void)viewDidMoveToWindow // [macOS]
{
[super viewDidMoveToWindow];
#endif // [macOS]
#if TARGET_OS_OSX // [macOS
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
if (self.window == nil) {
// Unregister scrollview's clipview bounds change notifications
[defaultCenter removeObserver:self
name:NSViewBoundsDidChangeNotification
object:_scrollView.contentView];
[defaultCenter removeObserver:self
name:NSPreferredScrollerStyleDidChangeNotification
object:nil];
} else {
// Register for scrollview's clipview bounds change notifications so we can track scrolling
[defaultCenter addObserver:self
selector:@selector(scrollViewDocumentViewBoundsDidChange:)
name:NSViewBoundsDidChangeNotification
object:_scrollView.contentView]; // NSClipView
// Observe system scrollbar style changes so we can update scrollbar insets for Yoga layout
[defaultCenter addObserver:self
selector:@selector(_preferredScrollerStyleDidChange:)
name:NSPreferredScrollerStyleDidChangeNotification
object:nil];
}
#endif // macOS]
if (!self.window) {
// The view is being removed, ensure that the scroll end event is dispatched
[self _handleScrollEndIfNeeded];
}
}
- (void)_handleScrollEndIfNeeded
{
#if !TARGET_OS_OSX // [macOS]
if (_scrollView.isDecelerating || !_scrollView.isTracking) {
if (!_eventEmitter) {
return;
}
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onMomentumScrollEnd([self _scrollViewMetrics]);
[self _updateStateWithContentOffset];
_isUserTriggeredScrolling = NO;
}
#endif // [macOS]
}
- (void)_handleFinishedScrolling:(RCTUIScrollView *)scrollView // [macOS]
{
[self _forceDispatchNextScrollEvent];
[self scrollViewDidScroll:scrollView];
if (!_eventEmitter) {
return;
}
static_cast<const ScrollViewEventEmitter &>(*_eventEmitter).onMomentumScrollEnd([self _scrollViewMetrics]);
[self _updateStateWithContentOffset];
}
- (void)scrollViewWillBeginZooming:(RCTUIScrollView *)scrollView withView:(nullable RCTUIView *)view // [macOS]
{