Remove legacy event dispatching logic (#55802)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/55802

Remove legacy Paper event emitters and deprecated methods (`receiveTouches`). InteropEvent still functions as before otherwise, and I've kept the `event.dispatch` API (although I believe events without a surface ID are dropped later in the pipeline?)

Changelog: [Android][Removed] Removed Paper-specific event dispatching methods.

Reviewed By: cortinico

Differential Revision: D91320248

fbshipit-source-id: a3228593c72a4286f7aac781d446fc3b0b1bd4ff
This commit is contained in:
Pieter De Baets authored and meta-codesync[bot] committed 2026-02-27 08:52:37 -08:00
1 parent f7091b437e
commit 05d64d9316
15 files changed
+35 -663

No files matched your search

@@ -4846,19 +4846,23 @@ public final class com/facebook/react/uimanager/events/NativeGestureUtil {
public abstract interface class com/facebook/react/uimanager/events/RCTEventEmitter : com/facebook/react/bridge/JavaScriptModule {
public abstract fun receiveEvent (ILjava/lang/String;Lcom/facebook/react/bridge/WritableMap;)V
public abstract fun receiveTouches (Ljava/lang/String;Lcom/facebook/react/bridge/WritableArray;Lcom/facebook/react/bridge/WritableArray;)V
}
public abstract interface class com/facebook/react/uimanager/events/RCTModernEventEmitter : com/facebook/react/uimanager/events/RCTEventEmitter {
public abstract fun receiveEvent (IILjava/lang/String;Lcom/facebook/react/bridge/WritableMap;)V
public abstract fun receiveEvent (IILjava/lang/String;ZILcom/facebook/react/bridge/WritableMap;I)V
public abstract fun receiveEvent (ILjava/lang/String;Lcom/facebook/react/bridge/WritableMap;)V
}
public final class com/facebook/react/uimanager/events/RCTModernEventEmitter$DefaultImpls {
public static fun receiveEvent (Lcom/facebook/react/uimanager/events/RCTModernEventEmitter;IILjava/lang/String;Lcom/facebook/react/bridge/WritableMap;)V
public static fun receiveEvent (Lcom/facebook/react/uimanager/events/RCTModernEventEmitter;ILjava/lang/String;Lcom/facebook/react/bridge/WritableMap;)V
}
public final class com/facebook/react/uimanager/events/TouchEvent : com/facebook/react/uimanager/events/Event {
public static final field Companion Lcom/facebook/react/uimanager/events/TouchEvent$Companion;
public static final field UNSET J
public fun canCoalesce ()Z
public fun dispatch (Lcom/facebook/react/uimanager/events/RCTEventEmitter;)V
public fun dispatchModern (Lcom/facebook/react/uimanager/events/RCTModernEventEmitter;)V
public fun getCoalescingKey ()S
public fun getEventCategory ()I
@@ -11,7 +11,6 @@ import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.ReadableType
import com.facebook.react.bridge.UnexpectedNativeTypeException
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.uimanager.events.EventCategoryDef
import com.facebook.react.uimanager.events.RCTModernEventEmitter
@@ -23,31 +22,6 @@ internal class EventAnimationDriver(
private val eventPath: List<String>,
@JvmField internal var valueNode: ValueAnimatedNode,
) : RCTModernEventEmitter {
@Deprecated(
"Deprecated in Java",
ReplaceWith("receiveEvent(surfaceId, targetTag, eventName, params)"),
)
override fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?) =
receiveEvent(-1, targetTag, eventName, params)
override fun receiveEvent(
surfaceId: Int,
targetTag: Int,
eventName: String,
params: WritableMap?,
) =
// We assume this event can't be coalesced. `customCoalesceKey` has no meaning in Fabric.
receiveEvent(surfaceId, targetTag, eventName, false, 0, params, EventCategoryDef.UNSPECIFIED)
@Deprecated("Deprecated in Java")
override fun receiveTouches(
eventName: String,
touches: WritableArray,
changedIndices: WritableArray,
) {
throw UnsupportedOperationException("receiveTouches is not support by native animated events")
}
override fun receiveEvent(
surfaceId: Int,
targetTag: Int,
@@ -7,32 +7,13 @@
package com.facebook.react.fabric.events
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.fabric.FabricUIManager
import com.facebook.react.uimanager.common.ViewUtil
import com.facebook.react.uimanager.events.EventCategoryDef
import com.facebook.react.uimanager.events.RCTModernEventEmitter
import com.facebook.systrace.Systrace
internal class FabricEventEmitter(private val uiManager: FabricUIManager) : RCTModernEventEmitter {
@Deprecated(
"Use receiveEvent with surfaceId instead.",
ReplaceWith("receiveEvent(surfaceId, targetTag, eventName, params)"),
)
override fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?): Unit {
receiveEvent(ViewUtil.NO_SURFACE_ID, targetTag, eventName, params)
}
override fun receiveEvent(
surfaceId: Int,
targetTag: Int,
eventName: String,
params: WritableMap?,
) {
receiveEvent(surfaceId, targetTag, eventName, false, 0, params, EventCategoryDef.UNSPECIFIED)
}
override fun receiveEvent(
surfaceId: Int,
targetTag: Int,
@@ -49,14 +30,4 @@ internal class FabricEventEmitter(private val uiManager: FabricUIManager) : RCTM
Systrace.endSection(Systrace.TRACE_TAG_REACT)
}
}
/** Touches are dispatched by [receiveTouches] */
@Deprecated("Deprecated in Java")
override fun receiveTouches(
eventName: String,
touches: WritableArray,
changedIndices: WritableArray,
): Unit {
throw UnsupportedOperationException("EventEmitter#receiveTouches is not supported by Fabric")
}
}
@@ -10,7 +10,6 @@
package com.facebook.react.internal.interop
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.common.annotations.VisibleForTesting
import com.facebook.react.common.annotations.internal.InteropLegacyArchitecture
@@ -36,24 +35,11 @@ internal class InteropEventEmitter(private val reactContext: ReactContext) : RCT
@Deprecated("Deprecated in Java")
override fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?) {
val dispatcher: EventDispatcher? =
eventDispatcherOverride
?: UIManagerHelper.getEventDispatcherForReactTag(reactContext, targetTag)
val dispatcher = eventDispatcherOverride ?: UIManagerHelper.getEventDispatcher(reactContext)
val surfaceId = UIManagerHelper.getSurfaceId(reactContext)
dispatcher?.dispatchEvent(InteropEvent(eventName, params, surfaceId, targetTag))
}
@Deprecated("Deprecated in Java")
override fun receiveTouches(
eventName: String,
touches: WritableArray,
changedIndices: WritableArray,
) {
throw UnsupportedOperationException(
"EventEmitter#receiveTouches is not supported by the Fabric Interop Layer"
)
}
@VisibleForTesting
fun overrideEventDispatcher(eventDispatcherOverride: EventDispatcher?) {
this.eventDispatcherOverride = eventDispatcherOverride
@@ -44,7 +44,6 @@ import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.common.ViewUtil;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.EventDispatcherImpl;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.facebook.react.uimanager.internal.LegacyArchitectureShadowNodeLogger;
import com.facebook.systrace.Systrace;
@@ -107,7 +106,6 @@ public class UIManagerModule extends ReactContextBaseJavaModule
private static final boolean DEBUG =
PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.UI_MANAGER);
private final EventDispatcher mEventDispatcher;
private final Map<String, Object> mModuleConstants;
private final Map<String, Object> mCustomDirectEvents;
private final ViewManagerRegistry mViewManagerRegistry;
@@ -121,11 +119,9 @@ public class UIManagerModule extends ReactContextBaseJavaModule
int minTimeLeftInFrameForNonBatchedOperationMs) {
super(reactContext);
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
mEventDispatcher = new EventDispatcherImpl(reactContext);
mModuleConstants = createConstants(viewManagerResolver);
mCustomDirectEvents = UIManagerModuleConstants.directEventTypeConstants;
mViewManagerRegistry = new ViewManagerRegistry(viewManagerResolver);
reactContext.addLifecycleEventListener(this);
}
@@ -135,11 +131,9 @@ public class UIManagerModule extends ReactContextBaseJavaModule
int minTimeLeftInFrameForNonBatchedOperationMs) {
super(reactContext);
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
mEventDispatcher = new EventDispatcherImpl(reactContext);
mCustomDirectEvents = MapBuilder.newHashMap();
mModuleConstants = createConstants(viewManagersList, null, mCustomDirectEvents);
mViewManagerRegistry = new ViewManagerRegistry(viewManagersList);
if (ReactBuildConfig.DEBUG) {
for (ViewManager<?, ?> viewManager : viewManagersList) {
LegacyArchitectureShadowNodeLogger.assertUnsupportedViewManager(
@@ -178,7 +172,6 @@ public class UIManagerModule extends ReactContextBaseJavaModule
@Override
public void invalidate() {
super.invalidate();
mEventDispatcher.onCatalystInstanceDestroyed();
ReactApplicationContext reactApplicationContext = getReactApplicationContext();
reactApplicationContext.unregisterComponentCallbacks(mMemoryTrimCallback);
@@ -571,7 +564,7 @@ public class UIManagerModule extends ReactContextBaseJavaModule
@Override
public EventDispatcher getEventDispatcher() {
return mEventDispatcher;
return null;
}
@ReactMethod
@@ -1,336 +0,0 @@
/*
* 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.uimanager.events
import android.util.LongSparseArray
import android.view.Choreographer
import com.facebook.react.bridge.LifecycleEventListener
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.UiThreadUtil.assertOnUiThread
import com.facebook.react.bridge.UiThreadUtil.runOnUiThread
import com.facebook.react.common.annotations.internal.InteropLegacyArchitecture
import com.facebook.react.modules.core.ReactChoreographer
import com.facebook.systrace.Systrace
import java.util.Arrays
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
/**
* Class responsible for dispatching UI events to JS. The main purpose of this class is to act as an
* intermediary between UI code generating events and JS, making sure we don't send more events than
* JS can process.
*
* To use it, create a subclass of [Event] and call [dispatchEvent] whenever there's a UI event to
* dispatch.
*
* This class works by installing a [Choreographer] frame callback on the main thread. This callback
* then enqueues a runnable on the JS thread (if one is not already pending) that is responsible for
* actually dispatch events to JS. This implementation depends on the properties that
* 1) FrameCallbacks run after UI events have been processed in [Choreographer]
* 2) when we enqueue a runnable on the JS queue thread, it won't be called until after any
* previously enqueued JS jobs have finished processing
*
* If JS is taking a long time processing events, then the UI events generated on the UI thread can
* be coalesced into fewer events so that when the runnable runs, we don't overload JS with a ton of
* events and make it get even farther behind.
*
* Ideally, we don't need this and JS is fast enough to process all the events each frame, but bad
* things happen, including load on CPUs from the system, and we should handle this case well.
*
* # Event Cookies
*
* An event cookie is made up of the event type id, view tag, and a custom coalescing key. Only
* Events that have the same cookie can be coalesced.
*
* Event Cookie Composition: VIEW_TAG_MASK = 0x00000000ffffffff EVENT_TYPE_ID_MASK =
* 0x0000ffff00000000 COALESCING_KEY_MASK = 0xffff000000000000
*/
@InteropLegacyArchitecture
internal class EventDispatcherImpl(private val reactContext: ReactApplicationContext) :
EventDispatcher, LifecycleEventListener {
private val eventsStagingLock = Any()
private val eventsToDispatchLock = Any()
private val eventCookieToLastEventIdx = LongSparseArray<Int>()
private val eventNameToEventId: MutableMap<String, Short> = mutableMapOf()
private val dispatchEventsRunnable: DispatchEventsRunnable = DispatchEventsRunnable()
private val eventStaging = ArrayList<Event<*>>()
private val listeners = CopyOnWriteArrayList<EventDispatcherListener>()
private val postEventDispatchListeners = CopyOnWriteArrayList<BatchEventDispatchedListener>()
private val currentFrameCallback: ScheduleDispatchFrameCallback = ScheduleDispatchFrameCallback()
private val hasDispatchScheduledCount = AtomicInteger()
private var eventsToDispatch: Array<Event<*>?> = arrayOfNulls(16)
private var eventsToDispatchSize = 0
private val reactEventEmitter: EventEmitterImpl
private var nextEventTypeId: Short = 0
@Volatile private var hasDispatchScheduled = false
init {
reactContext.addLifecycleEventListener(this)
reactEventEmitter = EventEmitterImpl(reactContext)
}
/** Sends the given Event to JS, coalescing eligible events if JS is backed up. */
override fun dispatchEvent(event: Event<*>) {
require(event.isInitialized) { "Dispatched event hasn't been initialized" }
for (listener in listeners) {
listener.onEventDispatch(event)
}
synchronized(eventsStagingLock) {
eventStaging.add(event)
Systrace.startAsyncFlow(Systrace.TRACE_TAG_REACT, event.getEventName(), event.uniqueID)
}
maybePostFrameCallbackFromNonUI()
}
override fun dispatchAllEvents() {
maybePostFrameCallbackFromNonUI()
}
private fun maybePostFrameCallbackFromNonUI() {
currentFrameCallback.maybePostFromNonUI()
}
/** Add a listener to this EventDispatcher. */
override fun addListener(listener: EventDispatcherListener) {
listeners.add(listener)
}
/** Remove a listener from this EventDispatcher. */
override fun removeListener(listener: EventDispatcherListener) {
listeners.remove(listener)
}
override fun addBatchEventDispatchedListener(listener: BatchEventDispatchedListener) {
postEventDispatchListeners.add(listener)
}
override fun removeBatchEventDispatchedListener(listener: BatchEventDispatchedListener) {
postEventDispatchListeners.remove(listener)
}
override fun onHostResume() {
maybePostFrameCallbackFromNonUI()
}
override fun onHostPause() {
stopFrameCallback()
}
override fun onHostDestroy() {
stopFrameCallback()
}
@Deprecated("Private API, should only be used when the concrete implementation is known.")
override fun onCatalystInstanceDestroyed() {
runOnUiThread { this.stopFrameCallback() }
}
private fun stopFrameCallback() {
assertOnUiThread()
currentFrameCallback.stop()
}
/**
* We use a staging data structure so that all UI events generated in a single frame are
* dispatched at once. Otherwise, a JS runnable enqueued in a previous frame could run while the
* UI thread is in the process of adding UI events and we might incorrectly send one event this
* frame and another from this frame during the next.
*/
private fun moveStagedEventsToDispatchQueue() {
synchronized(eventsStagingLock) {
synchronized(eventsToDispatchLock) {
for (i in eventStaging.indices) {
val event: Event<*> = eventStaging[i]
if (!event.canCoalesce()) {
addEventToEventsToDispatch(event)
continue
}
val eventCookie =
getEventCookie(event.viewTag, event.getEventName(), event.getCoalescingKey())
var eventToAdd: Event<*>? = null
var eventToDispose: Event<*>? = null
val lastEventIdx = eventCookieToLastEventIdx[eventCookie]
if (lastEventIdx == null) {
eventToAdd = event
eventCookieToLastEventIdx.put(eventCookie, eventsToDispatchSize)
} else {
val lastEvent: Event<*> = checkNotNull(eventsToDispatch[lastEventIdx])
val coalescedEvent = event.coalesce(lastEvent)
if (coalescedEvent !== lastEvent) {
eventToAdd = coalescedEvent
eventCookieToLastEventIdx.put(eventCookie, eventsToDispatchSize)
eventToDispose = lastEvent
eventsToDispatch[lastEventIdx] = null
} else {
eventToDispose = event
}
}
if (eventToAdd != null) {
addEventToEventsToDispatch(eventToAdd)
}
eventToDispose?.dispose()
}
}
eventStaging.clear()
}
}
private fun getEventCookie(viewTag: Int, eventName: String, coalescingKey: Short): Long {
val eventTypeId: Short
val eventIdObj = eventNameToEventId[eventName]
if (eventIdObj != null) {
eventTypeId = eventIdObj
} else {
eventTypeId = nextEventTypeId++
eventNameToEventId[eventName] = eventTypeId
}
return getEventCookie(viewTag, eventTypeId, coalescingKey)
}
private inner class ScheduleDispatchFrameCallback : Choreographer.FrameCallback {
@Volatile private var isPosted = false
private var shouldStop = false
override fun doFrame(frameTimeNanos: Long) {
assertOnUiThread()
if (shouldStop) {
isPosted = false
} else {
post()
}
Systrace.beginSection(Systrace.TRACE_TAG_REACT, "ScheduleDispatchFrameCallback")
try {
moveStagedEventsToDispatchQueue()
if (!hasDispatchScheduled) {
hasDispatchScheduled = true
Systrace.startAsyncFlow(
Systrace.TRACE_TAG_REACT,
"ScheduleDispatchFrameCallback",
hasDispatchScheduledCount.get(),
)
reactContext.runOnJSQueueThread(dispatchEventsRunnable)
}
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT)
}
}
fun stop() {
shouldStop = true
}
fun maybePost() {
if (!isPosted) {
isPosted = true
post()
}
}
fun post() {
ReactChoreographer.getInstance()
.postFrameCallback(ReactChoreographer.CallbackType.TIMERS_EVENTS, currentFrameCallback)
}
fun maybePostFromNonUI() {
if (isPosted) {
return
}
// We should only hit this slow path when we receive events while the host activity is paused.
if (reactContext.isOnUiQueueThread) {
maybePost()
} else {
reactContext.runOnUiQueueThread { maybePost() }
}
}
}
private inner class DispatchEventsRunnable : Runnable {
override fun run() {
Systrace.beginSection(Systrace.TRACE_TAG_REACT, "DispatchEventsRunnable")
try {
Systrace.endAsyncFlow(
Systrace.TRACE_TAG_REACT,
"ScheduleDispatchFrameCallback",
hasDispatchScheduledCount.getAndIncrement(),
)
hasDispatchScheduled = false
synchronized(eventsToDispatchLock) {
if (eventsToDispatchSize > 0) {
// We avoid allocating an array and iterator, and "sorting" if we don't need to.
// This occurs when the size of mEventsToDispatch is zero or one.
if (eventsToDispatchSize > 1) {
Arrays.sort(eventsToDispatch, 0, eventsToDispatchSize, EVENT_COMPARATOR)
}
for (eventIdx in 0..<eventsToDispatchSize) {
val event = eventsToDispatch[eventIdx] ?: continue
// Event can be null if it has been coalesced into another event.
Systrace.endAsyncFlow(Systrace.TRACE_TAG_REACT, event.getEventName(), event.uniqueID)
event.dispatchModern(reactEventEmitter)
event.dispose()
}
clearEventsToDispatch()
eventCookieToLastEventIdx.clear()
}
}
for (listener in postEventDispatchListeners) {
listener.onBatchEventDispatched()
}
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT)
}
}
}
private fun addEventToEventsToDispatch(event: Event<*>) {
if (eventsToDispatchSize == eventsToDispatch.size) {
eventsToDispatch = eventsToDispatch.copyOf(2 * eventsToDispatch.size)
}
eventsToDispatch[eventsToDispatchSize++] = event
}
private fun clearEventsToDispatch() {
Arrays.fill(eventsToDispatch, 0, eventsToDispatchSize, null)
eventsToDispatchSize = 0
}
companion object {
private val EVENT_COMPARATOR: java.util.Comparator<Event<*>?> =
java.util.Comparator { lhs, rhs ->
when {
lhs == null && rhs == null -> 0
lhs == null -> -1
rhs == null -> 1
else -> {
val diff = lhs.timestampMs - rhs.timestampMs
when {
diff == 0L -> 0
diff < 0 -> -1
else -> 1
}
}
}
}
private fun getEventCookie(viewTag: Int, eventTypeId: Short, coalescingKey: Short): Long =
(viewTag.toLong() or
(((eventTypeId.toLong()) and 0xffffL) shl 32) or
(((coalescingKey.toLong()) and 0xffffL) shl 48))
}
}
@@ -1,135 +0,0 @@
/*
* 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.
*/
// RCTEventEmitter usage throughout:
@file:Suppress("DEPRECATION")
package com.facebook.react.uimanager.events
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactNoCrashSoftException
import com.facebook.react.bridge.ReactSoftExceptionLogger.logSoftException
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.common.annotations.internal.InteropLegacyArchitecture
import com.facebook.react.uimanager.common.UIManagerType
import com.facebook.react.uimanager.common.ViewUtil.getUIManagerType
/**
* This class handles event emitting across the legacy and Fabric event emitting mechanisms. Based
* on the surfaceId and targetTag, it will route the event to the appropriate event emitter. It
* shims the RCTModernEventEmitter API for legacy Paper events.
*
* This class is constructed both by Paper's EventDispatcherImpl and the FabricEventDispatcher.
*/
@InteropLegacyArchitecture
internal class EventEmitterImpl(
private val reactContext: ReactApplicationContext,
) : RCTModernEventEmitter {
/** Corresponds to (Paper) EventEmitter, which is a JS interface */
private var legacyEventEmitter: RCTEventEmitter? = null
/** Corresponds to [com.facebook.react.fabric.events.FabricEventEmitter] */
private var fabricEventEmitter: RCTModernEventEmitter? = null
fun registerFabricEventEmitter(eventEmitter: RCTModernEventEmitter?) {
fabricEventEmitter = eventEmitter
}
@Deprecated(
"Please use RCTModernEventEmitter instead",
ReplaceWith("RCTModernEventEmitter.receiveEvent(surfaceId, targetTag, eventName, params)"),
)
override fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?) {
receiveEvent(-1, targetTag, eventName, params)
}
override fun receiveEvent(
surfaceId: Int,
targetTag: Int,
eventName: String,
params: WritableMap?,
) {
// We assume this event can't be coalesced. `customCoalesceKey` has no meaning in Fabric.
receiveEvent(surfaceId, targetTag, eventName, false, 0, params, EventCategoryDef.UNSPECIFIED)
}
/*
* This method should be unused by Fabric event processing pipeline, but leaving it here to make sure
* that any custom code using it in legacy renderer is compatible
*/
@Deprecated("Dispatch the TouchEvent using [EventDispatcher] instead")
override fun receiveTouches(
eventName: String,
touches: WritableArray,
changedIndices: WritableArray,
) {
check(touches.size() > 0)
val reactTag = touches.getMap(0)?.getInt(TouchesHelper.TARGET_KEY) ?: 0
@UIManagerType val uiManagerType = getUIManagerType(reactTag)
if (uiManagerType == UIManagerType.LEGACY) {
ensureLegacyEventEmitter()?.receiveTouches(eventName, touches, changedIndices)
}
}
/**
* Get default/Paper event emitter. Callers should have verified that this is not an event for a
* View managed by Fabric
*/
private fun ensureLegacyEventEmitter(): RCTEventEmitter? {
if (legacyEventEmitter == null) {
if (reactContext.hasActiveReactInstance()) {
legacyEventEmitter = reactContext.getJSModule(RCTEventEmitter::class.java)
} else {
logSoftException(
TAG,
ReactNoCrashSoftException(
"Cannot get RCTEventEmitter without active Catalyst instance!"
),
)
}
}
return legacyEventEmitter
}
override fun receiveEvent(
surfaceId: Int,
targetTag: Int,
eventName: String,
canCoalesceEvent: Boolean,
customCoalesceKey: Int,
params: WritableMap?,
@EventCategoryDef category: Int,
) {
@UIManagerType val uiManagerType = getUIManagerType(targetTag, surfaceId)
if (uiManagerType == UIManagerType.FABRIC) {
val fabricEventEmitter = fabricEventEmitter
if (fabricEventEmitter == null) {
logSoftException(
TAG,
ReactNoCrashSoftException("No fabricEventEmitter registered, cannot dispatch event"),
)
} else {
fabricEventEmitter.receiveEvent(
surfaceId,
targetTag,
eventName,
canCoalesceEvent,
customCoalesceKey,
params,
category,
)
}
} else if (uiManagerType == UIManagerType.LEGACY) {
ensureLegacyEventEmitter()?.receiveEvent(targetTag, eventName, params)
}
}
companion object {
private const val TAG = "ReactEventEmitter"
}
}
@@ -31,17 +31,14 @@ private const val TAG = "FabricEventDispatcher"
*/
internal class FabricEventDispatcher(
private val reactContext: ReactApplicationContext,
fabricEventEmitter: RCTModernEventEmitter,
private val eventEmitter: RCTModernEventEmitter,
) : EventDispatcher, LifecycleEventListener {
// TODO: Remove EventEmitterImpl indirection when new Fabric is fully rolled out
private val eventEmitter = EventEmitterImpl(reactContext)
private val listeners = CopyOnWriteArrayList<EventDispatcherListener>()
private val postEventDispatchListeners = CopyOnWriteArrayList<BatchEventDispatchedListener>()
private val currentFrameCallback = ScheduleDispatchFrameCallback()
init {
reactContext.addLifecycleEventListener(this)
eventEmitter.registerFabricEventEmitter(fabricEventEmitter)
}
override fun dispatchEvent(event: Event<*>) {
@@ -129,8 +126,6 @@ internal class FabricEventDispatcher(
}
fun invalidate() {
eventEmitter.registerFabricEventEmitter(null)
UiThreadUtil.runOnUiThread { cancelDispatchOfBatchedEvents() }
}
@@ -9,7 +9,6 @@ package com.facebook.react.uimanager.events
import com.facebook.proguard.annotations.DoNotStripAny
import com.facebook.react.bridge.JavaScriptModule
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.common.annotations.internal.InteropLegacyArchitecture
@@ -29,18 +28,4 @@ public interface RCTEventEmitter : JavaScriptModule {
*/
@Deprecated("Use [RCTModernEventEmitter.receiveEvent] instead")
public fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?)
/**
* Receive and process touches
*
* @param eventName JS event name
* @param touches active pointers data
* @param changedIndices indices of changed pointers
*/
@Deprecated("Dispatch the TouchEvent using [EventDispatcher] instead")
public fun receiveTouches(
eventName: String,
touches: WritableArray,
changedIndices: WritableArray,
)
}
@@ -20,7 +20,18 @@ import com.facebook.react.bridge.WritableMap
*/
@Suppress("DEPRECATION")
public interface RCTModernEventEmitter : RCTEventEmitter {
public fun receiveEvent(surfaceId: Int, targetTag: Int, eventName: String, params: WritableMap?)
@Deprecated(
"Use RCTModernEventEmitter",
ReplaceWith("RCTModernEventEmitter.receiveEvent(surfaceId, targetTag, eventName, params)"),
)
override fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?) {
receiveEvent(-1, targetTag, eventName, params)
}
public fun receiveEvent(surfaceId: Int, targetTag: Int, eventName: String, params: WritableMap?) {
// We assume this event can't be coalesced. `customCoalesceKey` has no meaning in Fabric.
receiveEvent(surfaceId, targetTag, eventName, false, 0, params, EventCategoryDef.UNSPECIFIED)
}
public fun receiveEvent(
surfaceId: Int,
@@ -14,8 +14,6 @@ import androidx.core.util.Pools.SynchronizedPool
import com.facebook.infer.annotation.Assertions
import com.facebook.react.bridge.ReactSoftExceptionLogger
import com.facebook.react.bridge.SoftAssertions
import com.facebook.react.uimanager.common.UIManagerType
import com.facebook.react.uimanager.common.ViewUtil.getUIManagerType
import com.facebook.react.uimanager.events.TouchEventType.Companion.getJSEventName
/**
@@ -115,25 +113,12 @@ public class TouchEvent private constructor() : Event<TouchEvent>() {
override fun getCoalescingKey(): Short = coalescingKey
@Deprecated("Deprecated in Java")
override fun dispatch(rctEventEmitter: RCTEventEmitter) {
if (verifyMotionEvent()) {
TouchesHelper.sendTouchesLegacy(rctEventEmitter, this)
}
}
override fun dispatchModern(rctEventEmitter: RCTModernEventEmitter) {
if (!verifyMotionEvent()) {
return
}
@UIManagerType val uiManagerType = getUIManagerType(viewTag, surfaceId)
if (uiManagerType == UIManagerType.FABRIC) {
// TouchesHelper.sendTouchEvent can be inlined here post Fabric rollout
TouchesHelper.sendTouchEvent(rctEventEmitter, this)
} else if (uiManagerType == UIManagerType.LEGACY) {
TouchesHelper.sendTouchesLegacy(rctEventEmitter, this)
}
TouchesHelper.sendTouchEvent(rctEventEmitter, this)
}
public override fun getEventCategory(): Int {
@@ -11,7 +11,6 @@ import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.uimanager.PixelUtil.pxToDp
import com.facebook.react.uimanager.events.TouchEventType.Companion.getJSEventName
import com.facebook.systrace.Systrace
/**
@@ -77,38 +76,6 @@ internal object TouchesHelper {
return touches
}
/**
* Generate and send touch event to RCTEventEmitter JS module associated with the given {@param *
* context} for legacy renderer. Touch event can encode multiple concurrent touches (pointers).
*
* @param rctEventEmitter Event emitter used to execute JS module call
* @param touchEvent native touch event to read pointers count and coordinates from
*/
@Suppress("DEPRECATION")
@JvmStatic
fun sendTouchesLegacy(rctEventEmitter: RCTEventEmitter, touchEvent: TouchEvent) {
val type = touchEvent.getTouchEventType()
val pointers = getWritableArray(/* copyObjects */ false, createPointersArray(touchEvent))
val motionEvent = touchEvent.getMotionEvent()
// For START and END events send only index of the pointer that is associated with that event
// For MOVE and CANCEL events 'changedIndices' array should contain all the pointers indices
val changedIndices = Arguments.createArray()
if (type == TouchEventType.MOVE || type == TouchEventType.CANCEL) {
for (i in 0 until motionEvent.pointerCount) {
changedIndices.pushInt(i)
}
} else if (type == TouchEventType.START || type == TouchEventType.END) {
changedIndices.pushInt(motionEvent.actionIndex)
} else {
throw RuntimeException("Unknown touch type: $type")
}
@Suppress("DEPRECATION")
rctEventEmitter.receiveTouches(getJSEventName(type), pointers, changedIndices)
}
/**
* Generate touch event data to match JS expectations. Combines logic in [sendTouchEvent] and
* [com.facebook.react.fabric.events.FabricEventEmitter] to create the same data structure in a
@@ -1,29 +0,0 @@
/*
* 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.
*/
@file:Suppress("DEPRECATION") // Suppressing as we want to fake a RCTEventEmitter here
package com.facebook.react.bridge.interop
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.common.annotations.UnstableReactNativeAPI
import com.facebook.react.uimanager.events.RCTEventEmitter
@UnstableReactNativeAPI
class FakeRCTEventEmitter : RCTEventEmitter {
@Deprecated("Deprecated in Java")
override fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?) = Unit
@Deprecated("Deprecated in Java")
override fun receiveTouches(
eventName: String,
touches: WritableArray,
changedIndices: WritableArray,
) = Unit
}
@@ -5,17 +5,17 @@
* LICENSE file in the root directory of this source tree.
*/
@file:Suppress(
"DEPRECATION"
) // Suppressing as we want to test specifically with RCTEventEmitter here
// Suppressing as we want to test specifically with RCTEventEmitter here
@file:Suppress("DEPRECATION")
package com.facebook.react.bridge.interop
import com.facebook.react.bridge.JavaScriptModule
import com.facebook.react.bridge.WritableMap
import com.facebook.react.common.annotations.UnstableReactNativeAPI
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsDefaults
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests
import com.facebook.react.modules.core.JSTimers
import com.facebook.react.uimanager.events.RCTEventEmitter
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
@@ -27,6 +27,14 @@ class InteropModuleRegistryTest {
private lateinit var underTest: InteropModuleRegistry
private interface FakeJavaScriptModule : JavaScriptModule
@Suppress("DEPRECATION")
private class FakeRCTEventEmitter : RCTEventEmitter {
@Deprecated("Use [RCTModernEventEmitter.receiveEvent] instead")
override fun receiveEvent(targetTag: Int, eventName: String, params: WritableMap?) = Unit
}
@Before
fun setup() {
underTest = InteropModuleRegistry()
@@ -61,7 +69,7 @@ class InteropModuleRegistryTest {
@Test
fun getInteropModule_withUnregisteredClass_returnsNull() {
overrideFeatureFlags(true, true)
val missingModule = underTest.getInteropModule(JSTimers::class.java)
val missingModule = underTest.getInteropModule(FakeJavaScriptModule::class.java)
assertThat(missingModule).isNull()
}
@@ -10,7 +10,6 @@
package com.facebook.react.internal.interop
import com.facebook.react.bridge.BridgeReactContext
import com.facebook.react.bridge.JavaOnlyArray
import com.facebook.react.bridge.JavaOnlyMap
import com.facebook.react.bridge.ReactContext
import com.facebook.testutils.fakes.FakeEventDispatcher
@@ -59,10 +58,4 @@ class InteropEventEmitterTest {
assertThat(dispatchedEventData).isNotNull()
assertThat(dispatchedEventData!!.getString("color")).isEqualTo("indigo")
}
@Test(expected = java.lang.UnsupportedOperationException::class)
fun receiveTouches_isNotSupported() {
val eventEmitter = InteropEventEmitter(reactContext)
eventEmitter.receiveTouches("a touch", JavaOnlyArray.of(), JavaOnlyArray.of())
}
}