Skip to content

Commit 3aed172

Browse files
authored
Forward RCTEventDispatcher observer events to C++ Native Animated
Summary: **Problem**: With C++ Native Animated enabled on iOS, native-driven `Animated.event` mappings no longer receive events that libraries deliver through `RCTEventDispatcher` observers. The legacy ObjC Native Animated module observed them; C++ Native Animated only reads Fabric event payloads (event dispatched with `eventEmitter->dispatchEvent(name, folly::dynamic)`), and codegen'd component events are not readable from C++. As a result, in some of `react-navigation` (oss library) examples, Gesture- and pager-driven animations (swipe-back in a JS stack navigator, tab indicators driven by a pager's `onPageScroll`) stop tracking user input. **Proposed change**: When C++ Native Animated is enabled, `RCTInstance` observes its `RCTEventDispatcher` and hands each component event, on the main thread, to an `EventEmitterListenerContainer` it publishes in the context container under `RCTEventDispatcherListeners`. On Apple platforms, `NativeAnimatedNodesManagerProvider::getOrCreate()` adds its event listener to that container when present, next to its Fabric event listener. An **alternative** is to let the library migrate to `EventEmitter::dispatchEvent` (so we fully get rid of the legacy event API); however dispatchEvent also delivers the event to JS. In android and RNCXX, we also maintain 2 paths to intercept js dispatchEvent and platform-only event. **Changes**: - iOS (`RCTInstance`, new `RCTEventDispatcherEventPayload`): registers as an `RCTEventDispatcherObserver` only when `cxxNativeAnimatedEnabled()` is on, and forwards only component events (`RCTEventEmitter.receiveEvent`). The payload reads values from the event body on demand, so events no listener reads are not converted; it is never dispatched to JS. - C++ (`NativeAnimatedNodesManagerProvider`, `__APPLE__` only): subscribes to `RCTEventDispatcherListeners` from the UIManager's context container. Covers the platform-driven and shared animation backend setups, and apps that create their own provider. - C++: `EventEmitterListener.h` moves from `react/renderer/animated` to `react/renderer/core` (the runtime only needs `core`); `react/renderer/animated/EventEmitterListener.h` forwards to it for existing includers. No public API changes. Found while auditing `cxxNativeAnimatedEnabled` against OSS react-navigation (7.x) and its peers react-native-gesture-handler, react-native-pager-view and react-native-screens. Changelog: [iOS][Fixed] - Native-driven `Animated.event` mappings receive events delivered through `RCTEventDispatcher` observers when C++ Native Animated is enabled Reviewed By: fkgozali Differential Revision: D129152896 Pull Request resolved: #59770
1 parent cfd25c8 commit 3aed172

7 files changed

Lines changed: 229 additions & 63 deletions

File tree

‎packages/react-native/ReactCommon/react/renderer/animated/EventEmitterListener.h‎

Lines changed: 1 addition & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -9,64 +9,4 @@
99

1010
#include <react/cxxstableapi/FrameworksGuard.h>
1111

12-
#include <mutex>
13-
#include <shared_mutex>
14-
15-
#include <React/RendererCore.h>
16-
17-
namespace facebook::react {
18-
19-
/**
20-
* Listener for events dispatched to JS runtime.
21-
* Return `true` to interrupt default dispatch to JS event emitter, `false` to
22-
* pass through to default handlers.
23-
*/
24-
25-
template <typename... TArgs>
26-
using EventListenerT = std::function<bool(TArgs...)>;
27-
28-
template <typename... TArgs>
29-
class EventListenerContainerT {
30-
public:
31-
/*
32-
* Invoke listeners in this container with the event.
33-
* Returns true if event was handled by the listener, false to continue
34-
* default dispatch.
35-
*/
36-
bool willDispatchEvent(TArgs... args)
37-
{
38-
std::shared_lock lock(mutex_);
39-
bool handled = false;
40-
for (const auto &listener : eventListeners_) {
41-
handled = (*listener)(args...);
42-
if (handled) {
43-
break;
44-
}
45-
}
46-
return handled;
47-
}
48-
49-
void addListener(std::shared_ptr<const EventListenerT<TArgs...>> listener)
50-
{
51-
std::unique_lock lock(mutex_);
52-
eventListeners_.push_back(std::move(listener));
53-
}
54-
55-
void removeListener(const std::shared_ptr<const EventListenerT<TArgs...>> &listener)
56-
{
57-
std::unique_lock lock(mutex_);
58-
auto it = std::find(eventListeners_.begin(), eventListeners_.end(), listener);
59-
if (it != eventListeners_.end()) {
60-
eventListeners_.erase(it);
61-
}
62-
}
63-
64-
private:
65-
std::shared_mutex mutex_;
66-
std::vector<std::shared_ptr<const EventListenerT<TArgs...>>> eventListeners_;
67-
};
68-
69-
using EventEmitterListener = EventListenerT<Tag, const std::string &, const EventPayload &>;
70-
using EventEmitterListenerContainer = EventListenerContainerT<Tag, const std::string &, const EventPayload &>;
71-
72-
} // namespace facebook::react
12+
#include <react/renderer/core/EventEmitterListener.h>

