Skip to content

Commit bc95fca

Browse files
ykdhanclaude
andcommitted
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Mt8dJ3CEswRqjzfUjLgZ3 Signed-off-by: YK <21373658+ykdhan@users.noreply.github.com>
1 parent d1204ac commit bc95fca

3 files changed

Lines changed: 235 additions & 1 deletion

File tree

‎packages/react-native/ReactAndroid/api/ReactAndroid.api‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5446,6 +5446,7 @@ public final class com/facebook/react/views/modal/ReactModalHostView : android/v
54465446
}
54475447

54485448
public final class com/facebook/react/views/modal/ReactModalHostView$DialogRootViewGroup : com/facebook/react/views/view/ReactViewGroup, com/facebook/react/uimanager/RootView {
5449+
public fun dispatchKeyEvent (Landroid/view/KeyEvent;)Z
54495450
public fun handleException (Ljava/lang/Throwable;)V
54505451
public fun onChildEndedNativeGesture (Landroid/view/View;Landroid/view/MotionEvent;)V
54515452
public fun onChildStartedNativeGesture (Landroid/view/MotionEvent;)V
@@ -5455,6 +5456,7 @@ public final class com/facebook/react/views/modal/ReactModalHostView$DialogRootV
54555456
public fun onInterceptHoverEvent (Landroid/view/MotionEvent;)Z
54565457
public fun onInterceptTouchEvent (Landroid/view/MotionEvent;)Z
54575458
public fun onTouchEvent (Landroid/view/MotionEvent;)Z
5459+
public fun requestChildFocus (Landroid/view/View;Landroid/view/View;)V
54585460
public fun requestDisallowInterceptTouchEvent (Z)V
54595461
public final fun updateState (II)V
54605462
}

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import android.app.Activity
1414
import android.app.Dialog
1515
import android.content.Context
1616
import android.content.DialogInterface
17+
import android.graphics.Rect
1718
import android.os.Build
1819
import android.view.KeyEvent
1920
import android.view.MotionEvent
@@ -41,12 +42,15 @@ import com.facebook.react.common.annotations.UnstableReactNativeAPI
4142
import com.facebook.react.common.annotations.VisibleForTesting
4243
import com.facebook.react.common.build.ReactBuildConfig
4344
import com.facebook.react.config.ReactFeatureFlags
45+
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags
46+
import com.facebook.react.uimanager.JSKeyDispatcher
4447
import com.facebook.react.uimanager.JSPointerDispatcher
4548
import com.facebook.react.uimanager.JSTouchDispatcher
4649
import com.facebook.react.uimanager.PixelUtil.pxToDp
4750
import com.facebook.react.uimanager.RootView
4851
import com.facebook.react.uimanager.StateWrapper
4952
import com.facebook.react.uimanager.ThemedReactContext
53+
import com.facebook.react.uimanager.UIManagerHelper
5054
import com.facebook.react.uimanager.UIManagerModule
5155
import com.facebook.react.uimanager.events.EventDispatcher
5256
import com.facebook.react.views.common.ContextUtils
@@ -319,6 +323,9 @@ public class ReactModalHostView(context: ThemedReactContext) :
319323
// to whether or not to allow the back/escape key to close the dialog. If it chooses
320324
// to, it can just set visible to false on the Modal and the Modal will go away
321325
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) {
326+
// Consuming the event here keeps it from reaching the dialog's views, so send the
327+
// keyup to JS ourselves to match the keydown it already received.
328+
dialogRootViewGroup.dispatchJSKeyEvent(event)
322329
handleCloseAction()
323330
return true
324331
} else {
@@ -328,7 +335,12 @@ public class ReactModalHostView(context: ThemedReactContext) :
328335
val innerCurrentActivity =
329336
(this@ReactModalHostView.context as ReactContext).currentActivity
330337
if (innerCurrentActivity != null) {
331-
return innerCurrentActivity.onKeyUp(keyCode, event)
338+
val handled = innerCurrentActivity.onKeyUp(keyCode, event)
339+
if (handled) {
340+
// The event won't reach the dialog's views, so send the keyup to JS here.
341+
dialogRootViewGroup.dispatchJSKeyEvent(event)
342+
}
343+
return handled
332344
}
333345
}
334346
}
@@ -523,6 +535,7 @@ public class ReactModalHostView(context: ThemedReactContext) :
523535
private var viewHeight = 0
524536
private val jSTouchDispatcher: JSTouchDispatcher = JSTouchDispatcher(this)
525537
private var jSPointerDispatcher: JSPointerDispatcher? = null
538+
private var jSKeyDispatcher: JSKeyDispatcher? = null
526539

