From e0968f462f89938f527f4ee6d5a6a1e439d96664 Mon Sep 17 00:00:00 2001 From: YK <21373658+ykdhan@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:42:04 +0900 Subject: [PATCH] Dispatch key events to views inside Modal on Android With enableKeyEvents on, React Native Android sends onKeyDown/onKeyUp from the React root's own key dispatch (ReactRootView, ReactSurfaceView). A Modal is shown in its own dialog window whose root, ReactModalHostView.DialogRootViewGroup, had no key dispatch and no focus tracking, so a focused View inside a Modal never received key events. Give DialogRootViewGroup the same JSKeyDispatcher handling that ReactSurfaceView has: track the focused child, and send keydown/keyup to JS from dispatchKeyEvent before children handle the event. The dialog's OnKeyListener consumes some key ups before they reach the dialog's views: BACK/ESCAPE (which close the Modal) and keys the activity handles (dev menu, double-tap R). Forward those key ups to JS too, so JS gets a keyup for every keydown it received. Fixes #59601 Co-Authored-By: Claude Opus 5.5 Signed-off-by: YK <21373658+ykdhan@users.noreply.github.com> --- .../ReactAndroid/api/ReactAndroid.api | 2 + .../react/views/modal/ReactModalHostView.kt | 65 ++++++- .../modal/DialogRootViewGroupKeyEventsTest.kt | 169 ++++++++++++++++++ 3 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/modal/DialogRootViewGroupKeyEventsTest.kt diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index e5609d383c48..c47f3bb57ff9 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -5446,6 +5446,7 @@ public final class com/facebook/react/views/modal/ReactModalHostView : android/v } public final class com/facebook/react/views/modal/ReactModalHostView$DialogRootViewGroup : com/facebook/react/views/view/ReactViewGroup, com/facebook/react/uimanager/RootView { + public fun dispatchKeyEvent (Landroid/view/KeyEvent;)Z public fun handleException (Ljava/lang/Throwable;)V public fun onChildEndedNativeGesture (Landroid/view/View;Landroid/view/MotionEvent;)V public fun onChildStartedNativeGesture (Landroid/view/MotionEvent;)V @@ -5455,6 +5456,7 @@ public final class com/facebook/react/views/modal/ReactModalHostView$DialogRootV public fun onInterceptHoverEvent (Landroid/view/MotionEvent;)Z public fun onInterceptTouchEvent (Landroid/view/MotionEvent;)Z public fun onTouchEvent (Landroid/view/MotionEvent;)Z + public fun requestChildFocus (Landroid/view/View;Landroid/view/View;)V public fun requestDisallowInterceptTouchEvent (Z)V public final fun updateState (II)V } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt index 0cd7342ccb7e..0e85f4c29191 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt @@ -14,6 +14,7 @@ import android.app.Activity import android.app.Dialog import android.content.Context import android.content.DialogInterface +import android.graphics.Rect import android.os.Build import android.view.KeyEvent import android.view.MotionEvent @@ -41,12 +42,15 @@ import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.common.annotations.VisibleForTesting import com.facebook.react.common.build.ReactBuildConfig import com.facebook.react.config.ReactFeatureFlags +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags +import com.facebook.react.uimanager.JSKeyDispatcher import com.facebook.react.uimanager.JSPointerDispatcher import com.facebook.react.uimanager.JSTouchDispatcher import com.facebook.react.uimanager.PixelUtil.pxToDp import com.facebook.react.uimanager.RootView import com.facebook.react.uimanager.StateWrapper import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.UIManagerHelper import com.facebook.react.uimanager.UIManagerModule import com.facebook.react.uimanager.events.EventDispatcher import com.facebook.react.views.common.ContextUtils @@ -319,6 +323,9 @@ public class ReactModalHostView(context: ThemedReactContext) : // to whether or not to allow the back/escape key to close the dialog. If it chooses // to, it can just set visible to false on the Modal and the Modal will go away if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) { + // Consuming the event here keeps it from reaching the dialog's views, so send the + // keyup to JS ourselves to match the keydown it already received. + dialogRootViewGroup.dispatchJSKeyEvent(event) handleCloseAction() return true } else { @@ -328,7 +335,12 @@ public class ReactModalHostView(context: ThemedReactContext) : val innerCurrentActivity = (this@ReactModalHostView.context as ReactContext).currentActivity if (innerCurrentActivity != null) { - return innerCurrentActivity.onKeyUp(keyCode, event) + val handled = innerCurrentActivity.onKeyUp(keyCode, event) + if (handled) { + // The event won't reach the dialog's views, so send the keyup to JS here. + dialogRootViewGroup.dispatchJSKeyEvent(event) + } + return handled } } } @@ -523,6 +535,7 @@ public class ReactModalHostView(context: ThemedReactContext) : private var viewHeight = 0 private val jSTouchDispatcher: JSTouchDispatcher = JSTouchDispatcher(this) private var jSPointerDispatcher: JSPointerDispatcher? = null + private var jSKeyDispatcher: JSKeyDispatcher? = null private val reactContext: ThemedReactContext get() = context as ThemedReactContext @@ -531,6 +544,9 @@ public class ReactModalHostView(context: ThemedReactContext) : if (ReactFeatureFlags.dispatchPointerEvents) { jSPointerDispatcher = JSPointerDispatcher(this) } + if (ReactNativeFeatureFlags.enableKeyEvents()) { + jSKeyDispatcher = JSKeyDispatcher() + } } override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) { @@ -633,5 +649,52 @@ public class ReactModalHostView(context: ThemedReactContext) : // No-op - override in order to still receive events to onInterceptTouchEvent // even when some other view disallow that } + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + // Dispatch during the capture phase before children handle the event as the focus could shift + dispatchJSKeyEvent(event) + return super.dispatchKeyEvent(event) + } + + /** + * Sends [event] to JS as a keydown or keyup event targeting the focused view in this Modal. + * + * The Modal is shown in its own window, so the key dispatch of the React root it belongs to + * never sees key events for views inside it. This mirrors what + * [com.facebook.react.runtime.ReactSurfaceView] and [com.facebook.react.ReactRootView] do for + * their own window. + */ + internal fun dispatchJSKeyEvent(event: KeyEvent) { + val keyDispatcher = jSKeyDispatcher ?: return + eventDispatcher?.let { eventDispatcher -> + keyDispatcher.handleKeyEvent(event, eventDispatcher, UIManagerHelper.getSurfaceId(this)) + } + } + + override fun requestChildFocus(child: View?, focused: View?) { + super.requestChildFocus(child, focused) + + if (ReactNativeFeatureFlags.enableKeyEvents()) { + val focusedViewTag = focused?.id + if (focusedViewTag != null) { + jSKeyDispatcher?.setFocusedView(focusedViewTag) + } + } + } + + override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) { + super.onFocusChanged(gainFocus, direction, previouslyFocusedRect) + + if (ReactNativeFeatureFlags.enableKeyEvents()) { + if (gainFocus) { + val focusedViewTag = focusedChild?.id + if (focusedViewTag != null) { + jSKeyDispatcher?.setFocusedView(focusedViewTag) + } + } else { + jSKeyDispatcher?.clearFocus() + } + } + } } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/modal/DialogRootViewGroupKeyEventsTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/modal/DialogRootViewGroupKeyEventsTest.kt new file mode 100644 index 000000000000..f4899805871c --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/modal/DialogRootViewGroupKeyEventsTest.kt @@ -0,0 +1,169 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.modal + +import android.view.KeyEvent +import com.facebook.react.bridge.ReactTestHelper.createTestReactApplicationContext +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.uimanager.ThemedReactContext +import com.facebook.react.uimanager.events.Event +import com.facebook.react.uimanager.events.EventDispatcher +import com.facebook.react.views.view.ReactViewGroup +import com.facebook.testutils.shadows.ShadowSoLoader +import org.assertj.core.api.Assertions.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +/** Tests that views inside a Modal receive key events when key events are enabled. */ +@RunWith(RobolectricTestRunner::class) +@Config(shadows = [ShadowSoLoader::class]) +class DialogRootViewGroupKeyEventsTest { + + private lateinit var eventDispatcher: EventDispatcher + private lateinit var root: ReactModalHostView.DialogRootViewGroup + private lateinit var firstChild: ReactViewGroup + private lateinit var secondChild: ReactViewGroup + + @Before + fun setUp() { + ReactNativeFeatureFlagsForTests.setUp() + eventDispatcher = mock() + } + + @After + fun tearDown() { + ReactNativeFeatureFlags.dangerouslyReset() + } + + /** + * Builds the view hierarchy. Feature flags must be overridden before anything reads them, so + * every test sets them through this method before creating any view or context. + */ + private fun setUpViews(enableKeyEvents: Boolean, attachEventDispatcher: Boolean = true) { + ReactNativeFeatureFlags.override( + object : ReactNativeFeatureFlagsDefaults() { + override fun enableKeyEvents(): Boolean = enableKeyEvents + }, + ) + + val reactContext = createTestReactApplicationContext(RuntimeEnvironment.getApplication()) + val themedContext = ThemedReactContext(reactContext, reactContext, null, SURFACE_ID) + + root = ReactModalHostView.DialogRootViewGroup(themedContext) + root.id = ROOT_TAG + if (attachEventDispatcher) { + root.eventDispatcher = eventDispatcher + } + + firstChild = ReactViewGroup(themedContext) + firstChild.id = FIRST_CHILD_TAG + root.addView(firstChild) + + secondChild = ReactViewGroup(themedContext) + secondChild.id = SECOND_CHILD_TAG + root.addView(secondChild) + } + + private fun keyEvent(action: Int, keyCode: Int = KeyEvent.KEYCODE_A): KeyEvent = + KeyEvent(action, keyCode) + + @Test + fun dispatchesKeyDownAndKeyUpToTheFocusedView() { + setUpViews(enableKeyEvents = true) + root.requestChildFocus(firstChild, firstChild) + + root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN)) + root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_UP)) + + val captor = argumentCaptor>() + verify(eventDispatcher, times(2)).dispatchEvent(captor.capture()) + assertThat(captor.allValues.map { it.getEventName() }).containsExactly("topKeyDown", "topKeyUp") + assertThat(captor.allValues.map { it.viewTag }) + .containsExactly(FIRST_CHILD_TAG, FIRST_CHILD_TAG) + assertThat(captor.allValues.map { it.surfaceId }).containsExactly(SURFACE_ID, SURFACE_ID) + } + + @Test + fun targetsTheNewlyFocusedViewAfterFocusMoves() { + setUpViews(enableKeyEvents = true) + root.requestChildFocus(firstChild, firstChild) + root.requestChildFocus(secondChild, secondChild) + + root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN)) + + val captor = argumentCaptor>() + verify(eventDispatcher).dispatchEvent(captor.capture()) + assertThat(captor.firstValue.viewTag).isEqualTo(SECOND_CHILD_TAG) + } + + @Test + fun dispatchJSKeyEventReachesTheFocusedView() { + // ReactModalHostView calls this for key events that its dialog consumes before they reach + // the dialog's views, such as the BACK and ESCAPE key ups that close the Modal. + setUpViews(enableKeyEvents = true) + root.requestChildFocus(firstChild, firstChild) + + root.dispatchJSKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ESCAPE)) + + val captor = argumentCaptor>() + verify(eventDispatcher).dispatchEvent(captor.capture()) + assertThat(captor.firstValue.getEventName()).isEqualTo("topKeyUp") + assertThat(captor.firstValue.viewTag).isEqualTo(FIRST_CHILD_TAG) + } + + @Test + fun dispatchesNothingWhenNoViewIsFocused() { + setUpViews(enableKeyEvents = true) + + root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN)) + + verify(eventDispatcher, never()).dispatchEvent(any()) + } + + @Test + fun dispatchesNothingWhenKeyEventsAreDisabled() { + setUpViews(enableKeyEvents = false) + root.requestChildFocus(firstChild, firstChild) + + root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN)) + root.dispatchJSKeyEvent(keyEvent(KeyEvent.ACTION_UP)) + + verify(eventDispatcher, never()).dispatchEvent(any()) + } + + @Test + fun doesNotThrowWithoutAnEventDispatcher() { + setUpViews(enableKeyEvents = true, attachEventDispatcher = false) + root.requestChildFocus(firstChild, firstChild) + + root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN)) + root.dispatchJSKeyEvent(keyEvent(KeyEvent.ACTION_UP)) + + verify(eventDispatcher, never()).dispatchEvent(any()) + } + + private companion object { + const val SURFACE_ID = 11 + const val ROOT_TAG = 100 + const val FIRST_CHILD_TAG = 101 + const val SECOND_CHILD_TAG = 102 + } +}