‎packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManager.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@
1818
#include <React/Debug.h>
1919
#include <React/RendererCore.h>
2020
#include <folly/dynamic.h>
21-
#include <react/renderer/animated/EventEmitterListener.h>
2221
#include <react/renderer/animated/event_drivers/EventAnimationDriver.h>
2322
#include <react/renderer/animationbackend/AnimatedPropsBuilder.h>
2423
#include <react/renderer/animationbackend/AnimationBackend.h>
24+
#include <react/renderer/core/EventEmitterListener.h>
2525
#include <react/renderer/uimanager/UIManagerAnimationBackend.h>
2626
#include <chrono>
2727
#include <memory>

‎packages/react-native/ReactCommon/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,17 @@ NativeAnimatedNodesManagerProvider::getOrCreate(
143143
addEventEmitterListener(
144144
nativeAnimatedNodesManager_->getEventEmitterListener());
145145

146+
#if defined(__APPLE__)
147+
// Events delivered to RCTEventDispatcher observers rather than through Fabric
148+
// event emitters.
149+
if (auto eventDispatcherListeners =
150+
uiManager->getContextContainer()
151+
->find<std::shared_ptr<EventEmitterListenerContainer>>(
152+
"RCTEventDispatcherListeners")) {
153+
(*eventDispatcherListeners)->addListener(getEventEmitterListener());
154+
}
155+
#endif
156+
146157
uiManager->addEventListener(
147158
std::make_shared<EventListener>(
148159
[eventEmitterListenerContainerWeak =
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#pragma once
9+
10+
#include <react/cxxstableapi/FrameworksGuard.h>
11+
12+
#include <mutex>
13+
#include <shared_mutex>
14+
15+
#include <react/renderer/core/EventPayload.h>
16+
#include <react/renderer/core/ReactPrimitives.h>
17+
18+
namespace facebook::react {
19+
20+
/**
21+
* Listener for events dispatched to JS runtime, used to drive native-driven
22+
* Animated.event mappings (C++ Native Animated) from event payloads.
23+
* Return `true` to interrupt default dispatch to JS event emitter, `false` to
24+
* pass through to default handlers.
25+
*/
26+
27+
template <typename... TArgs>
28+
using EventListenerT = std::function<bool(TArgs...)>;
29+
30+
template <typename... TArgs>
31+
class EventListenerContainerT {
32+
public:
33+
/*
34+
* Invoke listeners in this container with the event.
35+
* Returns true if event was handled by the listener, false to continue
36+
* default dispatch.
37+
*/
38+
bool willDispatchEvent(TArgs... args)
39+
{
40+
std::shared_lock lock(mutex_);
41+
bool handled = false;
42+
for (const auto &listener : eventListeners_) {
43+
handled = (*listener)(args...);
44+
if (handled) {
45+
break;
46+
}
47+
}
48+
return handled;
49+
}
50+
51+
void addListener(std::shared_ptr<const EventListenerT<TArgs...>> listener)
52+
{
53+
std::unique_lock lock(mutex_);
54+
eventListeners_.push_back(std::move(listener));
55+
}
56+
57+
void removeListener(const std::shared_ptr<const EventListenerT<TArgs...>> &listener)
58+
{
59+
std::unique_lock lock(mutex_);
60+
auto it = std::find(eventListeners_.begin(), eventListeners_.end(), listener);
61+
if (it != eventListeners_.end()) {
62+
eventListeners_.erase(it);
63+
}
64+
}
65+
66+
private:
67+
std::shared_mutex mutex_;
68+
std::vector<std::shared_ptr<const EventListenerT<TArgs...>>> eventListeners_;
69+
};
70+
71+
using EventEmitterListener = EventListenerT<Tag, const std::string &, const EventPayload &>;
72+
using EventEmitterListenerContainer = EventListenerContainerT<Tag, const std::string &, const EventPayload &>;
73+
74+
} // namespace facebook::react
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#pragma once
9+
10+
#include <react/cxxstableapi/PrivateGuard.h>
11+
12+
#import <React/RCTEventDispatcherProtocol.h>
13+
#import <react/renderer/core/EventPayload.h>
14+
15+
namespace facebook::react {
16+
17+
/*
18+
* Event payload for events native code delivers to RCTEventDispatcher
19+
* observers (`notifyObserversOfEvent:` or the
20+
* `RCTNotifyEventDispatcherObserversOfEvent_DEPRECATED` notification) rather
21+
* than through a Fabric event emitter. Some libraries send events this way so
22+
* that native-driven Animated.event mappings receive values their Fabric event
23+
* payloads cannot provide to C++.
24+
*
25+
* RCTInstance wraps each component RCTEvent (arguments
26+
* `@[viewTag, eventName, body]`) in this payload and passes it to the C++
27+
* listeners in `RCTEventDispatcherListeners`, which C++ Native Animated reads
28+
* with extractValue(). Values are read from the `NSDictionary` body on demand,
29+
* so events that no listener reads are not converted.
30+
*
31+
* Only C++ listeners receive it; JS receives these events separately, so it is
32+
* never dispatched to JS.
33+
*/
34+
class RCTEventDispatcherEventPayload : public EventPayload {
35+
public:
36+
explicit RCTEventDispatcherEventPayload(id<RCTEvent> event);
37+
38+
jsi::Value asJSIValue(jsi::Runtime &runtime) const override;
39+
EventPayloadType getType() const override;
40+
std::optional<double> extractValue(const std::vector<std::string> &path) const override;
41+
42+
private:
43+
id body() const;
44+
45+
id<RCTEvent> event_;
46+
};
47+
48+
} // namespace facebook::react
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#import "RCTEventDispatcherEventPayload.h"
9+
10+
#import <React/RCTLog.h>
11+
12+
namespace facebook::react {
13+
14+
RCTEventDispatcherEventPayload::RCTEventDispatcherEventPayload(id<RCTEvent> event) : event_(event) {}
15+
16+
jsi::Value RCTEventDispatcherEventPayload::asJSIValue(jsi::Runtime & /*runtime*/) const
17+
{
18+
// RCTInstance passes this payload only to the C++ listeners in
19+
// `RCTEventDispatcherListeners`, which read values with extractValue(). JS
20+
// receives these events separately, so reaching here means a listener started
21+
// forwarding it to JS.
22+
RCTLogError(@"RCTEventDispatcherEventPayload cannot be converted to a JS value");
23+
return jsi::Value::null();
24+
}
25+
26+
EventPayloadType RCTEventDispatcherEventPayload::getType() const
27+
{
28+
return EventPayloadType::ValueFactory;
29+
}
30+
31+
std::optional<double> RCTEventDispatcherEventPayload::extractValue(const std::vector<std::string> &path) const
32+
{
33+
id value = body();
34+
for (const auto &key : path) {
35+
if ([value isKindOfClass:[NSDictionary class]]) {
36+
value = ((NSDictionary *)value)[@(key.c_str())];
37+
} else if ([value isKindOfClass:[NSArray class]]) {
38+
char *end = nullptr;
39+
auto index = std::strtoul(key.c_str(), &end, 10);
40+
if (key.empty() || *end != '\0' || index >= ((NSArray *)value).count) {
41+
return std::nullopt;
42+
}
43+
value = ((NSArray *)value)[index];
44+
} else {
45+
return std::nullopt;
46+
}
47+
}
48+
if ([value isKindOfClass:[NSNumber class]]) {
49+
return [value doubleValue];
50+
}
51+
return std::nullopt;
52+
}
53+
54+
id RCTEventDispatcherEventPayload::body() const
55+
{
56+
// Component events (`+moduleDotMethod` is `RCTEventEmitter.receiveEvent`)
57+
// carry `@[viewTag, eventName, body]`; RCTInstance forwards only those. Other
58+
// events, e.g. touches (`@[eventName, touches, changedIndexes]`), lay out
59+
// their arguments differently.
60+
NSArray *arguments = event_.arguments;
61+
return arguments.count > 2 ? arguments[2] : nil;
62+
}
63+
64+
} // namespace facebook::react

‎packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,14 @@
3939
#import <jsinspector-modern/ReactCdp.h>
4040
#import <jsireact/JSIExecutor.h>
4141
#import <react/featureflags/ReactNativeFeatureFlags.h>
42+
#import <react/renderer/core/EventEmitterListener.h>
4243
#import <react/runtime/ReactInstance.h>
4344
#import <react/utils/ContextContainer.h>
4445
#import <react/utils/FollyConvert.h>
4546
#import <react/utils/ManagedObjectWrapper.h>
4647

4748
#import "ObjCTimerRegistry.h"
49+
#import "RCTEventDispatcherEventPayload.h"
4850
#import "RCTJSThreadManager.h"
4951
#ifndef RCT_REMOVE_LEGACY_COMPONENT_INTEROP
5052
#import "RCTLegacyUIManagerConstantsProvider.h"
@@ -58,7 +60,7 @@
5860
using namespace facebook;
5961
using namespace facebook::react;
6062

61-
@interface RCTInstance () <RCTTurboModuleManagerDelegate>
63+
@interface RCTInstance () <RCTTurboModuleManagerDelegate, RCTEventDispatcherObserver>
6264
@end
6365

6466
@implementation RCTInstance {
@@ -83,6 +85,8 @@ @implementation RCTInstance {
8385
RCTDevMenuConfigurationDecorator *_devMenuConfigurationDecorator;
8486

8587
jsinspector_modern::HostTarget *_parentInspectorTarget;
88+
89+
std::shared_ptr<EventEmitterListenerContainer> _eventDispatcherListeners;
8690
}
8791

8892
#pragma mark - Public
@@ -227,6 +231,24 @@ - (void)registerSegmentWithId:(NSNumber *)segmentId path:(NSString *)path
227231
}
228232
}
229233

234+
#pragma mark - RCTEventDispatcherObserver
235+
236+
- (void)eventDispatcherWillDispatchEvent:(id<RCTEvent>)event
237+
{
238+
// Only component events carry `@[viewTag, eventName, body]` as their arguments.
239+
Class<RCTEvent> eventClass = [event class];
240+
if (![[eventClass moduleDotMethod] isEqualToString:@"RCTEventEmitter.receiveEvent"]) {
241+
return;
242+
}
243+
auto listeners = _eventDispatcherListeners;
244+
auto tag = static_cast<Tag>(event.viewTag.integerValue);
245+
auto eventName = std::string(event.eventName.UTF8String ?: "");
246+
// Listeners run on the main thread, where C++ Native Animated handles events.
247+
RCTExecuteOnMainQueue(^{
248+
listeners->willDispatchEvent(tag, eventName, RCTEventDispatcherEventPayload(event));
249+
});
250+
}
251+
230252
#pragma mark - RCTTurboModuleManagerDelegate
231253

232254
- (Class)getModuleClassFromName:(const char *)name
@@ -384,6 +406,13 @@ - (void)_start
384406
contextContainer->insert(
385407
"RCTEventDispatcher",
386408
facebook::react::wrapManagedObject([_turboModuleManager moduleForName:"RCTEventDispatcher"]));
409+
if (ReactNativeFeatureFlags::cxxNativeAnimatedEnabled()) {
410+
// Lets C++ Native Animated receive events that native code delivers only to RCTEventDispatcher
411+
// observers, outside Fabric event emitters.
412+
_eventDispatcherListeners = std::make_shared<EventEmitterListenerContainer>();
413+
contextContainer->insert("RCTEventDispatcherListeners", _eventDispatcherListeners);
414+
[[_turboModuleManager moduleForName:"RCTEventDispatcher"] addDispatchObserver:self];
415+
}
387416
contextContainer->insert("RCTBridgeModuleDecorator", facebook::react::wrapManagedObject(_bridgeModuleDecorator));
388417
contextContainer->insert(RuntimeSchedulerKey, std::weak_ptr<RuntimeScheduler>(_reactInstance->getRuntimeScheduler()));
389418
contextContainer->insert("RCTBridgeProxy", facebook::react::wrapManagedObject(bridgeProxy));

0 commit comments

Comments
 (0)