527540
private val reactContext: ThemedReactContext
528541
get() = context as ThemedReactContext
@@ -531,6 +544,9 @@ public class ReactModalHostView(context: ThemedReactContext) :
531544
if (ReactFeatureFlags.dispatchPointerEvents) {
532545
jSPointerDispatcher = JSPointerDispatcher(this)
533546
}
547+
if (ReactNativeFeatureFlags.enableKeyEvents()) {
548+
jSKeyDispatcher = JSKeyDispatcher()
549+
}
534550
}
535551

536552
override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) {
@@ -633,5 +649,52 @@ public class ReactModalHostView(context: ThemedReactContext) :
633649
// No-op - override in order to still receive events to onInterceptTouchEvent
634650
// even when some other view disallow that
635651
}
652+
653+
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
654+
// Dispatch during the capture phase before children handle the event as the focus could shift
655+
dispatchJSKeyEvent(event)
656+
return super.dispatchKeyEvent(event)
657+
}
658+
659+
/**
660+
* Sends [event] to JS as a keydown or keyup event targeting the focused view in this Modal.
661+
*
662+
* The Modal is shown in its own window, so the key dispatch of the React root it belongs to
663+
* never sees key events for views inside it. This mirrors what
664+
* [com.facebook.react.runtime.ReactSurfaceView] and [com.facebook.react.ReactRootView] do for
665+
* their own window.
666+
*/
667+
internal fun dispatchJSKeyEvent(event: KeyEvent) {
668+
val keyDispatcher = jSKeyDispatcher ?: return
669+
eventDispatcher?.let { eventDispatcher ->
670+
keyDispatcher.handleKeyEvent(event, eventDispatcher, UIManagerHelper.getSurfaceId(this))
671+
}
672+
}
673+
674+
override fun requestChildFocus(child: View?, focused: View?) {
675+
super.requestChildFocus(child, focused)
676+
677+
if (ReactNativeFeatureFlags.enableKeyEvents()) {
678+
val focusedViewTag = focused?.id
679+
if (focusedViewTag != null) {
680+
jSKeyDispatcher?.setFocusedView(focusedViewTag)
681+
}
682+
}
683+
}
684+
685+
override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
686+
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
687+
688+
if (ReactNativeFeatureFlags.enableKeyEvents()) {
689+
if (gainFocus) {
690+
val focusedViewTag = focusedChild?.id
691+
if (focusedViewTag != null) {
692+
jSKeyDispatcher?.setFocusedView(focusedViewTag)
693+
}
694+
} else {
695+
jSKeyDispatcher?.clearFocus()
696+
}
697+
}
698+
}
636699
}
637700
}
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
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+
package com.facebook.react.views.modal
9+
10+
import android.view.KeyEvent
11+
import com.facebook.react.bridge.ReactTestHelper.createTestReactApplicationContext
12+
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags
13+
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsDefaults
14+
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests
15+
import com.facebook.react.uimanager.ThemedReactContext
16+
import com.facebook.react.uimanager.events.Event
17+
import com.facebook.react.uimanager.events.EventDispatcher
18+
import com.facebook.react.views.view.ReactViewGroup
19+
import com.facebook.testutils.shadows.ShadowSoLoader
20+
import org.assertj.core.api.Assertions.assertThat
21+
import org.junit.After
22+
import org.junit.Before
23+
import org.junit.Test
24+
import org.junit.runner.RunWith
25+
import org.mockito.kotlin.any
26+
import org.mockito.kotlin.argumentCaptor
27+
import org.mockito.kotlin.mock
28+
import org.mockito.kotlin.never
29+
import org.mockito.kotlin.times
30+
import org.mockito.kotlin.verify
31+
import org.robolectric.RobolectricTestRunner
32+
import org.robolectric.RuntimeEnvironment
33+
import org.robolectric.annotation.Config
34+
35+
/** Tests that views inside a Modal receive key events when key events are enabled. */
36+
@RunWith(RobolectricTestRunner::class)
37+
@Config(shadows = [ShadowSoLoader::class])
38+
class DialogRootViewGroupKeyEventsTest {
39+
40+
private lateinit var eventDispatcher: EventDispatcher
41+
private lateinit var root: ReactModalHostView.DialogRootViewGroup
42+
private lateinit var firstChild: ReactViewGroup
43+
private lateinit var secondChild: ReactViewGroup
44+
45+
@Before
46+
fun setUp() {
47+
ReactNativeFeatureFlagsForTests.setUp()
48+
eventDispatcher = mock()
49+
}
50+
51+
@After
52+
fun tearDown() {
53+
ReactNativeFeatureFlags.dangerouslyReset()
54+
}
55+
56+
/**
57+
* Builds the view hierarchy. Feature flags must be overridden before anything reads them, so
58+
* every test sets them through this method before creating any view or context.
59+
*/
60+
private fun setUpViews(enableKeyEvents: Boolean, attachEventDispatcher: Boolean = true) {
61+
ReactNativeFeatureFlags.override(
62+
object : ReactNativeFeatureFlagsDefaults() {
63+
override fun enableKeyEvents(): Boolean = enableKeyEvents
64+
},
65+
)
66+
67+
val reactContext = createTestReactApplicationContext(RuntimeEnvironment.getApplication())
68+
val themedContext = ThemedReactContext(reactContext, reactContext, null, SURFACE_ID)
69+
70+
root = ReactModalHostView.DialogRootViewGroup(themedContext)
71+
root.id = ROOT_TAG
72+
if (attachEventDispatcher) {
73+
root.eventDispatcher = eventDispatcher
74+
}
75+
76+
firstChild = ReactViewGroup(themedContext)
77+
firstChild.id = FIRST_CHILD_TAG
78+
root.addView(firstChild)
79+
80+
secondChild = ReactViewGroup(themedContext)
81+
secondChild.id = SECOND_CHILD_TAG
82+
root.addView(secondChild)
83+
}
84+
85+
private fun keyEvent(action: Int, keyCode: Int = KeyEvent.KEYCODE_A): KeyEvent =
86+
KeyEvent(action, keyCode)
87+
88+
@Test
89+
fun dispatchesKeyDownAndKeyUpToTheFocusedView() {
90+
setUpViews(enableKeyEvents = true)
91+
root.requestChildFocus(firstChild, firstChild)
92+
93+
root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))
94+
root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_UP))
95+
96+
val captor = argumentCaptor<Event<*>>()
97+
verify(eventDispatcher, times(2)).dispatchEvent(captor.capture())
98+
assertThat(captor.allValues.map { it.getEventName() }).containsExactly("topKeyDown", "topKeyUp")
99+
assertThat(captor.allValues.map { it.viewTag })
100+
.containsExactly(FIRST_CHILD_TAG, FIRST_CHILD_TAG)
101+
assertThat(captor.allValues.map { it.surfaceId }).containsExactly(SURFACE_ID, SURFACE_ID)
102+
}
103+
104+
@Test
105+
fun targetsTheNewlyFocusedViewAfterFocusMoves() {
106+
setUpViews(enableKeyEvents = true)
107+
root.requestChildFocus(firstChild, firstChild)
108+
root.requestChildFocus(secondChild, secondChild)
109+
110+
root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))
111+
112+
val captor = argumentCaptor<Event<*>>()
113+
verify(eventDispatcher).dispatchEvent(captor.capture())
114+
assertThat(captor.firstValue.viewTag).isEqualTo(SECOND_CHILD_TAG)
115+
}
116+
117+
@Test
118+
fun dispatchJSKeyEventReachesTheFocusedView() {
119+
// ReactModalHostView calls this for key events that its dialog consumes before they reach
120+
// the dialog's views, such as the BACK and ESCAPE key ups that close the Modal.
121+
setUpViews(enableKeyEvents = true)
122+
root.requestChildFocus(firstChild, firstChild)
123+
124+
root.dispatchJSKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ESCAPE))
125+
126+
val captor = argumentCaptor<Event<*>>()
127+
verify(eventDispatcher).dispatchEvent(captor.capture())
128+
assertThat(captor.firstValue.getEventName()).isEqualTo("topKeyUp")
129+
assertThat(captor.firstValue.viewTag).isEqualTo(FIRST_CHILD_TAG)
130+
}
131+
132+
@Test
133+
fun dispatchesNothingWhenNoViewIsFocused() {
134+
setUpViews(enableKeyEvents = true)
135+
136+
root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))
137+
138+
verify(eventDispatcher, never()).dispatchEvent(any())
139+
}
140+
141+
@Test
142+
fun dispatchesNothingWhenKeyEventsAreDisabled() {
143+
setUpViews(enableKeyEvents = false)
144+
root.requestChildFocus(firstChild, firstChild)
145+
146+
root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))
147+
root.dispatchJSKeyEvent(keyEvent(KeyEvent.ACTION_UP))
148+
149+
verify(eventDispatcher, never()).dispatchEvent(any())
150+
}
151+
152+
@Test
153+
fun doesNotThrowWithoutAnEventDispatcher() {
154+
setUpViews(enableKeyEvents = true, attachEventDispatcher = false)
155+
root.requestChildFocus(firstChild, firstChild)
156+
157+
root.dispatchKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))
158+
root.dispatchJSKeyEvent(keyEvent(KeyEvent.ACTION_UP))
159+
160+
verify(eventDispatcher, never()).dispatchEvent(any())
161+
}
162+
163+
private companion object {
164+
const val SURFACE_ID = 11
165+
const val ROOT_TAG = 100
166+
const val FIRST_CHILD_TAG = 101
167+
const val SECOND_CHILD_TAG = 102
168+
}
169+
}

0 commit comments

Comments
 (0)