From ed87f8eb805cf1be8d3336b47f160159e03da1a4 Mon Sep 17 00:00:00 2001 From: James Ide Date: Sat, 28 Nov 2026 02:41:18 -0800 Subject: [PATCH] Let iOS scroll views scroll inside a ScrollView JS responder On iOS a scroll view does not scroll while one of its ancestors is the JavaScript responder: `RCTScrollViewComponentView` answers NO from `touchesShouldCancelInContentView:`, and a `UIScrollView` that may not cancel its content's touches does not begin dragging. This is meant for a gesture that JavaScript owns, such as a `PanResponder` or a `Pressable` around a list. A `ScrollView` also takes the responder itself, for instance when a touch should dismiss the keyboard, and then the scroll views inside it could not be dragged: with the keyboard up, a drag on a horizontal list inside a vertical one did nothing, and the release dismissed the keyboard. On Android the inner list scrolls. Only a view group that is the responder takes its descendants' touches there (`JSResponderHandler`), and a scroll view is not one. Stop a scroll view only for an ancestor responder that is not a scroll view. A scroll view inside a `Pressable` or a `PanResponder` is unchanged, as on Android. When a drag or a pinch begins on a scroll view under a scroll view that is the responder, cancel the touches that began inside the inner scroll view, through the `RCTSurfaceTouchHandler` above the responder. The responder is then terminated, so the outer `ScrollView` does not dismiss the keyboard when the drag ends. The responder system does not do this: for an event that comes from inside the responder it offers the responder only to the views above it, so the inner `ScrollView` never gets `onScrollShouldSetResponder`. Android cancels at the same moment, in `NativeGestureUtil.notifyNativeGestureStarted`, and cancels every touch on the surface. Here a finger outside the inner scroll view keeps its touch. `cancelTouchesInView:` is declared in `RCTSurfaceTouchHandler+Internal.h` and is not public API. UIKit keeps reporting a touch until it ends, whatever the handler told JavaScript, so the touch and pointer handlers drop the later events of the touches they cancelled. Until those touches have ended they also keep from JavaScript a touch that begins inside the same view, which is part of the gesture the view took. --- .../ScrollView/RCTScrollViewComponentView.mm | 54 +++- .../RCTSurfacePointerHandler+Internal.h | 23 ++ .../React/Fabric/RCTSurfacePointerHandler.mm | 78 +++++- .../Fabric/RCTSurfaceTouchHandler+Internal.h | 26 ++ .../React/Fabric/RCTSurfaceTouchHandler.mm | 82 +++++- .../RCTScrollViewComponentViewTests.mm | 235 ++++++++++++++++++ 6 files changed, 492 insertions(+), 6 deletions(-) create mode 100644 packages/react-native/React/Fabric/RCTSurfacePointerHandler+Internal.h create mode 100644 packages/react-native/React/Fabric/RCTSurfaceTouchHandler+Internal.h diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm index 1353b88019b8..1950ec6153cd 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm @@ -10,6 +10,7 @@ #import #import #import +#import #import #import @@ -620,9 +621,16 @@ - (void)unmountChildComponentView:(UIView *)childCompo /* * Returns whether or not the scroll view interaction should be blocked because - * JavaScript was found to be the responder. + * JavaScript was found to be the responder. A scroll view that is the + * responder does not block the scroll views inside it. */ - (BOOL)_shouldDisableScrollInteraction +{ + UIView *ancestorJSResponder = [self _ancestorJSResponder]; + return ancestorJSResponder != nil && ![ancestorJSResponder isKindOfClass:[RCTScrollViewComponentView class]]; +} + +- (UIView *)_ancestorJSResponder { UIView *ancestorView = self.superview; @@ -630,14 +638,46 @@ - (BOOL)_shouldDisableScrollInteraction if ([ancestorView respondsToSelector:@selector(isJSResponder)]) { BOOL isJSResponder = ((UIView *)ancestorView).isJSResponder; if (isJSResponder) { - return YES; + return ancestorView; } } ancestorView = ancestorView.superview; } - return NO; + return nil; +} + +/* + * Cancels the touches that began inside this scroll view when a scroll view + * above it is the JavaScript responder, so that the responder is terminated + * when this scroll view takes the gesture. The responder system does not ask + * a view inside the responder whether it wants to take over, so this scroll + * view's `onScrollShouldSetResponder` is not called. The responder reaches + * its view asynchronously: one granted after the gesture began is not + * terminated. + */ +- (void)_cancelTouchesUnderScrollViewJSResponder +{ +#if !TARGET_OS_TV + UIView *ancestorView = [self _ancestorJSResponder]; + if (![ancestorView isKindOfClass:[RCTScrollViewComponentView class]]) { + return; + } + + // Cancel through the nearest touch handler above the responder, which is the one that sent it its touches. + // A modal and an input accessory view attach their own to views outside the surface's view. + while (ancestorView) { + for (UIGestureRecognizer *gestureRecognizer in ancestorView.gestureRecognizers) { + if ([gestureRecognizer isKindOfClass:[RCTSurfaceTouchHandler class]]) { + [(RCTSurfaceTouchHandler *)gestureRecognizer cancelTouchesInView:self]; + return; + } + } + + ancestorView = ancestorView.superview; + } +#endif } - (ScrollViewEventEmitter::Metrics)_scrollViewMetrics @@ -845,6 +885,7 @@ - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { + [self _cancelTouchesUnderScrollViewJSResponder]; [self _forceDispatchNextScrollEvent]; // A drag interrupts an animated programmatic scroll without `scrollViewDidEndScrollingAnimation`. @@ -1019,6 +1060,13 @@ - (void)_handleFinishedScrolling:(UIScrollView *)scrollView - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view { +#if !TARGET_OS_TV + // Cancel only for a pinch. UIKit also calls this method for a zoom that a command animates. + UIGestureRecognizerState pinchState = scrollView.pinchGestureRecognizer.state; + if (pinchState == UIGestureRecognizerStateBegan || pinchState == UIGestureRecognizerStateChanged) { + [self _cancelTouchesUnderScrollViewJSResponder]; + } +#endif [self _forceDispatchNextScrollEvent]; if (!_eventEmitter) { diff --git a/packages/react-native/React/Fabric/RCTSurfacePointerHandler+Internal.h b/packages/react-native/React/Fabric/RCTSurfacePointerHandler+Internal.h new file mode 100644 index 000000000000..88d15b3b32c2 --- /dev/null +++ b/packages/react-native/React/Fabric/RCTSurfacePointerHandler+Internal.h @@ -0,0 +1,23 @@ +/* + * 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 + +NS_ASSUME_NONNULL_BEGIN + +@interface RCTSurfacePointerHandler (Internal) + +/* + * Cancels the pointers of the touches that began inside `view`. JavaScript + * receives `pointercancel` for them and no further events for those touches, + * nor, until they have all ended, for a touch that begins inside `view`. + */ +- (void)cancelPointersInView:(UIView *)view; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native/React/Fabric/RCTSurfacePointerHandler.mm b/packages/react-native/React/Fabric/RCTSurfacePointerHandler.mm index 18246804d43b..aa685b7d3511 100644 --- a/packages/react-native/React/Fabric/RCTSurfacePointerHandler.mm +++ b/packages/react-native/React/Fabric/RCTSurfacePointerHandler.mm @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -#import "RCTSurfacePointerHandler.h" +#import "RCTSurfacePointerHandler+Internal.h" #import #import @@ -442,6 +442,17 @@ @implementation RCTSurfacePointerHandler { std::unordered_map<__unsafe_unretained UITouch *, ActivePointer, PointerHasher<__unsafe_unretained UITouch *>> _activePointers; + /* + * The touches whose pointers `cancelPointersInView:` cancelled and that have not ended. + * UIKit keeps reporting them, and their events are dropped. + */ + std::unordered_set<__unsafe_unretained UITouch *, PointerHasher<__unsafe_unretained UITouch *>> _cancelledTouches; + + /* + * The view whose touches were cancelled last. + */ + __weak UIView *_cancelledTouchesView; + /* * We hold the view weakly to prevent a retain cycle. */ @@ -658,6 +669,7 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; + touches = [self _touchesWithoutTouchesBeganInCancelledView:touches]; [self _registerTouches:touches withEvent:event]; [self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeStart]; @@ -672,6 +684,7 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; + touches = [self _touchesWithoutCancelledTouches:touches forgettingThem:NO]; [self _updateTouches:touches withEvent:event]; [self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeMove]; @@ -682,6 +695,7 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; + touches = [self _touchesWithoutCancelledTouches:touches forgettingThem:YES]; [self _updateTouches:touches withEvent:event]; [self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeEnd]; [self _unregisterTouches:touches]; @@ -697,6 +711,7 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesCancelled:touches withEvent:event]; + touches = [self _touchesWithoutCancelledTouches:touches forgettingThem:YES]; [self _updateTouches:touches withEvent:event]; [self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeCancel]; [self _unregisterTouches:touches]; @@ -712,6 +727,8 @@ - (void)reset { [super reset]; + _cancelledTouches.clear(); + if (!_activePointers.empty()) { std::vector activePointers; activePointers.reserve(_activePointers.size()); @@ -733,6 +750,65 @@ - (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecog return NO; } +- (void)cancelPointersInView:(UIView *)view +{ + NSMutableSet *touches = [NSMutableSet new]; + for (const auto &pair : _activePointers) { + if ([pair.second.initialComponentView isDescendantOfView:view]) { + [touches addObject:pair.first]; + } + } + + if (touches.count > 0) { + [self _dispatchActivePointers:[self _activePointersFromTouches:touches] eventType:RCTPointerEventTypeCancel]; + [self _unregisterTouches:touches]; + for (UITouch *touch in touches) { + _cancelledTouches.insert(touch); + } + _cancelledTouchesView = view; + } +} + +/* + * A touch that begins inside the view whose touches were cancelled, while one of those touches is still down, + * is part of the gesture that the view took. JavaScript is not told about it. Returns the other touches. + */ +- (NSSet *)_touchesWithoutTouchesBeganInCancelledView:(NSSet *)touches +{ + UIView *cancelledTouchesView = _cancelledTouchesView; + if (_cancelledTouches.empty() || cancelledTouchesView == nil) { + return touches; + } + + NSMutableSet *remainingTouches = [NSMutableSet setWithCapacity:touches.count]; + for (UITouch *touch in touches) { + if ([touch.view isDescendantOfView:cancelledTouchesView]) { + _cancelledTouches.insert(touch); + } else { + [remainingTouches addObject:touch]; + } + } + return remainingTouches; +} + +- (NSSet *)_touchesWithoutCancelledTouches:(NSSet *)touches forgettingThem:(BOOL)forgettingThem +{ + if (_cancelledTouches.empty()) { + return touches; + } + + NSMutableSet *remainingTouches = [NSMutableSet setWithCapacity:touches.count]; + for (UITouch *touch in touches) { + auto iterator = _cancelledTouches.find(touch); + if (iterator == _cancelledTouches.end()) { + [remainingTouches addObject:touch]; + } else if (forgettingThem) { + _cancelledTouches.erase(iterator); + } + } + return remainingTouches; +} + #pragma mark - Hover callbacks - (void)penHovering:(UIHoverGestureRecognizer *)recognizer API_AVAILABLE(ios(13.0)) diff --git a/packages/react-native/React/Fabric/RCTSurfaceTouchHandler+Internal.h b/packages/react-native/React/Fabric/RCTSurfaceTouchHandler+Internal.h new file mode 100644 index 000000000000..218ce8e1c08c --- /dev/null +++ b/packages/react-native/React/Fabric/RCTSurfaceTouchHandler+Internal.h @@ -0,0 +1,26 @@ +/* + * 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 + +NS_ASSUME_NONNULL_BEGIN + +@interface RCTSurfaceTouchHandler (Internal) + +/* + * Cancels the touches that began inside `view`. JavaScript receives + * `touchcancel` for them, and `pointercancel` when W3C pointer events are on, + * and no further events for those touches. Until they have all ended, + * JavaScript receives no events either for a touch that begins inside + * `view`. Touches outside `view` are not affected. A native view that takes + * a gesture away from JavaScript calls this. + */ +- (void)cancelTouchesInView:(UIView *)view; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native/React/Fabric/RCTSurfaceTouchHandler.mm b/packages/react-native/React/Fabric/RCTSurfaceTouchHandler.mm index 1bf565db2266..fe2cb22694d1 100644 --- a/packages/react-native/React/Fabric/RCTSurfaceTouchHandler.mm +++ b/packages/react-native/React/Fabric/RCTSurfaceTouchHandler.mm @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -#import "RCTSurfaceTouchHandler.h" +#import "RCTSurfaceTouchHandler+Internal.h" #import #import @@ -13,7 +13,7 @@ #import #import "RCTConversions.h" -#import "RCTSurfacePointerHandler.h" +#import "RCTSurfacePointerHandler+Internal.h" #import "RCTTouchableComponentViewProtocol.h" #if !TARGET_OS_TV @@ -137,6 +137,17 @@ @implementation RCTSurfaceTouchHandler { std::unordered_map<__unsafe_unretained UITouch *, ActiveTouch, PointerHasher<__unsafe_unretained UITouch *>> _activeTouches; + /* + * The touches that `cancelTouchesInView:` cancelled and that have not ended. + * UIKit keeps reporting them, and their events are dropped. + */ + std::unordered_set<__unsafe_unretained UITouch *, PointerHasher<__unsafe_unretained UITouch *>> _cancelledTouches; + + /* + * The view whose touches were cancelled last. + */ + __weak UIView *_cancelledTouchesView; + /* * We hold the view weakly to prevent a retain cycle. */ @@ -308,6 +319,7 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; + touches = [self _touchesWithoutTouchesBeganInCancelledView:touches]; [self _registerTouches:touches]; [self _dispatchActiveTouches:[self _activeTouchesFromTouches:touches] eventType:RCTTouchEventTypeTouchStart]; @@ -322,6 +334,7 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; + touches = [self _touchesWithoutCancelledTouches:touches forgettingThem:NO]; [self _updateTouches:touches]; [self _dispatchActiveTouches:[self _activeTouchesFromTouches:touches] eventType:RCTTouchEventTypeTouchMove]; @@ -332,6 +345,7 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; + touches = [self _touchesWithoutCancelledTouches:touches forgettingThem:YES]; [self _updateTouches:touches]; [self _dispatchActiveTouches:[self _activeTouchesFromTouches:touches] eventType:RCTTouchEventTypeTouchEnd]; [self _unregisterTouches:touches]; @@ -347,6 +361,7 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesCancelled:touches withEvent:event]; + touches = [self _touchesWithoutCancelledTouches:touches forgettingThem:YES]; [self _updateTouches:touches]; [self _dispatchActiveTouches:[self _activeTouchesFromTouches:touches] eventType:RCTTouchEventTypeTouchCancel]; [self _unregisterTouches:touches]; @@ -362,6 +377,8 @@ - (void)reset { [super reset]; + _cancelledTouches.clear(); + if (!_activeTouches.empty()) { std::vector activeTouches; activeTouches.reserve(_activeTouches.size()); @@ -411,6 +428,67 @@ - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer #pragma mark - +- (void)cancelTouchesInView:(UIView *)view +{ + NSMutableSet *touches = [NSMutableSet new]; + for (const auto &pair : _activeTouches) { + if ([pair.second.componentView isDescendantOfView:view]) { + [touches addObject:pair.first]; + } + } + + if (touches.count > 0) { + [self _dispatchActiveTouches:[self _activeTouchesFromTouches:touches] eventType:RCTTouchEventTypeTouchCancel]; + [self _unregisterTouches:touches]; + for (UITouch *touch in touches) { + _cancelledTouches.insert(touch); + } + _cancelledTouchesView = view; + } + + [_pointerHandler cancelPointersInView:view]; +} + +/* + * A touch that begins inside the view whose touches were cancelled, while one of those touches is still down, + * is part of the gesture that the view took. JavaScript is not told about it. Returns the other touches. + */ +- (NSSet *)_touchesWithoutTouchesBeganInCancelledView:(NSSet *)touches +{ + UIView *cancelledTouchesView = _cancelledTouchesView; + if (_cancelledTouches.empty() || cancelledTouchesView == nil) { + return touches; + } + + NSMutableSet *remainingTouches = [NSMutableSet setWithCapacity:touches.count]; + for (UITouch *touch in touches) { + if ([touch.view isDescendantOfView:cancelledTouchesView]) { + _cancelledTouches.insert(touch); + } else { + [remainingTouches addObject:touch]; + } + } + return remainingTouches; +} + +- (NSSet *)_touchesWithoutCancelledTouches:(NSSet *)touches forgettingThem:(BOOL)forgettingThem +{ + if (_cancelledTouches.empty()) { + return touches; + } + + NSMutableSet *remainingTouches = [NSMutableSet setWithCapacity:touches.count]; + for (UITouch *touch in touches) { + auto iterator = _cancelledTouches.find(touch); + if (iterator == _cancelledTouches.end()) { + [remainingTouches addObject:touch]; + } else if (forgettingThem) { + _cancelledTouches.erase(iterator); + } + } + return remainingTouches; +} + - (void)_cancelTouches { [self setEnabled:NO]; diff --git a/packages/react-native/React/Tests/Mounting/RCTScrollViewComponentViewTests.mm b/packages/react-native/React/Tests/Mounting/RCTScrollViewComponentViewTests.mm index eb9f977dca63..6679ddd18f8b 100644 --- a/packages/react-native/React/Tests/Mounting/RCTScrollViewComponentViewTests.mm +++ b/packages/react-native/React/Tests/Mounting/RCTScrollViewComponentViewTests.mm @@ -6,8 +6,12 @@ */ #import +#import #import #import +#import +#import +#import #import #import #import @@ -15,8 +19,10 @@ #import #import #import +#import #import #import +#import #import #import #import @@ -45,9 +51,11 @@ using facebook::react::ContextContainer; using facebook::react::EventBeat; using facebook::react::EventDispatcher; +using facebook::react::EventListener; using facebook::react::EventLogger; using facebook::react::EventQueue; using facebook::react::EventQueueProcessor; +using facebook::react::RawEvent; using facebook::react::ReactNativeFeatureFlags; using facebook::react::ReactNativeFeatureFlagsDefaults; using facebook::react::RuntimeScheduler; @@ -55,10 +63,12 @@ using facebook::react::ScrollContentViewShadowNode; using facebook::react::ScrollContentViewState; using facebook::react::ShadowNodeFamily; +using facebook::react::SharedTouchEventEmitter; using facebook::react::State; using facebook::react::StateData; using facebook::react::StatePipe; using facebook::react::StateUpdate; +using facebook::react::TouchEventEmitter; class ImmediateScrollContentFeatureFlags : public ReactNativeFeatureFlagsDefaults { public: @@ -156,8 +166,119 @@ void flushQueuedState() std::shared_ptr initialData_ = std::make_shared(); }; +// Records the types of the events that a touch event emitter dispatches, in order. +class TouchEventRecorder { + public: + TouchEventRecorder() : runtimeScheduler_([](std::function && /*callback*/) {}) + { + StatePipe statePipe = [](const StateUpdate & /*update*/) {}; + auto ownerBox = std::make_shared(); + dispatcher_ = std::make_shared( + EventQueueProcessor({}, {}, statePipe, {}), + std::make_unique(ownerBox, runtimeScheduler_), + statePipe, + std::weak_ptr{}); + ownerBox->owner = dispatcher_; + // Return true to keep the event out of the queue, which needs a JavaScript runtime to drain + dispatcher_->addListener(std::make_shared([this](const RawEvent &event) { + [eventTypes addObject:@(event.type.c_str())]; + return true; + })); + eventEmitter = std::make_shared(nullptr, dispatcher_); + } + + NSMutableArray *eventTypes = [NSMutableArray new]; + SharedTouchEventEmitter eventEmitter; + + private: + RuntimeScheduler runtimeScheduler_; + std::shared_ptr dispatcher_; +}; + } // namespace +// A view that takes touches as a component view does and records the touch events sent to it. +@interface RCTTouchRecordingView : UIView +@property (nonatomic, readonly) NSArray *eventTypes; +@end + +@implementation RCTTouchRecordingView { + TouchEventRecorder _recorder; +} + +- (SharedTouchEventEmitter)touchEventEmitterAtPoint:(CGPoint)point +{ + return _recorder.eventEmitter; +} + +- (NSArray *)eventTypes +{ + return [_recorder.eventTypes copy]; +} + +@end + +// A touch on a given view. `RCTSurfaceTouchHandler` reads only what is overridden here. +@interface RCTTestTouch : UITouch +@property (nonatomic, strong) UIView *testView; +@property (nonatomic, assign) UITouchPhase testPhase; +@end + +@implementation RCTTestTouch + ++ (instancetype)touchOnView:(UIView *)view +{ + RCTTestTouch *touch = [RCTTestTouch new]; + touch.testView = view; + touch.testPhase = UITouchPhaseBegan; + return touch; +} + +- (UIView *)view +{ + return _testView; +} + +- (UITouchPhase)phase +{ + return _testPhase; +} + +- (CGPoint)locationInView:(UIView *)view +{ + return CGPointZero; +} + +- (NSTimeInterval)timestamp +{ + return 1; +} + +- (CGFloat)force +{ + return 0; +} + +- (CGFloat)maximumPossibleForce +{ + return 1; +} + +@end + +@interface RCTTestTouchEvent : UIEvent +@property (nonatomic, copy) NSSet *testTouches; +@end + +@implementation RCTTestTouchEvent + +- (NSSet *)allTouches +{ + return _testTouches; +} + +@end + @interface RCTScrollViewComponentView (Tests) - (void)_keyboardWillChangeFrame:(NSNotification *)notification; @end @@ -228,6 +349,120 @@ - (void)testAutomaticallyAdjustKeyboardInsetsAcrossRecycling XCTAssertEqual(view.scrollView.contentInset.bottom, 50); } +- (void)testViewJSResponderDisablesScrollingAndIsNotCancelled +{ + UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; + RCTSurfaceTouchHandler *touchHandler = [RCTSurfaceTouchHandler new]; + [touchHandler attachToView:window]; + RCTViewComponentView *responder = [RCTViewComponentView new]; + [window addSubview:responder]; + RCTScrollViewComponentView *scrollView = + [[RCTScrollViewComponentView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; + [responder addSubview:scrollView]; + RCTTouchRecordingView *content = [RCTTouchRecordingView new]; + [scrollView.scrollView addSubview:content]; + + XCTAssertTrue([scrollView.scrollView touchesShouldCancelInContentView:content]); + + [responder setIsJSResponder:YES]; + XCTAssertFalse([scrollView.scrollView touchesShouldCancelInContentView:content]); + + RCTTestTouch *touch = [RCTTestTouch touchOnView:content]; + RCTTestTouchEvent *event = [RCTTestTouchEvent new]; + event.testTouches = [NSSet setWithObject:touch]; + [touchHandler touchesBegan:event.testTouches withEvent:event]; + [(id)scrollView scrollViewWillBeginDragging:scrollView.scrollView]; + XCTAssertEqualObjects(content.eventTypes, (@[ @"topTouchStart" ])); + + [responder setIsJSResponder:NO]; + XCTAssertTrue([scrollView.scrollView touchesShouldCancelInContentView:content]); + + // Take the window out of its scene, where UIKit would keep laying it out + window.windowScene = nil; +} + +- (void)testDragUnderScrollViewJSResponderCancelsOnlyTheTouchesInsideTheScrollView +{ + UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; + RCTSurfaceTouchHandler *touchHandler = [RCTSurfaceTouchHandler new]; + [touchHandler attachToView:window]; + RCTScrollViewComponentView *responder = [[RCTScrollViewComponentView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; + [window addSubview:responder]; + RCTTouchRecordingView *outside = [RCTTouchRecordingView new]; + [responder.scrollView addSubview:outside]; + RCTScrollViewComponentView *scrollView = [[RCTScrollViewComponentView alloc] initWithFrame:CGRectMake(0, 0, 100, 50)]; + [responder.scrollView addSubview:scrollView]; + RCTTouchRecordingView *inside = [RCTTouchRecordingView new]; + [scrollView.scrollView addSubview:inside]; + + [responder setIsJSResponder:YES]; + XCTAssertTrue([scrollView.scrollView touchesShouldCancelInContentView:inside]); + + // The touch handler warns when UIKit reports a touch it does not know + __block NSUInteger warningCount = 0; + RCTLogFunction previousLogFunction = RCTGetLogFunction(); + RCTSetLogFunction( + ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { + if (level >= RCTLogLevelWarning) { + warningCount++; + } + }); + [self addTeardownBlock:^{ + RCTSetLogFunction(previousLogFunction); + }]; + + RCTTestTouch *insideTouch = [RCTTestTouch touchOnView:inside]; + RCTTestTouch *outsideTouch = [RCTTestTouch touchOnView:outside]; + RCTTestTouchEvent *event = [RCTTestTouchEvent new]; + event.testTouches = [NSSet setWithObjects:insideTouch, outsideTouch, nil]; + [touchHandler touchesBegan:event.testTouches withEvent:event]; + + [(id)scrollView scrollViewWillBeginDragging:scrollView.scrollView]; + XCTAssertEqualObjects(inside.eventTypes, (@[ @"topTouchStart", @"topTouchCancel" ])); + XCTAssertEqualObjects(outside.eventTypes, (@[ @"topTouchStart" ])); + + // A finger that lands inside the scroll view during its gesture is not reported to JavaScript + RCTTestTouch *lateTouch = [RCTTestTouch touchOnView:inside]; + RCTTestTouchEvent *lateEvent = [RCTTestTouchEvent new]; + lateEvent.testTouches = [NSSet setWithObjects:insideTouch, outsideTouch, lateTouch, nil]; + [touchHandler touchesBegan:[NSSet setWithObject:lateTouch] withEvent:lateEvent]; + lateTouch.testPhase = UITouchPhaseCancelled; + [touchHandler touchesCancelled:[NSSet setWithObject:lateTouch] withEvent:lateEvent]; + XCTAssertEqualObjects(inside.eventTypes, (@[ @"topTouchStart", @"topTouchCancel" ])); + + // UIKit keeps reporting the cancelled touch; only the other one reaches JavaScript + insideTouch.testPhase = UITouchPhaseMoved; + outsideTouch.testPhase = UITouchPhaseMoved; + [touchHandler touchesMoved:event.testTouches withEvent:event]; + insideTouch.testPhase = UITouchPhaseEnded; + outsideTouch.testPhase = UITouchPhaseEnded; + [touchHandler touchesEnded:event.testTouches withEvent:event]; + XCTAssertEqualObjects(inside.eventTypes, (@[ @"topTouchStart", @"topTouchCancel" ])); + XCTAssertEqualObjects(outside.eventTypes, (@[ @"topTouchStart", @"topTouchMove", @"topTouchEnd" ])); + + // The next touch inside the scroll view is delivered as usual + RCTTestTouch *nextTouch = [RCTTestTouch touchOnView:inside]; + event.testTouches = [NSSet setWithObject:nextTouch]; + [touchHandler touchesBegan:event.testTouches withEvent:event]; + nextTouch.testPhase = UITouchPhaseEnded; + [touchHandler touchesEnded:event.testTouches withEvent:event]; + XCTAssertEqualObjects( + inside.eventTypes, (@[ @"topTouchStart", @"topTouchCancel", @"topTouchStart", @"topTouchEnd" ])); + + // A zoom that a command animates begins without a pinch and takes no gesture from JavaScript + RCTTestTouch *heldTouch = [RCTTestTouch touchOnView:inside]; + event.testTouches = [NSSet setWithObject:heldTouch]; + [touchHandler touchesBegan:event.testTouches withEvent:event]; + scrollView.scrollView.maximumZoomScale = 2; + XCTAssertNotNil(scrollView.scrollView.pinchGestureRecognizer); + [(id)scrollView scrollViewWillBeginZooming:scrollView.scrollView withView:nil]; + XCTAssertEqualObjects(inside.eventTypes.lastObject, @"topTouchStart"); + + XCTAssertEqual(warningCount, 0u); + // Take the window out of its scene, where UIKit would keep laying it out + window.windowScene = nil; +} + // XCTest assertion macros use variadic reporting and catch framework exceptions by value. // NOLINTBEGIN(cppcoreguidelines-pro-type-vararg, misc-throw-by-value-catch-by-reference) - (void)testSafeAreaCorrectionPreservesPullToRefreshInset