From bb92824b374d2644746f7644beed30b1e983dd7c Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 20 Nov 2026 01:33:42 +0200 Subject: [PATCH 1/2] 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; From 81a882b6d8228365879eb70e3774908cb3c183e4 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 16 Oct 2026 14:13:54 +0300 Subject: [PATCH 2/2] Keep focusable={false} Android text out of keyboard navigation A Text with onPress or onLongPress is accessible, so setAccessible made it focusable, and a hardware keyboard's Tab, Shift+Tab and arrow keys stopped on it. Text had no focusable prop to take it out, so a pressable label between two inputs was always an extra keyboard stop. The text view managers now collect accessible, focusable, screenReaderFocusable and importantForAccessibility in the FocusProps #59048 gives View, and ReactTextView and PreparedLayoutTextView apply them after each transaction: isFocusable follows focusable, and accessible while focusable is unset, and an accessible text that keyboard navigation passes over stays one accessibility element through screenReaderFocusable. FocusProps gains applyTo and onFocusChanged, which ReactViewGroup now calls in place of its own copy of them. A selectable text stays focusable, and so does a ReactTextView whose dataDetectorType detects links while focusable is unset, as TextView keeps them. setTextIsSelectable, which ReactTextView calls on every attach, and setMovementMethod rewrite the view's focusability, so ReactTextView applies its focus props again after each. On Android a Paragraph's KeyboardFocusable trait takes the same rule, counting detected links only outside enablePreparedTextLayout, since PreparedLayoutTextView detects none, so a scroll view's focus search, which FocusOrderingHelper answers from that trait, agrees with the text view. TextProps and the legacy Text types declare the prop; the base view config already sends it. ReactAndroid.api gains ReactTextView.onInitializeAccessibilityNodeInfo, ReactTextViewManager.setFocusable, and ReactTextViewManager's setImportantForAccessibility and setScreenReaderFocusable overrides. --- .../react-native/Libraries/Text/TextProps.js | 10 + .../ReactAndroid/api/ReactAndroid.api | 6 + .../views/text/PreparedLayoutTextView.kt | 29 ++ .../text/PreparedLayoutTextViewManager.kt | 30 +- .../react/views/text/ReactTextView.java | 55 +++ .../react/views/text/ReactTextViewManager.kt | 25 +- .../facebook/react/views/view/FocusProps.kt | 29 +- .../react/views/view/ReactViewGroup.kt | 11 +- .../react/views/text/TextKeyboardFocusTest.kt | 453 ++++++++++++++++++ .../components/text/ParagraphShadowNode.cpp | 11 +- .../components/view/tests/ViewTest.cpp | 73 ++- packages/react-native/ReactNativeApi.d.ts | 11 +- .../types_DEPRECATED/Libraries/Text/Text.d.ts | 8 + 13 files changed, 730 insertions(+), 21 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/TextKeyboardFocusTest.kt diff --git a/packages/react-native/Libraries/Text/TextProps.js b/packages/react-native/Libraries/Text/TextProps.js index 6fb8b163595a..ce9718edeb3d 100644 --- a/packages/react-native/Libraries/Text/TextProps.js +++ b/packages/react-native/Libraries/Text/TextProps.js @@ -94,6 +94,16 @@ export type TextPropsAndroid = { */ disabled?: ?boolean, + /** + * Whether this `Text` should be focusable with a non-touch input device, eg. + * receive focus with a hardware keyboard. An accessible `Text` is focusable + * unless this is `false`, and accessibility services reach it either way. A + * `selectable` `Text` stays focusable, as selecting text takes focus. + * + * @platform android + */ + focusable?: ?boolean, + /** * Highlight color of the text when selected. * diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index d88414b0990a..da83d546fad0 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -6040,6 +6040,7 @@ public class com/facebook/react/views/text/ReactTextView : androidx/appcompat/wi public fun onAttachedToWindow ()V protected fun onDraw (Landroid/graphics/Canvas;)V public final fun onFocusChanged (ZILandroid/graphics/Rect;)V + public fun onInitializeAccessibilityNodeInfo (Landroid/view/accessibility/AccessibilityNodeInfo;)V protected fun onLayout (ZIIII)V protected fun onMeasure (II)V protected fun onSizeChanged (IIII)V @@ -6102,7 +6103,10 @@ public class com/facebook/react/views/text/ReactTextViewManager : com/facebook/r public final fun setDataDetectorType (Lcom/facebook/react/views/text/ReactTextView;Ljava/lang/String;)V public final fun setDisabled (Lcom/facebook/react/views/text/ReactTextView;Z)V public final fun setEllipsizeMode (Lcom/facebook/react/views/text/ReactTextView;Ljava/lang/String;)V + public final fun setFocusable (Lcom/facebook/react/views/text/ReactTextView;Ljava/lang/Boolean;)V public final fun setFontSize (Lcom/facebook/react/views/text/ReactTextView;F)V + public synthetic fun setImportantForAccessibility (Landroid/view/View;Ljava/lang/String;)V + public fun setImportantForAccessibility (Lcom/facebook/react/views/text/ReactTextView;Ljava/lang/String;)V public final fun setIncludeFontPadding (Lcom/facebook/react/views/text/ReactTextView;Z)V public final fun setLetterSpacing (Lcom/facebook/react/views/text/ReactTextView;F)V public final fun setLineBreak (Lcom/facebook/react/views/text/ReactTextView;Ljava/lang/String;)V @@ -6111,6 +6115,8 @@ public class com/facebook/react/views/text/ReactTextViewManager : com/facebook/r public synthetic fun setPadding (Landroid/view/View;IIII)V public fun setPadding (Lcom/facebook/react/views/text/ReactTextView;IIII)V protected final fun setReactTextViewManagerCallback (Lcom/facebook/react/views/text/ReactTextViewManagerCallback;)V + public synthetic fun setScreenReaderFocusable (Landroid/view/View;Z)V + public fun setScreenReaderFocusable (Lcom/facebook/react/views/text/ReactTextView;Z)V public final fun setSelectable (Lcom/facebook/react/views/text/ReactTextView;Z)V public final fun setSelectionColor (Lcom/facebook/react/views/text/ReactTextView;Ljava/lang/Integer;)V public final fun setTextAlignVertical (Lcom/facebook/react/views/text/ReactTextView;Ljava/lang/String;)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt index e1ae6ac7ff6e..4c27d8f8818b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextView.kt @@ -21,6 +21,7 @@ import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.ViewParent +import android.view.accessibility.AccessibilityNodeInfo import androidx.annotation.ColorInt import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi @@ -30,12 +31,14 @@ import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.uimanager.BackgroundStyleApplicator import com.facebook.react.uimanager.ReactCompoundView import com.facebook.react.uimanager.RootView +import com.facebook.react.uimanager.ScreenReaderFocusableHelper import com.facebook.react.uimanager.style.Overflow import com.facebook.react.views.text.internal.span.AnimatedEffectSpan import com.facebook.react.views.text.internal.span.CanvasEffectSpan import com.facebook.react.views.text.internal.span.ReactFragmentIndexSpan import com.facebook.react.views.text.internal.span.ReactLinkSpan import com.facebook.react.views.text.internal.span.TouchableSpan +import com.facebook.react.views.view.FocusProps import kotlin.collections.ArrayList import kotlin.math.roundToInt @@ -91,6 +94,11 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re @ColorInt var selectionColor: Int? = null + internal var focusProps: FocusProps = FocusProps.DEFAULT + private set + + private var focusPropsChanged = false + val text: CharSequence? // Avoid mangling the getter name, to allow black box E2E tests to read text content via // reflection. Returns the full logical text, not `layout.text`, which can be an ellipsized @@ -108,6 +116,8 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re overflow = Overflow.VISIBLE selection = null selectionColor = null + focusProps = FocusProps.DEFAULT + focusPropsChanged = false lastFrameTimeNanos = 0L preparedLayout = null hasClickableSpansCache = null @@ -422,6 +432,7 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re clearSelection() } super.onFocusChanged(gainFocus, direction, previouslyFocusedRect) + focusProps.onFocusChanged(this, gainFocus) val accessibilityDelegateCompat = ViewCompat.getAccessibilityDelegate(this) if ( accessibilityDelegateCompat != null && @@ -431,6 +442,24 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re } } + internal fun updateFocusProps(focusProps: FocusProps) { + this.focusProps = focusProps + focusPropsChanged = true + } + + internal fun applyFocusProps() { + if (!focusPropsChanged) { + return + } + focusPropsChanged = false + focusProps.applyTo(this) + } + + override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) { + super.onInitializeAccessibilityNodeInfo(info) + ScreenReaderFocusableHelper.initializeAccessibilityNodeInfo(this, info) + } + override fun dispatchKeyEvent(event: KeyEvent): Boolean { val accessibilityDelegateCompat = ViewCompat.getAccessibilityDelegate(this) val delegateHandled = diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextViewManager.kt index ba3b7af18994..c642f1e9aa25 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextViewManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/PreparedLayoutTextViewManager.kt @@ -18,6 +18,7 @@ import com.facebook.react.module.annotations.ReactModule import com.facebook.react.uimanager.BackgroundStyleApplicator import com.facebook.react.uimanager.BaseViewManager import com.facebook.react.uimanager.IViewGroupManager +import com.facebook.react.uimanager.ImportantForAccessibilityHelper import com.facebook.react.uimanager.LayoutShadowNode import com.facebook.react.uimanager.LengthPercentage import com.facebook.react.uimanager.PointerEvents @@ -59,6 +60,11 @@ internal class PreparedLayoutTextViewManager : override fun getName(): String = REACT_CLASS + override fun onAfterUpdateTransaction(view: PreparedLayoutTextView) { + view.applyFocusProps() + super.onAfterUpdateTransaction(view) + } + override fun updateViewAccessibility(view: PreparedLayoutTextView) { ReactTextViewAccessibilityDelegate.setDelegate( view, @@ -108,7 +114,29 @@ internal class PreparedLayoutTextViewManager : @ReactProp(name = "accessible") fun setAccessible(view: PreparedLayoutTextView, accessible: Boolean) { - view.isFocusable = accessible + view.updateFocusProps(view.focusProps.copy(accessible = accessible)) + } + + @ReactProp(name = "focusable") + fun setFocusable(view: PreparedLayoutTextView, focusable: Boolean?) { + view.updateFocusProps(view.focusProps.copy(focusable = focusable)) + } + + override fun setScreenReaderFocusable( + view: PreparedLayoutTextView, + screenReaderFocusable: Boolean, + ) { + view.updateFocusProps(view.focusProps.copy(screenReaderFocusable = screenReaderFocusable)) + } + + override fun setImportantForAccessibility( + view: PreparedLayoutTextView, + importantForAccessibility: String?, + ) { + val mode = + ImportantForAccessibilityHelper.parseImportantForAccessibility(importantForAccessibility) + ?: return + view.updateFocusProps(view.focusProps.copy(importantForAccessibility = mode)) } @ReactProp(name = "selectable", defaultBoolean = false) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java index 20b45e9f8f01..e1476ec128be 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java @@ -26,6 +26,7 @@ import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; +import android.view.accessibility.AccessibilityNodeInfo; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; @@ -45,6 +46,7 @@ import com.facebook.react.uimanager.LengthPercentageType; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.ReactCompoundView; +import com.facebook.react.uimanager.ScreenReaderFocusableHelper; import com.facebook.react.uimanager.ViewDefaults; import com.facebook.react.uimanager.style.BorderRadiusProp; import com.facebook.react.uimanager.style.BorderStyle; @@ -55,6 +57,7 @@ import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan; import com.facebook.react.views.text.internal.span.ReactFragmentIndexSpan; import com.facebook.react.views.text.internal.span.ReactTagSpan; +import com.facebook.react.views.view.FocusProps; import com.facebook.yoga.YogaMeasureMode; import java.lang.reflect.Method; @@ -84,6 +87,9 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie private boolean mShouldAdjustSpannableFontSize; private Overflow mOverflow = Overflow.VISIBLE; + private FocusProps mFocusProps = FocusProps.TEXT_DEFAULT; + private boolean mFocusPropsChanged; + private @Nullable Spannable mSpanned; // Fitting the font size to the view shrinks the font size spans of mSpanned in place. These are // the spans it had before the first fit, so that a later fit (when the view's size changes) can @@ -141,6 +147,8 @@ private void initView() { mAdjustsFontSizeToFit = false; mLinkifyMaskType = 0; mTextIsSelectable = false; + mFocusProps = FocusProps.TEXT_DEFAULT; + mFocusPropsChanged = false; mShouldAdjustSpannableFontSize = false; mEllipsizeLocation = TextUtils.TruncateAt.END; mFontSize = Float.NaN; @@ -420,7 +428,14 @@ public void setText(ReactTextUpdate update) { spanned = new SpannableString(spanned); } Linkify.addLinks((Spannable) spanned, mLinkifyMaskType); + boolean wasFocused = isFocused(); + // A movement method makes TextView focusable, and a window holding no focus outside touch + // mode gives it focus at once. setMovementMethod(LinkMovementMethod.getInstance()); + applyTextFocusProps(); + if (!wasFocused && isFocused() && !getAppliedFocusProps().getKeyboardFocusable()) { + clearFocus(); + } } applyBaseTextAttributes(update.getBaseTextAttributes()); setText(spanned); @@ -553,6 +568,11 @@ public void setTextIsSelectable(boolean selectable) { super.setTextIsSelectable(selectable); } + /* package */ void setSelectable(boolean selectable) { + setTextIsSelectable(selectable); + mFocusPropsChanged = true; + } + @Override public void onAttachedToWindow() { super.onAttachedToWindow(); @@ -565,6 +585,8 @@ public void onAttachedToWindow() { } else { setTextIsSelectable(false); } + // TextView's setTextIsSelectable resets the view's focusability. + applyTextFocusProps(); } @Override @@ -765,6 +787,38 @@ public PreparedLayout getPreparedLayout() { public void setLinkifyMask(int mask) { mLinkifyMaskType = mask; + mFocusPropsChanged = true; + } + + /* package */ FocusProps getFocusProps() { + return mFocusProps; + } + + /* package */ void updateFocusProps(FocusProps focusProps) { + mFocusProps = focusProps; + mFocusPropsChanged = true; + } + + /* package */ void applyFocusProps() { + if (!mFocusPropsChanged) { + return; + } + mFocusPropsChanged = false; + applyTextFocusProps(); + } + + private void applyTextFocusProps() { + getAppliedFocusProps().applyTo(this); + } + + private FocusProps getAppliedFocusProps() { + return mFocusProps.forText(mTextIsSelectable, mLinkifyMaskType > 0); + } + + @Override + public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { + super.onInitializeAccessibilityNodeInfo(info); + ScreenReaderFocusableHelper.INSTANCE.initializeAccessibilityNodeInfo(this, info); } @Override @@ -795,6 +849,7 @@ protected boolean dispatchHoverEvent(MotionEvent event) { public final void onFocusChanged( boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); + getAppliedFocusProps().onFocusChanged(this, gainFocus); AccessibilityDelegateCompat accessibilityDelegateCompat = ViewCompat.getAccessibilityDelegate(this); if (accessibilityDelegateCompat != null diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.kt index c513c2e9af27..0c8eb9adfcca 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextViewManager.kt @@ -28,6 +28,7 @@ import com.facebook.react.module.annotations.ReactModule import com.facebook.react.uimanager.BackgroundStyleApplicator import com.facebook.react.uimanager.BaseViewManager import com.facebook.react.uimanager.IViewManagerWithChildren +import com.facebook.react.uimanager.ImportantForAccessibilityHelper import com.facebook.react.uimanager.LayoutShadowNode import com.facebook.react.uimanager.LengthPercentage import com.facebook.react.uimanager.LengthPercentageType @@ -111,6 +112,7 @@ public constructor( override fun getShadowNodeClass(): Class = LayoutShadowNode::class.java override fun onAfterUpdateTransaction(view: ReactTextView) { + view.applyFocusProps() super.onAfterUpdateTransaction(view) view.updateView() } @@ -251,7 +253,26 @@ public constructor( @ReactProp(name = "accessible") public fun setAccessible(view: ReactTextView, accessible: Boolean) { - view.isFocusable = accessible + view.updateFocusProps(view.focusProps.copy(accessible = accessible)) + } + + @ReactProp(name = "focusable") + public fun setFocusable(view: ReactTextView, focusable: Boolean?) { + view.updateFocusProps(view.focusProps.copy(focusable = focusable)) + } + + override fun setScreenReaderFocusable(view: ReactTextView, screenReaderFocusable: Boolean) { + view.updateFocusProps(view.focusProps.copy(screenReaderFocusable = screenReaderFocusable)) + } + + override fun setImportantForAccessibility( + view: ReactTextView, + importantForAccessibility: String?, + ) { + val mode = + ImportantForAccessibilityHelper.parseImportantForAccessibility(importantForAccessibility) + ?: return + view.updateFocusProps(view.focusProps.copy(importantForAccessibility = mode)) } // maxLines can only be set in master view (block), doesn't really make sense to set in a span @@ -307,7 +328,7 @@ public constructor( @ReactProp(name = "selectable") public fun setSelectable(view: ReactTextView, isSelectable: Boolean) { - view.setTextIsSelectable(isSelectable) + view.setSelectable(isSelectable) } @ReactProp(name = "selectionColor", customType = "Color") 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 index ba1ed9e4619a..b7c85bfc9182 100644 --- 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 @@ -8,6 +8,7 @@ package com.facebook.react.views.view import android.view.View +import com.facebook.react.uimanager.ReactAxOrderHelper internal data class FocusProps( val focusable: Boolean? = null, @@ -40,7 +41,33 @@ internal data class FocusProps( importantForAccessibility } + // Android selects text, and moves through its links, only in a view that can take focus. + fun forText(isSelectable: Boolean, detectsLinks: Boolean): FocusProps = + when { + isSelectable -> copy(focusable = true) + detectsLinks && focusable == null -> copy(focusable = true) + else -> this + } + + fun applyTo(view: View) { + ReactAxOrderHelper.setFocusable(view, isFocusable(view.isFocused)) + ReactAxOrderHelper.setScreenReaderFocusable(view, isScreenReaderFocusable) + view.importantForAccessibility = + importantForAccessibility(hasContentDescription = !view.contentDescription.isNullOrEmpty()) + } + + fun onFocusChanged(view: View, gainFocus: Boolean) { + if (!gainFocus && focusableOnlyFromJS) { + ReactAxOrderHelper.setFocusable(view, false) + } + } + companion object { - val DEFAULT: FocusProps = FocusProps() + @JvmField val DEFAULT: FocusProps = FocusProps() + + // TextView's constructor makes the view important for accessibility. + @JvmField + val TEXT_DEFAULT: FocusProps = + FocusProps(importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES) } } 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 09f5f3f80791..a208ec1823d4 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 @@ -608,19 +608,12 @@ public open class ReactViewGroup public constructor(context: Context?) : return } focusPropsChanged = false - ReactAxOrderHelper.setFocusable(this, focusProps.isFocusable(isFocused)) - ReactAxOrderHelper.setScreenReaderFocusable(this, focusProps.isScreenReaderFocusable) - importantForAccessibility = - focusProps.importantForAccessibility( - hasContentDescription = !contentDescription.isNullOrEmpty() - ) + focusProps.applyTo(this) } override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect) - if (!gainFocus && focusProps.focusableOnlyFromJS) { - ReactAxOrderHelper.setFocusable(this, false) - } + focusProps.onFocusChanged(this, gainFocus) } override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) { diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/TextKeyboardFocusTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/TextKeyboardFocusTest.kt new file mode 100644 index 000000000000..f6171b35304a --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/TextKeyboardFocusTest.kt @@ -0,0 +1,453 @@ +/* + * 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.text + +import android.app.Activity +import android.content.Context +import android.os.Build +import android.os.Looper +import android.text.SpannableString +import android.util.DisplayMetrics +import android.view.FocusFinder +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.view.accessibility.AccessibilityNodeInfo +import android.view.inputmethod.EditorInfo +import android.widget.EditText +import androidx.core.view.accessibility.AccessibilityNodeInfoCompat +import com.facebook.react.bridge.JavaOnlyMap +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.facebook.react.uimanager.ReactStylesDiffMap +import com.facebook.react.uimanager.ViewManager +import com.facebook.react.uimanager.ViewProps +import com.facebook.react.views.view.ReactViewGroup +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.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.android.controller.ActivityController +import org.robolectric.annotation.Config + +abstract class TextKeyboardFocusTest { + + protected lateinit var context: Context + private lateinit var manager: ViewManager + private val activityControllers = mutableListOf>() + + protected abstract fun createManager(): ViewManager + + protected abstract fun createTextView(context: Context): T + + protected abstract fun recycle(text: T) + + @Before + fun setUp() { + ReactNativeFeatureFlagsForTests.setUp() + DisplayMetricsHolder.setScreenDisplayMetrics(DisplayMetrics()) + val activityController = Robolectric.buildActivity(Activity::class.java).setup() + activityControllers.add(activityController) + context = activityController.get() + manager = createManager() + } + + @After + fun tearDown() { + activityControllers.forEach { it.pause().stop().destroy() } + DisplayMetricsHolder.setScreenDisplayMetrics(null) + } + + @Test + fun `focusable false - Tab and the arrow keys pass over an accessible text`() { + val leading = control(top = 0) + val excluded = excludedText(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 text passes over it`() { + val leading = control(top = 0) + val excluded = excludedText(top = 10) + val trailing = control(top = 20) + excluded.id = View.generateViewId() + 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 text moves focus on`() { + val excluded = excludedText(top = 10) + val trailing = control(top = 20) + excluded.id = View.generateViewId() + val editor = + EditText(context).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 text`() { + val excluded = excludedText(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 text`() { + val excluded = excludedText(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 - offers accessibility services no focus action`() { + val excluded = excludedText(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 - an accessible text stays one screen reader element`() { + val excluded = excludedText(top = 0) + 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 text reports itself screen reader focusable`() { + val excluded = excludedText(top = 0) + 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 - keyboard focus follows accessible`() { + val leading = control(top = 0) + val text = text(top = 10, ACCESSIBLE to true) + val trailing = control(top = 20) + val root = attach(leading, text, trailing) + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(text) + + update(text, ACCESSIBLE to false) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(trailing) + } + + @Test + fun `focusable true - returns an excluded text to keyboard navigation`() { + val leading = control(top = 0) + val excluded = excludedText(top = 10) + val root = attach(leading, excluded) + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isNull() + + update(excluded, FOCUSABLE to true) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(excluded) + } + + @Test + fun `focusable removed - returns an excluded text to the keyboard focus accessible gives it`() { + val leading = control(top = 0) + val excluded = excludedText(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 `focusable turning false keeps focus on a focused text until focus moves on`() { + val text = text(top = 0, ACCESSIBLE to true) + val trailing = control(top = 10) + val root = attach(text, trailing) + assertThat(text.requestFocus()).isTrue() + + update(text, FOCUSABLE to false) + + assertThat(text.isFocused).isTrue() + trailing.requestFocus() + assertThat(nextFocus(root, trailing, View.FOCUS_BACKWARD)).isNull() + assertThat(text.requestFocus()).isFalse() + } + + @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 = text(top = 0, ACCESSIBLE to accessible) + update(accessibleFirst, FOCUSABLE to focusable) + val focusableFirst = text(top = 10, FOCUSABLE to focusable) + 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 `recycling returns a text to the focus state a new text has`() { + val fresh = text(top = 0) + val excluded = excludedText(top = 10, ViewProps.SCREEN_READER_FOCUSABLE to true) + attach(fresh, excluded) + assertThat(excluded.isFocusable).isFalse() + (excluded.parent as ViewGroup).removeView(excluded) + + recycle(excluded) + update(excluded, ACCESSIBLE to true) + update(fresh, ACCESSIBLE to true) + + assertThat(excluded.isFocusable).isTrue() + assertThat(focusState(excluded)).isEqualTo(focusState(fresh)) + } + + protected fun excludedText(top: Int, vararg props: Pair): T = + text(top, ACCESSIBLE to true, FOCUSABLE to false, *props) + + protected fun text(top: Int, vararg props: Pair): T = + createTextView(context).apply { + layout(0, top, 100, top + 10) + update(this, *props) + } + + protected fun update(text: T, vararg props: Pair) { + manager.updateProperties( + text, + ReactStylesDiffMap(JavaOnlyMap.of(*props.flatMap { it.toList() }.toTypedArray())), + ) + } + + protected fun control(top: Int): View = + View(context).apply { + isFocusable = true + layout(0, top, 100, top + 10) + } + + protected fun attach(vararg views: View): ReactViewGroup { + val root = ReactViewGroup(context) + 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 + } + + protected 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: View): FocusState { + val node = AccessibilityNodeInfoCompat.wrap(view.createAccessibilityNodeInfo()) + return FocusState( + focusable = view.isFocusable, + screenReaderFocusable = node.isScreenReaderFocusable, + importantForAccessibility = view.importantForAccessibility, + ) + } + + protected companion object { + const val ACCESSIBLE = "accessible" + const val FOCUSABLE = "focusable" + } + + private data class FocusState( + val focusable: Boolean, + val screenReaderFocusable: Boolean, + val importantForAccessibility: Int, + ) +} + +@RunWith(RobolectricTestRunner::class) +@Config( + sdk = + [ + Build.VERSION_CODES.TIRAMISU, + Build.VERSION_CODES.UPSIDE_DOWN_CAKE, + Build.VERSION_CODES.VANILLA_ICE_CREAM, + ], +) +class ReactTextViewKeyboardFocusTest : TextKeyboardFocusTest() { + + override fun createManager(): ViewManager = ReactTextViewManager() + + override fun createTextView(context: Context): ReactTextView = ReactTextView(context) + + override fun recycle(text: ReactTextView) { + text.recycleView() + } + + @Test + fun `focusable false - a selectable text stays focusable, as selecting text needs focus`() { + val leading = control(top = 0) + val text = excludedText(top = 10, SELECTABLE to true) + val root = attach(leading, text) + + assertThat(text.isFocusable).isTrue() + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(text) + } + + @Test + fun `focusable false - a text that stops being selectable leaves keyboard navigation`() { + val leading = control(top = 0) + val text = excludedText(top = 10, SELECTABLE to true) + val root = attach(leading, text) + + update(text, SELECTABLE to false) + + assertThat(text.isFocusable).isFalse() + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isNull() + } + + @Test + fun `focusable unset - an accessible text that stops being selectable stays a keyboard stop`() { + val leading = control(top = 0) + val text = text(top = 10, ACCESSIBLE to true, SELECTABLE to true) + val root = attach(leading, text) + + update(text, SELECTABLE to false) + + assertThat(text.isFocusable).isTrue() + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(text) + } + + @Test + fun `a text with detected links stays a keyboard stop once attached, as moving through links needs focus`() { + val leading = control(top = 0) + val linked = text(top = 10, DATA_DETECTOR_TYPE to "link") + linked.setText(textUpdate("Visit https://reactnative.dev")) + val root = attach(leading, linked) + + assertThat(linked.isFocusable).isTrue() + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(linked) + } + + @Test + fun `focusable false - a text that detects links after it attaches stays out of keyboard navigation`() { + val leading = control(top = 0) + val text = excludedText(top = 10) + val root = attach(leading, text) + + update(text, DATA_DETECTOR_TYPE to "link") + text.setText(textUpdate("Visit https://reactnative.dev")) + + assertThat(text.isFocusable).isFalse() + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isNull() + } + + @Test + fun `a text that stops detecting links leaves keyboard navigation`() { + val leading = control(top = 0) + val text = text(top = 10, DATA_DETECTOR_TYPE to "link") + text.setText(textUpdate("Visit https://reactnative.dev")) + val root = attach(leading, text) + + update(text, DATA_DETECTOR_TYPE to "none") + text.setText(textUpdate("Visit the site")) + + assertThat(text.isFocusable).isFalse() + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isNull() + } + + private fun textUpdate(text: String): ReactTextUpdate = + ReactTextUpdate(SpannableString(text), -1, Gravity.START, 0, 0) + + private companion object { + const val DATA_DETECTOR_TYPE = "dataDetectorType" + const val SELECTABLE = "selectable" + } +} + +@RunWith(RobolectricTestRunner::class) +@Config( + sdk = + [ + Build.VERSION_CODES.TIRAMISU, + Build.VERSION_CODES.UPSIDE_DOWN_CAKE, + Build.VERSION_CODES.VANILLA_ICE_CREAM, + ], +) +internal class PreparedLayoutTextViewKeyboardFocusTest : + TextKeyboardFocusTest() { + + override fun createManager(): ViewManager = + PreparedLayoutTextViewManager() + + override fun createTextView(context: Context): PreparedLayoutTextView = + PreparedLayoutTextView(context) + + override fun recycle(text: PreparedLayoutTextView) { + text.recycleView() + } + + @Test + fun `focusable false - the inline views of an excluded text stay keyboard stops`() { + val leading = control(top = 0) + val excluded = excludedText(top = 10) + val inlineView = control(top = 0) + excluded.addView(inlineView) + val root = attach(leading, excluded) + + assertThat(nextFocus(root, leading, View.FOCUS_FORWARD)).isSameAs(inlineView) + } +} diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp index 910d73f39460..3ee71e903704 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp @@ -60,8 +60,17 @@ const char ParagraphComponentName[] = "Paragraph"; void ParagraphShadowNode::initialize() noexcept { #ifdef ANDROID - if (getConcreteProps().isSelectable) { + // Android selects text, and moves through its links, only in a view that can + // take focus; otherwise the text views' keyboard focus takes `focusable` over + // `accessible`. PreparedLayoutTextView detects no links. + const auto& props = getConcreteProps(); + bool detectsLinks = !ReactNativeFeatureFlags::enablePreparedTextLayout() && + props.dataDetectorType.has_value() && + *props.dataDetectorType != DataDetectorType::None; + if (props.isSelectable || (detectsLinks && !props.focusable.has_value())) { traits_.set(ShadowNodeTraits::Trait::KeyboardFocusable); + } else if (props.focusable == false) { + traits_.unset(ShadowNodeTraits::Trait::KeyboardFocusable); } #endif } 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 ee7f35a7b894..2658fa483815 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 @@ -92,6 +92,31 @@ class ImperativeFocusViewTest : public ::testing::Test { } }; +template +class TextLayoutFlags : public ReactNativeFeatureFlagsDefaults { + public: + bool enablePreparedTextLayout() override { + return PreparedTextLayout; + } +}; + +template +class TextLayoutTest : public ::testing::Test { + protected: + void SetUp() override { + ReactNativeFeatureFlags::dangerouslyReset(); + ReactNativeFeatureFlags::override( + std::make_unique>()); + } + + void TearDown() override { + ReactNativeFeatureFlags::dangerouslyReset(); + } +}; + +using ReactTextViewLayoutTest = TextLayoutTest; +using PreparedTextLayoutViewTest = TextLayoutTest; + } // namespace TEST(ViewTest, keyboardFocusableTraitTakesFocusableThenAccessible) { @@ -113,7 +138,7 @@ TEST(ViewTest, keyboardFocusableTraitTakesFocusableThenAccessible) { EXPECT_FALSE(isKeyboardFocusable(folly::dynamic::object("focusable", false))); } -TEST(ViewTest, paragraphKeyboardFocusableTraitTakesFocusableOrAccessible) { +TEST(ViewTest, paragraphKeyboardFocusableTraitTakesFocusableThenAccessible) { auto builder = simpleComponentBuilder(); std::shared_ptr paragraph; builder.build( @@ -127,8 +152,52 @@ TEST(ViewTest, paragraphKeyboardFocusableTraitTakesFocusableOrAccessible) { 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( + EXPECT_TRUE(isKeyboardFocusable(folly::dynamic::object("selectable", true))); + EXPECT_FALSE(isKeyboardFocusable( folly::dynamic::object("accessible", true)("focusable", false))); + EXPECT_TRUE(isKeyboardFocusable( + folly::dynamic::object("selectable", true)("focusable", false))); +} + +TEST_F( + ReactTextViewLayoutTest, + paragraphKeyboardFocusableTraitTakesLinksReactTextViewDetects) { + 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_TRUE( + isKeyboardFocusable(folly::dynamic::object("dataDetectorType", "link"))); + EXPECT_FALSE( + isKeyboardFocusable(folly::dynamic::object("dataDetectorType", "none"))); + EXPECT_FALSE(isKeyboardFocusable( + folly::dynamic::object("dataDetectorType", "link")("focusable", false))); +} + +TEST_F( + PreparedTextLayoutViewTest, + paragraphKeyboardFocusableTraitIgnoresLinksPreparedLayoutTextViewDoesNotDetect) { + 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("dataDetectorType", "link"))); + EXPECT_TRUE(isKeyboardFocusable( + folly::dynamic::object("dataDetectorType", "link")("accessible", true))); + EXPECT_TRUE(isKeyboardFocusable(folly::dynamic::object("selectable", true))); } TEST(ViewTest, focusableFalseFormsNoViewWithoutImperativeFocus) { diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 55e761e65927..e28bc5ac15b9 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -5286,6 +5286,7 @@ declare type TextPropsAndroid = { adjustsFontSizeToFit?: boolean dataDetectorType?: "all" | "email" | "link" | "none" | "phoneNumber" disabled?: boolean + focusable?: boolean minimumFontScale?: number selectionColor?: ColorValue textBreakStrategy?: "balanced" | "highQuality" | "simple" @@ -5886,12 +5887,12 @@ export { AlertOptions, // 8a116d2a AlertType, // 5ab91217 AndroidKeyboardEvent, // e03becc8 - Animated, // 4dd69575 + Animated, // a7643921 AnimatedFlatList, // 2605f07c AnimatedImage, // f63d372c AnimatedScrollView, // f109a9f5 AnimatedSectionList, // cc26f27d - AnimatedText, // 7deca110 + AnimatedText, // b2d6224a AnimatedView, // 0e3634b9 AppConfig, // 80afc5fa AppRegistry, // a9925121 @@ -6127,7 +6128,7 @@ export { TVViewPropsIOS, // 1c612e4e TargetedEvent, // 16e98910 TaskProvider, // 266dedf2 - Text, // 9bbb7bc0 + Text, // 237c57f2 TextContentType, // 239b3ecc TextInput, // 153a9b12 TextInputAndroidProps, // 9ebbc103 @@ -6144,7 +6145,7 @@ export { TextInputSubmitEditingEvent, // 260f6e41 TextInstance, // c927e793 TextLayoutEvent, // e9765128 - TextProps, // 325e93b5 + TextProps, // f60c8f62 TextStyle, // 55ea5e42 ToastAndroid, // 88a8969a TouchableHighlight, // 0a900542 diff --git a/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts index e793c03bc6d5..94eabe690e1a 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts @@ -61,6 +61,14 @@ export interface TextPropsAndroid { */ disabled?: boolean | undefined; + /** + * Whether this `Text` should be focusable with a non-touch input device, eg. receive focus with + * a hardware keyboard. An accessible `Text` is focusable unless this is `false`, and + * accessibility services reach it either way. A `selectable` `Text` stays focusable, as selecting + * text takes focus. + */ + focusable?: boolean | undefined; + /** * Lets the user select text, to use the native copy and paste functionality. */