From bb92824b374d2644746f7644beed30b1e983dd7c Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 20 Nov 2026 01:33:42 +0200 Subject: [PATCH] Take focusable={false} Android views out of keyboard navigation isFocusable, the flag every Android keyboard path reads, carried accessible: setAccessible set it so accessibility services treat the view as one element, and setFocusable(false) left it alone. Tab, the arrow keys, nextFocus*, default focus, cluster navigation and an editor's IME Next all reached an accessible view given focusable={false} or tabIndex={-1}. isFocusable now follows focusable, and accessible while focusable is unset. An accessible view that keyboard navigation passes over stays one accessibility element through screenReaderFocusable, kept below API 28 in a view tag and the node's extras, and is made important for accessibility, which Android derives from screenReaderFocusable only from API 35. As with a negative tabindex in HTML, ref.focus() still focuses the view where enableImperativeFocus dispatches it, the view leaves keyboard navigation once focus moves on, and there a View with an explicit focusable={false} keeps its native view so the call reaches it. ReactViewManager collects accessible, focusable, screenReaderFocusable and importantForAccessibility, and ReactViewGroup applies them once per transaction, so the order the props apply in no longer changes the result. focusable is optional from HostPlatformViewProps to setFocusable, so an explicit false reaches the view under Props 2.0 diffing and removing it returns the view to what accessible gives. ReactAndroid.api gains the overrides this takes: ReactViewManager's onAfterUpdateTransaction, setImportantForAccessibility and setScreenReaderFocusable, and ReactViewGroup's onFocusChanged and onInitializeAccessibilityNodeInfo. On Android a View's KeyboardFocusable trait takes the same rule, while other components and platforms keep main's, as their views do, and FocusOrderingHelper takes its candidates from the trait alone. While an accessibility order holds a view's focus, ReactViewGroup and BaseViewManager.setScreenReaderFocusable write through ReactAxOrderHelper.setFocusable and setScreenReaderFocusable, which keep the value for the order to restore. The view with accessibilityOrder records the views it holds and gives their focus back when its order changes, when accessibility services turn off and when it is dropped, which also drops its order, including a view that removeClippedSubviews clipped out or that view flattening moved out of its subtree. A view follows an order only while it is in that order's subtree, so the order parent tag buildAxOrderList leaves on it needs no clearing. ReactAxOrderHelper's public cleanUpAxOrder, restoreFocusability and disableFocusForSubtree, which walked the order's current subtree, are removed. --- .../ReactAndroid/api/ReactAndroid.api | 13 +- .../react/uimanager/BaseViewManager.java | 15 +- .../ImportantForAccessibilityHelper.kt | 23 + .../react/uimanager/ReactAxOrderHelper.kt | 146 ++-- .../uimanager/ScreenReaderFocusableHelper.kt | 38 + .../facebook/react/views/view/FocusProps.kt | 46 ++ .../react/views/view/ReactViewGroup.kt | 112 ++- .../react/views/view/ReactViewManager.kt | 40 +- .../jni/react/fabric/FocusOrderingHelper.cpp | 6 +- .../main/res/views/uimanager/values/ids.xml | 5 +- .../react/uimanager/BaseViewManagerTest.kt | 25 +- .../ImportantForAccessibilityHelperTest.kt | 41 + .../react/views/view/ReactViewFocusTest.kt | 759 ++++++++++++++++++ .../components/view/ViewShadowNode.cpp | 19 + .../components/view/HostPlatformViewProps.cpp | 6 +- .../components/view/HostPlatformViewProps.h | 2 +- .../view/HostPlatformViewTraitsInitializer.h | 8 +- .../view/tests/ViewPropsDiffTest.cpp | 12 + .../components/view/tests/ViewTest.cpp | 96 +++ .../.maestro/keyboard-focus-exclusion.yml | 34 + .../FocusEventsExample.android.js | 75 +- .../api-snapshots/ReactAndroidDebugCxx.api | 1 + .../ReactAndroidFrameworksCxx.api | 1 + .../api-snapshots/ReactAndroidNewarchCxx.api | 1 + .../api-snapshots/ReactAndroidReleaseCxx.api | 1 + 25 files changed, 1389 insertions(+), 136 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ImportantForAccessibilityHelper.kt create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ScreenReaderFocusableHelper.kt create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/FocusProps.kt create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ImportantForAccessibilityHelperTest.kt create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/view/ReactViewFocusTest.kt create mode 100644 packages/rn-tester/.maestro/keyboard-focus-exclusion.yml diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index dd68644b691e..d88414b0990a 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -3733,9 +3733,6 @@ public final class com/facebook/react/uimanager/ReactAccessibilityDelegate$Role$ public final class com/facebook/react/uimanager/ReactAxOrderHelper { public static final field INSTANCE Lcom/facebook/react/uimanager/ReactAxOrderHelper; public final fun buildAxOrderList (Landroid/view/View;Landroid/view/View;Ljava/util/List;[Landroid/view/View;)V - public static final fun cleanUpAxOrder (Landroid/view/View;)V - public final fun disableFocusForSubtree (Landroid/view/View;Ljava/util/List;)V - public static final fun restoreFocusability (Landroid/view/View;)V } public abstract interface class com/facebook/react/uimanager/ReactClippingProhibitedView { @@ -6483,7 +6480,9 @@ public class com/facebook/react/views/view/ReactViewGroup : android/view/ViewGro protected fun onAttachedToWindow ()V protected fun onConfigurationChanged (Landroid/content/res/Configuration;)V protected fun onDetachedFromWindow ()V + protected fun onFocusChanged (ZILandroid/graphics/Rect;)V public fun onHoverEvent (Landroid/view/MotionEvent;)Z + public fun onInitializeAccessibilityNodeInfo (Landroid/view/accessibility/AccessibilityNodeInfo;)V public fun onInterceptTouchEvent (Landroid/view/MotionEvent;)Z protected fun onLayout (ZIIII)V protected fun onMeasure (II)V @@ -6529,6 +6528,8 @@ public class com/facebook/react/views/view/ReactViewManager : com/facebook/react public fun nextFocusLeft (Lcom/facebook/react/views/view/ReactViewGroup;I)V public fun nextFocusRight (Lcom/facebook/react/views/view/ReactViewGroup;I)V public fun nextFocusUp (Lcom/facebook/react/views/view/ReactViewGroup;I)V + public synthetic fun onAfterUpdateTransaction (Landroid/view/View;)V + protected fun onAfterUpdateTransaction (Lcom/facebook/react/views/view/ReactViewGroup;)V public synthetic fun onDropViewInstance (Landroid/view/View;)V public fun onDropViewInstance (Lcom/facebook/react/views/view/ReactViewGroup;)V public synthetic fun prepareToRecycleView (Lcom/facebook/react/uimanager/ThemedReactContext;Landroid/view/View;)Landroid/view/View; @@ -6555,8 +6556,10 @@ public class com/facebook/react/views/view/ReactViewManager : com/facebook/react public fun setExperimentalBackgroundPosition (Lcom/facebook/react/views/view/ReactViewGroup;Lcom/facebook/react/bridge/ReadableArray;)V public fun setExperimentalBackgroundRepeat (Lcom/facebook/react/views/view/ReactViewGroup;Lcom/facebook/react/bridge/ReadableArray;)V public fun setExperimentalBackgroundSize (Lcom/facebook/react/views/view/ReactViewGroup;Lcom/facebook/react/bridge/ReadableArray;)V - public fun setFocusable (Lcom/facebook/react/views/view/ReactViewGroup;Z)V + public fun setFocusable (Lcom/facebook/react/views/view/ReactViewGroup;Ljava/lang/Boolean;)V public fun setHitSlop (Lcom/facebook/react/views/view/ReactViewGroup;Lcom/facebook/react/bridge/Dynamic;)V + public synthetic fun setImportantForAccessibility (Landroid/view/View;Ljava/lang/String;)V + public fun setImportantForAccessibility (Lcom/facebook/react/views/view/ReactViewGroup;Ljava/lang/String;)V public fun setNativeBackground (Lcom/facebook/react/views/view/ReactViewGroup;Lcom/facebook/react/bridge/ReadableMap;)V public fun setNativeForeground (Lcom/facebook/react/views/view/ReactViewGroup;Lcom/facebook/react/bridge/ReadableMap;)V public fun setNeedsOffscreenAlphaCompositing (Lcom/facebook/react/views/view/ReactViewGroup;Z)V @@ -6564,6 +6567,8 @@ public class com/facebook/react/views/view/ReactViewManager : com/facebook/react public fun setOpacity (Lcom/facebook/react/views/view/ReactViewGroup;F)V public fun setOverflow (Lcom/facebook/react/views/view/ReactViewGroup;Ljava/lang/String;)V public fun setPointerEvents (Lcom/facebook/react/views/view/ReactViewGroup;Ljava/lang/String;)V + public synthetic fun setScreenReaderFocusable (Landroid/view/View;Z)V + public fun setScreenReaderFocusable (Lcom/facebook/react/views/view/ReactViewGroup;Z)V public fun setTVPreferredFocus (Lcom/facebook/react/views/view/ReactViewGroup;Z)V public synthetic fun setTransformProperty (Landroid/view/View;Lcom/facebook/react/bridge/ReadableArray;Lcom/facebook/react/bridge/ReadableArray;)V protected fun setTransformProperty (Lcom/facebook/react/views/view/ReactViewGroup;Lcom/facebook/react/bridge/ReadableArray;Lcom/facebook/react/bridge/ReadableArray;)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java index db3dd2871cc6..bcec851aa240 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java @@ -515,21 +515,18 @@ public void setAccessibilityValue(T view, ReadableMap accessibilityValue) { @ReactProp(name = ViewProps.IMPORTANT_FOR_ACCESSIBILITY) public void setImportantForAccessibility( @NonNull T view, @Nullable String importantForAccessibility) { - if (importantForAccessibility == null || importantForAccessibility.equals("auto")) { - view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); - } else if (importantForAccessibility.equals("yes")) { - view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES); - } else if (importantForAccessibility.equals("no")) { - view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); - } else if (importantForAccessibility.equals("no-hide-descendants")) { - view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); + @Nullable + Integer mode = + ImportantForAccessibilityHelper.parseImportantForAccessibility(importantForAccessibility); + if (mode != null) { + view.setImportantForAccessibility(mode); } } @ReactProp(name = ViewProps.SCREEN_READER_FOCUSABLE) public void setScreenReaderFocusable(@NonNull T view, boolean screenReaderFocusable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - view.setScreenReaderFocusable(screenReaderFocusable); + ReactAxOrderHelper.internal_setScreenReaderFocusable(view, screenReaderFocusable); } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ImportantForAccessibilityHelper.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ImportantForAccessibilityHelper.kt new file mode 100644 index 000000000000..eeb1407e398c --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ImportantForAccessibilityHelper.kt @@ -0,0 +1,23 @@ +/* + * 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 + +import android.view.View + +internal object ImportantForAccessibilityHelper { + @JvmStatic + fun parseImportantForAccessibility(importantForAccessibility: String?): Int? = + when (importantForAccessibility) { + null, + "auto" -> View.IMPORTANT_FOR_ACCESSIBILITY_AUTO + "yes" -> View.IMPORTANT_FOR_ACCESSIBILITY_YES + "no" -> View.IMPORTANT_FOR_ACCESSIBILITY_NO + "no-hide-descendants" -> View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + else -> null + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAxOrderHelper.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAxOrderHelper.kt index 78407dc50385..3792cc3f6af1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAxOrderHelper.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAxOrderHelper.kt @@ -10,89 +10,42 @@ package com.facebook.react.uimanager import android.view.View import android.view.ViewGroup import com.facebook.react.R +import java.util.Collections +import java.util.WeakHashMap /** * Helper object for managing accessibility order in React Native views. * - * This object provides utilities to manage the accessibility focus order of views by storing and - * restoring focusability states, and building ordered lists of views based on accessibility order - * preferences. + * This object provides utilities to build ordered lists of views based on accessibility order + * preferences, and to write the focus flags of views whose focus an accessibility order holds. */ public object ReactAxOrderHelper { - /** - * Cleans up accessibility order state from a view and its children. - * - * This method removes stored focusability states and accessibility order parent references from - * the view hierarchy. It recursively processes all children of ViewGroup instances. - * - * @param view The view from which to clean up accessibility order state - */ - @JvmStatic - public fun cleanUpAxOrder(view: View) { - val originalFocusability = view.getTag(R.id.original_focusability) as Boolean? + // A focus flag set while an accessibility order holds the view's focus is the one it restores. + internal fun setFocusable(view: View, focusable: Boolean) { + val originalFocusability = view.originalFocusability if (originalFocusability != null) { - view.isFocusable = originalFocusability - } - - val axOrderParent = view.getTag(R.id.accessibility_order_parent) as View? - if (axOrderParent != null) { - view.setTag(R.id.accessibility_order_parent, null) - } - - if (view is ViewGroup) { - for (i in 0..) { - if (!axOrderList.contains(view.getTag(R.id.view_tag_native_id))) { - if (view.getTag(R.id.original_focusability) == null) { - view.setTag(R.id.original_focusability, view.isFocusable) - } - view.isFocusable = false - } - - if (view is ViewGroup) { - for (i in 0.. = Collections.newSetFromMap(WeakHashMap()) + + fun disableFocusForSubtree(view: View, axOrderList: List<*>) { + if (!axOrderList.contains(view.getTag(R.id.view_tag_native_id))) { + hold(view) + } + + if (view is ViewGroup) { + for (i in 0..= Build.VERSION_CODES.P) { + view.isScreenReaderFocusable + } else { + view.getTag(R.id.screen_reader_focusable) == true + } + + fun setScreenReaderFocusable(view: View, screenReaderFocusable: Boolean) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + view.isScreenReaderFocusable = screenReaderFocusable + } else { + view.setTag(R.id.screen_reader_focusable, screenReaderFocusable) + } + } + + fun initializeAccessibilityNodeInfo(view: View, info: AccessibilityNodeInfo) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && isScreenReaderFocusable(view)) { + AccessibilityNodeInfoCompat.wrap(info).isScreenReaderFocusable = true + } + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/FocusProps.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/FocusProps.kt new file mode 100644 index 000000000000..ba1ed9e4619a --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/FocusProps.kt @@ -0,0 +1,46 @@ +/* + * 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.view + +import android.view.View + +internal data class FocusProps( + val focusable: Boolean? = null, + val accessible: Boolean = false, + val screenReaderFocusable: Boolean = false, + val importantForAccessibility: Int = View.IMPORTANT_FOR_ACCESSIBILITY_AUTO, +) { + val keyboardFocusable: Boolean + get() = focusable ?: accessible + + // HTML's focus() reaches an element a negative tabindex keeps out of sequential navigation. + val focusableOnlyFromJS: Boolean + get() = focusable == false + + // An accessible view that keyboard navigation passes over stays one element for screen readers. + val isScreenReaderFocusable: Boolean + get() = screenReaderFocusable || (accessible && !keyboardFocusable) + + fun isFocusable(isFocused: Boolean): Boolean = + keyboardFocusable || (focusableOnlyFromJS && isFocused) + + // Android makes a labelled view important, and a screenReaderFocusable one only from API 35. + fun importantForAccessibility(hasContentDescription: Boolean): Int = + if ( + importantForAccessibility == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO && + (isScreenReaderFocusable || hasContentDescription) + ) { + View.IMPORTANT_FOR_ACCESSIBILITY_YES + } else { + importantForAccessibility + } + + companion object { + val DEFAULT: FocusProps = FocusProps() + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt index 9f78deac9ce1..09f5f3f80791 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt @@ -26,6 +26,7 @@ import android.view.ViewGroup import android.view.ViewStructure import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager +import android.view.accessibility.AccessibilityNodeInfo import com.facebook.common.logging.FLog import com.facebook.react.R import com.facebook.react.bridge.ReactNoCrashSoftException @@ -40,6 +41,7 @@ import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags import com.facebook.react.touch.OnInterceptTouchEventListener import com.facebook.react.touch.ReactHitSlopView import com.facebook.react.touch.ReactInterceptingViewGroup +import com.facebook.react.uimanager.AccessibilityOrderHolds import com.facebook.react.uimanager.BackgroundStyleApplicator.clipToPaddingBox import com.facebook.react.uimanager.BackgroundStyleApplicator.getPaddingBoxRect import com.facebook.react.uimanager.BackgroundStyleApplicator.setBackgroundColor @@ -63,6 +65,7 @@ import com.facebook.react.uimanager.ReactClippingViewGroup import com.facebook.react.uimanager.ReactClippingViewGroupHelper.calculateClippingRect import com.facebook.react.uimanager.ReactOverflowViewWithInset import com.facebook.react.uimanager.ReactPointerEventsView +import com.facebook.react.uimanager.ScreenReaderFocusableHelper import com.facebook.react.uimanager.style.BorderRadiusProp import com.facebook.react.uimanager.style.BorderStyle import com.facebook.react.uimanager.style.LogicalEdge @@ -151,6 +154,9 @@ public open class ReactViewGroup public constructor(context: Context?) : public var axOrderList: MutableList? = null + internal var accessibilityOrderHolds: AccessibilityOrderHolds? = null + private set + private var childrenLayoutChangeListener: ChildrenLayoutChangeListener? = null private var onInterceptTouchEventListener: OnInterceptTouchEventListener? = null private var needsOffscreenAlphaCompositing = false @@ -164,6 +170,11 @@ public open class ReactViewGroup public constructor(context: Context?) : // Receives the HOVER_EXIT that pairs with the last accessibility HOVER_ENTER. private var accessibilityHoverSource: View? = null + internal var focusProps: FocusProps = FocusProps.DEFAULT + private set + + private var focusPropsChanged = false + internal var nativeBackgroundMap: ReadableMap? = null internal var nativeForegroundMap: ReadableMap? = null @@ -207,6 +218,8 @@ public open class ReactViewGroup public constructor(context: Context?) : accessibilityHoverSource = null nativeBackgroundMap = null nativeForegroundMap = null + focusProps = FocusProps.DEFAULT + focusPropsChanged = false } internal open fun recycleView() { @@ -585,11 +598,48 @@ public open class ReactViewGroup public constructor(context: Context?) : updateClippingToRect(clippingRect, excludedViews) } + internal fun updateFocusProps(focusProps: FocusProps) { + this.focusProps = focusProps + focusPropsChanged = true + } + + internal fun applyFocusProps() { + if (!focusPropsChanged) { + return + } + focusPropsChanged = false + ReactAxOrderHelper.setFocusable(this, focusProps.isFocusable(isFocused)) + ReactAxOrderHelper.setScreenReaderFocusable(this, focusProps.isScreenReaderFocusable) + importantForAccessibility = + focusProps.importantForAccessibility( + hasContentDescription = !contentDescription.isNullOrEmpty() + ) + } + + override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) { + super.onFocusChanged(gainFocus, direction, previouslyFocusedRect) + if (!gainFocus && focusProps.focusableOnlyFromJS) { + ReactAxOrderHelper.setFocusable(this, false) + } + } + + override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) { + super.onInitializeAccessibilityNodeInfo(info) + ScreenReaderFocusableHelper.initializeAccessibilityNodeInfo(this, info) + } + internal fun requestFocusFromJS() { - if (isAttachedToWindow) { - super.requestFocus(FOCUS_DOWN, null) - } else { + if (!isAttachedToWindow) { focusOnAttach = true + return + } + val grantsFocus = focusProps.focusableOnlyFromJS && !isFocusable + if (grantsFocus) { + ReactAxOrderHelper.setFocusable(this, true) + } + super.requestFocus(FOCUS_DOWN, null) + if (grantsFocus && !isFocused) { + ReactAxOrderHelper.setFocusable(this, false) } } @@ -1144,11 +1194,8 @@ public open class ReactViewGroup public constructor(context: Context?) : } override fun addChildrenForAccessibility(outChildren: ArrayList) { - val axOrderParent = getTag(R.id.accessibility_order_parent) - var axOrderParentOrderList: MutableList? = null - if (axOrderParent is ReactViewGroup) { - axOrderParentOrderList = (axOrderParent as ReactViewGroup?)?.axOrderList - } + val axOrderParent = accessibilityOrderParent() + val axOrderParentOrderList = axOrderParent?.axOrderList val axOrder: MutableList<*>? = axOrderList if (axOrder != null) { @@ -1159,9 +1206,7 @@ public open class ReactViewGroup public constructor(context: Context?) : val newAccessibilityStateChangeListener = AccessibilityManager.AccessibilityStateChangeListener { enabled -> if (!enabled) { - for (i in 0..) { try { super.addChildrenForAccessibility(outChildren) @@ -1223,6 +1269,24 @@ public open class ReactViewGroup public constructor(context: Context?) : } } + internal fun dropAccessibilityOrder() { + restoreAccessibilityOrderFocusability() + axOrderList = null + cleanUpAxOrderListener() + } + + internal fun restoreAccessibilityOrderFocusability() { + val holds = accessibilityOrderHolds ?: return + accessibilityOrderHolds = null + holds.restoreFocusability() + } + + private fun disableFocusForAccessibilityOrder(view: View, axOrderList: List<*>) { + val holds = + accessibilityOrderHolds ?: AccessibilityOrderHolds().also { accessibilityOrderHolds = it } + holds.disableFocusForSubtree(view, axOrderList) + } + public fun cleanUpAxOrderListener() { val am = this.context.getSystemService(Context.ACCESSIBILITY_SERVICE) as? AccessibilityManager if (am != null) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt index e7c71c6f32bf..f9a1560da9c2 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt @@ -21,10 +21,10 @@ import com.facebook.react.common.ReactConstants import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags import com.facebook.react.module.annotations.ReactModule import com.facebook.react.uimanager.BackgroundStyleApplicator +import com.facebook.react.uimanager.ImportantForAccessibilityHelper import com.facebook.react.uimanager.LengthPercentage import com.facebook.react.uimanager.PixelUtil.dpToPx import com.facebook.react.uimanager.PointerEvents -import com.facebook.react.uimanager.ReactAxOrderHelper import com.facebook.react.uimanager.Spacing import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.UIManagerHelper @@ -91,13 +91,32 @@ public open class ReactViewManager : ReactClippingViewManager() } override fun onDropViewInstance(view: ReactViewGroup) { + view.dropAccessibilityOrder() super.onDropViewInstance(view) - view.cleanUpAxOrderListener() + } + + override fun onAfterUpdateTransaction(view: ReactViewGroup) { + view.applyFocusProps() + super.onAfterUpdateTransaction(view) } @ReactProp(name = "accessible") public open fun setAccessible(view: ReactViewGroup, accessible: Boolean) { - view.isFocusable = accessible + view.updateFocusProps(view.focusProps.copy(accessible = accessible)) + } + + override fun setScreenReaderFocusable(view: ReactViewGroup, screenReaderFocusable: Boolean) { + view.updateFocusProps(view.focusProps.copy(screenReaderFocusable = screenReaderFocusable)) + } + + override fun setImportantForAccessibility( + view: ReactViewGroup, + importantForAccessibility: String?, + ) { + val mode = + ImportantForAccessibilityHelper.parseImportantForAccessibility(importantForAccessibility) + ?: return + view.updateFocusProps(view.focusProps.copy(importantForAccessibility = mode)) } @ReactProp(name = ViewProps.ACCESSIBILITY_ORDER) @@ -106,9 +125,7 @@ public open class ReactViewManager : ReactClippingViewManager() return } - for (i in 0 until view.childCount) { - ReactAxOrderHelper.cleanUpAxOrder(view.getChildAt(i)) - } + view.restoreAccessibilityOrderFocusability() if (nativeIds == null) { view.axOrderList = null @@ -436,23 +453,18 @@ public open class ReactViewManager : ReactClippingViewManager() } @ReactProp(name = "focusable") - public open fun setFocusable(view: ReactViewGroup, focusable: Boolean) { - if (focusable) { + public open fun setFocusable(view: ReactViewGroup, focusable: Boolean?) { + view.updateFocusProps(view.focusProps.copy(focusable = focusable)) + if (focusable == true) { view.setOnClickListener { val eventDispatcher = UIManagerHelper.getEventDispatcher(view.context as ReactContext) eventDispatcher?.dispatchEvent( ViewGroupClickEvent(UIManagerHelper.getSurfaceId(view.context), view.id), ) } - - // Clickable elements are focusable. On API 26, this is taken care by setClickable. - // Explicitly calling setFocusable here for backward compatibility. - view.isFocusable = true } else { view.setOnClickListener(null) view.isClickable = false - // Don't set view.setFocusable(false) because we might still want it to be focusable for - // accessibility reasons } } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.cpp index 1e4e04c49d9c..53c003ced714 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FocusOrderingHelper.cpp @@ -201,13 +201,9 @@ void FocusOrderingHelper::traverseAndUpdateNextFocusableElement( Rect sourceRect, std::optional& nextRect, std::shared_ptr& nextNode) { - const auto* props = - dynamic_cast(currNode->getProps().get()); - // We only care about focusable elements since only they can be both // focused and present in the hierarchy - if (currNode->getTraits().check(ShadowNodeTraits::Trait::KeyboardFocusable) || - (props != nullptr && (props->focusable || props->accessible))) { + if (currNode->getTraits().check(ShadowNodeTraits::Trait::KeyboardFocusable)) { LayoutMetrics nodeLayoutMetrics = uimanager.getRelativeLayoutMetrics( *currNode, parentShadowNode.get(), {.includeTransform = true}); diff --git a/packages/react-native/ReactAndroid/src/main/res/views/uimanager/values/ids.xml b/packages/react-native/ReactAndroid/src/main/res/views/uimanager/values/ids.xml index f03f85cdc201..44fb06d156cb 100644 --- a/packages/react-native/ReactAndroid/src/main/res/views/uimanager/values/ids.xml +++ b/packages/react-native/ReactAndroid/src/main/res/views/uimanager/values/ids.xml @@ -12,9 +12,12 @@ - + + + + diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt index 666aa2bd71e2..54fafa76ba98 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/BaseViewManagerTest.kt @@ -340,11 +340,18 @@ class BaseViewManagerTest { mutableListOf(), arrayOfNulls(0), ) - ReactAxOrderHelper.disableFocusForSubtree(previous, mutableListOf()) + AccessibilityOrderHolds().disableFocusForSubtree(previous, emptyList()) } Assertions.assertThat(recycled.getTag(R.id.accessibility_order_parent)).isNull() - Assertions.assertThat(recycled.getTag(R.id.original_focusability)).isNull() + viewManager.updateProperties( + recycled, + ReactStylesDiffMap( + JavaOnlyMap.of("focusable", true, ViewProps.SCREEN_READER_FOCUSABLE, true) + ), + ) + Assertions.assertThat(recycled.isFocusable).isTrue() + Assertions.assertThat(ViewCompat.isScreenReaderFocusable(recycled)).isTrue() } @Test @@ -419,6 +426,20 @@ class BaseViewManagerTest { Assertions.assertThat(view.elevation).isEqualTo(0f) } + @Test + fun testScreenReaderFocusableSetWhileAnAccessibilityOrderHoldsFocusWaitsForItToLetGo() { + val manager = ReactScrollViewManager() + val scrollView = createView(manager, JavaOnlyMap()) + val holds = AccessibilityOrderHolds() + holds.disableFocusForSubtree(scrollView, emptyList()) + + manager.setScreenReaderFocusable(scrollView, true) + + Assertions.assertThat(ViewCompat.isScreenReaderFocusable(scrollView)).isFalse() + holds.restoreFocusability() + Assertions.assertThat(ViewCompat.isScreenReaderFocusable(scrollView)).isTrue() + } + private fun recycleView( previousProps: JavaOnlyMap, beforeDrop: (ReactViewGroup) -> Unit = {}, diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ImportantForAccessibilityHelperTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ImportantForAccessibilityHelperTest.kt new file mode 100644 index 000000000000..f208d48f3cbe --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/ImportantForAccessibilityHelperTest.kt @@ -0,0 +1,41 @@ +/* + * 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 + +import android.view.View +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test + +class ImportantForAccessibilityHelperTest { + + @Test + fun parseImportantForAccessibility_mapsEachValueToItsViewMode() { + val values = + listOf( + null to View.IMPORTANT_FOR_ACCESSIBILITY_AUTO, + "auto" to View.IMPORTANT_FOR_ACCESSIBILITY_AUTO, + "yes" to View.IMPORTANT_FOR_ACCESSIBILITY_YES, + "no" to View.IMPORTANT_FOR_ACCESSIBILITY_NO, + "no-hide-descendants" to View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, + ) + for ((value, expected) in values) { + assertThat(ImportantForAccessibilityHelper.parseImportantForAccessibility(value)) + .describedAs("$value") + .isEqualTo(expected) + } + } + + @Test + fun parseImportantForAccessibility_valuesOutsideThePropsValuesMapToNoMode() { + for (value in listOf("", "sometimes", "YES", " auto ")) { + assertThat(ImportantForAccessibilityHelper.parseImportantForAccessibility(value)) + .describedAs(value) + .isNull() + } + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/view/ReactViewFocusTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/view/ReactViewFocusTest.kt new file mode 100644 index 000000000000..c7261a9afc4f --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/view/ReactViewFocusTest.kt @@ -0,0 +1,759 @@ +/* + * 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.view + +import android.app.Activity +import android.os.Build +import android.os.Looper +import android.util.DisplayMetrics +import android.view.FocusFinder +import android.view.View +import android.view.ViewGroup +import android.view.accessibility.AccessibilityManager +import android.view.accessibility.AccessibilityNodeInfo +import android.view.inputmethod.EditorInfo +import android.widget.EditText +import android.widget.TextView +import androidx.core.view.accessibility.AccessibilityNodeInfoCompat +import com.facebook.react.bridge.JavaOnlyArray +import com.facebook.react.bridge.JavaOnlyMap +import com.facebook.react.bridge.ReactApplicationContext +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.touch.JSResponderHandler +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.facebook.react.uimanager.ReactClippingViewGroupHelper +import com.facebook.react.uimanager.ReactStylesDiffMap +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.ViewProps +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.mock +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.android.controller.ActivityController +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config( + sdk = + [ + Build.VERSION_CODES.TIRAMISU, + Build.VERSION_CODES.UPSIDE_DOWN_CAKE, + Build.VERSION_CODES.VANILLA_ICE_CREAM, + ], +) +class ReactViewFocusTest { + + private lateinit var themedReactContext: ThemedReactContext + private lateinit var viewManager: ReactViewManager + private val activityControllers = mutableListOf>() + private var nextTag = 1 + + @Before + fun setUp() { + ReactNativeFeatureFlagsForTests.setUp() + ReactNativeFeatureFlags.override( + object : ReactNativeFeatureFlagsDefaults() { + override fun enableAccessibilityOrder(): Boolean = true + + override fun enableImperativeFocus(): Boolean = true + + override fun enableViewRecycling(): Boolean = true + }, + ) + DisplayMetricsHolder.setScreenDisplayMetrics(DisplayMetrics()) + themedReactContext = + ThemedReactContext( + mock(), + RuntimeEnvironment.getApplication(), + null, + -1, + ) + viewManager = ReactViewManager() + } + + @After + fun tearDown() { + activityControllers.forEach { it.pause().stop().destroy() } + DisplayMetricsHolder.setScreenDisplayMetrics(null) + ReactNativeFeatureFlags.dangerouslyReset() + } + + @Test + fun `focusable false - Tab and the arrow keys pass over an accessible view`() { + val leading = control(top = 0) + val excluded = excludedView(top = 10) + val trailing = control(top = 20) + val root = attach(leading, excluded, trailing) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(trailing) + assertThat(nextFocus(root, trailing, View.FOCUS_BACKWARD)).isSameAs(leading) + assertThat(nextFocus(root, leading, View.FOCUS_DOWN)).isSameAs(trailing) + assertThat(nextFocus(root, trailing, View.FOCUS_UP)).isSameAs(leading) + } + + @Test + fun `focusable false - a next focus id naming an excluded view passes over it`() { + val leading = control(top = 0) + val excluded = excludedView(top = 10) + val trailing = control(top = 20) + leading.nextFocusForwardId = excluded.id + val root = attach(leading, excluded, trailing) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(trailing) + } + + @Test + fun `focusable false - an editor's next action toward an excluded view moves focus on`() { + val excluded = excludedView(top = 10) + val trailing = control(top = 20) + val editor = + EditText(themedReactContext).apply { + layout(0, 0, 100, 10) + imeOptions = EditorInfo.IME_ACTION_NEXT + nextFocusForwardId = excluded.id + } + attach(editor, excluded, trailing) + editor.requestFocus() + + editor.onEditorAction(EditorInfo.IME_ACTION_NEXT) + + assertThat(trailing.isFocused).isTrue() + } + + @Test + fun `focusable false - cluster navigation passes over an excluded view`() { + val excluded = excludedView(top = 0) + val trailing = control(top = 10) + val root = attach(excluded, trailing) + + ViewGroup::class.java.getMethod("restoreFocusNotInCluster").invoke(root) + + assertThat(excluded.isFocused).isFalse() + assertThat(trailing.isFocused).isTrue() + } + + @Test + fun `focusable false - default focus passes over an excluded view`() { + val excluded = excludedView(top = 0) + val trailing = control(top = 10) + val root = attach(excluded, trailing) + + assertThat(root.requestFocus(View.FOCUS_DOWN)).isTrue() + + assertThat(excluded.isFocused).isFalse() + assertThat(trailing.isFocused).isTrue() + } + + @Test + fun `focusable false - the descendants of an excluded view stay keyboard stops`() { + val leading = control(top = 0) + val excluded = excludedView(top = 10) + val descendant = control(top = 0) + excluded.addView(descendant) + val root = attach(leading, excluded) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(descendant) + } + + @Test + fun `focusable false - offers accessibility services no focus action`() { + val excluded = excludedView(top = 0) + attach(excluded) + + val actions = excluded.createAccessibilityNodeInfo().actionList + + assertThat(actions).doesNotContain(AccessibilityNodeInfo.AccessibilityAction.ACTION_FOCUS) + assertThat(excluded.performAccessibilityAction(AccessibilityNodeInfo.ACTION_FOCUS, null)) + .isFalse() + assertThat(excluded.isFocused).isFalse() + } + + @Test + fun `focusable false - takes a view that is not accessible out of keyboard navigation`() { + val leading = control(top = 0) + val view = reactView(FOCUSABLE to true, top = 10) + val trailing = control(top = 20) + val root = attach(leading, view, trailing) + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(view) + + update(view, FOCUSABLE to false) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(trailing) + assertThat(view.requestFocus()).isFalse() + } + + @Test + fun `focusable unset - keyboard focus follows accessible`() { + val leading = control(top = 0) + val view = reactView(ACCESSIBLE to true, top = 10) + val trailing = control(top = 20) + val root = attach(leading, view, trailing) + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(view) + + update(view, ACCESSIBLE to false) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(trailing) + } + + @Test + fun `focusable removed - returns an excluded view to the keyboard focus accessible gives it`() { + val leading = control(top = 0) + val excluded = excludedView(top = 10) + val root = attach(leading, excluded) + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isNull() + + update(excluded, FOCUSABLE to null) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(excluded) + } + + @Test + fun `ref focus - focuses an excluded accessible view`() { + val excluded = excludedView(top = 0) + attach(excluded) + + focusFromJS(excluded) + + assertThat(excluded.isFocused).isTrue() + } + + @Test + fun `ref focus - focuses a focusable false view that is not accessible`() { + val view = reactView(FOCUSABLE to false, top = 0) + attach(view) + + focusFromJS(view) + + assertThat(view.isFocused).isTrue() + } + + @Test + fun `ref focus - an excluded view leaves keyboard navigation once focus moves on`() { + val leading = control(top = 0) + val excluded = excludedView(top = 10) + val trailing = control(top = 20) + val root = attach(leading, excluded, trailing) + focusFromJS(excluded) + assertThat(nextFocus(root, excluded, View.FOCUS_FORWARD)).isSameAs(trailing) + assertThat(nextFocus(root, excluded, View.FOCUS_BACKWARD)).isSameAs(leading) + + trailing.requestFocus() + + assertThat(nextFocus(root, trailing, View.FOCUS_BACKWARD)).isSameAs(leading) + assertThat(excluded.requestFocus()).isFalse() + } + + @Test + fun `ref focus - a failed request leaves an excluded view out of keyboard navigation`() { + val excluded = excludedView(top = 0).apply { visibility = View.GONE } + attach(excluded) + + focusFromJS(excluded) + excluded.visibility = View.VISIBLE + + assertThat(excluded.isFocused).isFalse() + assertThat(excluded.requestFocus()).isFalse() + } + + @Test + fun `ref focus - a view with neither prop hands focus to its first focusable descendant`() { + val view = reactView(top = 0) + val descendant = control(top = 0) + view.addView(descendant) + attach(view) + + focusFromJS(view) + + assertThat(view.isFocused).isFalse() + assertThat(descendant.isFocused).isTrue() + } + + @Test + fun `focusable turning false keeps focus on a focused view until focus moves on`() { + val view = reactView(FOCUSABLE to true, top = 0) + val trailing = control(top = 10) + val root = attach(view, trailing) + view.requestFocus() + + update(view, FOCUSABLE to false) + + assertThat(view.isFocused).isTrue() + trailing.requestFocus() + assertThat(nextFocus(root, trailing, View.FOCUS_BACKWARD)).isNull() + assertThat(view.requestFocus()).isFalse() + } + + @Test + fun `focusable false - an accessible view stays one screen reader element`() { + val excluded = excludedView(top = 0) + val title = text("Title") + excluded.addView(title) + val root = attach(excluded) + + assertThat(excluded.createAccessibilityNodeInfo().isScreenReaderFocusable).isTrue() + assertThat(excluded.isImportantForAccessibility).isTrue() + assertThat(accessibilityChildren(root)).containsExactly(excluded) + } + + @Test + @Config(sdk = [Build.VERSION_CODES.O_MR1]) + fun `focusable false - below API 28 an accessible view reports itself screen reader focusable`() { + val excluded = excludedView(top = 0) + excluded.addView(text("Title")) + val root = attach(excluded) + + val node = AccessibilityNodeInfoCompat.wrap(excluded.createAccessibilityNodeInfo()) + + assertThat(node.isScreenReaderFocusable).isTrue() + assertThat(excluded.isImportantForAccessibility).isTrue() + assertThat(excluded.isFocusable).isFalse() + assertThat(accessibilityChildren(root)).containsExactly(excluded) + } + + @Test + fun `focusable unset - an accessible view keeps the accessibility state it has on main`() { + val view = reactView(ACCESSIBLE to true, top = 0) + attach(view) + + assertThat(view.isFocusable).isTrue() + assertThat(view.createAccessibilityNodeInfo().isScreenReaderFocusable).isFalse() + assertThat(view.importantForAccessibility).isEqualTo(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) + assertThat(view.isImportantForAccessibility).isTrue() + } + + @Test + fun `screenReaderFocusable - puts a view in the accessibility tree as one element`() { + val view = reactView(ViewProps.SCREEN_READER_FOCUSABLE to true, top = 0) + view.addView(text("Title")) + val root = attach(view) + + assertThat(view.isFocusable).isFalse() + assertThat(view.createAccessibilityNodeInfo().isScreenReaderFocusable).isTrue() + assertThat(accessibilityChildren(root)).containsExactly(view) + } + + @Test + fun `importantForAccessibility no - keeps an excluded view out of the accessibility tree`() { + val excluded = + reactView( + ACCESSIBLE to true, + FOCUSABLE to false, + ViewProps.IMPORTANT_FOR_ACCESSIBILITY to "no", + top = 0, + ) + attach(excluded) + + assertThat(excluded.isImportantForAccessibility).isFalse() + } + + @Test + fun `importantForAccessibility auto - leaves an excluded view in the accessibility tree as one element`() { + val excluded = excludedView(top = 0) + excluded.addView(text("Title")) + val root = attach(excluded) + + update(excluded, ViewProps.IMPORTANT_FOR_ACCESSIBILITY to "auto") + + assertThat(excluded.isImportantForAccessibility).isTrue() + assertThat(accessibilityChildren(root)).containsExactly(excluded) + } + + @Test + fun `importantForAccessibility outside its values - keeps the importance the other props give`() { + val view = reactView(ViewProps.SCREEN_READER_FOCUSABLE to true, top = 0) + attach(view) + + update(view, ViewProps.IMPORTANT_FOR_ACCESSIBILITY to "sometimes") + update(view, ViewProps.SCREEN_READER_FOCUSABLE to false) + + assertThat(view.importantForAccessibility).isEqualTo(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) + } + + @Test + fun `a label keeps a view that is not accessible in the accessibility tree`() { + val view = reactView(ACCESSIBLE to false, ViewProps.ACCESSIBILITY_LABEL to "Profile", top = 0) + val excluded = reactView(FOCUSABLE to false, ViewProps.ACCESSIBILITY_LABEL to "Close", top = 10) + attach(view, excluded) + + assertThat(view.isImportantForAccessibility).isTrue() + assertThat(excluded.isImportantForAccessibility).isTrue() + } + + @Test + fun `accessibilityOrder - takes an excluded accessible view as one element`() { + val excluded = excludedView(top = 0, ViewProps.NATIVE_ID to "excluded") + excluded.addView(text("Title")) + val container = + reactView(ViewProps.ACCESSIBILITY_ORDER to JavaOnlyArray.of("excluded"), top = 0) + container.addView(excluded) + attach(container) + + assertThat(accessibilityChildren(container)).containsExactly(excluded) + } + + @Test + fun `accessibilityOrder - a container that reads its subtree keeps an excluded descendant from being read on its own`() { + val excluded = excludedView(top = 0) + excluded.addView(text("Delete")) + val reader = readerUnderAccessibilityOrder(excluded) + + walkAccessibilityOrder(reader) + + val node = excluded.createAccessibilityNodeInfo() + assertThat(node.isFocusable).isFalse() + assertThat(node.isScreenReaderFocusable).isFalse() + } + + @Test + fun `accessibilityOrder - a view focused from JS leaves keyboard navigation once the order lets it go`() { + val excluded = excludedView(top = 0) + val reader = readerUnderAccessibilityOrder(excluded) + focusFromJS(excluded) + assertThat(excluded.isFocused).isTrue() + walkAccessibilityOrder(reader) + + update(reader.parent as ReactViewGroup, ViewProps.ACCESSIBILITY_ORDER to null) + + assertThat(focusState(excluded)).isEqualTo(focusStateOfANewExcludedView()) + } + + @Test + fun `accessibilityOrder - focus props applied while the order holds a view's focus take effect once it lets go`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val reader = readerUnderAccessibilityOrder(view) + walkAccessibilityOrder(reader) + + update(view, FOCUSABLE to false) + + assertThat(focusState(view).focusable).isFalse() + assertThat(focusState(view).screenReaderFocusable).isFalse() + update(reader.parent as ReactViewGroup, ViewProps.ACCESSIBILITY_ORDER to null) + assertThat(focusState(view)).isEqualTo(focusStateOfANewExcludedView()) + } + + @Test + fun `accessibilityOrder - takes the focus state a view has each time it holds the view's focus`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val reader = readerUnderAccessibilityOrder(view) + val container = reader.parent as ReactViewGroup + walkAccessibilityOrder(reader) + update(container, ViewProps.ACCESSIBILITY_ORDER to null) + update(view, FOCUSABLE to false) + update(container, ViewProps.ACCESSIBILITY_ORDER to JavaOnlyArray.of("reader")) + walkAccessibilityOrder(reader) + + update(container, ViewProps.ACCESSIBILITY_ORDER to null) + + assertThat(focusState(view)).isEqualTo(focusStateOfANewExcludedView()) + } + + @Test + fun `accessibilityOrder - walking it again gives back the focus a view had before the first walk`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val reader = readerUnderAccessibilityOrder(view) + walkAccessibilityOrder(reader) + walkAccessibilityOrder(reader) + + update(reader.parent as ReactViewGroup, ViewProps.ACCESSIBILITY_ORDER to null) + + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to true)) + } + + @Test + fun `accessibilityOrder - lets go only of the views it still holds`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val firstReader = readerUnderAccessibilityOrder(view) + walkAccessibilityOrder(firstReader) + firstReader.removeView(view) + val secondReader = readerUnderAccessibilityOrder(view) + walkAccessibilityOrder(secondReader) + + update(firstReader.parent as ReactViewGroup, ViewProps.ACCESSIBILITY_ORDER to null) + + assertThat(focusState(view).focusable).isFalse() + update(secondReader.parent as ReactViewGroup, ViewProps.ACCESSIBILITY_ORDER to null) + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to true)) + } + + @Test + fun `accessibilityOrder - gives back the focus it holds when its view is dropped`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val reader = readerUnderAccessibilityOrder(view) + walkAccessibilityOrder(reader) + + viewManager.onDropViewInstance(reader.parent as ReactViewGroup) + + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to true)) + update(view, ACCESSIBLE to false) + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to false)) + } + + @Test + fun `accessibilityOrder - holds no focus once its view is dropped without being recycled`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val reader = readerUnderAccessibilityOrder(view) + val container = reader.parent as ReactViewGroup + walkAccessibilityOrder(reader) + + container.removeView(reader) + object : ReactViewManager() {}.onDropViewInstance(container) + attach(reader) + accessibilityChildren(reader) + + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to true)) + } + + @Test + fun `accessibilityOrder - gives back the focus it holds on a view clipped out of the hierarchy`() { + val view = reactView(ACCESSIBLE to true, top = 100) + val reader = readerUnderAccessibilityOrder(clippingParentOf(view)) + walkAccessibilityOrder(reader) + clipOut(view) + + update(reader.parent as ReactViewGroup, ViewProps.ACCESSIBILITY_ORDER to null) + + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to true)) + } + + @Test + fun `accessibilityOrder - gives back the focus it holds on a clipped view once accessibility services turn off`() { + val view = reactView(ACCESSIBLE to true, top = 100) + val reader = readerUnderAccessibilityOrder(clippingParentOf(view)) + walkAccessibilityOrder(reader) + clipOut(view) + + shadowOf(themedReactContext.getSystemService(AccessibilityManager::class.java)) + .setEnabled(false) + + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to true)) + } + + @Test + fun `accessibilityOrder - keeps its holds only while it holds a view's focus`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val reader = readerUnderAccessibilityOrder(view) + val container = reader.parent as ReactViewGroup + assertThat(container.accessibilityOrderHolds).isNull() + + walkAccessibilityOrder(reader) + assertThat(container.accessibilityOrderHolds).isNotNull() + + update(container, ViewProps.ACCESSIBILITY_ORDER to null) + assertThat(container.accessibilityOrderHolds).isNull() + } + + @Test + fun `accessibilityOrder - a view moved out of its subtree no longer follows it`() { + val view = reactView(ACCESSIBLE to true, top = 0) + val reader = readerUnderAccessibilityOrder(view) + val container = reader.parent as ReactViewGroup + accessibilityChildren(container) + container.removeView(reader) + attach(reader) + + accessibilityChildren(reader) + + assertThat(focusState(view)).isEqualTo(focusStateOfANewView(ACCESSIBLE to true)) + } + + @Test + fun `a ReactViewGroup another manager drives keeps its own focusability once focus moves on`() { + val view = + ReactViewGroup(themedReactContext).apply { + isFocusable = true + layout(0, 0, 100, 10) + } + val trailing = control(top = 10) + attach(view, trailing) + view.requestFocus() + + trailing.requestFocus() + + assertThat(view.isFocusable).isTrue() + assertThat(view.requestFocus()).isTrue() + } + + @Test + fun `the focus state is the same whichever prop applies first`() { + for ((accessible, focusable) in listOf(true to false, false to true)) { + val accessibleFirst = reactView(ACCESSIBLE to accessible, top = 0) + update(accessibleFirst, FOCUSABLE to focusable) + val focusableFirst = reactView(FOCUSABLE to focusable, top = 10) + update(focusableFirst, ACCESSIBLE to accessible) + attach(accessibleFirst, focusableFirst) + + assertThat(focusableFirst.isFocusable) + .describedAs("accessible $accessible, focusable $focusable") + .isEqualTo(focusable) + assertThat(focusState(focusableFirst)).isEqualTo(focusState(accessibleFirst)) + } + } + + @Test + fun `applying the same props again changes nothing`() { + val leading = control(top = 0) + val excluded = excludedView(top = 10) + attach(leading, excluded) + val before = focusState(excluded) + + update(excluded, ACCESSIBLE to true, FOCUSABLE to false) + + assertThat(focusState(excluded)).isEqualTo(before) + assertThat(excluded.isFocused).isFalse() + } + + @Test + fun `recycling returns a view to the focus state a new view has`() { + val fresh = reactView(top = 0) + val excluded = excludedView(top = 10, ViewProps.SCREEN_READER_FOCUSABLE to true) + attach(fresh, excluded) + focusFromJS(excluded) + + viewManager.onDropViewInstance(excluded) + val recycled = reactView(top = 0) + + assertThat(recycled).isSameAs(excluded) + assertThat(recycled.isFocused).isFalse() + assertThat(focusState(recycled)).isEqualTo(focusState(fresh)) + update(recycled, ACCESSIBLE to false) + update(fresh, ACCESSIBLE to false) + assertThat(focusState(recycled)).isEqualTo(focusState(fresh)) + } + + @Test + fun `views without focus props share one default focus props, also once recycled`() { + val fresh = reactView(top = 0) + val excluded = excludedView(top = 10) + + viewManager.onDropViewInstance(excluded) + val recycled = reactView(top = 0) + + assertThat(recycled).isSameAs(excluded) + assertThat(recycled.focusProps).isSameAs(fresh.focusProps) + } + + private fun reactView(vararg props: Pair, top: Int): ReactViewGroup = + viewManager + .createView( + nextTag++, + themedReactContext, + diffMap(*props), + null, + JSResponderHandler(), + ) + .apply { layout(0, top, 100, top + 10) } + + private fun excludedView(top: Int, vararg props: Pair): ReactViewGroup = + reactView(ACCESSIBLE to true, FOCUSABLE to false, *props, top = top) + + private fun update(view: ReactViewGroup, vararg props: Pair) { + viewManager.updateProperties(view, diffMap(*props)) + } + + private fun focusFromJS(view: ReactViewGroup) { + viewManager.receiveCommand(view, "focus", JavaOnlyArray()) + } + + private fun diffMap(vararg props: Pair): ReactStylesDiffMap = + ReactStylesDiffMap(JavaOnlyMap.of(*props.flatMap { it.toList() }.toTypedArray())) + + private fun control(top: Int): View = + View(themedReactContext).apply { + isFocusable = true + layout(0, top, 100, top + 10) + } + + private fun text(content: String): TextView = + TextView(themedReactContext).apply { + text = content + layout(0, 0, 100, 10) + } + + private fun attach(vararg views: View): ReactViewGroup { + val root = ReactViewGroup(themedReactContext) + views.forEach(root::addView) + val activityController = Robolectric.buildActivity(Activity::class.java).setup() + activityControllers.add(activityController) + activityController.get().setContentView(root) + shadowOf(Looper.getMainLooper()).idle() + return root + } + + private fun focusStateOfANewExcludedView(): FocusState = + focusStateOfANewView(ACCESSIBLE to true, FOCUSABLE to false) + + private fun focusStateOfANewView(vararg props: Pair): FocusState { + val view = reactView(*props, top = 10) + attach(view) + return focusState(view) + } + + private fun clippingParentOf(view: View): ReactViewGroup = + reactView(top = 0).apply { addView(view) } + + private fun clipOut(view: View) { + update( + view.parent as ReactViewGroup, + ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS to true, + ) + assertThat(view.parent).isNull() + } + + private fun readerUnderAccessibilityOrder(vararg views: View): ReactViewGroup { + val reader = reactView(ACCESSIBLE to true, ViewProps.NATIVE_ID to "reader", top = 0) + views.forEach(reader::addView) + val container = reactView(ViewProps.ACCESSIBILITY_ORDER to JavaOnlyArray.of("reader"), top = 0) + container.addView(reader) + attach(container) + return reader + } + + private fun walkAccessibilityOrder(reader: ReactViewGroup) { + accessibilityChildren(reader.parent as ReactViewGroup) + accessibilityChildren(reader) + } + + private fun nextFocus(root: ViewGroup, focused: View, direction: Int): View? = + FocusFinder.getInstance().findNextFocus(root, focused, direction) + + private fun accessibilityChildren(view: ViewGroup): List { + val children = ArrayList() + view.addChildrenForAccessibility(children) + return children + } + + private fun focusState(view: ReactViewGroup): FocusState { + val node = AccessibilityNodeInfoCompat.wrap(view.createAccessibilityNodeInfo()) + return FocusState( + focusable = view.isFocusable, + screenReaderFocusable = node.isScreenReaderFocusable, + importantForAccessibility = view.importantForAccessibility, + clickable = view.isClickable, + ) + } + + private companion object { + const val ACCESSIBLE = "accessible" + const val FOCUSABLE = "focusable" + } + + private data class FocusState( + val focusable: Boolean, + val screenReaderFocusable: Boolean, + val importantForAccessibility: Int, + val clickable: Boolean, + ) +} diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp index 5dca96365803..7a348719db22 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/ViewShadowNode.cpp @@ -6,6 +6,7 @@ */ #include "ViewShadowNode.h" +#include #include #include @@ -74,6 +75,13 @@ void ViewShadowNode::initialize() noexcept { HostPlatformViewTraitsInitializer::formsView(viewProps) || viewProps.outlineWidth > 0; +#ifdef ANDROID + // Only enableImperativeFocus lets ref.focus() reach focusable={false}. + formsView = formsView || + (viewProps.focusable.has_value() && + ReactNativeFeatureFlags::enableImperativeFocus()); +#endif + if (formsView) { traits_.set(ShadowNodeTraits::Trait::FormsView); } else { @@ -91,6 +99,17 @@ void ViewShadowNode::initialize() noexcept { } else { traits_.unset(ShadowNodeTraits::Trait::ChildrenFormStackingContext); } + +#ifdef ANDROID + // ReactViewGroup's keyboard focus takes `focusable` over `accessible`. + if (viewProps.focusable.has_value()) { + if (*viewProps.focusable) { + traits_.set(ShadowNodeTraits::Trait::KeyboardFocusable); + } else { + traits_.unset(ShadowNodeTraits::Trait::KeyboardFocusable); + } + } +#endif } } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp index 22e4ebff747c..6127e37bd359 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp @@ -528,7 +528,11 @@ folly::dynamic HostPlatformViewProps::getDiffProps( } if (focusable != oldProps->focusable) { - result["focusable"] = focusable; + if (focusable.has_value()) { + result["focusable"] = focusable.value(); + } else { + result["focusable"] = folly::dynamic(nullptr); + } } if (needsOffscreenAlphaCompositing != diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h index d1cdbb86f2d1..ac05f2bb7b3f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.h @@ -41,7 +41,7 @@ class HostPlatformViewProps : public BaseViewProps { std::optional nativeBackground{}; std::optional nativeForeground{}; - bool focusable{false}; + std::optional focusable{}; bool needsOffscreenAlphaCompositing{false}; bool renderToHardwareTextureAndroid{false}; bool screenReaderFocusable{false}; diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h index f155014e5f61..ef3015a29507 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewTraitsInitializer.h @@ -21,14 +21,14 @@ inline bool formsStackingContext(const ViewProps &viewProps) inline bool formsView(const ViewProps &viewProps) { - return viewProps.nativeBackground.has_value() || viewProps.nativeForeground.has_value() || viewProps.focusable || - viewProps.needsOffscreenAlphaCompositing || viewProps.renderToHardwareTextureAndroid || - viewProps.screenReaderFocusable; + return viewProps.nativeBackground.has_value() || viewProps.nativeForeground.has_value() || + viewProps.focusable.value_or(false) || viewProps.needsOffscreenAlphaCompositing || + viewProps.renderToHardwareTextureAndroid || viewProps.screenReaderFocusable; } inline bool isKeyboardFocusable(const ViewProps &viewProps) { - return viewProps.focusable; + return viewProps.focusable.value_or(false); } } // namespace facebook::react::HostPlatformViewTraitsInitializer diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewPropsDiffTest.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewPropsDiffTest.cpp index 7fe5a6dfdab3..0e2a7ea5897d 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewPropsDiffTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewPropsDiffTest.cpp @@ -144,6 +144,18 @@ TEST(ViewPropsDiffTest, emitsAnExplicitRoleNone) { {{dynamic::object("role", "none")("accessibilityRole", "button")}}); } +// ReactViewManager tells an explicit focusable={false} from an unset one. +TEST(ViewPropsDiffTest, emitsAnExplicitFocusableFalse) { + expectPayloads({{dynamic::object("focusable", false)}}); +} + +TEST(ViewPropsDiffTest, removingFocusableEmitsNull) { + expectPayloads({ + {dynamic::object("focusable", false)}, + {dynamic::object("focusable", nullptr)}, + }); +} + // BaseViewManager clears the value and the content description only for null. TEST(ViewPropsDiffTest, removingAccessibilityValueEmitsNull) { expectPayloads({ diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp index 1e0a06b31da1..ee7f35a7b894 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp @@ -10,6 +10,8 @@ #include +#include +#include #include #include #include @@ -48,6 +50,100 @@ TEST(ViewTest, constexprBaseTraits) { rootTraits.get() | ShadowNodeTraits::Trait::Unstable_uncullableView)); } +#ifdef ANDROID +namespace { + +ShadowNodeTraits traitsWithProps( + const ShadowNode& shadowNode, + const folly::dynamic& rawProps) { + ContextContainer contextContainer{}; + PropsParserContext parserContext{-1, contextContainer}; + auto props = shadowNode.getComponentDescriptor().cloneProps( + parserContext, nullptr, RawProps(rawProps)); + return shadowNode.clone(ShadowNodeFragment{.props = props})->getTraits(); +} + +bool viewFormsView(const folly::dynamic& rawProps) { + auto builder = simpleComponentBuilder(); + std::shared_ptr view; + builder.build( + Element().tag(1).children( + {Element().tag(2).reference(view)})); + return traitsWithProps(*view, rawProps) + .check(ShadowNodeTraits::Trait::FormsView); +} + +class ImperativeFocusFlags : public ReactNativeFeatureFlagsDefaults { + public: + bool enableImperativeFocus() override { + return true; + } +}; + +class ImperativeFocusViewTest : public ::testing::Test { + protected: + void SetUp() override { + ReactNativeFeatureFlags::dangerouslyReset(); + ReactNativeFeatureFlags::override(std::make_unique()); + } + + void TearDown() override { + ReactNativeFeatureFlags::dangerouslyReset(); + } +}; + +} // namespace + +TEST(ViewTest, keyboardFocusableTraitTakesFocusableThenAccessible) { + auto builder = simpleComponentBuilder(); + std::shared_ptr view; + builder.build( + Element().tag(1).children( + {Element().tag(2).reference(view)})); + auto isKeyboardFocusable = [&](const folly::dynamic& rawProps) { + return traitsWithProps(*view, rawProps) + .check(ShadowNodeTraits::Trait::KeyboardFocusable); + }; + + EXPECT_FALSE(isKeyboardFocusable(folly::dynamic::object())); + EXPECT_TRUE(isKeyboardFocusable(folly::dynamic::object("accessible", true))); + EXPECT_TRUE(isKeyboardFocusable(folly::dynamic::object("focusable", true))); + EXPECT_FALSE(isKeyboardFocusable( + folly::dynamic::object("accessible", true)("focusable", false))); + EXPECT_FALSE(isKeyboardFocusable(folly::dynamic::object("focusable", false))); +} + +TEST(ViewTest, paragraphKeyboardFocusableTraitTakesFocusableOrAccessible) { + auto builder = simpleComponentBuilder(); + std::shared_ptr paragraph; + builder.build( + Element().tag(1).children( + {Element().tag(2).reference(paragraph)})); + auto isKeyboardFocusable = [&](const folly::dynamic& rawProps) { + return traitsWithProps(*paragraph, rawProps) + .check(ShadowNodeTraits::Trait::KeyboardFocusable); + }; + + EXPECT_FALSE(isKeyboardFocusable(folly::dynamic::object())); + EXPECT_TRUE(isKeyboardFocusable(folly::dynamic::object("accessible", true))); + EXPECT_TRUE(isKeyboardFocusable(folly::dynamic::object("focusable", true))); + EXPECT_TRUE(isKeyboardFocusable( + folly::dynamic::object("accessible", true)("focusable", false))); +} + +TEST(ViewTest, focusableFalseFormsNoViewWithoutImperativeFocus) { + EXPECT_FALSE(viewFormsView(folly::dynamic::object())); + EXPECT_FALSE(viewFormsView(folly::dynamic::object("focusable", false))); + EXPECT_TRUE(viewFormsView(folly::dynamic::object("focusable", true))); +} + +TEST_F(ImperativeFocusViewTest, explicitFocusableFormsView) { + EXPECT_FALSE(viewFormsView(folly::dynamic::object())); + EXPECT_TRUE(viewFormsView(folly::dynamic::object("focusable", false))); + EXPECT_TRUE(viewFormsView(folly::dynamic::object("focusable", true))); +} +#endif + class YogaDirtyFlagTest : public ::testing::Test { protected: ComponentBuilder builder_; diff --git a/packages/rn-tester/.maestro/keyboard-focus-exclusion.yml b/packages/rn-tester/.maestro/keyboard-focus-exclusion.yml new file mode 100644 index 000000000000..4f1b90f107a0 --- /dev/null +++ b/packages/rn-tester/.maestro/keyboard-focus-exclusion.yml @@ -0,0 +1,34 @@ +appId: ${APP_ID} # iOS: com.meta.RNTester.localDevelopment | Android: com.facebook.react.uiapp +tags: + - android-only +--- +- runFlow: + when: + platform: Android + commands: + - launchApp + - stopApp + - openLink: rntester://example/FocusEventsExample/keyboard-focus-exclusion + - runFlow: ./helpers/confirm-open-link.yml + - extendedWaitUntil: + visible: + id: 'keyboard_focus_view_input' + timeout: 120000 + - tapOn: + id: 'keyboard_focus_view_input' + - pressKey: Remote Dpad Down + - assertVisible: + id: 'keyboard_focus_view_next' + focused: true + - assertVisible: + id: 'keyboard_focus_view_excluded' + focused: false + - tapOn: + id: 'keyboard_focus_scroll_input' + - pressKey: Remote Dpad Down + - assertVisible: + id: 'keyboard_focus_scroll_next' + focused: true + - assertVisible: + id: 'keyboard_focus_scroll_excluded' + focused: false diff --git a/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js b/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js index 547c9908fad6..67dbc544fead 100644 --- a/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js +++ b/packages/rn-tester/js/examples/FocusEventsExample/FocusEventsExample.android.js @@ -12,7 +12,14 @@ import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import RNTesterText from '../../components/RNTesterText'; import {useState} from 'react'; -import {Alert, Pressable, StyleSheet, TextInput, View} from 'react-native'; +import { + Alert, + Pressable, + ScrollView, + StyleSheet, + TextInput, + View, +} from 'react-native'; type SectionProps = { children: React.Node, @@ -33,16 +40,29 @@ const FocusEventSection = ({children}: SectionProps): React.Node => { ); }; -const ViewExampleInnerRow = ({focusable}: {focusable: boolean}) => { +type ViewExampleInnerRowProps = { + accessible?: boolean, + focusable: boolean, + testID?: string, +}; + +const ViewExampleInnerRow = ({ + accessible, + focusable, + testID, +}: ViewExampleInnerRowProps) => { const [focused, setFocused] = useState(false); return ( setFocused(true)} onBlur={() => setFocused(false)} - style={[styles.viewInnerRow]}> + style={[styles.viewInnerRow]} + testID={testID}> Focusable: {focusable ? 'true' : 'false'} + {accessible === true ? ', accessible: true' : ''} Focused: {focused ? 'true' : 'false'} @@ -62,6 +82,44 @@ const ViewExample = () => { ); }; +const KeyboardFocusExclusionExample = () => { + return ( + <> + + Tap a text input, then press Tab: focus passes over the accessible view + with focusable=false. + + + + + + + + + + + ); +}; + const PressableExample = () => { const [pressableFocused, setPressableFocused] = useState(false); const [disabledPressableFocused, setDisabledPressableFocused] = @@ -126,6 +184,10 @@ const styles = StyleSheet.create({ padding: 8, rowGap: 16, }, + scrollView: { + height: 180, + marginTop: 4, + }, sectionSubtitle: { paddingBottom: 8, }, @@ -174,6 +236,13 @@ export default { return ; }, }, + { + title: 'Keyboard Focus Exclusion Example', + name: 'keyboard-focus-exclusion', + render: function (): React.Node { + return ; + }, + }, { title: 'TextInput Example', render: function (): React.Node { diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index f6d983a0272d..f7f13f0864f9 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -1335,6 +1335,7 @@ class facebook::react::HostPlatformViewProps : public facebook::react::BaseViewP public bool renderToHardwareTextureAndroid; public bool screenReaderFocusable; public facebook::react::Float elevation; + public std::optional focusable; public std::optional nativeBackground; public std::optional nativeForeground; public std::optional nextFocusDown; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index 6a7f3f69bce1..29c9d677cbcf 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -2069,6 +2069,7 @@ class facebook::react::HostPlatformViewProps : public facebook::react::BaseViewP public bool renderToHardwareTextureAndroid; public bool screenReaderFocusable; public facebook::react::Float elevation; + public std::optional focusable; public std::optional nativeBackground; public std::optional nativeForeground; public std::optional nextFocusDown; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index 7d2118c15877..edcb5ccb23ad 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -1334,6 +1334,7 @@ class facebook::react::HostPlatformViewProps : public facebook::react::BaseViewP public bool renderToHardwareTextureAndroid; public bool screenReaderFocusable; public facebook::react::Float elevation; + public std::optional focusable; public std::optional nativeBackground; public std::optional nativeForeground; public std::optional nextFocusDown; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index 7d2118c15877..edcb5ccb23ad 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -1334,6 +1334,7 @@ class facebook::react::HostPlatformViewProps : public facebook::react::BaseViewP public bool renderToHardwareTextureAndroid; public bool screenReaderFocusable; public facebook::react::Float elevation; + public std::optional focusable; public std::optional nativeBackground; public std::optional nativeForeground; public std::optional nextFocusDown;