Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/react-native/ReactAndroid/api/ReactAndroid.api
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}
}
}
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down Expand Up @@ -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()
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -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<Event<*>>()
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<Event<*>>()
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<Event<*>>()
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
}
}