From 3a7cccdb6ee5294114cb154f298b517542dcae9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20M=C3=B3rawski?= Date: Fri, 28 Aug 2026 16:05:36 +0200 Subject: [PATCH 01/50] feat: add MD3 keyboard focus indicators --- src/components/Card/Card.tsx | 9 +- src/components/Checkbox/Checkbox.tsx | 2 + src/components/Chip/Chip.tsx | 67 +++------ src/components/FAB/Menu.tsx | 41 ++---- src/components/FAB/Shell.tsx | 49 +++---- src/components/FAB/tokens.ts | 11 -- src/components/FAB/useFocusRing.ts | 41 ------ src/components/List/ListItem.tsx | 1 + .../RadioButton/RadioButtonItem.tsx | 1 + .../SegmentedButtons/SegmentedButtonItem.tsx | 1 + src/components/Switch/Switch.tsx | 53 +++---- .../TouchableRipple.native.tsx | 44 +++++- .../TouchableRipple/TouchableRipple.tsx | 42 +++++- .../__tests__/TouchableRipple.test.tsx | 68 +++++++++ .../TouchableRippleFocusWeb.test.tsx | 95 ++++++++++++ .../__tests__/focusRingWiring.test.tsx | 103 +++++++++++++ src/utils/__tests__/focusRingContrast.test.ts | 63 ++++++++ src/utils/__tests__/useFocusRing.test.tsx | 136 ++++++++++++++++++ src/utils/useFocusRing.ts | 91 ++++++++++++ 19 files changed, 714 insertions(+), 204 deletions(-) delete mode 100644 src/components/FAB/useFocusRing.ts create mode 100644 src/components/__tests__/TouchableRippleFocusWeb.test.tsx create mode 100644 src/components/__tests__/focusRingWiring.test.tsx create mode 100644 src/utils/__tests__/focusRingContrast.test.ts create mode 100644 src/utils/__tests__/useFocusRing.test.tsx create mode 100644 src/utils/useFocusRing.ts diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 249eefaabf..99053adb01 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -19,6 +19,7 @@ import { getCardColors } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; +import { getFocusRingStyle, useFocusRing } from '../../utils/useFocusRing'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; @@ -165,7 +166,7 @@ const Card = ({ ...rest }: (OutlinedCardProps | ElevatedCardProps | ContainedCardProps) & Props) => { const theme = useInternalTheme(themeOverrides); - + const focusRing = useFocusRing(disabled); const isMode = React.useCallback( (modeToCompare: Mode) => { return cardMode === modeToCompare; @@ -267,6 +268,12 @@ const Card = ({ onPressIn={handlePressIn} onPressOut={handlePressOut} testID={testID} + onFocus={focusRing.onFocus} + onBlur={focusRing.onBlur} + style={[ + { borderRadius }, + getFocusRingStyle(focusRing.focused, theme.colors.secondary), + ]} > {content} diff --git a/src/components/Checkbox/Checkbox.tsx b/src/components/Checkbox/Checkbox.tsx index 78a59a29b7..924f945e6e 100644 --- a/src/components/Checkbox/Checkbox.tsx +++ b/src/components/Checkbox/Checkbox.tsx @@ -500,6 +500,8 @@ const Checkbox = ({ onBlur={handleBlur} {...interactionHandlers} borderless + // Checkbox draws its own circular ring around the state layer. + focusRing="none" // The platform press paints the wrong thing: it covers the whole 48dp // target instead of the 40dp state layer, tints with a neutral role, // and on web its hover overlay doubles up with the layer. Android also diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index bfdebbaa52..9d5fde9a9c 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -3,14 +3,11 @@ import { Platform, StyleSheet, Pressable, View } from 'react-native'; import type { ColorValue, GestureResponderEvent, - NativeSyntheticEvent, PressableAndroidRippleConfig, StyleProp, - TargetedEvent, TextProps, TextStyle, ViewProps, - ViewStyle, } from 'react-native'; import useLatestCallback from 'use-latest-callback'; @@ -20,11 +17,14 @@ import type { ChipAvatarProps } from './helpers'; import { ChipTokens } from './tokens'; import { useInternalTheme } from '../../core/theming'; import { white } from '../../theme/colors'; -import { tokens } from '../../theme/tokens'; import type { ThemeProp } from '../../theme/types'; import getMinInteractiveSizeHitSlop from '../../utils/getMinInteractiveSizeHitSlop'; import hasTouchHandler from '../../utils/hasTouchHandler'; -import { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent'; +import { + getFocusRingStyle, + toStyleList, + useFocusRing, +} from '../../utils/useFocusRing'; import type { IconSource } from '../Icon'; import Icon from '../Icon'; import MaterialCommunityIcon from '../MaterialCommunityIcon'; @@ -188,13 +188,6 @@ const CHIP_BODY_HIT_SLOP = getMinInteractiveSizeHitSlop({ // The close column spans the chip's height, so it gets the same vertical slop. const CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET = CHIP_BODY_HIT_SLOP?.top ?? 0; -const CLOSE_ICON_SIZE = 18; -const CLOSE_FOCUS_THICKNESS = tokens.md.sys.state.focusIndicator.thickness; - -// Web-only style; `outline` is outside ViewStyle. -// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -const webNoOutline = { outline: 'none' } as unknown as ViewStyle; - /** * Chips are compact elements that can represent inputs, attributes, or actions. * They can have an icon or avatar on the left, and a close button icon on the right. @@ -251,9 +244,9 @@ const Chip = ({ ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); + const closeFocusRing = useFocusRing(disabled); const [pressed, setPressed] = React.useState(false); - const [closeFocused, setCloseFocused] = React.useState(false); const elevation = elevated ? (pressed ? 2 : 1) : 0; const hasPassedTouchHandler = hasTouchHandler({ @@ -275,18 +268,6 @@ const Chip = ({ setPressed(false); }); - const handleCloseFocus = useLatestCallback( - (e: NativeSyntheticEvent) => { - if (Platform.OS === 'web' && isKeyboardFocusEvent(e)) { - setCloseFocused(true); - } - } - ); - - const handleCloseBlur = useLatestCallback(() => { - setCloseFocused(false); - }); - const elevationTransitionDuration = theme.motion.duration[pressed ? 'short4' : 'short3'] * theme.animation.scale; @@ -342,6 +323,7 @@ const Chip = ({ > {/* react-native-web removed `hitSlop` in 0.13.0, so web needs a real element the browser can @@ -466,15 +453,6 @@ const Chip = ({ )} - {closeFocused && !disabled ? ( - - ) : null} {closeIcon ? ( ) : ( @@ -569,15 +547,6 @@ const styles = StyleSheet.create({ height: '100%', justifyContent: 'center', }, - closeFocusRing: { - position: 'absolute', - top: -CLOSE_FOCUS_THICKNESS, - left: -CLOSE_FOCUS_THICKNESS, - width: CLOSE_ICON_SIZE + 2 * CLOSE_FOCUS_THICKNESS, - height: CLOSE_ICON_SIZE + 2 * CLOSE_FOCUS_THICKNESS, - borderRadius: CLOSE_ICON_SIZE / 2 + CLOSE_FOCUS_THICKNESS, - borderWidth: CLOSE_FOCUS_THICKNESS, - }, closeButtonWebTouchTarget: { position: 'absolute', top: -CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET, diff --git a/src/components/FAB/Menu.tsx b/src/components/FAB/Menu.tsx index e4884647d6..539950175e 100644 --- a/src/components/FAB/Menu.tsx +++ b/src/components/FAB/Menu.tsx @@ -14,15 +14,8 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import Content from './Content'; import Shell from './Shell'; -import { - MenuTokens, - Tokens, - FOCUS_RING_INSET, - FOCUS_RING_THICKNESS, - webNoOutline, -} from './tokens'; +import { MenuTokens, Tokens } from './tokens'; import type { Size, Variant } from './tokens'; -import { useFocusRing } from './useFocusRing'; import { resolveColors } from './utils'; import { useLocale } from '../../core/locale'; import { useInternalTheme } from '../../core/theming'; @@ -30,6 +23,12 @@ import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import { toRawSpring } from '../../theme/tokens/sys/motion'; import type { InternalTheme, ThemeProp } from '../../theme/types'; import { resolveCornerRadius } from '../../theme/utils/shape'; +import { + getFocusRingStyle, + toStyleList, + useFocusRing, + webNoOutline, +} from '../../utils/useFocusRing'; import Icon from '../Icon'; import type { IconSource } from '../Icon'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; @@ -249,10 +248,7 @@ const MenuItem = ({ MenuTokens.listItem; const borderRadius = resolveCornerRadius(theme, shape); - const { focusedSV, onFocus, onBlur } = useFocusRing(); - const focusRingStyle = useAnimatedStyle(() => ({ - opacity: focusedSV.value ? 1 : 0, - })); + const { focused, onFocus, onBlur } = useFocusRing(); return ( @@ -260,10 +256,12 @@ const MenuItem = ({ style={[ styles.menuItem, { height, borderRadius, backgroundColor: colors.container }, + ...toStyleList(getFocusRingStyle(focused, theme.colors.secondary)), ]} > - ); }; @@ -686,15 +674,6 @@ const styles = StyleSheet.create({ menuItem: { overflow: 'hidden', }, - menuItemFocusRing: { - position: 'absolute', - top: -FOCUS_RING_INSET, - left: -FOCUS_RING_INSET, - right: -FOCUS_RING_INSET, - bottom: -FOCUS_RING_INSET, - borderWidth: FOCUS_RING_THICKNESS, - pointerEvents: 'none', - }, triggerSlot: { justifyContent: 'flex-start', }, diff --git a/src/components/FAB/Shell.tsx b/src/components/FAB/Shell.tsx index 26bd118885..2787872b69 100644 --- a/src/components/FAB/Shell.tsx +++ b/src/components/FAB/Shell.tsx @@ -17,20 +17,20 @@ import type { SharedValue } from 'react-native-reanimated'; import type { AnimatedStyle } from 'react-native-reanimated'; import Content from './Content'; -import { - Tokens, - FOCUS_RING_INSET, - FOCUS_RING_THICKNESS, - webNoOutline, -} from './tokens'; +import { Tokens } from './tokens'; import type { Size, Variant } from './tokens'; -import { useFocusRing } from './useFocusRing'; import { getDimensions, resolveColors } from './utils'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import { toRawSpring } from '../../theme/tokens/sys/motion'; import type { Elevation, ThemeProp } from '../../theme/types'; import type { ShapeToken } from '../../theme/utils/shape'; +import { + getFocusRingStyle, + toStyleList, + useFocusRing, + webNoOutline, +} from '../../utils/useFocusRing'; import type { IconSource } from '../Icon'; import Surface from '../Surface'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; @@ -297,15 +297,7 @@ const Shell = ({ [borderRadius, containerBg] ); - const { focusedSV, onFocus, onBlur } = useFocusRing(); - - const focusRingStyle = useAnimatedStyle( - () => ({ - opacity: focusedSV.value ? 1 : 0, - borderRadius: borderRadius.value + FOCUS_RING_INSET, - }), - [borderRadius] - ); + const { focused, onFocus, onBlur } = useFocusRing(); return ( - + {overlay} - ); }; @@ -389,15 +381,6 @@ const styles = StyleSheet.create({ pointerEventsNone: { pointerEvents: 'none', }, - focusRing: { - position: 'absolute', - top: -FOCUS_RING_INSET, - left: -FOCUS_RING_INSET, - right: -FOCUS_RING_INSET, - bottom: -FOCUS_RING_INSET, - borderWidth: FOCUS_RING_THICKNESS, - pointerEvents: 'none', - }, }); export default Shell; diff --git a/src/components/FAB/tokens.ts b/src/components/FAB/tokens.ts index 0fb79d1d9c..4188bc340a 100644 --- a/src/components/FAB/tokens.ts +++ b/src/components/FAB/tokens.ts @@ -1,6 +1,3 @@ -import type { ViewStyle } from 'react-native'; - -import { tokens } from '../../theme/tokens'; import type { ColorRole, Elevation, @@ -119,11 +116,3 @@ export const MenuTokens = { listItem, spacing, }; - -const focusIndicator = tokens.md.sys.state.focusIndicator; -export const FOCUS_RING_THICKNESS = focusIndicator.thickness; -export const FOCUS_RING_OUTER_OFFSET = focusIndicator.outerOffset; -export const FOCUS_RING_INSET = FOCUS_RING_OUTER_OFFSET + FOCUS_RING_THICKNESS; - -// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -export const webNoOutline = { outline: 'none' } as unknown as ViewStyle; diff --git a/src/components/FAB/useFocusRing.ts b/src/components/FAB/useFocusRing.ts deleted file mode 100644 index bb056a10c8..0000000000 --- a/src/components/FAB/useFocusRing.ts +++ /dev/null @@ -1,41 +0,0 @@ -import * as React from 'react'; -import { Platform } from 'react-native'; - -import { useSharedValue, type SharedValue } from 'react-native-reanimated'; - -export type FocusRingState = { - /** - * `true` when the surface is keyboard-focused. Drive the focus ring's - * `opacity` from this in a `useAnimatedStyle`. - */ - focusedSV: SharedValue; - /** Wire to the `Pressable`/`TouchableRipple`'s `onFocus`. */ - onFocus: () => void; - /** Wire to the `Pressable`/`TouchableRipple`'s `onBlur`. */ - onBlur: () => void; -}; - -/** - * Drives an MD3 focus indicator for FAB-flavored surfaces. On web, focus is - * gated by `:focus-visible` so a mouse click does not light the ring; on - * native, every focus event is honored. - */ -export function useFocusRing(): FocusRingState { - const focusedSV = useSharedValue(false); - - const onFocus = React.useCallback(() => { - if ( - Platform.OS === 'web' && - !document.activeElement?.matches(':focus-visible') - ) { - return; - } - focusedSV.value = true; - }, [focusedSV]); - - const onBlur = React.useCallback(() => { - focusedSV.value = false; - }, [focusedSV]); - - return { focusedSV, onFocus, onBlur }; -} diff --git a/src/components/List/ListItem.tsx b/src/components/List/ListItem.tsx index c183bb43b9..5e6069b924 100644 --- a/src/components/List/ListItem.tsx +++ b/src/components/List/ListItem.tsx @@ -233,6 +233,7 @@ const ListItem = ({ handlePress({ onPress: onPress, diff --git a/src/components/SegmentedButtons/SegmentedButtonItem.tsx b/src/components/SegmentedButtons/SegmentedButtonItem.tsx index 10bf51f638..e81a63c9dd 100644 --- a/src/components/SegmentedButtons/SegmentedButtonItem.tsx +++ b/src/components/SegmentedButtons/SegmentedButtonItem.tsx @@ -212,6 +212,7 @@ const SegmentedButtonItem = ({ { + if (isDisabled) { + focusedSV.value = 0; + } + }, [isDisabled, focusedSV]); const checkedSV = useSharedValue(checked ? 1 : 0); const hasIconSV = useSharedValue(hasIcon ? 1 : 0); const isDisabledSV = useSharedValue(isDisabled ? 1 : 0); @@ -323,10 +332,6 @@ const Switch = ({ ], })); - const focusRingAnimatedStyle = useAnimatedStyle(() => ({ - opacity: focusedSV.value, - })); - const paint = resolveSwitchPaint(colors, isEnabled, checked); const stateLayerColor = checked ? colors.checkedStateLayerColor @@ -363,10 +368,11 @@ const Switch = ({ hoveredSV.value = 0; }} onFocus={(e) => { - if (!isKeyboardFocusEvent(e)) return; - focusedSV.value = 1; + focusRing.onFocus(e); + if (!isDisabled && isKeyboardFocusEvent(e)) focusedSV.value = 1; }} onBlur={() => { + focusRing.onBlur(); focusedSV.value = 0; }} android_ripple={{ color: 'transparent' }} @@ -384,6 +390,9 @@ const Switch = ({ style={[ styles.track, { backgroundColor: paint.track, opacity: trackOpacityValue }, + ...toStyleList( + getFocusRingStyle(focusRing.focused, colors.focusIndicatorColor) + ), ]} > {showOutline ? ( @@ -446,22 +455,6 @@ const Switch = ({ ) : null} - - ); }; @@ -525,10 +518,6 @@ const styles = StyleSheet.create({ height: SELECTED_ICON, pointerEvents: 'none', }, - focusRing: { - position: 'absolute', - pointerEvents: 'none', - }, absoluteFill: { position: 'absolute', top: 0, @@ -538,8 +527,4 @@ const styles = StyleSheet.create({ }, }); -// Web-only style; not in StyleSheet because `outline` is outside ViewStyle. -// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -const webNoOutline = { outline: 'none' } as unknown as ViewStyle; - export default Switch; diff --git a/src/components/TouchableRipple/TouchableRipple.native.tsx b/src/components/TouchableRipple/TouchableRipple.native.tsx index 519fc41c0c..899edcc6a5 100644 --- a/src/components/TouchableRipple/TouchableRipple.native.tsx +++ b/src/components/TouchableRipple/TouchableRipple.native.tsx @@ -6,6 +6,8 @@ import type { ViewStyle, GestureResponderEvent, ColorValue, + NativeSyntheticEvent, + TargetedEvent, } from 'react-native'; import type { PressableProps } from './Pressable'; @@ -16,6 +18,12 @@ import type { Settings } from '../../core/settings'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; +import type { FocusRingPlacement } from '../../utils/useFocusRing'; +import { + getFocusRingStyle, + toStyleList, + useFocusRing, +} from '../../utils/useFocusRing'; const ANDROID_VERSION_LOLLIPOP = 21; const ANDROID_VERSION_PIE = 28; @@ -25,6 +33,18 @@ export type Props = PressableProps & { background?: PressableAndroidRippleConfig; centered?: boolean; disabled?: boolean; + /** + * Where to draw the MD3 keyboard focus indicator. + * + * - `outward` - just outside the bounds. The MD3 default. + * - `inward` - just inside, for controls a clipping ancestor would trim or + * that sit flush against a neighbour. + * - `none` - no indicator. Only for a control that draws its own. + * + * Has no effect on iOS, which does not dispatch focus events for a + * `Pressable`. + */ + focusRing?: FocusRingPlacement; onPress?: (e: GestureResponderEvent) => void | null; onLongPress?: (e: GestureResponderEvent) => void; onPressIn?: (e: GestureResponderEvent) => void; @@ -44,6 +64,9 @@ const TouchableRipple = ({ underlayColor, children, theme: themeOverrides, + focusRing = 'outward', + onFocus, + onBlur, ref, ...rest }: Props) => { @@ -61,6 +84,19 @@ const TouchableRipple = ({ const disabled = disabledProp || !hasPassedTouchHandler; + const ring = useFocusRing(disabled || focusRing === 'none'); + const handleFocus = (e: NativeSyntheticEvent) => { + onFocus?.(e); + ring.onFocus(e); + }; + const handleBlur = (e: NativeSyntheticEvent) => { + onBlur?.(e); + ring.onBlur(); + }; + const ringStyles = toStyleList( + getFocusRingStyle(ring.focused, theme.colors.secondary, focusRing) + ); + const { calculatedRippleColor, calculatedUnderlayColor } = getTouchableRippleColors({ theme, @@ -82,8 +118,8 @@ const TouchableRipple = ({ baseStyle: StyleProp ): PressableProps['style'] => typeof style === 'function' - ? (state) => [baseStyle, style(state)] - : [baseStyle, style]; + ? (state) => [baseStyle, style(state), ...ringStyles] + : [baseStyle, style, ...ringStyles]; if (TouchableRipple.supported) { const androidRipple = rippleEffectEnabled @@ -99,6 +135,8 @@ const TouchableRipple = ({ {...rest} ref={ref} disabled={disabled} + onFocus={handleFocus} + onBlur={handleBlur} style={resolveStyle(useForeground && styles.overflowHidden)} android_ripple={androidRipple} > @@ -114,6 +152,8 @@ const TouchableRipple = ({ {...rest} ref={ref} disabled={disabled} + onFocus={handleFocus} + onBlur={handleBlur} style={resolveStyle(borderless && styles.overflowHidden)} > {(state) => ( diff --git a/src/components/TouchableRipple/TouchableRipple.tsx b/src/components/TouchableRipple/TouchableRipple.tsx index 0e8c13de54..c68ffa15e9 100644 --- a/src/components/TouchableRipple/TouchableRipple.tsx +++ b/src/components/TouchableRipple/TouchableRipple.tsx @@ -3,7 +3,9 @@ import { Platform, StyleSheet, View } from 'react-native'; import type { ColorValue, GestureResponderEvent, + NativeSyntheticEvent, StyleProp, + TargetedEvent, ViewStyle, } from 'react-native'; @@ -17,6 +19,12 @@ import type { Settings } from '../../core/settings'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; +import type { FocusRingPlacement } from '../../utils/useFocusRing'; +import { + getFocusRingStyle, + toStyleList, + useFocusRing, +} from '../../utils/useFocusRing'; export type Props = PressableProps & { /** @@ -41,6 +49,18 @@ export type Props = PressableProps & { * Whether to prevent interaction with the touchable. */ disabled?: boolean; + /** + * Where to draw the MD3 keyboard focus indicator. + * + * - `outward` - just outside the bounds. The MD3 default. + * - `inward` - just inside, for controls a clipping ancestor would trim or + * that sit flush against a neighbour. + * - `none` - no indicator. Only for a control that draws its own. + * + * Has no effect on iOS, which does not dispatch focus events for a + * `Pressable`. + */ + focusRing?: FocusRingPlacement; /** * Function to execute on press. If not set, will cause the touchable to be disabled. */ @@ -119,6 +139,9 @@ const TouchableRipple = ({ children, theme: themeOverrides, hitSlop, + focusRing = 'outward', + onFocus, + onBlur, ref, ...rest }: Props) => { @@ -281,20 +304,35 @@ const TouchableRipple = ({ const disabled = disabledProp || !hasPassedTouchHandler; + const ring = useFocusRing(disabled || focusRing === 'none'); + const handleFocus = (e: NativeSyntheticEvent) => { + onFocus?.(e); + ring.onFocus(e); + }; + const handleBlur = (e: NativeSyntheticEvent) => { + onBlur?.(e); + ring.onBlur(); + }; + return ( [ styles.touchable, - // focused state is not ready yet: https://github.com/necolas/react-native-web/issues/1849 - // state.focused && { backgroundColor: ___ }, + // RNW's own `state.focused` fires for mouse clicks too, so the ring is + // driven by onFocus instead: https://github.com/necolas/react-native-web/issues/1849 state.hovered && { backgroundColor: hoverColor }, disabled && styles.disabled, typeof style === 'function' ? style(state) : style, + ...toStyleList( + getFocusRingStyle(ring.focused, theme.colors.secondary, focusRing) + ), ]} > {(state) => { diff --git a/src/components/__tests__/TouchableRipple.test.tsx b/src/components/__tests__/TouchableRipple.test.tsx index 7111e67006..c917c7a18d 100644 --- a/src/components/__tests__/TouchableRipple.test.tsx +++ b/src/components/__tests__/TouchableRipple.test.tsx @@ -164,3 +164,71 @@ describe('TouchableRipple', () => { }); }); }); + +describe('TouchableRipple focus ring', () => { + const focus = async () => { + await act(async () => { + await fireEvent(screen.getByTestId('ripple'), 'focus'); + }); + }; + + it('rings on keyboard focus and clears on blur', async () => { + await render( + {}}> + Button + + ); + + await focus(); + expect(screen.getByTestId('ripple')).toHaveStyle({ + outlineWidth: 3, + outlineOffset: 2, + }); + + await act(async () => { + await fireEvent(screen.getByTestId('ripple'), 'blur'); + }); + expect(screen.getByTestId('ripple')).not.toHaveStyle({ outlineWidth: 3 }); + }); + + // Inward is opt-in, for controls a clipping ancestor would trim. + it('draws the ring inward only when asked', async () => { + await render( + {}} focusRing="inward"> + Button + + ); + + await focus(); + expect(screen.getByTestId('ripple')).toHaveStyle({ + outlineWidth: 3, + outlineOffset: -3, + }); + }); + + // The non-interactive case is covered in useFocusRing's own tests. It cannot + // be asserted here: RNTL will not dispatch to a disabled element, so a + // touchable with no press handler passes for free. + it('does not ring when the ring is turned off', async () => { + await render( + {}} focusRing="none"> + Button + + ); + + await focus(); + expect(screen.getByTestId('ripple')).not.toHaveStyle({ outlineWidth: 3 }); + }); + + it('still calls a caller onFocus', async () => { + const onFocus = jest.fn(); + await render( + {}} onFocus={onFocus}> + Button + + ); + + await focus(); + expect(onFocus).toHaveBeenCalled(); + }); +}); diff --git a/src/components/__tests__/TouchableRippleFocusWeb.test.tsx b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx new file mode 100644 index 0000000000..7b34a946ff --- /dev/null +++ b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx @@ -0,0 +1,95 @@ +import { Platform, Text } from 'react-native'; + +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest, +} from '@jest/globals'; +import { act, fireEvent } from '@testing-library/react-native'; + +import { render, screen } from '../../test-utils'; +import { tokens } from '../../theme/tokens'; +// By extension: a bare import resolves to `.native` under the jest preset, so +// the web implementation would never be exercised. +import TouchableRipple from '../TouchableRipple/TouchableRipple.tsx'; + +const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; + +// react-native-web hands `onFocus` a real DOM node, and `isKeyboardFocusEvent` +// asks it whether it matches `:focus-visible`. +const keyboardFocus = { currentTarget: { matches: () => true } }; +const pointerFocus = { currentTarget: { matches: () => false } }; + +const focus = async (data: unknown) => { + await act(async () => { + await fireEvent(screen.getByTestId('ripple'), 'focus', data); + }); +}; + +const renderRipple = (props = {}) => + render( + {}} {...props}> + Button + + ); + +describe('TouchableRipple focus ring (web implementation)', () => { + const original = Platform.OS; + beforeEach(() => { + Platform.OS = 'web'; + }); + afterEach(() => { + Platform.OS = original; + }); + + it('rings on keyboard focus, in the theme secondary colour', async () => { + await renderRipple(); + + await focus(keyboardFocus); + + // colour matters: a ring the same colour as its surface is invisible + expect(screen.getByTestId('ripple')).toHaveStyle({ + outlineWidth: thickness, + outlineOffset: outerOffset, + outlineStyle: 'solid', + outlineColor: 'rgba(98, 91, 113, 1)', + }); + }); + + it('does not ring on a pointer focus', async () => { + await renderRipple(); + + await focus(pointerFocus); + + expect(screen.getByTestId('ripple')).not.toHaveStyle({ + outlineWidth: thickness, + }); + }); + + it('draws inward when asked', async () => { + await renderRipple({ focusRing: 'inward' }); + + await focus(keyboardFocus); + + expect(screen.getByTestId('ripple')).toHaveStyle({ + outlineOffset: -thickness, + }); + }); + + it('forwards onFocus and onBlur to the caller', async () => { + const onFocus = jest.fn(); + const onBlur = jest.fn(); + await renderRipple({ onFocus, onBlur }); + + await focus(keyboardFocus); + await act(async () => { + await fireEvent(screen.getByTestId('ripple'), 'blur'); + }); + + expect(onFocus).toHaveBeenCalled(); + expect(onBlur).toHaveBeenCalled(); + }); +}); diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx new file mode 100644 index 0000000000..97b416b560 --- /dev/null +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -0,0 +1,103 @@ +/* eslint-disable testing-library/no-node-access, @typescript-eslint/no-unsafe-type-assertion, no-restricted-syntax -- + The node carrying the ring is an unnamed internal view (Card's Pressable, + Switch's track, FAB's clip view). There is no testID to query it by, and + which node it is IS the thing under test, so the tree has to be walked. */ +import { StyleSheet, Text } from 'react-native'; +import type { ViewStyle } from 'react-native'; + +import { describe, expect, it } from '@jest/globals'; +import { act, fireEvent } from '@testing-library/react-native'; + +import { render, screen } from '../../test-utils'; +import { tokens } from '../../theme/tokens'; +import Card from '../Card/Card'; +import Chip from '../Chip/Chip'; +import FAB from '../FAB/FAB'; +import ListItem from '../List/ListItem'; +import Switch from '../Switch/Switch'; + +const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; +const OUTWARD = outerOffset; +const INWARD = -thickness; + +type Node = { props?: Record; children?: unknown[] }; + +const walk = (node: Node | undefined, hit: (n: Node) => boolean): Node[] => { + if (!node || typeof node !== 'object') return []; + const here = hit(node) ? [node] : []; + const kids = (node.children ?? []).flatMap((c) => walk(c as Node, hit)); + return [...here, ...kids]; +}; + +const style = (n: Node) => + StyleSheet.flatten(n.props?.style as ViewStyle) ?? {}; + +/** The node carrying the ring is often not the one that took focus. */ +const ringOffset = () => { + const root = (screen as unknown as { root: Node }).root; + const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); + return ringed.length ? style(ringed[0]).outlineOffset : undefined; +}; + +/** Focus whichever node actually has the handler wired. */ +const focusFirstFocusable = async () => { + const root = (screen as unknown as { root: Node }).root; + const target = walk(root, (n) => typeof n.props?.onFocus === 'function')[0]; + expect(target).toBeDefined(); + await act(async () => { + await fireEvent(target as never, 'focus'); + }); +}; + +/** + * Each component decides where its ring goes, and getting it backwards is + * invisible to a snapshot because the ring only exists while focused. Pin the + * placement per component so a wiring change cannot pass silently. + */ +describe('focus ring wiring', () => { + it('List.Item rings inward, clear of the rows above and below', async () => { + await render( {}} />); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + + it('Chip rings inward, so a scrolling chip row cannot trim it', async () => { + await render( {}}>chip); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + + it('Card rings outward', async () => { + await render( + {}}> + card + + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + }); + + it('FAB rings outward on its clip view', async () => { + await render( {}} />); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + }); + + // Inward here lands on the filled track, where `secondary` is ~1:1 against + // `primary` and effectively invisible. + it('Switch rings outward on its track, not inside it', async () => { + await render( {}} />); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + }); +}); diff --git a/src/utils/__tests__/focusRingContrast.test.ts b/src/utils/__tests__/focusRingContrast.test.ts new file mode 100644 index 0000000000..5ff9e9cf6f --- /dev/null +++ b/src/utils/__tests__/focusRingContrast.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from '@jest/globals'; + +import { DarkTheme, LightTheme } from '../../theme/schemes'; + +/** + * The MD3 tonal palette is luminance-matched by tone, so a `secondary` ring on + * any other role at the same tone is ~1:1 and vanishes in greyscale. The ring + * is drawn outward onto the page background for exactly this reason; these + * tests pin the surfaces it is allowed to land on. + * + * WCAG 1.4.11 Non-text Contrast wants 3:1. + */ +const MIN_RATIO = 3; + +const luminance = (rgb: string) => { + const [r, g, b] = (rgb.match(/\d+/g) ?? []).slice(0, 3).map(Number); + const channel = (c: number) => { + const s = c / 255; + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; + }; + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); +}; + +const contrastRatio = (a: string, b: string) => { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (hi + 0.05) / (lo + 0.05); +}; + +describe.each([ + ['light', LightTheme], + ['dark', DarkTheme], +])('focus ring contrast (%s)', (_name, theme) => { + const ring = String(theme.colors.secondary); + + // Surfaces an outward ring actually lands on. + const landsOn: (keyof typeof theme.colors)[] = [ + 'background', + 'surface', + 'surfaceVariant', + 'secondaryContainer', + ]; + it.each(landsOn)('has 3:1 against %s', (role) => { + expect( + contrastRatio(ring, String(theme.colors[role])) + ).toBeGreaterThanOrEqual(MIN_RATIO); + }); + + // Guards the reason the ring is outward rather than inward: these are the + // fills it would sit on top of, and it is invisible against them. + const wouldVanishOn: (keyof typeof theme.colors)[] = [ + 'primary', + 'tertiary', + 'error', + ]; + it.each(wouldVanishOn)( + 'is documented as unusable inward on the %s fill', + (role) => { + expect(contrastRatio(ring, String(theme.colors[role]))).toBeLessThan( + MIN_RATIO + ); + } + ); +}); diff --git a/src/utils/__tests__/useFocusRing.test.tsx b/src/utils/__tests__/useFocusRing.test.tsx new file mode 100644 index 0000000000..f7a400edd3 --- /dev/null +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -0,0 +1,136 @@ +import { Platform, Pressable, Text } from 'react-native'; + +import { describe, expect, it, jest } from '@jest/globals'; +import { act, fireEvent } from '@testing-library/react-native'; + +import { render, screen } from '../../test-utils'; +import { tokens } from '../../theme/tokens'; +import { getFocusRingStyle, useFocusRing } from '../useFocusRing'; + +const focus = async (data?: unknown) => { + await act(async () => { + await fireEvent(screen.getByTestId('probe'), 'focus', data); + }); +}; + +const blur = async () => { + await act(async () => { + await fireEvent(screen.getByTestId('probe'), 'blur'); + }); +}; + +const Probe = ({ + disabled, + onRender, +}: { + disabled?: boolean; + onRender?: () => void; +}) => { + const { focused, onFocus, onBlur } = useFocusRing(disabled); + onRender?.(); + return ( + {}} + onFocus={onFocus} + onBlur={onBlur} + style={getFocusRingStyle(focused, 'rebeccapurple')} + > + probe + + ); +}; + +describe('getFocusRingStyle', () => { + it('returns nothing when not focused', () => { + expect(getFocusRingStyle(false, 'rebeccapurple')).toBeNull(); + }); + + // Values must come from the design tokens, not be hardcoded here, or the + // token is decorative. Derive the expectation from the token itself. + it('takes its thickness and offset from the focusIndicator tokens', () => { + const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; + + expect(getFocusRingStyle(true, 'rebeccapurple')).toEqual({ + outlineWidth: thickness, + outlineColor: 'rebeccapurple', + outlineStyle: 'solid', + outlineOffset: outerOffset, + }); + expect(getFocusRingStyle(true, 'rebeccapurple', 'inward')).toEqual({ + outlineWidth: thickness, + outlineColor: 'rebeccapurple', + outlineStyle: 'solid', + outlineOffset: -thickness, + }); + }); +}); + +describe('useFocusRing', () => { + it('applies the outline on focus and removes it on blur', async () => { + await render(); + expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + + await focus(); + expect(screen.getByTestId('probe')).toHaveStyle({ + outlineWidth: 3, + outlineColor: 'rebeccapurple', + outlineOffset: 2, + }); + + await blur(); + expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + }); + + // `disabled` goes to the hook only, never to the Pressable: RNTL will not + // dispatch to a disabled element, so that would pass for free. + it('never rings a disabled control, even if a focus event arrives', async () => { + await render(); + + await focus(); + + expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + }); + + it('ignores a non-keyboard focus event on web, so a mouse click does not ring', async () => { + const original = Platform.OS; + Platform.OS = 'web'; + try { + await render(); + + await focus({ currentTarget: { matches: () => false } }); + + expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + } finally { + Platform.OS = original; + } + }); + + // The gate has to skip the state update, not just mask the result, or a + // suppressed ring still costs a render on the library's hottest primitive. + it('costs no re-render when the ring is suppressed', async () => { + const onRender = jest.fn(); + await render(); + const before = onRender.mock.calls.length; + + await focus(); + + expect(onRender.mock.calls.length).toBe(before); + }); + + it('does not restore the ring when a control is re-enabled', async () => { + const { rerender } = await render(); + await focus(); + expect(screen.getByTestId('probe')).toHaveStyle({ outlineWidth: 3 }); + + await act(async () => { + await rerender(); + }); + await act(async () => { + await rerender(); + }); + + // no focus event happened in between, so nothing should be ringed + expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + }); +}); diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts new file mode 100644 index 0000000000..776776f642 --- /dev/null +++ b/src/utils/useFocusRing.ts @@ -0,0 +1,91 @@ +import * as React from 'react'; +import type { + ColorValue, + NativeSyntheticEvent, + TargetedEvent, + ViewStyle, +} from 'react-native'; + +import { isKeyboardFocusEvent } from './isKeyboardFocusEvent'; +import { tokens } from '../theme/tokens'; + +const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; + +export type FocusRingPlacement = 'outward' | 'inward' | 'none'; + +export type FocusRingState = { + focused: boolean; + onFocus: (e: NativeSyntheticEvent) => void; + onBlur: () => void; +}; + +/** + * Tracks keyboard focus for an MD3 focus indicator. + * + * Fires on web and Android only. iOS never dispatches `onFocus` for a View or + * Pressable unless the `enableImperativeFocus` flag is on, and it defaults off. + */ +export function useFocusRing(disabled?: boolean): FocusRingState { + const [focused, setFocused] = React.useState(false); + + const onFocus = React.useCallback( + (e: NativeSyntheticEvent) => { + // Symmetric, and skipped entirely when there is nothing to show, so a + // suppressed ring costs no render. + if (!disabled) { + setFocused(isKeyboardFocusEvent(e)); + } + }, + [disabled] + ); + + const onBlur = React.useCallback(() => setFocused(false), []); + + // The focusable node can unmount while this hook stays mounted, and neither + // the DOM nor React fires blur for that, so clear rather than only masking. + React.useEffect(() => { + if (disabled) { + setFocused(false); + } + }, [disabled]); + + return { focused: focused && !disabled, onFocus, onBlur }; +} + +/** + * MD3 focus indicator, drawn with the platform's own `outline`. Costs no + * layout, takes its radius from the view it sits on, and `borderless` does not + * clip it. + * + * Outward by default, per MD3 (hence the `outerOffset` token): the ring lands + * on the page background, where it has a predictable contrast ratio. Pass + * `inward` only where an outward ring is measurably clipped or would land on a + * neighbour - list rows, flush segments, chips in a scrolling row. + * + * Never pair this with `outline: 'none'`. Ours overrides the browser's, so if + * it never runs the user still gets the browser ring instead of nothing. + */ +export const getFocusRingStyle = ( + focused: boolean, + color: ColorValue, + placement: FocusRingPlacement = 'outward' +): ViewStyle | null => + focused && placement !== 'none' + ? { + outlineWidth: thickness, + outlineColor: color, + outlineStyle: 'solid', + outlineOffset: placement === 'inward' ? -thickness : outerOffset, + } + : null; + +/** Spread into a style array so an absent ring adds no entry. */ +export const toStyleList = (s: ViewStyle | null): ViewStyle[] => (s ? [s] : []); + +/** + * Suppresses the browser's own focus ring. Only for controls that draw the MD3 + * ring on a different element, where the browser's would land on the wrong box + * or be clipped. Anywhere else, leaving it alone is the safer default. + */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion +export const webNoOutline = { outline: 'none' } as unknown as ViewStyle; From 34a207a675e19bd56784ecc889ec5e0cfe1d5bee Mon Sep 17 00:00:00 2001 From: Konrad Rydygier Date: Mon, 7 Sep 2026 13:41:41 +0200 Subject: [PATCH 02/50] fix: drive the focus ring with :focus-visible on web, not JS state --- src/components/Card/Card.tsx | 17 +- src/components/Chip/Chip.tsx | 28 ++- src/components/FAB/Menu.tsx | 33 +-- src/components/FAB/Shell.tsx | 39 ++-- src/components/Switch/Switch.tsx | 35 +-- .../TouchableRipple.native.tsx | 30 +-- .../TouchableRipple/TouchableRipple.tsx | 48 ++-- .../TouchableRippleFocusWeb.test.tsx | 76 +++--- .../__snapshots__/FABExtended.test.tsx.snap | 6 - .../__snapshots__/FABMenu.test.tsx.snap | 25 -- .../__snapshots__/Switch.test.tsx.snap | 6 - src/utils/__tests__/useFocusRing.test.tsx | 182 +++++++++++---- src/utils/useFocusRing.ts | 218 +++++++++++++----- 13 files changed, 455 insertions(+), 288 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 99053adb01..d574310882 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -19,7 +19,7 @@ import { getCardColors } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; -import { getFocusRingStyle, useFocusRing } from '../../utils/useFocusRing'; +import { useFocusRing } from '../../utils/useFocusRing'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; @@ -166,7 +166,10 @@ const Card = ({ ...rest }: (OutlinedCardProps | ElevatedCardProps | ContainedCardProps) & Props) => { const theme = useInternalTheme(themeOverrides); - const focusRing = useFocusRing(disabled); + const { target: focusTarget, ring: focusRing } = useFocusRing( + disabled, + theme.colors.secondary + ); const isMode = React.useCallback( (modeToCompare: Mode) => { return cardMode === modeToCompare; @@ -268,12 +271,10 @@ const Card = ({ onPressIn={handlePressIn} onPressOut={handlePressOut} testID={testID} - onFocus={focusRing.onFocus} - onBlur={focusRing.onBlur} - style={[ - { borderRadius }, - getFocusRingStyle(focusRing.focused, theme.colors.secondary), - ]} + onFocus={focusTarget.onFocus} + onBlur={focusTarget.onBlur} + {...focusRing.dataSetProps} + style={[{ borderRadius }, ...focusRing.style]} > {content} diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index 9d5fde9a9c..16571b9452 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -20,11 +20,7 @@ import { white } from '../../theme/colors'; import type { ThemeProp } from '../../theme/types'; import getMinInteractiveSizeHitSlop from '../../utils/getMinInteractiveSizeHitSlop'; import hasTouchHandler from '../../utils/hasTouchHandler'; -import { - getFocusRingStyle, - toStyleList, - useFocusRing, -} from '../../utils/useFocusRing'; +import { useFocusRing } from '../../utils/useFocusRing'; import type { IconSource } from '../Icon'; import Icon from '../Icon'; import MaterialCommunityIcon from '../MaterialCommunityIcon'; @@ -244,7 +240,14 @@ const Chip = ({ ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); - const closeFocusRing = useFocusRing(disabled); + // The close affordance is a plain `Pressable`, not a `TouchableRipple` + // (see below), so it calls `useFocusRing` directly instead of going + // through `TouchableRipple`'s `focusRing` prop like the body does. + const { target: closeFocusTarget, ring: closeFocusRing } = useFocusRing( + disabled, + theme.colors.secondary, + 'inward' + ); const [pressed, setPressed] = React.useState(false); const elevation = elevated ? (pressed ? 2 : 1) : 0; @@ -432,18 +435,13 @@ const Chip = ({ aria-label={closeIconAccessibilityLabel} testID={closeIconTestID} hitSlop={disabled ? undefined : CHIP_BODY_HIT_SLOP} - onFocus={closeFocusRing.onFocus} - onBlur={closeFocusRing.onBlur} + onFocus={closeFocusTarget.onFocus} + onBlur={closeFocusTarget.onBlur} + {...closeFocusRing.dataSetProps} style={[ styles.closeButton, { borderRadius }, - ...toStyleList( - getFocusRingStyle( - closeFocusRing.focused, - theme.colors.secondary, - 'inward' - ) - ), + ...closeFocusRing.style, ]} > {/* react-native-web removed `hitSlop` in 0.13.0, diff --git a/src/components/FAB/Menu.tsx b/src/components/FAB/Menu.tsx index 539950175e..8a26648d34 100644 --- a/src/components/FAB/Menu.tsx +++ b/src/components/FAB/Menu.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Platform, StyleSheet, View } from 'react-native'; +import { StyleSheet, View } from 'react-native'; import type { ColorValue, GestureResponderEvent } from 'react-native'; import Animated, { @@ -23,12 +23,7 @@ import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import { toRawSpring } from '../../theme/tokens/sys/motion'; import type { InternalTheme, ThemeProp } from '../../theme/types'; import { resolveCornerRadius } from '../../theme/utils/shape'; -import { - getFocusRingStyle, - toStyleList, - useFocusRing, - webNoOutline, -} from '../../utils/useFocusRing'; +import { useFocusRing } from '../../utils/useFocusRing'; import Icon from '../Icon'; import type { IconSource } from '../Icon'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; @@ -248,7 +243,17 @@ const MenuItem = ({ MenuTokens.listItem; const borderRadius = resolveCornerRadius(theme, shape); - const { focused, onFocus, onBlur } = useFocusRing(); + // `scope: 'within'`: the ring belongs on the pill below, not the inner + // `TouchableRipple` that actually receives focus. + // + // `undefined` disabled: menu items have no `disabled` prop today. Wire the + // real value through here if that ever changes. + const { target: focusTarget, ring: focusRing } = useFocusRing( + undefined, + theme.colors.secondary, + 'outward', + 'within' + ); return ( @@ -256,21 +261,19 @@ const MenuItem = ({ style={[ styles.menuItem, { height, borderRadius, backgroundColor: colors.container }, - ...toStyleList(getFocusRingStyle(focused, theme.colors.secondary)), + ...focusRing.style, ]} + {...focusRing.dataSetProps} > {overlay} {children ?? ( { if (isDisabled) { @@ -175,6 +169,16 @@ const Switch = ({ const colors = React.useMemo(() => getDefaultSwitchColors(theme), [theme]); + // `scope: 'within'`: the ring is drawn on the track below, not this + // Pressable - it also suppresses the browser's own outline here on web, so + // only the track's ring shows. + const { target: focusTarget, ring: focusRing } = useFocusRing( + isDisabled, + colors.focusIndicatorColor, + 'outward', + 'within' + ); + const reanimatedReduceMotion = reduceMotion ? ReduceMotion.Always : ReduceMotion.Never; @@ -368,11 +372,14 @@ const Switch = ({ hoveredSV.value = 0; }} onFocus={(e) => { - focusRing.onFocus(e); + // Not the ring - it's real CSS on web now. This drives the + // handle's own separate focused-visual animation, native and web + // alike, so it keeps its own keyboard-vs-pointer check. + focusTarget.onFocus?.(e); if (!isDisabled && isKeyboardFocusEvent(e)) focusedSV.value = 1; }} onBlur={() => { - focusRing.onBlur(); + focusTarget.onBlur?.(); focusedSV.value = 0; }} android_ripple={{ color: 'transparent' }} @@ -381,19 +388,15 @@ const Switch = ({ aria-checked={checked} aria-label={ariaLabel} testID={testID} - style={[ - styles.touchable, - Platform.OS === 'web' ? webNoOutline : undefined, - ]} + style={[styles.touchable, ...focusTarget.style]} > {showOutline ? ( diff --git a/src/components/TouchableRipple/TouchableRipple.native.tsx b/src/components/TouchableRipple/TouchableRipple.native.tsx index 899edcc6a5..3398200d19 100644 --- a/src/components/TouchableRipple/TouchableRipple.native.tsx +++ b/src/components/TouchableRipple/TouchableRipple.native.tsx @@ -19,11 +19,7 @@ import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; import type { FocusRingPlacement } from '../../utils/useFocusRing'; -import { - getFocusRingStyle, - toStyleList, - useFocusRing, -} from '../../utils/useFocusRing'; +import { useFocusRing } from '../../utils/useFocusRing'; const ANDROID_VERSION_LOLLIPOP = 21; const ANDROID_VERSION_PIE = 28; @@ -41,8 +37,8 @@ export type Props = PressableProps & { * that sit flush against a neighbour. * - `none` - no indicator. Only for a control that draws its own. * - * Has no effect on iOS, which does not dispatch focus events for a - * `Pressable`. + * Has no effect on iOS today - see `useFocusRing`'s doc comment for why + * (`enableImperativeFocus`, off by default). */ focusRing?: FocusRingPlacement; onPress?: (e: GestureResponderEvent) => void | null; @@ -84,18 +80,22 @@ const TouchableRipple = ({ const disabled = disabledProp || !hasPassedTouchHandler; - const ring = useFocusRing(disabled || focusRing === 'none'); + // Keyed off `disabledProp`, not `disabled`: the latter also folds in + // "no press handler passed", which is a non-interactivity signal, not a + // disabled one - the ring should only react to real disablement. + const { target, ring } = useFocusRing( + disabledProp, + theme.colors.secondary, + focusRing + ); const handleFocus = (e: NativeSyntheticEvent) => { onFocus?.(e); - ring.onFocus(e); + target.onFocus?.(e); }; const handleBlur = (e: NativeSyntheticEvent) => { onBlur?.(e); - ring.onBlur(); + target.onBlur?.(); }; - const ringStyles = toStyleList( - getFocusRingStyle(ring.focused, theme.colors.secondary, focusRing) - ); const { calculatedRippleColor, calculatedUnderlayColor } = getTouchableRippleColors({ @@ -118,8 +118,8 @@ const TouchableRipple = ({ baseStyle: StyleProp ): PressableProps['style'] => typeof style === 'function' - ? (state) => [baseStyle, style(state), ...ringStyles] - : [baseStyle, style, ...ringStyles]; + ? (state) => [baseStyle, style(state), ...ring.style] + : [baseStyle, style, ...ring.style]; if (TouchableRipple.supported) { const androidRipple = rippleEffectEnabled diff --git a/src/components/TouchableRipple/TouchableRipple.tsx b/src/components/TouchableRipple/TouchableRipple.tsx index c68ffa15e9..a0114ee413 100644 --- a/src/components/TouchableRipple/TouchableRipple.tsx +++ b/src/components/TouchableRipple/TouchableRipple.tsx @@ -3,9 +3,7 @@ import { Platform, StyleSheet, View } from 'react-native'; import type { ColorValue, GestureResponderEvent, - NativeSyntheticEvent, StyleProp, - TargetedEvent, ViewStyle, } from 'react-native'; @@ -20,11 +18,7 @@ import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; import type { FocusRingPlacement } from '../../utils/useFocusRing'; -import { - getFocusRingStyle, - toStyleList, - useFocusRing, -} from '../../utils/useFocusRing'; +import { useFocusRing } from '../../utils/useFocusRing'; export type Props = PressableProps & { /** @@ -57,8 +51,8 @@ export type Props = PressableProps & { * that sit flush against a neighbour. * - `none` - no indicator. Only for a control that draws its own. * - * Has no effect on iOS, which does not dispatch focus events for a - * `Pressable`. + * Has no effect on iOS today - see `useFocusRing`'s doc comment for why + * (`enableImperativeFocus`, off by default). */ focusRing?: FocusRingPlacement; /** @@ -140,8 +134,6 @@ const TouchableRipple = ({ theme: themeOverrides, hitSlop, focusRing = 'outward', - onFocus, - onBlur, ref, ...rest }: Props) => { @@ -304,15 +296,19 @@ const TouchableRipple = ({ const disabled = disabledProp || !hasPassedTouchHandler; - const ring = useFocusRing(disabled || focusRing === 'none'); - const handleFocus = (e: NativeSyntheticEvent) => { - onFocus?.(e); - ring.onFocus(e); - }; - const handleBlur = (e: NativeSyntheticEvent) => { - onBlur?.(e); - ring.onBlur(); - }; + // No JS focus tracking here: the ring is real CSS, driven by the browser's + // own `:focus-visible`, keyed off the `data-focus-ring` attribute spread + // below. `onFocus`/`onBlur` reach the caller unmodified via `rest`, nothing + // to intercept. + // + // Keyed off `disabledProp`, not `disabled`: the latter also folds in + // "no press handler passed", which is a non-interactivity signal, not a + // disabled one - the ring should only react to real disablement. + const { ring } = useFocusRing( + disabledProp, + theme.colors.secondary, + focusRing + ); return ( [ styles.touchable, - // RNW's own `state.focused` fires for mouse clicks too, so the ring is - // driven by onFocus instead: https://github.com/necolas/react-native-web/issues/1849 + // RNW's own `state.focused` fires for mouse clicks too, which is + // exactly the distinction `:focus-visible` exists to make. + // https://github.com/necolas/react-native-web/issues/1849 state.hovered && { backgroundColor: hoverColor }, disabled && styles.disabled, typeof style === 'function' ? style(state) : style, - ...toStyleList( - getFocusRingStyle(ring.focused, theme.colors.secondary, focusRing) - ), + ...ring.style, ]} > {(state) => { diff --git a/src/components/__tests__/TouchableRippleFocusWeb.test.tsx b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx index 7b34a946ff..99c5a7d107 100644 --- a/src/components/__tests__/TouchableRippleFocusWeb.test.tsx +++ b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx @@ -1,4 +1,5 @@ import { Platform, Text } from 'react-native'; +import type { ViewStyle } from 'react-native'; import { afterEach, @@ -11,24 +12,16 @@ import { import { act, fireEvent } from '@testing-library/react-native'; import { render, screen } from '../../test-utils'; -import { tokens } from '../../theme/tokens'; // By extension: a bare import resolves to `.native` under the jest preset, so // the web implementation would never be exercised. import TouchableRipple from '../TouchableRipple/TouchableRipple.tsx'; -const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; - -// react-native-web hands `onFocus` a real DOM node, and `isKeyboardFocusEvent` -// asks it whether it matches `:focus-visible`. -const keyboardFocus = { currentTarget: { matches: () => true } }; -const pointerFocus = { currentTarget: { matches: () => false } }; - -const focus = async (data: unknown) => { - await act(async () => { - await fireEvent(screen.getByTestId('ripple'), 'focus', data); - }); -}; - +// There is no DOM in this repo's Jest, so there is no real `:focus-visible` to +// fire - the mechanism is now the browser's, not this library's. These prove +// the wiring instead: the right `data-focus-ring[-within]` attribute and CSS +// colour variable land on the rendered element for a given `focusRing` prop. +// Real focus behaviour is a manual, browser-only check (see the PR +// description). const renderRipple = (props = {}) => render( {}} {...props}> @@ -45,46 +38,55 @@ describe('TouchableRipple focus ring (web implementation)', () => { Platform.OS = original; }); - it('rings on keyboard focus, in the theme secondary colour', async () => { + it('emits data-focus-ring="outward" and the secondary colour by default', async () => { await renderRipple(); - await focus(keyboardFocus); - - // colour matters: a ring the same colour as its surface is invisible - expect(screen.getByTestId('ripple')).toHaveStyle({ - outlineWidth: thickness, - outlineOffset: outerOffset, - outlineStyle: 'solid', - outlineColor: 'rgba(98, 91, 113, 1)', + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('ripple').props.dataSet).toEqual({ + focusRing: 'outward', }); + expect(screen.getByTestId('ripple')).toHaveStyle( + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + { + ['--rnp-focus-ring-color']: 'rgba(98, 91, 113, 1)', + } as unknown as ViewStyle + ); }); - it('does not ring on a pointer focus', async () => { - await renderRipple(); - - await focus(pointerFocus); + it('emits data-focus-ring="inward" when asked', async () => { + await renderRipple({ focusRing: 'inward' }); - expect(screen.getByTestId('ripple')).not.toHaveStyle({ - outlineWidth: thickness, + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('ripple').props.dataSet).toEqual({ + focusRing: 'inward', }); }); - it('draws inward when asked', async () => { - await renderRipple({ focusRing: 'inward' }); + it('emits no attribute when the ring is turned off', async () => { + await renderRipple({ focusRing: 'none' }); - await focus(keyboardFocus); + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('ripple').props.dataSet).toBeUndefined(); + }); - expect(screen.getByTestId('ripple')).toHaveStyle({ - outlineOffset: -thickness, - }); + it('emits no attribute when disabled', async () => { + await renderRipple({ disabled: true }); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('ripple').props.dataSet).toBeUndefined(); }); - it('forwards onFocus and onBlur to the caller', async () => { + // Not reference equality: RN's own `Pressable` wraps the handler it is + // given internally, on every platform, ring or no ring. What matters here + // is that this library stops doing its own extra wrapping around it. + it('still calls a caller onFocus and onBlur', async () => { const onFocus = jest.fn(); const onBlur = jest.fn(); await renderRipple({ onFocus, onBlur }); - await focus(keyboardFocus); + await act(async () => { + await fireEvent(screen.getByTestId('ripple'), 'focus'); + }); await act(async () => { await fireEvent(screen.getByTestId('ripple'), 'blur'); }); diff --git a/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap b/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap index 2e737824b9..db4530892f 100644 --- a/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap @@ -158,7 +158,6 @@ exports[`renders extended FAB collapsed 1`] = ` }, [ null, - null, ], ] } @@ -483,7 +482,6 @@ exports[`renders extended FAB expanded 1`] = ` }, [ null, - null, ], ] } @@ -808,7 +806,6 @@ exports[`renders extended FAB large size 1`] = ` }, [ null, - null, ], ] } @@ -1133,7 +1130,6 @@ exports[`renders extended FAB medium size 1`] = ` }, [ null, - null, ], ] } @@ -1458,7 +1454,6 @@ exports[`renders extended FAB not visible 1`] = ` }, [ null, - null, ], ] } @@ -1783,7 +1778,6 @@ exports[`renders extended FAB transitioning to collapsed 1`] = ` }, [ null, - null, ], ] } diff --git a/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap b/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap index 8b66657112..fba13f6cfa 100644 --- a/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap @@ -139,7 +139,6 @@ exports[`renders FAB.Menu closed 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -315,7 +314,6 @@ exports[`renders FAB.Menu closed 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -622,7 +620,6 @@ exports[`renders FAB.Menu closed 1`] = ` { "flex": 1, }, - null, ], ] } @@ -916,7 +913,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -1092,7 +1088,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -1399,7 +1394,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` { "flex": 1, }, - null, ], ] } @@ -1693,7 +1687,6 @@ exports[`renders FAB.Menu open 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -1869,7 +1862,6 @@ exports[`renders FAB.Menu open 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -2176,7 +2168,6 @@ exports[`renders FAB.Menu open 1`] = ` { "flex": 1, }, - null, ], ] } @@ -2470,7 +2461,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -2646,7 +2636,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -2822,7 +2811,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -2998,7 +2986,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -3174,7 +3161,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -3350,7 +3336,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -3657,7 +3642,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "flex": 1, }, - null, ], ] } @@ -3952,7 +3936,6 @@ exports[`renders FAB.Menu with center alignment 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -4128,7 +4111,6 @@ exports[`renders FAB.Menu with center alignment 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -4435,7 +4417,6 @@ exports[`renders FAB.Menu with center alignment 1`] = ` { "flex": 1, }, - null, ], ] } @@ -4729,7 +4710,6 @@ exports[`renders FAB.Menu with items having icons 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -4935,7 +4915,6 @@ exports[`renders FAB.Menu with items having icons 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -5272,7 +5251,6 @@ exports[`renders FAB.Menu with items having icons 1`] = ` { "flex": 1, }, - null, ], ] } @@ -5566,7 +5544,6 @@ exports[`renders FAB.Menu with start alignment 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -5742,7 +5719,6 @@ exports[`renders FAB.Menu with start alignment 1`] = ` { "borderRadius": 9999, }, - null, ], ] } @@ -6049,7 +6025,6 @@ exports[`renders FAB.Menu with start alignment 1`] = ` { "flex": 1, }, - null, ], ] } diff --git a/src/components/__tests__/__snapshots__/Switch.test.tsx.snap b/src/components/__tests__/__snapshots__/Switch.test.tsx.snap index e38a5145e1..9b641a7ae7 100644 --- a/src/components/__tests__/__snapshots__/Switch.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/Switch.test.tsx.snap @@ -54,7 +54,6 @@ exports[`Switch render renders disabled off 1`] = ` "justifyContent": "center", "width": 52, }, - undefined, ] } > @@ -269,7 +268,6 @@ exports[`Switch render renders disabled on 1`] = ` "justifyContent": "center", "width": 52, }, - undefined, ] } > @@ -464,7 +462,6 @@ exports[`Switch render renders off 1`] = ` "justifyContent": "center", "width": 52, }, - undefined, ] } > @@ -662,7 +659,6 @@ exports[`Switch render renders on 1`] = ` "justifyContent": "center", "width": 52, }, - undefined, ] } > @@ -840,7 +836,6 @@ exports[`Switch render renders with checked icon 1`] = ` "justifyContent": "center", "width": 52, }, - undefined, ] } > @@ -1089,7 +1084,6 @@ exports[`Switch render renders with per-state icons 1`] = ` "justifyContent": "center", "width": 52, }, - undefined, ] } > diff --git a/src/utils/__tests__/useFocusRing.test.tsx b/src/utils/__tests__/useFocusRing.test.tsx index f7a400edd3..4a4f7e6d93 100644 --- a/src/utils/__tests__/useFocusRing.test.tsx +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -1,11 +1,20 @@ -import { Platform, Pressable, Text } from 'react-native'; - -import { describe, expect, it, jest } from '@jest/globals'; +import { Platform, Pressable, Text, View } from 'react-native'; +import type { ViewStyle } from 'react-native'; + +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest, +} from '@jest/globals'; import { act, fireEvent } from '@testing-library/react-native'; import { render, screen } from '../../test-utils'; import { tokens } from '../../theme/tokens'; -import { getFocusRingStyle, useFocusRing } from '../useFocusRing'; +import type { FocusRingPlacement, FocusRingScope } from '../useFocusRing'; +import { buildFocusRingStylesheet, useFocusRing } from '../useFocusRing'; const focus = async (data?: unknown) => { await act(async () => { @@ -26,60 +35,68 @@ const Probe = ({ disabled?: boolean; onRender?: () => void; }) => { - const { focused, onFocus, onBlur } = useFocusRing(disabled); + const { target, ring } = useFocusRing(disabled, 'rebeccapurple'); onRender?.(); return ( {}} - onFocus={onFocus} - onBlur={onBlur} - style={getFocusRingStyle(focused, 'rebeccapurple')} + onFocus={target.onFocus} + onBlur={target.onBlur} + style={ring.style} > probe ); }; -describe('getFocusRingStyle', () => { - it('returns nothing when not focused', () => { - expect(getFocusRingStyle(false, 'rebeccapurple')).toBeNull(); +describe('buildFocusRingStylesheet', () => { + const css = buildFocusRingStylesheet(); + + it('rings `self` via :focus-visible and `within` via :has(:focus-visible), for both placements', () => { + expect(css).toContain('[data-focus-ring="outward"]:focus-visible'); + expect(css).toContain('[data-focus-ring="inward"]:focus-visible'); + expect(css).toContain( + '[data-focus-ring-within="outward"]:has(:focus-visible)' + ); + expect(css).toContain( + '[data-focus-ring-within="inward"]:has(:focus-visible)' + ); }); // Values must come from the design tokens, not be hardcoded here, or the // token is decorative. Derive the expectation from the token itself. - it('takes its thickness and offset from the focusIndicator tokens', () => { + it('takes its thickness and offsets from the focusIndicator tokens', () => { const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; - expect(getFocusRingStyle(true, 'rebeccapurple')).toEqual({ - outlineWidth: thickness, - outlineColor: 'rebeccapurple', - outlineStyle: 'solid', - outlineOffset: outerOffset, - }); - expect(getFocusRingStyle(true, 'rebeccapurple', 'inward')).toEqual({ - outlineWidth: thickness, - outlineColor: 'rebeccapurple', - outlineStyle: 'solid', - outlineOffset: -thickness, - }); + expect(css).toContain(`outline: ${thickness}px solid`); + expect(css).toContain(`outline-offset: ${outerOffset}px;`); + expect(css).toContain(`outline-offset: ${-thickness}px;`); }); }); -describe('useFocusRing', () => { +describe('useFocusRing (native)', () => { + // Derived from the token, not hardcoded - see the note on the stylesheet + // test above. + const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; + it('applies the outline on focus and removes it on blur', async () => { await render(); - expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + expect(screen.getByTestId('probe')).not.toHaveStyle({ + outlineWidth: thickness, + }); await focus(); expect(screen.getByTestId('probe')).toHaveStyle({ - outlineWidth: 3, + outlineWidth: thickness, outlineColor: 'rebeccapurple', - outlineOffset: 2, + outlineOffset: outerOffset, }); await blur(); - expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + expect(screen.getByTestId('probe')).not.toHaveStyle({ + outlineWidth: thickness, + }); }); // `disabled` goes to the hook only, never to the Pressable: RNTL will not @@ -89,21 +106,9 @@ describe('useFocusRing', () => { await focus(); - expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); - }); - - it('ignores a non-keyboard focus event on web, so a mouse click does not ring', async () => { - const original = Platform.OS; - Platform.OS = 'web'; - try { - await render(); - - await focus({ currentTarget: { matches: () => false } }); - - expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); - } finally { - Platform.OS = original; - } + expect(screen.getByTestId('probe')).not.toHaveStyle({ + outlineWidth: thickness, + }); }); // The gate has to skip the state update, not just mask the result, or a @@ -121,7 +126,9 @@ describe('useFocusRing', () => { it('does not restore the ring when a control is re-enabled', async () => { const { rerender } = await render(); await focus(); - expect(screen.getByTestId('probe')).toHaveStyle({ outlineWidth: 3 }); + expect(screen.getByTestId('probe')).toHaveStyle({ + outlineWidth: thickness, + }); await act(async () => { await rerender(); @@ -131,6 +138,89 @@ describe('useFocusRing', () => { }); // no focus event happened in between, so nothing should be ringed - expect(screen.getByTestId('probe')).not.toHaveStyle({ outlineWidth: 3 }); + expect(screen.getByTestId('probe')).not.toHaveStyle({ + outlineWidth: thickness, + }); + }); +}); + +// There is no DOM in this repo's Jest, so these can only prove the wiring - +// the right data attribute and CSS variable land on the right element. Real +// `:focus-visible`/`:has()` behaviour is a manual, browser-only check (see +// the PR description). +describe('useFocusRing (web)', () => { + const original = Platform.OS; + beforeEach(() => { + Platform.OS = 'web'; + }); + afterEach(() => { + Platform.OS = original; + }); + + const WebProbe = ({ + disabled, + placement, + scope, + }: { + disabled?: boolean; + placement?: FocusRingPlacement; + scope?: FocusRingScope; + }) => { + const { target, ring } = useFocusRing( + disabled, + 'rebeccapurple', + placement, + scope + ); + return ( + + + + ); + }; + + it('emits data-focus-ring and the colour variable for scope "self"', async () => { + await render(); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('probe').props.dataSet).toEqual({ + focusRing: 'outward', + }); + expect(screen.getByTestId('probe')).toHaveStyle( + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + { '--rnp-focus-ring-color': 'rebeccapurple' } as unknown as ViewStyle + ); + }); + + it('emits data-focus-ring-within for scope "within", and suppresses the target element\'s own outline', async () => { + await render(); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('probe').props.dataSet).toEqual({ + focusRingWithin: 'inward', + }); + expect(screen.getByTestId('target')).toHaveStyle( + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + { outline: 'none' } as unknown as ViewStyle + ); + }); + + it('does not suppress the target element\'s outline for scope "self"', async () => { + await render(); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('target').props.style).toEqual([]); + }); + + it('emits nothing when disabled or when the ring is turned off', async () => { + await render(); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('probe').props.dataSet).toBeUndefined(); + + await render(); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('probe').props.dataSet).toBeUndefined(); }); }); diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index 776776f642..a13fb75b06 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -1,9 +1,10 @@ import * as React from 'react'; -import type { - ColorValue, - NativeSyntheticEvent, - TargetedEvent, - ViewStyle, +import { + Platform, + type ColorValue, + type NativeSyntheticEvent, + type TargetedEvent, + type ViewStyle, } from 'react-native'; import { isKeyboardFocusEvent } from './isKeyboardFocusEvent'; @@ -13,30 +14,90 @@ const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; export type FocusRingPlacement = 'outward' | 'inward' | 'none'; -export type FocusRingState = { - focused: boolean; - onFocus: (e: NativeSyntheticEvent) => void; - onBlur: () => void; +/** + * `'self'` - the ring is drawn on the element that receives focus. + * `'within'` - the ring is drawn on an ancestor (a track/clip view), because + * the focusable element's own box is the wrong shape or size for it. + */ +export type FocusRingScope = 'self' | 'within'; + +export type FocusRingResult = { + /** Spread onto the element that receives focus. */ + target: { + onFocus?: (e: NativeSyntheticEvent) => void; + onBlur?: () => void; + style: ViewStyle[]; + }; + /** Spread onto the element that draws the ring. */ + ring: { + style: ViewStyle[]; + /** + * Spread onto the ring element, e.g. ``. + * `dataSet` isn't in RN's core view prop types, though react-native-web + * renders it as real `data-*` attributes - the mechanism the shared + * stylesheet below keys off. Typed as `object` so it spreads onto any + * host component without a prop-type mismatch; empty (a no-op spread) + * on native and when the ring is suppressed. + */ + dataSetProps: object; + }; +}; + +const toDataSetProps = (dataSet: Record | undefined): object => + dataSet ? { dataSet } : {}; + +const EMPTY: FocusRingResult = { + target: { style: [] }, + ring: { style: [], dataSetProps: {} }, }; +/** Suppresses the browser's own focus ring, for `scope: 'within'` on web. */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion +const webNoOutlineStyle = { outline: 'none' } as unknown as ViewStyle; + /** - * Tracks keyboard focus for an MD3 focus indicator. + * MD3 keyboard focus indicator, from one hook shared by every component built + * on it. * - * Fires on web and Android only. iOS never dispatches `onFocus` for a View or - * Pressable unless the `enableImperativeFocus` flag is on, and it defaults off. + * On native there is no CSS, so this tracks focus in state and computes the + * ring as an `outline*` style, live. On web the ring is real CSS: a shared + * stylesheet keyed off a `data-focus-ring[-within]` attribute and + * `:focus-visible`/`:has(:focus-visible)`, with only the (theme-dependent) + * color passed through as a CSS custom property. Nothing here tracks focus in + * JS on web - the browser drives it. + * + * `scope: 'within'` is for a control whose ring belongs on an ancestor of the + * element that actually receives focus (Switch's track, FAB's clip view): + * `target` also suppresses the browser's default outline on the focused + * element itself on web, so only the ring shows. + * + * iOS: `onFocus`/`onBlur` never reach here today. Fabric's view does call + * `-becomeFirstResponder`/`-resignFirstResponder` for hardware-keyboard/Full + * Keyboard Access navigation, but only emits the JS event when the + * `enableImperativeFocus` feature flag is on, and it defaults off (old + * architecture has no equivalent path at all). Pre-existing, not something + * this hook introduces - the library's older FAB, Checkbox, and Switch rings + * were equally inert on iOS. */ -export function useFocusRing(disabled?: boolean): FocusRingState { +export function useFocusRing( + disabled: boolean | undefined, + color: ColorValue, + placement: FocusRingPlacement = 'outward', + scope: FocusRingScope = 'self' +): FocusRingResult { + const suppressed = disabled || placement === 'none'; + + // Rules of hooks: called unconditionally regardless of platform. Cheap - + // native's is a no-op until focus/blur actually fires, web's is stateless. const [focused, setFocused] = React.useState(false); const onFocus = React.useCallback( (e: NativeSyntheticEvent) => { - // Symmetric, and skipped entirely when there is nothing to show, so a - // suppressed ring costs no render. - if (!disabled) { + if (!suppressed) { setFocused(isKeyboardFocusEvent(e)); } }, - [disabled] + [suppressed] ); const onBlur = React.useCallback(() => setFocused(false), []); @@ -44,48 +105,99 @@ export function useFocusRing(disabled?: boolean): FocusRingState { // The focusable node can unmount while this hook stays mounted, and neither // the DOM nor React fires blur for that, so clear rather than only masking. React.useEffect(() => { - if (disabled) { + if (suppressed) { setFocused(false); } - }, [disabled]); + }, [suppressed]); - return { focused: focused && !disabled, onFocus, onBlur }; + const isNativeFocused = focused && !suppressed; + + return React.useMemo(() => { + if (suppressed) { + return EMPTY; + } + + if (Platform.OS === 'web') { + const dataKey = scope === 'within' ? 'focusRingWithin' : 'focusRing'; + return { + target: { style: scope === 'within' ? [webNoOutlineStyle] : [] }, + ring: { + style: [ + // A style key starting with `--` becomes a real CSS custom + // property on web (react-native-web's setValueForStyles), read + // by the shared stylesheet below. Not reactive to focus - the + // browser's own `:focus-visible`/`:has()` shows the ring. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + { ['--rnp-focus-ring-color']: color } as unknown as ViewStyle, + ], + dataSetProps: toDataSetProps({ [dataKey]: placement }), + }, + }; + } + + return { + target: { onFocus, onBlur, style: [] }, + ring: { + style: isNativeFocused + ? [ + { + outlineWidth: thickness, + outlineColor: color, + outlineStyle: 'solid' as const, + outlineOffset: + placement === 'inward' ? -thickness : outerOffset, + }, + ] + : [], + dataSetProps: {}, + }, + }; + }, [suppressed, scope, color, placement, isNativeFocused, onFocus, onBlur]); } -/** - * MD3 focus indicator, drawn with the platform's own `outline`. Costs no - * layout, takes its radius from the view it sits on, and `borderless` does not - * clip it. - * - * Outward by default, per MD3 (hence the `outerOffset` token): the ring lands - * on the page background, where it has a predictable contrast ratio. Pass - * `inward` only where an outward ring is measurably clipped or would land on a - * neighbour - list rows, flush segments, chips in a scrolling row. - * - * Never pair this with `outline: 'none'`. Ours overrides the browser's, so if - * it never runs the user still gets the browser ring instead of nothing. - */ -export const getFocusRingStyle = ( - focused: boolean, - color: ColorValue, - placement: FocusRingPlacement = 'outward' -): ViewStyle | null => - focused && placement !== 'none' - ? { - outlineWidth: thickness, - outlineColor: color, - outlineStyle: 'solid', - outlineOffset: placement === 'inward' ? -thickness : outerOffset, - } - : null; +const STYLE_ELEMENT_ATTR = 'data-rnp-focus-ring-styles'; -/** Spread into a style array so an absent ring adds no entry. */ -export const toStyleList = (s: ViewStyle | null): ViewStyle[] => (s ? [s] : []); +const focusRingRule = ( + selector: (placement: 'outward' | 'inward') => string +) => ` +${selector('outward')} { + outline: ${thickness}px solid var(--rnp-focus-ring-color); + outline-offset: ${outerOffset}px; +} +${selector('inward')} { + outline: ${thickness}px solid var(--rnp-focus-ring-color); + outline-offset: ${-thickness}px; +}`; /** - * Suppresses the browser's own focus ring. Only for controls that draw the MD3 - * ring on a different element, where the browser's would land on the wrong box - * or be clipped. Anywhere else, leaving it alone is the safer default. + * The shared web stylesheet text, as a pure function of the design tokens - + * exported so its contents can be asserted without a DOM. */ -// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -export const webNoOutline = { outline: 'none' } as unknown as ViewStyle; +export const buildFocusRingStylesheet = (): string => + [ + focusRingRule((p) => `[data-focus-ring="${p}"]:focus-visible`), + focusRingRule((p) => `[data-focus-ring-within="${p}"]:has(:focus-visible)`), + ].join('\n'); + +let injected = false; + +/** Idempotent: safe to call from every module that needs the ring on web. */ +export const injectFocusRingStylesheet = (): void => { + if (injected || Platform.OS !== 'web' || typeof document === 'undefined') { + return; + } + if (document.querySelector(`style[${STYLE_ELEMENT_ATTR}]`)) { + injected = true; + return; + } + + const style = document.createElement('style'); + style.setAttribute(STYLE_ELEMENT_ATTR, ''); + style.textContent = buildFocusRingStylesheet(); + document.head.appendChild(style); + injected = true; +}; + +if (Platform.OS === 'web') { + injectFocusRingStylesheet(); +} From b5b4e1a41f40f8a8691d2cb1bd099f022f0b7e6c Mon Sep 17 00:00:00 2001 From: Konrad Rydygier Date: Mon, 7 Sep 2026 14:24:44 +0200 Subject: [PATCH 03/50] chore: update snapshots after rebasing onto main --- .../__tests__/__snapshots__/FAB.test.tsx.snap | 312 ---------- .../__snapshots__/FABExtended.test.tsx.snap | 138 ----- .../__snapshots__/FABMenu.test.tsx.snap | 575 ------------------ .../__snapshots__/ListItem.test.tsx.snap | 8 + .../__snapshots__/Switch.test.tsx.snap | 138 ----- 5 files changed, 8 insertions(+), 1163 deletions(-) diff --git a/src/components/__tests__/__snapshots__/FAB.test.tsx.snap b/src/components/__tests__/__snapshots__/FAB.test.tsx.snap index 4b06302358..246de68391 100644 --- a/src/components/__tests__/__snapshots__/FAB.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/FAB.test.tsx.snap @@ -156,7 +156,6 @@ exports[`renders FAB large size 1`] = ` }, [ null, - null, ], ] } @@ -213,29 +212,6 @@ exports[`renders FAB large size 1`] = ` - `; @@ -395,7 +371,6 @@ exports[`renders FAB medium size 1`] = ` }, [ null, - null, ], ] } @@ -452,29 +427,6 @@ exports[`renders FAB medium size 1`] = ` - `; @@ -634,7 +586,6 @@ exports[`renders FAB transitioning to not visible 1`] = ` }, [ null, - null, ], ] } @@ -691,29 +642,6 @@ exports[`renders FAB transitioning to not visible 1`] = ` - `; @@ -873,7 +801,6 @@ exports[`renders FAB transitioning to visible 1`] = ` }, [ null, - null, ], ] } @@ -930,29 +857,6 @@ exports[`renders FAB transitioning to visible 1`] = ` - `; @@ -1113,7 +1017,6 @@ exports[`renders FAB with aria-label 1`] = ` }, [ null, - null, ], ] } @@ -1170,29 +1073,6 @@ exports[`renders FAB with aria-label 1`] = ` - `; @@ -1352,7 +1232,6 @@ exports[`renders FAB with containerColor and contentColor overrides 1`] = ` }, [ null, - null, ], ] } @@ -1409,29 +1288,6 @@ exports[`renders FAB with containerColor and contentColor overrides 1`] = ` - `; @@ -1591,7 +1447,6 @@ exports[`renders FAB with containerColor override 1`] = ` }, [ null, - null, ], ] } @@ -1648,29 +1503,6 @@ exports[`renders FAB with containerColor override 1`] = ` - `; @@ -1830,7 +1662,6 @@ exports[`renders FAB with default props 1`] = ` }, [ null, - null, ], ] } @@ -1887,29 +1718,6 @@ exports[`renders FAB with default props 1`] = ` - `; @@ -2069,7 +1877,6 @@ exports[`renders FAB with primary variant 1`] = ` }, [ null, - null, ], ] } @@ -2126,29 +1933,6 @@ exports[`renders FAB with primary variant 1`] = ` - `; @@ -2308,7 +2092,6 @@ exports[`renders FAB with secondary variant 1`] = ` }, [ null, - null, ], ] } @@ -2365,29 +2148,6 @@ exports[`renders FAB with secondary variant 1`] = ` - `; @@ -2547,7 +2307,6 @@ exports[`renders FAB with tertiary variant 1`] = ` }, [ null, - null, ], ] } @@ -2604,29 +2363,6 @@ exports[`renders FAB with tertiary variant 1`] = ` - `; @@ -2786,7 +2522,6 @@ exports[`renders FAB with tonalSecondary variant 1`] = ` }, [ null, - null, ], ] } @@ -2843,29 +2578,6 @@ exports[`renders FAB with tonalSecondary variant 1`] = ` - `; @@ -3025,7 +2737,6 @@ exports[`renders FAB with tonalTertiary variant 1`] = ` }, [ null, - null, ], ] } @@ -3082,28 +2793,5 @@ exports[`renders FAB with tonalTertiary variant 1`] = ` - `; diff --git a/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap b/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap index db4530892f..33a1ab1a5d 100644 --- a/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap @@ -256,29 +256,6 @@ exports[`renders extended FAB collapsed 1`] = ` - - - - - - - - @@ -745,29 +699,6 @@ exports[`renders FAB.Menu closed 1`] = ` - @@ -977,29 +908,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` - - @@ -1519,29 +1404,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` - @@ -1751,29 +1613,6 @@ exports[`renders FAB.Menu open 1`] = ` - - @@ -2293,29 +2109,6 @@ exports[`renders FAB.Menu open 1`] = ` - @@ -2525,29 +2318,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` - - - - - - @@ -3767,29 +3422,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` - @@ -4000,29 +3632,6 @@ exports[`renders FAB.Menu with center alignment 1`] = ` - - @@ -4542,29 +4128,6 @@ exports[`renders FAB.Menu with center alignment 1`] = ` - @@ -4804,29 +4367,6 @@ exports[`renders FAB.Menu with items having icons 1`] = ` - - @@ -5376,29 +4893,6 @@ exports[`renders FAB.Menu with items having icons 1`] = ` - @@ -5608,29 +5102,6 @@ exports[`renders FAB.Menu with start alignment 1`] = ` - - @@ -6150,29 +5598,6 @@ exports[`renders FAB.Menu with start alignment 1`] = ` - diff --git a/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap b/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap index bfa1299b87..09388e0abd 100644 --- a/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap @@ -169,6 +169,7 @@ exports[`renders list item with custom description 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -388,6 +389,7 @@ exports[`renders list item with custom description 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -558,6 +560,7 @@ exports[`renders list item with custom title and description styles 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -702,6 +705,7 @@ exports[`renders list item with left and right items 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -891,6 +895,7 @@ exports[`renders list item with left item 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -1046,6 +1051,7 @@ exports[`renders list item with right item 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -1157,6 +1163,7 @@ exports[`renders list item with title and description 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -1297,6 +1304,7 @@ exports[`renders with a description with typeof number 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} + onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} diff --git a/src/components/__tests__/__snapshots__/Switch.test.tsx.snap b/src/components/__tests__/__snapshots__/Switch.test.tsx.snap index 9b641a7ae7..d94d99fffa 100644 --- a/src/components/__tests__/__snapshots__/Switch.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/Switch.test.tsx.snap @@ -188,29 +188,6 @@ exports[`Switch render renders disabled off 1`] = ` } /> - `; @@ -382,29 +359,6 @@ exports[`Switch render renders disabled on 1`] = ` } /> - `; @@ -579,29 +533,6 @@ exports[`Switch render renders off 1`] = ` } /> - `; @@ -756,29 +687,6 @@ exports[`Switch render renders on 1`] = ` } /> - `; @@ -1004,29 +912,6 @@ exports[`Switch render renders with checked icon 1`] = ` - `; @@ -1252,28 +1137,5 @@ exports[`Switch render renders with per-state icons 1`] = ` - `; From 7332cec5d8f182d56919d27c889604687cc6e7da Mon Sep 17 00:00:00 2001 From: Konrad Rydygier Date: Wed, 9 Sep 2026 08:37:04 +0200 Subject: [PATCH 04/50] test: correct snapshots after combining focus-ring and hitSlop rebase The snapshots carried over from the pre-rebase commit didn't account for the per-component hitSlop changes now merged in from 48dp-touch-targets. --- .../__tests__/__snapshots__/ListItem.test.tsx.snap | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap b/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap index 09388e0abd..bfa1299b87 100644 --- a/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap @@ -169,7 +169,6 @@ exports[`renders list item with custom description 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -389,7 +388,6 @@ exports[`renders list item with custom description 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -560,7 +558,6 @@ exports[`renders list item with custom title and description styles 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -705,7 +702,6 @@ exports[`renders list item with left and right items 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -895,7 +891,6 @@ exports[`renders list item with left item 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -1051,7 +1046,6 @@ exports[`renders list item with right item 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -1163,7 +1157,6 @@ exports[`renders list item with title and description 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} @@ -1304,7 +1297,6 @@ exports[`renders with a description with typeof number 1`] = ` onBlur={[Function]} onClick={[Function]} onFocus={[Function]} - onLayout={[Function]} onResponderGrant={[Function]} onResponderMove={[Function]} onResponderRelease={[Function]} From a4c31b458f73b324c2e81cb6f444d7e59ade8d48 Mon Sep 17 00:00:00 2001 From: Konrad Rydygier Date: Wed, 23 Sep 2026 10:24:57 +0200 Subject: [PATCH 05/50] test: fix snapshots after rebase --- src/components/__tests__/__snapshots__/ListItem.test.tsx.snap | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap b/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap index bfa1299b87..1d2124fb4e 100644 --- a/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/ListItem.test.tsx.snap @@ -43,6 +43,9 @@ exports[`renders list item with custom content style 1`] = ` }, undefined, ], + { + "--rnp-focus-ring-color": "rgba(98, 91, 113, 1)", + }, ] } testID="list-item" From e2d40c30393e0abbfd2022b66346f46884225d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 6 Nov 2026 17:19:02 +0100 Subject: [PATCH 06/50] test: fix imports and snapshots after rebasing onto #5108 --- src/components/__tests__/TouchableRipple.test.tsx | 2 +- src/components/__tests__/__snapshots__/Chip.test.tsx.snap | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/components/__tests__/TouchableRipple.test.tsx b/src/components/__tests__/TouchableRipple.test.tsx index c917c7a18d..d826112ad9 100644 --- a/src/components/__tests__/TouchableRipple.test.tsx +++ b/src/components/__tests__/TouchableRipple.test.tsx @@ -2,7 +2,7 @@ import { Platform, Text } from 'react-native'; import type { GestureResponderEvent } from 'react-native'; import { afterAll, beforeAll, describe, expect, it, jest } from '@jest/globals'; -import { userEvent } from '@testing-library/react-native'; +import { act, fireEvent, userEvent } from '@testing-library/react-native'; import { render, screen } from '../../test-utils'; import TouchableRipple from '../TouchableRipple/TouchableRipple.native'; diff --git a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap index 48e5dad591..34d1da63de 100644 --- a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap @@ -317,7 +317,9 @@ exports[`renders chip with close button 1`] = ` "justifyContent": "center", "width": "100%", }, - undefined, + { + "borderRadius": 8, + }, ] } > @@ -690,7 +692,9 @@ exports[`renders chip with custom close button 1`] = ` "justifyContent": "center", "width": "100%", }, - undefined, + { + "borderRadius": 8, + }, ] } > From 2256d799519ef705a1801e9d038a28737eeddf9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Tue, 10 Nov 2026 16:13:49 +0100 Subject: [PATCH 07/50] fix(switch): show the focus ring on the track on web --- src/components/Switch/Switch.tsx | 9 ++-- .../__tests__/focusRingWiring.test.tsx | 34 +++++++++++++- src/utils/__tests__/useFocusRing.test.tsx | 41 +++++++++++++++++ src/utils/useFocusRing.ts | 44 +++++++++++++++---- 4 files changed, 113 insertions(+), 15 deletions(-) diff --git a/src/components/Switch/Switch.tsx b/src/components/Switch/Switch.tsx index e8bf06b4bc..1631c84119 100644 --- a/src/components/Switch/Switch.tsx +++ b/src/components/Switch/Switch.tsx @@ -169,14 +169,14 @@ const Switch = ({ const colors = React.useMemo(() => getDefaultSwitchColors(theme), [theme]); - // `scope: 'within'`: the ring is drawn on the track below, not this - // Pressable - it also suppresses the browser's own outline here on web, so - // only the track's ring shows. + // `scope: 'descendant'`: the ring is drawn on the track, a child of this + // Pressable, not on the Pressable itself - it also suppresses the browser's + // own outline here on web, so only the track's ring shows. const { target: focusTarget, ring: focusRing } = useFocusRing( isDisabled, colors.focusIndicatorColor, 'outward', - 'within' + 'descendant' ); const reanimatedReduceMotion = reduceMotion @@ -389,6 +389,7 @@ const Switch = ({ aria-label={ariaLabel} testID={testID} style={[styles.touchable, ...focusTarget.style]} + {...focusTarget.dataSetProps} > { expect(ringOffset()).toBe(OUTWARD); }); }); + +describe('focus ring wiring (web)', () => { + const original = Platform.OS; + beforeEach(() => { + Platform.OS = 'web'; + }); + afterEach(() => { + Platform.OS = original; + }); + + // The track is a child of the focused Pressable, so it can't be ringed with + // `:has(:focus-visible)` (that only matches ancestors of the focused node). + it('Switch marks its Pressable as the focus target and rings the track inside it', async () => { + await render( {}} />); + + const pressable = screen.getByRole('switch'); + expect(pressable.props.dataSet).toEqual({ focusRingTarget: 'true' }); + + const ringed = walk( + pressable, + (n) => + (n.props?.dataSet as Record | undefined) + ?.focusRingDescendant !== undefined + ); + expect(ringed).toHaveLength(1); + expect( + (ringed[0].props?.dataSet as Record).focusRingDescendant + ).toBe('outward'); + }); +}); diff --git a/src/utils/__tests__/useFocusRing.test.tsx b/src/utils/__tests__/useFocusRing.test.tsx index 4a4f7e6d93..5c822f161d 100644 --- a/src/utils/__tests__/useFocusRing.test.tsx +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -64,6 +64,17 @@ describe('buildFocusRingStylesheet', () => { ); }); + // `:has()` only looks down from the ringed element, so a ring on a child of + // the focused element needs its own rule, keyed off the focused ancestor. + it('rings `descendant` from its focused ancestor, for both placements', () => { + expect(css).toContain( + '[data-focus-ring-target]:focus-visible [data-focus-ring-descendant="outward"]' + ); + expect(css).toContain( + '[data-focus-ring-target]:focus-visible [data-focus-ring-descendant="inward"]' + ); + }); + // Values must come from the design tokens, not be hardcoded here, or the // token is decorative. Derive the expectation from the token itself. it('takes its thickness and offsets from the focusIndicator tokens', () => { @@ -205,6 +216,36 @@ describe('useFocusRing (web)', () => { ); }); + it('marks the focused element and its ringed child for scope "descendant", and suppresses the target element\'s own outline', async () => { + const DescendantProbe = () => { + const { target, ring } = useFocusRing( + false, + 'rebeccapurple', + 'outward', + 'descendant' + ); + return ( + + + + ); + }; + await render(); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('target').props.dataSet).toEqual({ + focusRingTarget: 'true', + }); + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('probe').props.dataSet).toEqual({ + focusRingDescendant: 'outward', + }); + expect(screen.getByTestId('target')).toHaveStyle( + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + { outline: 'none' } as unknown as ViewStyle + ); + }); + it('does not suppress the target element\'s outline for scope "self"', async () => { await render(); diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index a13fb75b06..759c00021e 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -18,8 +18,10 @@ export type FocusRingPlacement = 'outward' | 'inward' | 'none'; * `'self'` - the ring is drawn on the element that receives focus. * `'within'` - the ring is drawn on an ancestor (a track/clip view), because * the focusable element's own box is the wrong shape or size for it. + * `'descendant'` - the ring is drawn on a child of the element that receives + * focus (Switch's track inside its 48dp-tall Pressable), for the same reason. */ -export type FocusRingScope = 'self' | 'within'; +export type FocusRingScope = 'self' | 'within' | 'descendant'; export type FocusRingResult = { /** Spread onto the element that receives focus. */ @@ -27,6 +29,12 @@ export type FocusRingResult = { onFocus?: (e: NativeSyntheticEvent) => void; onBlur?: () => void; style: ViewStyle[]; + /** + * Spread onto the focused element, like `ring.dataSetProps`. Only set + * for `scope: 'descendant'` on web, where the stylesheet needs to find + * the focused ancestor of the ring; empty otherwise. + */ + dataSetProps: object; }; /** Spread onto the element that draws the ring. */ ring: { @@ -47,11 +55,14 @@ const toDataSetProps = (dataSet: Record | undefined): object => dataSet ? { dataSet } : {}; const EMPTY: FocusRingResult = { - target: { style: [] }, + target: { style: [], dataSetProps: {} }, ring: { style: [], dataSetProps: {} }, }; -/** Suppresses the browser's own focus ring, for `scope: 'within'` on web. */ +/** + * Suppresses the browser's own focus ring, for `scope: 'within'` and + * `scope: 'descendant'` on web. + */ // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion const webNoOutlineStyle = { outline: 'none' } as unknown as ViewStyle; @@ -67,9 +78,10 @@ const webNoOutlineStyle = { outline: 'none' } as unknown as ViewStyle; * JS on web - the browser drives it. * * `scope: 'within'` is for a control whose ring belongs on an ancestor of the - * element that actually receives focus (Switch's track, FAB's clip view): - * `target` also suppresses the browser's default outline on the focused - * element itself on web, so only the ring shows. + * element that actually receives focus (FAB's clip view), and + * `scope: 'descendant'` for one whose ring belongs on a child of it (Switch's + * track): `target` also suppresses the browser's default outline on the + * focused element itself on web, so only the ring shows. * * iOS: `onFocus`/`onBlur` never reach here today. Fabric's view does call * `-becomeFirstResponder`/`-resignFirstResponder` for hardware-keyboard/Full @@ -118,9 +130,19 @@ export function useFocusRing( } if (Platform.OS === 'web') { - const dataKey = scope === 'within' ? 'focusRingWithin' : 'focusRing'; + const dataKey = + scope === 'within' + ? 'focusRingWithin' + : scope === 'descendant' + ? 'focusRingDescendant' + : 'focusRing'; return { - target: { style: scope === 'within' ? [webNoOutlineStyle] : [] }, + target: { + style: scope === 'self' ? [] : [webNoOutlineStyle], + dataSetProps: toDataSetProps( + scope === 'descendant' ? { focusRingTarget: 'true' } : undefined + ), + }, ring: { style: [ // A style key starting with `--` becomes a real CSS custom @@ -136,7 +158,7 @@ export function useFocusRing( } return { - target: { onFocus, onBlur, style: [] }, + target: { onFocus, onBlur, style: [], dataSetProps: {} }, ring: { style: isNativeFocused ? [ @@ -177,6 +199,10 @@ export const buildFocusRingStylesheet = (): string => [ focusRingRule((p) => `[data-focus-ring="${p}"]:focus-visible`), focusRingRule((p) => `[data-focus-ring-within="${p}"]:has(:focus-visible)`), + focusRingRule( + (p) => + `[data-focus-ring-target]:focus-visible [data-focus-ring-descendant="${p}"]` + ), ].join('\n'); let injected = false; From 4a7ed7ddcd0001b7bf257d93702675ca06f3c75d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Tue, 10 Nov 2026 16:15:49 +0100 Subject: [PATCH 08/50] fix(bottom-navigation): draw the tab focus ring inward Tabs fill the bar edge to edge and the bar clips (`overflow: 'hidden'`), so the default outward ring lost its top and bottom and showed only as vertical lines between tabs. Pass `focusRing: 'inward'` to `renderTouchable` and forward it explicitly in the default `Touchable` so it does not leak to the iOS `Pressable` fallback. --- .../BottomNavigation/BottomNavigationBar.tsx | 6 +++++ .../__tests__/focusRingWiring.test.tsx | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/components/BottomNavigation/BottomNavigationBar.tsx b/src/components/BottomNavigation/BottomNavigationBar.tsx index 99ee8591d9..154f872a91 100644 --- a/src/components/BottomNavigation/BottomNavigationBar.tsx +++ b/src/components/BottomNavigation/BottomNavigationBar.tsx @@ -213,6 +213,7 @@ const Touchable = ({ borderless, centered, rippleColor, + focusRing, ...rest }: TouchableProps) => TouchableRipple.supported ? ( @@ -222,6 +223,7 @@ const Touchable = ({ borderless={borderless} centered={centered} rippleColor={rippleColor} + focusRing={focusRing} style={style} > {children} @@ -574,6 +576,10 @@ const BottomNavigationBar = ({ borderless: true, centered: true, rippleColor: 'transparent', + // Tabs fill the bar edge to edge and the bar clips + // (`overflow: 'hidden'`), so an outward ring would lose its top + // and bottom and read as two vertical lines between tabs. + focusRing: 'inward', onPress: () => onTabPress(eventForIndex(index)), onLongPress: () => onTabLongPress?.(eventForIndex(index)), testID: getTestID({ route }), diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 0481ab4ff8..6353891da4 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -10,11 +10,13 @@ import { act, fireEvent } from '@testing-library/react-native'; import { render, screen } from '../../test-utils'; import { tokens } from '../../theme/tokens'; +import BottomNavigation from '../BottomNavigation/BottomNavigation'; import Card from '../Card/Card'; import Chip from '../Chip/Chip'; import FAB from '../FAB/FAB'; import ListItem from '../List/ListItem'; import Switch from '../Switch/Switch'; +import TouchableRipple from '../TouchableRipple/TouchableRipple.native'; const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; const OUTWARD = outerOffset; @@ -71,6 +73,31 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(INWARD); }); + // The bar clips (`overflow: 'hidden'`) and tabs fill it edge to edge, so an + // outward ring loses its top and bottom. Rendered through a custom + // `renderTouchable` so the test runs the ring path on every platform. + it('BottomNavigation.Bar rings its tabs inward', async () => { + await render( + {}} + renderTouchable={({ key, route: _route, ...props }) => ( + + )} + /> + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> From 72662630eb0c86a3e49113b55f1cbed9fba1d889 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:24:44 +0100 Subject: [PATCH 09/50] fix(chip): draw the body focus ring outward MD3 and Material Web ring chips outward (3dp, 2dp gap). The chip body was inward so a scrolling chip row could not trim it, but that clip belongs to the app's container, not to the chip, so the chip follows the spec. --- src/components/Chip/Chip.tsx | 1 - src/components/__tests__/focusRingWiring.test.tsx | 6 ++++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index 16571b9452..f4b5c17a1c 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -326,7 +326,6 @@ const Chip = ({ > { expect(ringOffset()).toBe(INWARD); }); - it('Chip rings inward, so a scrolling chip row cannot trim it', async () => { + // Outward like MD3 and Material Web. A scrolling chip row that trims it is + // the app's container, not the chip's own view. + it('Chip rings outward', async () => { await render( {}}>chip); await focusFirstFocusable(); - expect(ringOffset()).toBe(INWARD); + expect(ringOffset()).toBe(OUTWARD); }); // The bar clips (`overflow: 'hidden'`) and tabs fill it edge to edge, so an From 900a103031ba32ddd3f19ba9d1a898446ac66106 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:27:02 +0100 Subject: [PATCH 10/50] fix(chip): ring the close button with a circle around the glyph Material Web rings the remove button with a circle around the icon. The ring was a rounded rectangle around the whole 34dp close column from #5108, reaching the label. Focus still lands on the column, so its touch target is unchanged; the ring is drawn outward on a 24dp circle (4/3 of the 18dp icon, like Material Web) inside it, through the 'descendant' scope. --- src/components/Chip/Chip.tsx | 36 ++++++++++++-- .../__snapshots__/Chip.test.tsx.snap | 14 ++++++ .../__tests__/focusRingWiring.test.tsx | 47 +++++++++++++++++++ src/utils/useFocusRing.ts | 3 +- 4 files changed, 94 insertions(+), 6 deletions(-) diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index f4b5c17a1c..534a78dc3e 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -171,6 +171,13 @@ const CLOSE_AFFORDANCE_WIDTH = 34; */ const CLOSE_AFFORDANCE_MIN_WIDTH = 26; +/** + * The close button's focus ring is a circle around the glyph, not around the + * whole column, sized like Material Web's trailing action (4/3 of the 18dp + * icon). It fits inside the column's 26dp floor. + */ +const CLOSE_FOCUS_RING_SIZE = 24; + /** * The label makes a default chip 32dp tall, so the slop to reach the 48dp * minimum is a constant rather than something to measure. Width grows with the @@ -242,11 +249,14 @@ const Chip = ({ const theme = useInternalTheme(themeOverrides); // The close affordance is a plain `Pressable`, not a `TouchableRipple` // (see below), so it calls `useFocusRing` directly instead of going - // through `TouchableRipple`'s `focusRing` prop like the body does. + // through `TouchableRipple`'s `focusRing` prop like the body does. The + // `Pressable` is the whole close column, but the ring follows the glyph's + // round shape, so it goes on a circle inside it (`'descendant'`). const { target: closeFocusTarget, ring: closeFocusRing } = useFocusRing( disabled, theme.colors.secondary, - 'inward' + 'outward', + 'descendant' ); const [pressed, setPressed] = React.useState(false); @@ -436,11 +446,11 @@ const Chip = ({ hitSlop={disabled ? undefined : CHIP_BODY_HIT_SLOP} onFocus={closeFocusTarget.onFocus} onBlur={closeFocusTarget.onBlur} - {...closeFocusRing.dataSetProps} + {...closeFocusTarget.dataSetProps} style={[ styles.closeButton, { borderRadius }, - ...closeFocusRing.style, + ...closeFocusTarget.style, ]} > {/* react-native-web removed `hitSlop` in 0.13.0, @@ -449,7 +459,16 @@ const Chip = ({ {Platform.OS === 'web' && !disabled && ( )} - + {closeIcon ? ( ) : ( @@ -544,6 +563,13 @@ const styles = StyleSheet.create({ height: '100%', justifyContent: 'center', }, + closeFocusRing: { + width: CLOSE_FOCUS_RING_SIZE, + height: CLOSE_FOCUS_RING_SIZE, + borderRadius: CLOSE_FOCUS_RING_SIZE / 2, + alignItems: 'center', + justifyContent: 'center', + }, closeButtonWebTouchTarget: { position: 'absolute', top: -CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET, diff --git a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap index 34d1da63de..0e130cfb80 100644 --- a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap @@ -337,6 +337,13 @@ exports[`renders chip with close button 1`] = ` "marginRight": 0, "padding": 0, }, + { + "alignItems": "center", + "borderRadius": 12, + "height": 24, + "justifyContent": "center", + "width": 24, + }, ] } > @@ -712,6 +719,13 @@ exports[`renders chip with custom close button 1`] = ` "marginRight": 0, "padding": 0, }, + { + "alignItems": "center", + "borderRadius": 12, + "height": 24, + "justifyContent": "center", + "width": 24, + }, ] } > diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index e2eb263ada..c4f661d294 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -100,6 +100,30 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(INWARD); }); + // Material Web rings the remove button with a circle around the glyph, not + // the whole close column. + it('Chip rings its close button with a circle around the glyph', async () => { + await render( + {}} onClose={() => {}}> + chip + + ); + + await act(async () => { + await fireEvent(screen.getByLabelText('Close'), 'focus'); + }); + + const root = (screen as unknown as { root: Node }).root; + const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(ringed).toHaveLength(1); + expect(style(ringed[0])).toMatchObject({ + outlineOffset: OUTWARD, + width: 24, + height: 24, + borderRadius: 12, + }); + }); + it('Card rings outward', async () => { await render( {}}> @@ -159,4 +183,27 @@ describe('focus ring wiring (web)', () => { (ringed[0].props?.dataSet as Record).focusRingDescendant ).toBe('outward'); }); + + it('Chip marks its close button as the focus target and rings the glyph circle inside it', async () => { + await render( + {}} onClose={() => {}}> + chip + + ); + + const close = screen.getByLabelText('Close'); + expect(close.props.dataSet).toEqual({ focusRingTarget: 'true' }); + + const ringed = walk( + close, + (n) => + (n.props?.dataSet as Record | undefined) + ?.focusRingDescendant !== undefined + ); + expect(ringed).toHaveLength(1); + expect( + (ringed[0].props?.dataSet as Record).focusRingDescendant + ).toBe('outward'); + expect(style(ringed[0])).toMatchObject({ width: 24, borderRadius: 12 }); + }); }); diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index 759c00021e..8540d69885 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -19,7 +19,8 @@ export type FocusRingPlacement = 'outward' | 'inward' | 'none'; * `'within'` - the ring is drawn on an ancestor (a track/clip view), because * the focusable element's own box is the wrong shape or size for it. * `'descendant'` - the ring is drawn on a child of the element that receives - * focus (Switch's track inside its 48dp-tall Pressable), for the same reason. + * focus (Switch's track inside its 48dp-tall Pressable, the circle around + * Chip's close glyph inside its close column), for the same reason. */ export type FocusRingScope = 'self' | 'within' | 'descendant'; From 99076199c9e50a769dc1be762c3cd8e2e9d1a39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:27:43 +0100 Subject: [PATCH 11/50] fix(checkbox): draw the Checkbox.Item focus ring inward Checkbox.Item is a full-width row, like List.Item and RadioButton.Item, which already ring inward. An outward ring ran into the rows above and below it. --- src/components/Checkbox/CheckboxItem.tsx | 2 ++ src/components/__tests__/focusRingWiring.test.tsx | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/src/components/Checkbox/CheckboxItem.tsx b/src/components/Checkbox/CheckboxItem.tsx index e924f0c07a..a1a4c0e1da 100644 --- a/src/components/Checkbox/CheckboxItem.tsx +++ b/src/components/Checkbox/CheckboxItem.tsx @@ -163,6 +163,8 @@ const CheckboxItem = ({ return ( { }); }); + it('Checkbox.Item rings inward, clear of the rows above and below', async () => { + await render( + {}} /> + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> From 125bd2e036391db50b14ce2a85d8b7a3d76f49e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:28:06 +0100 Subject: [PATCH 12/50] fix(list): draw the List.Accordion focus ring inward List.Accordion is a full-width row like List.Item, which already rings inward, so the two were inconsistent and the accordion's outward ring ran into the rows around it. --- src/components/List/ListAccordion.tsx | 3 +++ src/components/__tests__/focusRingWiring.test.tsx | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/components/List/ListAccordion.tsx b/src/components/List/ListAccordion.tsx index fa4438e3db..43314743bd 100644 --- a/src/components/List/ListAccordion.tsx +++ b/src/components/List/ListAccordion.tsx @@ -248,6 +248,9 @@ const ListAccordion = ({ { expect(ringOffset()).toBe(INWARD); }); + it('List.Accordion rings inward, like List.Item', async () => { + await render( + + + + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> From cc291baf43bffcce9e7f1acda909e61e5a2841f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:29:28 +0100 Subject: [PATCH 13/50] fix(menu): draw the Menu.Item focus ring inward Menu items fill the menu's scroll view edge to edge with no gap between them, so an outward ring was clipped by the menu and ran into the neighbouring items. Material Web rings menu items inward too. --- src/components/Menu/MenuItem.tsx | 3 +++ src/components/__tests__/focusRingWiring.test.tsx | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/components/Menu/MenuItem.tsx b/src/components/Menu/MenuItem.tsx index c76bee0557..561bb02800 100644 --- a/src/components/Menu/MenuItem.tsx +++ b/src/components/Menu/MenuItem.tsx @@ -182,6 +182,9 @@ const MenuItem = ({ return ( { expect(ringOffset()).toBe(INWARD); }); + it("Menu.Item rings inward, inside the menu's scroll view", async () => { + await render( {}} />); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> From 3f3c43b451df0628800a1b60fd22cb915f679e03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:30:22 +0100 Subject: [PATCH 14/50] fix(fab): draw the FAB.Menu item focus ring inward Menu items are only 4dp apart (MenuTokens.spacing.betweenItems), but an outward ring reaches 5dp past the pill (2dp gap plus 3dp thickness), so the focused item's ring ran into the next one. The MD3 FAB menu spec draws the item rings inward, and the PR description already said so. --- src/components/FAB/Menu.tsx | 6 ++++- .../__tests__/focusRingWiring.test.tsx | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/components/FAB/Menu.tsx b/src/components/FAB/Menu.tsx index 8a26648d34..998550d18c 100644 --- a/src/components/FAB/Menu.tsx +++ b/src/components/FAB/Menu.tsx @@ -246,12 +246,16 @@ const MenuItem = ({ // `scope: 'within'`: the ring belongs on the pill below, not the inner // `TouchableRipple` that actually receives focus. // + // Inward, as in the MD3 FAB menu spec: items are only + // `MenuTokens.spacing.betweenItems` (4dp) apart, so an outward ring (2dp gap + // plus 3dp thickness) would run into the neighbouring item. + // // `undefined` disabled: menu items have no `disabled` prop today. Wire the // real value through here if that ever changes. const { target: focusTarget, ring: focusRing } = useFocusRing( undefined, theme.colors.secondary, - 'outward', + 'inward', 'within' ); diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 57cc50d264..6aebcc3190 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -15,6 +15,7 @@ import Card from '../Card/Card'; import CheckboxItem from '../Checkbox/CheckboxItem'; import Chip from '../Chip/Chip'; import FAB from '../FAB/FAB'; +import FABMenu from '../FAB/Menu'; import ListAccordion from '../List/ListAccordion'; import ListItem from '../List/ListItem'; import MenuItem from '../Menu/MenuItem'; @@ -179,6 +180,28 @@ describe('focus ring wiring', () => { // Inward here lands on the filled track, where `secondary` is ~1:1 against // `primary` and effectively invisible. + // Items are 4dp apart, less than an outward ring's 2dp gap plus 3dp + // thickness, so it would run into the next item. + it('FAB.Menu rings its items inward, clear of the neighbouring items', async () => { + await render( + {}} + trigger={{ icon: 'plus' }} + items={[ + { label: 'first', onPress: () => {}, testID: 'item-0' }, + { label: 'second', onPress: () => {}, testID: 'item-1' }, + ]} + /> + ); + + await act(async () => { + await fireEvent(screen.getByTestId('item-0'), 'focus'); + }); + + expect(ringOffset()).toBe(INWARD); + }); + it('Switch rings outward on its track, not inside it', async () => { await render( {}} />); From a22daf1408221b0896d5dba55933f430a9352b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:31:07 +0100 Subject: [PATCH 15/50] test(button): pin the outward focus ring and drop a stale TODO The TODO from #5097 expected the focus ring work to land as #5084 and worried that Button's clip view would trim an outward ring. Neither that view nor the Surface sets overflow, so the ring is whole (checked on web). Replace the TODO with what is true now and pin the placement in a test. --- src/components/Button/Button.tsx | 11 +++-------- src/components/__tests__/focusRingWiring.test.tsx | 9 +++++++++ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/components/Button/Button.tsx b/src/components/Button/Button.tsx index 37cd23a29d..5ba90f16b8 100644 --- a/src/components/Button/Button.tsx +++ b/src/components/Button/Button.tsx @@ -446,14 +446,9 @@ const Button = ({ // The clip carries the same radius transition as the `Surface`, so the // ripple and the disabled overlay follow the morph. // - // TODO: revisit the focus ring's placement once #5084 lands. - // https://github.com/callstack/react-native-paper/pull/5084 adds MD3 keyboard - // focus indicators to every `TouchableRipple` consumer, so Button gets one - // with no code here. Deliberately not implemented locally: a second ring here - // would double up with it. The catch is placement — that PR defaults to - // `focusRing="outward"` and warns an outward ring is trimmed by "any clipping - // ancestor sized to its content", which is exactly this view. Button will - // likely need `focusRing="inward"`, or the ring on the outer view. + // The keyboard focus ring is `TouchableRipple`'s default outward one, drawn + // on the ripple itself. Neither this view nor the `Surface` sets `overflow`, + // so nothing here trims it. const shapeTransitionStyle = { transitionProperty: 'borderRadius', transitionDuration: shapeTransitionDuration, diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 6aebcc3190..78b6635980 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -11,6 +11,7 @@ import { act, fireEvent } from '@testing-library/react-native'; import { render, screen } from '../../test-utils'; import { tokens } from '../../theme/tokens'; import BottomNavigation from '../BottomNavigation/BottomNavigation'; +import Button from '../Button/Button'; import Card from '../Card/Card'; import CheckboxItem from '../Checkbox/CheckboxItem'; import Chip from '../Chip/Chip'; @@ -158,6 +159,14 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(INWARD); }); + it('Button rings outward', async () => { + await render(); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + }); + it('Card rings outward', async () => { await render( {}}> From df007cb29495c3ff48f105c9319e230951a81516 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:44:17 +0100 Subject: [PATCH 16/50] fix(chip): size the close ring like Material Web, clear of the label Material Web's trailing action draws its ring right outside a 24dp circle, with no outer offset (`inset: unset`), so it ends 30dp across. Ours was a 24dp circle plus the shared 2dp offset, 34dp across, which filled the whole close column and touched the label. Shrink the ringed view by the offset so the ring ends where Material Web's does, 2dp clear of the label. --- src/components/Chip/Chip.tsx | 10 +++++++--- .../__tests__/__snapshots__/Chip.test.tsx.snap | 12 ++++++------ src/components/__tests__/focusRingWiring.test.tsx | 14 ++++++++++---- 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index 534a78dc3e..2ec6524951 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -17,6 +17,7 @@ import type { ChipAvatarProps } from './helpers'; import { ChipTokens } from './tokens'; import { useInternalTheme } from '../../core/theming'; import { white } from '../../theme/colors'; +import { tokens } from '../../theme/tokens'; import type { ThemeProp } from '../../theme/types'; import getMinInteractiveSizeHitSlop from '../../utils/getMinInteractiveSizeHitSlop'; import hasTouchHandler from '../../utils/hasTouchHandler'; @@ -173,10 +174,13 @@ const CLOSE_AFFORDANCE_MIN_WIDTH = 26; /** * The close button's focus ring is a circle around the glyph, not around the - * whole column, sized like Material Web's trailing action (4/3 of the 18dp - * icon). It fits inside the column's 26dp floor. + * whole column, matching Material Web's trailing action: a 24dp circle (4/3 + * of the 18dp icon) with the 3dp ring right outside it and no outer offset + * (`inset: unset`). The shared ring adds the 2dp offset, so the view is that + * much smaller. The ring ends 30dp across, 2dp clear of the label. */ -const CLOSE_FOCUS_RING_SIZE = 24; +const CLOSE_FOCUS_RING_SIZE = + 24 - 2 * tokens.md.sys.state.focusIndicator.outerOffset; /** * The label makes a default chip 32dp tall, so the slop to reach the 48dp diff --git a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap index 0e130cfb80..bef2789856 100644 --- a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap @@ -339,10 +339,10 @@ exports[`renders chip with close button 1`] = ` }, { "alignItems": "center", - "borderRadius": 12, - "height": 24, + "borderRadius": 10, + "height": 20, "justifyContent": "center", - "width": 24, + "width": 20, }, ] } @@ -721,10 +721,10 @@ exports[`renders chip with custom close button 1`] = ` }, { "alignItems": "center", - "borderRadius": 12, - "height": 24, + "borderRadius": 10, + "height": 20, "justifyContent": "center", - "width": 24, + "width": 20, }, ] } diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 78b6635980..201619fe3d 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -121,11 +121,14 @@ describe('focus ring wiring', () => { const root = (screen as unknown as { root: Node }).root; const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); expect(ringed).toHaveLength(1); + // Material Web: a 24dp circle with the ring right outside it. The shared + // ring adds the outer offset, so the view is that much smaller. + const size = 24 - 2 * outerOffset; expect(style(ringed[0])).toMatchObject({ outlineOffset: OUTWARD, - width: 24, - height: 24, - borderRadius: 12, + width: size, + height: size, + borderRadius: size / 2, }); }); @@ -269,6 +272,9 @@ describe('focus ring wiring (web)', () => { expect( (ringed[0].props?.dataSet as Record).focusRingDescendant ).toBe('outward'); - expect(style(ringed[0])).toMatchObject({ width: 24, borderRadius: 12 }); + expect(style(ringed[0])).toMatchObject({ + width: 24 - 2 * outerOffset, + borderRadius: 12 - outerOffset, + }); }); }); From bfca5dbb218b8875f8e66badc6a14ac45a19928f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:53:56 +0100 Subject: [PATCH 17/50] fix(data-table): draw the DataTable.Row focus ring inward Rows stack edge to edge with no gap, so an outward ring ran into the rows above and below. MD3 has no data table component, so the row follows MD3 and Material Web lists, which ring their items inward. --- src/components/DataTable/DataTableRow.tsx | 3 +++ src/components/__tests__/focusRingWiring.test.tsx | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/components/DataTable/DataTableRow.tsx b/src/components/DataTable/DataTableRow.tsx index a833fda7b1..24a6627004 100644 --- a/src/components/DataTable/DataTableRow.tsx +++ b/src/components/DataTable/DataTableRow.tsx @@ -70,6 +70,9 @@ const DataTableRow = ({ return ( { expect(ringOffset()).toBe(OUTWARD); }); + it('DataTable.Row rings inward, clear of the rows above and below', async () => { + await render( + {}}> + cell + + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> From 8c154cdb00ad787d2f4822e73642aa843dc44a1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:54:48 +0100 Subject: [PATCH 18/50] feat(data-table): add the focus ring to sortable DataTable.Title A DataTable.Title with onPress is a button, but it is a plain Pressable, so it had no MD3 focus ring and fell back to the browser's outline on web. It now uses the shared hook, inward like the rows, since titles sit side by side in the header row. A caller's own onFocus and onBlur still run. --- src/components/DataTable/DataTableTitle.tsx | 27 ++++++++++++++- .../__tests__/focusRingWiring.test.tsx | 33 ++++++++++++++++++- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/components/DataTable/DataTableTitle.tsx b/src/components/DataTable/DataTableTitle.tsx index d6420ea41e..2b4c93671b 100644 --- a/src/components/DataTable/DataTableTitle.tsx +++ b/src/components/DataTable/DataTableTitle.tsx @@ -20,6 +20,7 @@ import { useLocale } from '../../core/locale'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import type { ThemeProp } from '../../theme/types'; +import { useFocusRing } from '../../utils/useFocusRing'; import MaterialCommunityIcon from '../MaterialCommunityIcon'; import Text from '../Typography/Text'; @@ -95,9 +96,19 @@ const DataTableTitle = ({ theme: themeOverrides, numberOfLines = 1, maxFontSizeMultiplier, + onFocus, + onBlur, ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); + // A sortable title is a button, so it gets the keyboard focus ring. It is a + // plain `Pressable`, not a `TouchableRipple`, so it calls the hook directly. + // Inward: titles sit side by side in the header row, like the rows below. + const { target: focusTarget, ring: focusRing } = useFocusRing( + !onPress, + theme.colors.secondary, + 'inward' + ); const reduceMotion = useReduceMotion(); const { direction } = useLocale(); @@ -136,7 +147,21 @@ const DataTableTitle = ({ disabled={!onPress} onPress={onPress} {...rest} - style={[styles.container, numeric && styles.right, style]} + onFocus={(e) => { + focusTarget.onFocus?.(e); + onFocus?.(e); + }} + onBlur={(e) => { + focusTarget.onBlur?.(); + onBlur?.(e); + }} + {...focusRing.dataSetProps} + style={[ + styles.container, + numeric && styles.right, + style, + ...focusRing.style, + ]} > {icon} diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 8a55c94d84..6ff3f0890a 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -5,7 +5,14 @@ import { Platform, StyleSheet, Text } from 'react-native'; import type { ViewStyle } from 'react-native'; -import { afterEach, beforeEach, describe, expect, it } from '@jest/globals'; +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest, +} from '@jest/globals'; import { act, fireEvent } from '@testing-library/react-native'; import { render, screen } from '../../test-utils'; @@ -16,6 +23,7 @@ import Card from '../Card/Card'; import CheckboxItem from '../Checkbox/CheckboxItem'; import Chip from '../Chip/Chip'; import DataTableRow from '../DataTable/DataTableRow'; +import DataTableTitle from '../DataTable/DataTableTitle'; import FAB from '../FAB/FAB'; import FABMenu from '../FAB/Menu'; import ListAccordion from '../List/ListAccordion'; @@ -183,6 +191,29 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(INWARD); }); + it('DataTable.Title rings inward when sortable, and keeps its own onFocus', async () => { + const onFocus = jest.fn(); + await render( + {}} onFocus={onFocus}> + title + + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + expect(onFocus).toHaveBeenCalledTimes(1); + }); + + // Without `onPress` the title is plain text and takes no focus. + it('DataTable.Title draws no ring when it is not pressable', async () => { + await render(title); + + await focusFirstFocusable(); + + expect(ringOffset()).toBeUndefined(); + }); + it('Card rings outward', async () => { await render( {}}> From a6746e3073cac9be74443ffe43fee8961e21ee8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:55:50 +0100 Subject: [PATCH 19/50] feat(drawer): add the focus ring to Drawer.CollapsedItem Drawer.CollapsedItem is a navigation rail item built on a plain Pressable, so it had no MD3 focus ring. MD3 rings a rail item as a whole (icon and label) with a rounded rectangle inside the rail, and Material Web's navigation tab does the same (inward, small corner). The Pressable also spans the 12dp gap below the item, so the ring goes on the item inside it through the 'descendant' scope. --- src/components/Drawer/DrawerCollapsedItem.tsx | 25 +++++- .../DrawerCollapsedItem.test.tsx.snap | 90 ++++++++++++------- .../__tests__/focusRingWiring.test.tsx | 45 ++++++++++ 3 files changed, 129 insertions(+), 31 deletions(-) diff --git a/src/components/Drawer/DrawerCollapsedItem.tsx b/src/components/Drawer/DrawerCollapsedItem.tsx index dc9211bf0f..4192b9eb08 100644 --- a/src/components/Drawer/DrawerCollapsedItem.tsx +++ b/src/components/Drawer/DrawerCollapsedItem.tsx @@ -18,6 +18,7 @@ import Animated, { import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; +import { useFocusRing } from '../../utils/useFocusRing'; import Badge from '../Badge'; import Icon from '../Icon'; import type { IconSource } from '../Icon'; @@ -117,6 +118,17 @@ const DrawerCollapsedItem = ({ const theme = useInternalTheme(themeOverrides); const { scale } = theme.animation; + // MD3 rings a navigation rail item as a whole (icon and label) with a + // rounded rectangle inside the rail, like Material Web's navigation tab + // (inward, small corner). The `Pressable` also spans the gap below the + // item, so the ring goes on the item inside it (`'descendant'`). + const { target: focusTarget, ring: focusRing } = useFocusRing( + disabled, + theme.colors.secondary, + 'inward', + 'descendant' + ); + const [numOfLines, setNumOfLines] = React.useState(1); const outlineScale = useSharedValue(active ? 1 : 0.5); @@ -182,8 +194,19 @@ const DrawerCollapsedItem = ({ aria-selected={active} aria-label={ariaLabel} testID={testID} + onFocus={focusTarget.onFocus} + onBlur={focusTarget.onBlur} + {...focusTarget.dataSetProps} + style={focusTarget.style} > - + { expect(ringOffset()).toBeUndefined(); }); + // MD3 rings a navigation rail item as a whole, inside the rail. The + // Pressable also spans the gap below the item, so the ring is on the item. + it('Drawer.CollapsedItem rings the item inward, not the Pressable', async () => { + await render( + {}} + /> + ); + + const pressable = screen.getByRole('button'); + await act(async () => { + await fireEvent(pressable, 'focus'); + }); + + expect(style(pressable).outlineStyle).toBeUndefined(); + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> @@ -296,6 +317,30 @@ describe('focus ring wiring (web)', () => { ).toBe('outward'); }); + it('Drawer.CollapsedItem marks its Pressable as the focus target and rings the item inside it', async () => { + await render( + {}} + /> + ); + + const pressable = screen.getByRole('button'); + expect(pressable.props.dataSet).toEqual({ focusRingTarget: 'true' }); + + const ringed = walk( + pressable, + (n) => + (n.props?.dataSet as Record | undefined) + ?.focusRingDescendant !== undefined + ); + expect(ringed).toHaveLength(1); + expect( + (ringed[0].props?.dataSet as Record).focusRingDescendant + ).toBe('inward'); + }); + it('Chip marks its close button as the focus target and rings the glyph circle inside it', async () => { await render( {}} onClose={() => {}}> From fa7e2103bd4c12011e88f59b04bac917725f9543 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:56:50 +0100 Subject: [PATCH 20/50] feat(appbar): add the focus ring to pressable Appbar.Content With onPress, Appbar.Content is a button built on a plain Pressable, so it had no MD3 focus ring and fell back to the browser's outline on web. MD3 has no pressable app bar title, but its app bar guidance says interactive elements get focus rings, so it now uses the shared hook with the default outward ring. A caller's own onFocus and onBlur still run. --- src/components/Appbar/AppbarContent.tsx | 19 +++++++++++++++++++ .../__tests__/focusRingWiring.test.tsx | 13 +++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/components/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx index 37c3b28e2c..dbf372b021 100644 --- a/src/components/Appbar/AppbarContent.tsx +++ b/src/components/Appbar/AppbarContent.tsx @@ -11,6 +11,7 @@ import type { import { modeTextVariant } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; +import { useFocusRing } from '../../utils/useFocusRing'; import Text from '../Typography/Text'; import type { TextRef } from '../Typography/Text'; @@ -101,6 +102,14 @@ const AppbarContent = ({ const theme = useInternalTheme(themeOverrides); const { colors, fonts } = theme; + // With `onPress` the title is a button, so it gets the keyboard focus ring + // (MD3: interactive elements in an app bar have focus rings). It is a plain + // `Pressable`, so it calls the hook directly. Outward, the default. + const { target: focusTarget, ring: focusRing } = useFocusRing( + disabled || !onPress, + colors.secondary + ); + const titleTextColor = titleColor ? titleColor : colors.onSurface; const modeContainerStyles = { @@ -153,6 +162,16 @@ const AppbarContent = ({ onPress={onPress} disabled={disabled} {...contentWrapperProps} + onFocus={(e) => { + focusTarget.onFocus?.(e); + rest.onFocus?.(e); + }} + onBlur={(e) => { + focusTarget.onBlur?.(); + rest.onBlur?.(e); + }} + {...focusRing.dataSetProps} + style={[...contentWrapperProps.style, ...focusRing.style]} > {content} diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index f93b1ef548..dd799f179c 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -17,6 +17,7 @@ import { act, fireEvent } from '@testing-library/react-native'; import { render, screen } from '../../test-utils'; import { tokens } from '../../theme/tokens'; +import AppbarContent from '../Appbar/AppbarContent'; import BottomNavigation from '../BottomNavigation/BottomNavigation'; import Button from '../Button/Button'; import Card from '../Card/Card'; @@ -235,6 +236,18 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(INWARD); }); + it('Appbar.Content with onPress rings outward, and keeps its own onFocus', async () => { + const onFocus = jest.fn(); + await render( + {}} onFocus={onFocus} /> + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + expect(onFocus).toHaveBeenCalledTimes(1); + }); + it('Card rings outward', async () => { await render( {}}> From bd4f112e7476ce225dd6f0d917100bfe27cec05f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:57:24 +0100 Subject: [PATCH 21/50] docs(segmented-buttons): explain the inward focus ring and pin it The MD3 segmented button accessibility figure draws the focus ring on the segment's edge, in its shape, and segments share borders, so an outward ring would cover the neighbouring segment. Material Web's labs segmented button rings outward; note that the MD3 figure wins here, and pin the placement in a test. --- .../SegmentedButtons/SegmentedButtonItem.tsx | 4 ++++ .../__tests__/focusRingWiring.test.tsx | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/components/SegmentedButtons/SegmentedButtonItem.tsx b/src/components/SegmentedButtons/SegmentedButtonItem.tsx index e81a63c9dd..c0df4c8b7a 100644 --- a/src/components/SegmentedButtons/SegmentedButtonItem.tsx +++ b/src/components/SegmentedButtons/SegmentedButtonItem.tsx @@ -212,6 +212,10 @@ const SegmentedButtonItem = ({ { expect(onFocus).toHaveBeenCalledTimes(1); }); + // MD3's segmented button figure puts the ring on the segment's edge; + // segments share borders, so outward would cover the neighbour. + it('SegmentedButtons rings each segment inward', async () => { + await render( + {}} + buttons={[ + { value: 'a', label: 'A' }, + { value: 'b', label: 'B' }, + ]} + /> + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> From 4f0d8fe9999a9ae2fdbbde656a56a617e0e86bf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 12:59:23 +0100 Subject: [PATCH 22/50] fix: keep a caller's own dataSet alongside the focus ring attribute On web the ring is keyed off a `data-focus-ring` attribute, passed as `dataSet`. TouchableRipple, DataTable.Title and Appbar.Content spread it after the caller's props, so a caller's own `dataSet` (e.g. test hooks) was dropped whenever the ring was active. Merge the two instead, through a shared `mergeDataSetProps` helper. --- src/components/Appbar/AppbarContent.tsx | 4 +-- src/components/DataTable/DataTableTitle.tsx | 4 +-- .../TouchableRipple/TouchableRipple.tsx | 4 +-- .../TouchableRippleFocusWeb.test.tsx | 22 +++++++++++++++ .../__tests__/focusRingWiring.test.tsx | 28 +++++++++++++++++++ src/utils/__tests__/useFocusRing.test.tsx | 28 ++++++++++++++++++- src/utils/useFocusRing.ts | 22 +++++++++++++++ 7 files changed, 105 insertions(+), 7 deletions(-) diff --git a/src/components/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx index dbf372b021..7c07d5b8b3 100644 --- a/src/components/Appbar/AppbarContent.tsx +++ b/src/components/Appbar/AppbarContent.tsx @@ -11,7 +11,7 @@ import type { import { modeTextVariant } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; -import { useFocusRing } from '../../utils/useFocusRing'; +import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; import Text from '../Typography/Text'; import type { TextRef } from '../Typography/Text'; @@ -170,7 +170,7 @@ const AppbarContent = ({ focusTarget.onBlur?.(); rest.onBlur?.(e); }} - {...focusRing.dataSetProps} + {...mergeDataSetProps(rest, focusRing.dataSetProps)} style={[...contentWrapperProps.style, ...focusRing.style]} > {content} diff --git a/src/components/DataTable/DataTableTitle.tsx b/src/components/DataTable/DataTableTitle.tsx index 2b4c93671b..33c1ceaff9 100644 --- a/src/components/DataTable/DataTableTitle.tsx +++ b/src/components/DataTable/DataTableTitle.tsx @@ -20,7 +20,7 @@ import { useLocale } from '../../core/locale'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import type { ThemeProp } from '../../theme/types'; -import { useFocusRing } from '../../utils/useFocusRing'; +import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; import MaterialCommunityIcon from '../MaterialCommunityIcon'; import Text from '../Typography/Text'; @@ -155,7 +155,7 @@ const DataTableTitle = ({ focusTarget.onBlur?.(); onBlur?.(e); }} - {...focusRing.dataSetProps} + {...mergeDataSetProps(rest, focusRing.dataSetProps)} style={[ styles.container, numeric && styles.right, diff --git a/src/components/TouchableRipple/TouchableRipple.tsx b/src/components/TouchableRipple/TouchableRipple.tsx index a0114ee413..77fa673da4 100644 --- a/src/components/TouchableRipple/TouchableRipple.tsx +++ b/src/components/TouchableRipple/TouchableRipple.tsx @@ -18,7 +18,7 @@ import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; import type { FocusRingPlacement } from '../../utils/useFocusRing'; -import { useFocusRing } from '../../utils/useFocusRing'; +import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; export type Props = PressableProps & { /** @@ -317,7 +317,7 @@ const TouchableRipple = ({ onPressIn={handlePressIn} onPressOut={handlePressOut} disabled={disabled} - {...ring.dataSetProps} + {...mergeDataSetProps(rest, ring.dataSetProps)} style={(state) => [ styles.touchable, // RNW's own `state.focused` fires for mouse clicks too, which is diff --git a/src/components/__tests__/TouchableRippleFocusWeb.test.tsx b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx index 99c5a7d107..287308d1c0 100644 --- a/src/components/__tests__/TouchableRippleFocusWeb.test.tsx +++ b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx @@ -94,4 +94,26 @@ describe('TouchableRipple focus ring (web implementation)', () => { expect(onFocus).toHaveBeenCalled(); expect(onBlur).toHaveBeenCalled(); }); + + // react-native-web renders `dataSet` as `data-*` attributes, which callers + // use too (e.g. for test hooks). The ring's attribute must join theirs, not + // replace it. + it("keeps a caller's own dataSet alongside the ring attribute", async () => { + await renderRipple({ dataSet: { qa: 'save' } }); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('ripple').props.dataSet).toEqual({ + qa: 'save', + focusRing: 'outward', + }); + }); + + it("keeps a caller's own dataSet when the ring is turned off", async () => { + await renderRipple({ dataSet: { qa: 'save' }, focusRing: 'none' }); + + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('ripple').props.dataSet).toEqual({ + qa: 'save', + }); + }); }); diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 02a0d1e319..9ceb7a0674 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -350,6 +350,34 @@ describe('focus ring wiring (web)', () => { ).toBe('outward'); }); + // These spread the caller's props onto the ringed element, so the ring's + // `data-*` attribute must join the caller's `dataSet`, not replace it. + it("DataTable.Title and Appbar.Content keep a caller's own dataSet", async () => { + const dataSet = { qa: 'title' }; + await render( + <> + {}} testID="table" {...{ dataSet }}> + title + + {}} + testID="appbar" + {...{ dataSet }} + /> + + ); + + expect(screen.getByTestId('table').props.dataSet).toEqual({ + qa: 'title', + focusRing: 'inward', + }); + expect(screen.getByTestId('appbar').props.dataSet).toEqual({ + qa: 'title', + focusRing: 'outward', + }); + }); + it('Drawer.CollapsedItem marks its Pressable as the focus target and rings the item inside it', async () => { await render( { await act(async () => { @@ -86,6 +90,28 @@ describe('buildFocusRingStylesheet', () => { }); }); +describe('mergeDataSetProps', () => { + it("keeps the caller's dataSet alongside the ring attribute", () => { + expect( + mergeDataSetProps( + { dataSet: { qa: 'save' } }, + { dataSet: { focusRing: 'outward' } } + ) + ).toEqual({ dataSet: { qa: 'save', focusRing: 'outward' } }); + }); + + // With no ring attribute the caller's own spread already carries theirs. + it('adds nothing when there is no ring attribute', () => { + expect(mergeDataSetProps({ dataSet: { qa: 'save' } }, {})).toEqual({}); + }); + + it('passes the ring attribute through when the caller has no dataSet', () => { + expect(mergeDataSetProps({}, { dataSet: { focusRing: 'inward' } })).toEqual( + { dataSet: { focusRing: 'inward' } } + ); + }); +}); + describe('useFocusRing (native)', () => { // Derived from the token, not hardcoded - see the note on the stylesheet // test above. diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index 8540d69885..dcfb52630c 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -55,6 +55,28 @@ export type FocusRingResult = { const toDataSetProps = (dataSet: Record | undefined): object => dataSet ? { dataSet } : {}; +const readDataSet = (props: object): object | undefined => + 'dataSet' in props && props.dataSet && typeof props.dataSet === 'object' + ? props.dataSet + : undefined; + +/** + * `dataSetProps` merged with a caller's own `dataSet`, for a component that + * spreads the caller's props onto the same element as the ring. Spreading + * `dataSetProps` after them would replace the caller's `dataSet` (e.g. their + * test hooks); this keeps both. Empty when there is no ring attribute, so the + * caller's `dataSet` passes through their own spread untouched. + */ +export const mergeDataSetProps = ( + callerProps: object, + dataSetProps: object +): object => { + const ringDataSet = readDataSet(dataSetProps); + return ringDataSet + ? { dataSet: { ...readDataSet(callerProps), ...ringDataSet } } + : {}; +}; + const EMPTY: FocusRingResult = { target: { style: [], dataSetProps: {} }, ring: { style: [], dataSetProps: {} }, From ff417384c5e76c4e702753ed35ee6ca7c93d7ffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 13:00:36 +0100 Subject: [PATCH 23/50] fix(data-table): draw the DataTable.Cell focus ring inward A DataTable.Cell with onPress fills a row, and rows stack edge to edge, so an outward ring ran into the rows above and below, as DataTable.Row's did. --- src/components/DataTable/DataTableCell.tsx | 3 +++ src/components/__tests__/focusRingWiring.test.tsx | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/components/DataTable/DataTableCell.tsx b/src/components/DataTable/DataTableCell.tsx index af332b3ae4..47a84b9f8b 100644 --- a/src/components/DataTable/DataTableCell.tsx +++ b/src/components/DataTable/DataTableCell.tsx @@ -78,6 +78,9 @@ const DataTableCell = ({ }: Props) => { return ( { expect(ringOffset()).toBe(INWARD); }); + it('DataTable.Cell with onPress rings inward, like its row', async () => { + await render( {}}>cell); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Card rings outward', async () => { await render( {}}> From bc8698c0e06819c931cc50866a742ab92922e812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 13:07:56 +0100 Subject: [PATCH 24/50] fix(drawer): draw the Drawer.CollapsedItem ring above the indicator An inward ring is painted under its element's children, so the active indicator covered the ring's top edge. Draw it on an overlay laid over the item instead, and start the overlay above the item so the ring clears the indicator by the usual 2dp gap, as in the MD3 navigation rail figure. The 12dp gap below the item above leaves room for it. --- src/components/Drawer/DrawerCollapsedItem.tsx | 37 +++- .../DrawerCollapsedItem.test.tsx.snap | 170 ++++++++++++------ .../__tests__/focusRingWiring.test.tsx | 7 + 3 files changed, 150 insertions(+), 64 deletions(-) diff --git a/src/components/Drawer/DrawerCollapsedItem.tsx b/src/components/Drawer/DrawerCollapsedItem.tsx index 4192b9eb08..79717dd976 100644 --- a/src/components/Drawer/DrawerCollapsedItem.tsx +++ b/src/components/Drawer/DrawerCollapsedItem.tsx @@ -17,6 +17,7 @@ import Animated, { } from 'react-native-reanimated'; import { useInternalTheme } from '../../core/theming'; +import { tokens } from '../../theme/tokens'; import type { ThemeProp } from '../../theme/types'; import { useFocusRing } from '../../utils/useFocusRing'; import Badge from '../Badge'; @@ -121,7 +122,12 @@ const DrawerCollapsedItem = ({ // MD3 rings a navigation rail item as a whole (icon and label) with a // rounded rectangle inside the rail, like Material Web's navigation tab // (inward, small corner). The `Pressable` also spans the gap below the - // item, so the ring goes on the item inside it (`'descendant'`). + // item, so the ring goes on an overlay inside it (`'descendant'`). An + // overlay, not the item itself: an inward ring is painted under the item's + // children, and the active indicator would cover its top edge. The overlay + // starts above the item, so the ring clears the indicator by the usual 2dp + // gap instead of cutting into it; the 12dp gap below the item above it + // leaves room. const { target: focusTarget, ring: focusRing } = useFocusRing( disabled, theme.colors.secondary, @@ -199,14 +205,7 @@ const DrawerCollapsedItem = ({ {...focusTarget.dataSetProps} style={focusTarget.style} > - + ) : null} + + @@ -252,7 +261,17 @@ const DrawerCollapsedItem = ({ DrawerCollapsedItem.displayName = 'Drawer.CollapsedItem'; +const { thickness: focusThickness, outerOffset: focusOuterOffset } = + tokens.md.sys.state.focusIndicator; + const styles = StyleSheet.create({ + focusRing: { + position: 'absolute', + top: -(focusOuterOffset + focusThickness), + left: 0, + right: 0, + bottom: 0, + }, wrapper: { width: 80, marginBottom: 12, diff --git a/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap b/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap index 1fec857294..184365e685 100644 --- a/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap +++ b/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap @@ -37,17 +37,12 @@ exports[`DrawerCollapsedItem should display focused icon in active state 1`] = ` > + @@ -162,17 +174,12 @@ exports[`DrawerCollapsedItem should display focused icon in inactive state, if u > + @@ -287,17 +311,12 @@ exports[`DrawerCollapsedItem should display unfocused icon in inactive state, if > + @@ -412,17 +448,12 @@ exports[`DrawerCollapsedItem should have regular outline if label is specified 1 > starred + @@ -578,17 +626,12 @@ exports[`DrawerCollapsedItem should have rounded outline if label is not specifi > + diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 2f90aa2b98..3ddc2f84d1 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -236,6 +236,13 @@ describe('focus ring wiring', () => { expect(style(pressable).outlineStyle).toBeUndefined(); expect(ringOffset()).toBe(INWARD); + + // An inward ring is painted under its own element's children, where the + // active indicator would cover it, so it is on an overlay drawn last. + const root = (screen as unknown as { root: Node }).root; + const [ringed] = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(style(ringed).position).toBe('absolute'); + expect(ringed.children ?? []).toHaveLength(0); }); it('Appbar.Content with onPress rings outward, and keeps its own onFocus', async () => { From 8fcf97802afec10245ddbd479bef6fb4ce778f36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 13:24:54 +0100 Subject: [PATCH 25/50] fix(chip): keep the close ring round on Android On Android the close button's ring came out square: drawn on the view that holds the icon, its border radius was ignored. Draw it on a childless overlay filling the glyph's box instead, which Android rounds like the other rings. Web is unchanged. --- src/components/Chip/Chip.tsx | 19 +++++++--- .../__snapshots__/Chip.test.tsx.snap | 36 +++++++++++++++++-- .../__tests__/focusRingWiring.test.tsx | 12 ++++--- 3 files changed, 57 insertions(+), 10 deletions(-) diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index 2ec6524951..fe7462951e 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -255,7 +255,9 @@ const Chip = ({ // (see below), so it calls `useFocusRing` directly instead of going // through `TouchableRipple`'s `focusRing` prop like the body does. The // `Pressable` is the whole close column, but the ring follows the glyph's - // round shape, so it goes on a circle inside it (`'descendant'`). + // round shape, so it goes on a circle inside it (`'descendant'`). The + // circle is a childless overlay on the glyph: Android drew the ring square + // when it sat on the view holding the icon, ignoring its border radius. const { target: closeFocusTarget, ring: closeFocusRing } = useFocusRing( disabled, theme.colors.secondary, @@ -469,9 +471,7 @@ const Chip = ({ styles.closeIcon, styles.md3CloseIcon, styles.closeFocusRing, - ...closeFocusRing.style, ]} - {...closeFocusRing.dataSetProps} > {closeIcon ? ( @@ -483,6 +483,15 @@ const Chip = ({ direction="ltr" /> )} + @@ -570,10 +579,12 @@ const styles = StyleSheet.create({ closeFocusRing: { width: CLOSE_FOCUS_RING_SIZE, height: CLOSE_FOCUS_RING_SIZE, - borderRadius: CLOSE_FOCUS_RING_SIZE / 2, alignItems: 'center', justifyContent: 'center', }, + closeFocusRingShape: { + borderRadius: CLOSE_FOCUS_RING_SIZE / 2, + }, closeButtonWebTouchTarget: { position: 'absolute', top: -CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET, diff --git a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap index bef2789856..61f10a53b5 100644 --- a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap @@ -339,7 +339,6 @@ exports[`renders chip with close button 1`] = ` }, { "alignItems": "center", - "borderRadius": 10, "height": 20, "justifyContent": "center", "width": 20, @@ -376,6 +375,23 @@ exports[`renders chip with close button 1`] = ` > close + @@ -721,7 +737,6 @@ exports[`renders chip with custom close button 1`] = ` }, { "alignItems": "center", - "borderRadius": 10, "height": 20, "justifyContent": "center", "width": 20, @@ -758,6 +773,23 @@ exports[`renders chip with custom close button 1`] = ` > arrow-down + diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 3ddc2f84d1..e3e19c18a3 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -135,14 +135,18 @@ describe('focus ring wiring', () => { const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); expect(ringed).toHaveLength(1); // Material Web: a 24dp circle with the ring right outside it. The shared - // ring adds the outer offset, so the view is that much smaller. + // ring adds the outer offset, so the circle is that much smaller. It is + // an overlay filling the glyph's box, which sets the size. const size = 24 - 2 * outerOffset; expect(style(ringed[0])).toMatchObject({ outlineOffset: OUTWARD, - width: size, - height: size, + position: 'absolute', borderRadius: size / 2, }); + const box = walk(root, (n) => + (n.children ?? []).some((c) => c === ringed[0]) + )[0]; + expect(style(box)).toMatchObject({ width: size, height: size }); }); it('Checkbox.Item rings inward, clear of the rows above and below', async () => { @@ -439,7 +443,7 @@ describe('focus ring wiring (web)', () => { (ringed[0].props?.dataSet as Record).focusRingDescendant ).toBe('outward'); expect(style(ringed[0])).toMatchObject({ - width: 24 - 2 * outerOffset, + position: 'absolute', borderRadius: 12 - outerOffset, }); }); From ae301c96d26656d095ce2427777c8e2a6d034882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 13:34:44 +0100 Subject: [PATCH 26/50] fix: drop Android's grey focus highlight under the focus ring Android draws a grey default focus highlight on a focusable view whose background has no focused state, so the plain Pressables that now draw the MD3 ring (Chip's close button, Card, DataTable.Title, Appbar.Content, Drawer.CollapsedItem) showed both. Give them a transparent android_ripple, as Switch already does, so the ripple drawable owns the focused state and only the ring shows. --- src/components/Appbar/AppbarContent.tsx | 3 +++ src/components/Card/Card.tsx | 3 +++ src/components/Chip/Chip.tsx | 3 +++ src/components/DataTable/DataTableTitle.tsx | 3 +++ src/components/Drawer/DrawerCollapsedItem.tsx | 3 +++ 5 files changed, 15 insertions(+) diff --git a/src/components/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx index 7c07d5b8b3..a7ed41f2d9 100644 --- a/src/components/Appbar/AppbarContent.tsx +++ b/src/components/Appbar/AppbarContent.tsx @@ -162,6 +162,9 @@ const AppbarContent = ({ onPress={onPress} disabled={disabled} {...contentWrapperProps} + // Like Switch: a ripple drawable owns the focused state, so Android does + // not add its grey default focus highlight on top of the ring. + android_ripple={{ color: 'transparent' }} onFocus={(e) => { focusTarget.onFocus?.(e); rest.onFocus?.(e); diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index d574310882..863008b7d9 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -271,6 +271,9 @@ const Card = ({ onPressIn={handlePressIn} onPressOut={handlePressOut} testID={testID} + // Like Switch: a ripple drawable owns the focused state, so Android does + // not add its grey default focus highlight on top of the ring. + android_ripple={{ color: 'transparent' }} onFocus={focusTarget.onFocus} onBlur={focusTarget.onBlur} {...focusRing.dataSetProps} diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index fe7462951e..ccfa658107 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -450,6 +450,9 @@ const Chip = ({ aria-label={closeIconAccessibilityLabel} testID={closeIconTestID} hitSlop={disabled ? undefined : CHIP_BODY_HIT_SLOP} + // Like Switch: a ripple drawable owns the focused state, so Android does + // not add its grey default focus highlight on top of the ring. + android_ripple={{ color: 'transparent' }} onFocus={closeFocusTarget.onFocus} onBlur={closeFocusTarget.onBlur} {...closeFocusTarget.dataSetProps} diff --git a/src/components/DataTable/DataTableTitle.tsx b/src/components/DataTable/DataTableTitle.tsx index 33c1ceaff9..e9f66bfe57 100644 --- a/src/components/DataTable/DataTableTitle.tsx +++ b/src/components/DataTable/DataTableTitle.tsx @@ -147,6 +147,9 @@ const DataTableTitle = ({ disabled={!onPress} onPress={onPress} {...rest} + // Like Switch: a ripple drawable owns the focused state, so Android does + // not add its grey default focus highlight on top of the ring. + android_ripple={{ color: 'transparent' }} onFocus={(e) => { focusTarget.onFocus?.(e); onFocus?.(e); diff --git a/src/components/Drawer/DrawerCollapsedItem.tsx b/src/components/Drawer/DrawerCollapsedItem.tsx index 79717dd976..15e51e3331 100644 --- a/src/components/Drawer/DrawerCollapsedItem.tsx +++ b/src/components/Drawer/DrawerCollapsedItem.tsx @@ -200,6 +200,9 @@ const DrawerCollapsedItem = ({ aria-selected={active} aria-label={ariaLabel} testID={testID} + // Like Switch: a ripple drawable owns the focused state, so Android does + // not add its grey default focus highlight on top of the ring. + android_ripple={{ color: 'transparent' }} onFocus={focusTarget.onFocus} onBlur={focusTarget.onBlur} {...focusTarget.dataSetProps} From cc24440a6a3a502af79cadc986074d5003e05b3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 13 Nov 2026 13:44:07 +0100 Subject: [PATCH 27/50] fix(chip): keep the close button inside the chip on Android The 34dp close column from #5108 sized itself and its Pressable with `height: '100%'`. On Android the column came out taller than the chip, so the vertically centred glyph, and with it the focus ring, sat below the chip. Stretch the column with `top: 0` / `bottom: 0` and the Pressable with `flex: 1` instead, which lays out the same on web and keeps the glyph centred in the chip on Android. --- src/components/Chip/Chip.tsx | 6 +++--- .../__tests__/__snapshots__/Chip.test.tsx.snap | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index ccfa658107..37121d2d86 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -572,11 +572,11 @@ const styles = StyleSheet.create({ // wins over maxWidth. minWidth: CLOSE_AFFORDANCE_MIN_WIDTH, maxWidth: '50%', - height: '100%', + top: 0, + bottom: 0, }, closeButton: { - width: '100%', - height: '100%', + flex: 1, justifyContent: 'center', }, closeFocusRing: { diff --git a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap index 61f10a53b5..03327f3217 100644 --- a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap @@ -261,11 +261,12 @@ exports[`renders chip with close button 1`] = ` Date: Sun, 15 Nov 2026 20:43:39 +0200 Subject: [PATCH 28/50] docs(migration): describe the keyboard focus indicator --- docs/6.x/docs/guides/migration.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 4004b584d8..8cd1e74dcd 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -360,6 +360,30 @@ App tests change with it: a display-only element is no longer found by a role it In a disabled `TextInput`, every `TextInput.Icon` takes the disabled color, also over `iconColor` and the error color. One with a handler is a disabled `IconButton`, and an `opacity` in its `style` doesn't apply. +### Focus indicator + +Interactive components now draw the Material Design 3 keyboard focus indicator: a 3dp ring in `theme.colors.secondary`, 2dp outside the component. On web it shows when an element gets focus from the keyboard (`:focus-visible`), and on Android when it gets focus from a hardware keyboard or D-pad. Clicking or touching an element shows no ring. iOS shows no ring. + +Components that fill a clipping container or touch their neighbours draw the ring 3dp inside their edge instead: `List.Item`, `List.Accordion`, `Checkbox.Item`, `RadioButton.Item`, `Menu.Item`, the `FAB.Menu` items, `Drawer.CollapsedItem`, the `BottomNavigation` tabs, `DataTable.Row`, `DataTable.Cell`, `DataTable.Title` and `SegmentedButtons`. `FAB` and `Switch` draw this ring instead of their own, and `Checkbox` keeps its circular ring around the state layer. + +A `TouchableRipple`, and every component built on it, rings only while it can be pressed. A disabled one shows no ring. One with no touch handler and no `disabled` is the plain view described in [TouchableRipple without a press handler](#touchableripple-without-a-press-handler): it isn't a keyboard stop, so it never rings. This applies to `TouchableRipple` only: a `Switch` or `Drawer.CollapsedItem` without a handler is still a keyboard stop and rings. + +An outward ring sits outside the component, so a scroll view or a container with `overflow: 'hidden'` clips it, and a neighbour that touches the component can cover it. Chips in a horizontal `ScrollView`, or a `TouchableRipple` that fills the width of a scroll view, show only part of the ring. Give the container 5dp of padding, or pass `focusRing="inward"` where the component takes it: + +```tsx + + Music + + + + Settings + +``` + +`TouchableRipple` takes a new `focusRing` prop, and so do the components whose props include it, such as `IconButton`, `List.Item`, `DataTable.Row` and `DataTable.Cell`. It is `'outward'`, `'inward'` or `'none'`. `'none'` draws no ring, but on web it leaves the browser's own focus outline, so a component that draws its own indicator also needs `outline: 'none'` on web. + +On web the ring comes from a stylesheet that Paper adds to the page, and on these elements it takes precedence over your own `:focus-visible` outline styles. There is no app-wide switch to turn the ring off. Its color follows `theme.colors.secondary`, from the theme or a component's `theme` prop. + ### Libraries built on Paper Libraries built on Paper may not support 6.x yet. For example, `react-native-paper-dates` 0.24.1 still uses `HelperText`, the 5.x theme exports and `theme.roundness`, so its `DatePickerInput` crashes when it shows a validation error. @@ -673,6 +697,8 @@ Corner radii set through `style` no longer shape the press, hover and disabled f `hitSlop` now works on web: the touchable renders an invisible target that extends past its bounds. An ancestor with `overflow: 'hidden'` or a scroll view clips it, as on Android. +`TouchableRipple` draws the keyboard focus ring and takes a new `focusRing` prop. See [Focus indicator](#focus-indicator). + ### TextInput The Paper 6.x `TextInput` is a complete rewrite with a new API. Import the component the same way, but note that the props and behavior have changed significantly. From 8b48201aaa442bf25a1e07949bfb662b73b51490 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:46:03 +0200 Subject: [PATCH 29/50] fix: don't ring a container when focus moves inside it --- .../__tests__/TouchableRipple.test.tsx | 4 +-- .../__tests__/focusRingWiring.test.tsx | 10 +++---- src/test-utils.tsx | 10 +++++++ src/utils/__tests__/useFocusRing.test.tsx | 21 +++++++++++++-- src/utils/useFocusRing.ts | 26 ++++++++++++------- 5 files changed, 53 insertions(+), 18 deletions(-) diff --git a/src/components/__tests__/TouchableRipple.test.tsx b/src/components/__tests__/TouchableRipple.test.tsx index c6587ff45f..c29d1b7db5 100644 --- a/src/components/__tests__/TouchableRipple.test.tsx +++ b/src/components/__tests__/TouchableRipple.test.tsx @@ -14,7 +14,7 @@ import { } from '@jest/globals'; import { act, fireEvent, userEvent } from '@testing-library/react-native'; -import { render, screen } from '../../test-utils'; +import { ownFocusEvent, render, screen } from '../../test-utils'; import TouchableRipple from '../TouchableRipple/TouchableRipple.native'; describe('TouchableRipple', () => { @@ -544,7 +544,7 @@ describe('TouchableRipple', () => { describe('TouchableRipple focus ring', () => { const focus = async () => { await act(async () => { - await fireEvent(screen.getByTestId('ripple'), 'focus'); + await fireEvent(screen.getByTestId('ripple'), 'focus', ownFocusEvent()); }); }; diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index c62bd65e6a..760bfda5a5 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -15,7 +15,7 @@ import { } from '@jest/globals'; import { act, fireEvent } from '@testing-library/react-native'; -import { render, screen } from '../../test-utils'; +import { ownFocusEvent, render, screen } from '../../test-utils'; import { tokens } from '../../theme/tokens'; import AppbarContent from '../Appbar/AppbarContent'; import BottomNavigation from '../BottomNavigation/BottomNavigation'; @@ -65,7 +65,7 @@ const focusFirstFocusable = async () => { const target = walk(root, (n) => typeof n.props?.onFocus === 'function')[0]; expect(target).toBeDefined(); await act(async () => { - await fireEvent(target as never, 'focus'); + await fireEvent(target as never, 'focus', ownFocusEvent()); }); }; @@ -128,7 +128,7 @@ describe('focus ring wiring', () => { ); await act(async () => { - await fireEvent(screen.getByLabelText('Close'), 'focus'); + await fireEvent(screen.getByLabelText('Close'), 'focus', ownFocusEvent()); }); const root = (screen as unknown as { root: Node }).root; @@ -239,7 +239,7 @@ describe('focus ring wiring', () => { const pressable = screen.getByRole('button'); await act(async () => { - await fireEvent(pressable, 'focus'); + await fireEvent(pressable, 'focus', ownFocusEvent()); }); expect(style(pressable).outlineStyle).toBeUndefined(); @@ -330,7 +330,7 @@ describe('focus ring wiring', () => { ); await act(async () => { - await fireEvent(screen.getByTestId('item-0'), 'focus'); + await fireEvent(screen.getByTestId('item-0'), 'focus', ownFocusEvent()); }); expect(ringOffset()).toBe(INWARD); diff --git a/src/test-utils.tsx b/src/test-utils.tsx index 4eec1e548e..2eb7a2500c 100644 --- a/src/test-utils.tsx +++ b/src/test-utils.tsx @@ -21,5 +21,15 @@ const Wrapper = ({ children }: { children: React.ReactNode }) => ( const customRender = (ui: React.ReactElement, options?: RenderOptions) => render(ui, { wrapper: Wrapper, ...options }); +/** + * A focus or blur event that the element fired itself, for `fireEvent`. Native + * focus events bubble, and the focus ring ignores one whose `target` isn't the + * element it is attached to, so the event needs a matching pair. + */ +export const ownFocusEvent = () => { + const node = {}; + return { nativeEvent: { target: 0 }, target: node, currentTarget: node }; +}; + export * from '@testing-library/react-native'; export { customRender as render }; diff --git a/src/utils/__tests__/useFocusRing.test.tsx b/src/utils/__tests__/useFocusRing.test.tsx index f7dacdb8a0..2b07b41251 100644 --- a/src/utils/__tests__/useFocusRing.test.tsx +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -11,7 +11,7 @@ import { } from '@jest/globals'; import { act, fireEvent } from '@testing-library/react-native'; -import { render, screen } from '../../test-utils'; +import { ownFocusEvent, render, screen } from '../../test-utils'; import { tokens } from '../../theme/tokens'; import type { FocusRingPlacement, FocusRingScope } from '../useFocusRing'; import { @@ -20,7 +20,7 @@ import { useFocusRing, } from '../useFocusRing'; -const focus = async (data?: unknown) => { +const focus = async (data: unknown = ownFocusEvent()) => { await act(async () => { await fireEvent(screen.getByTestId('probe'), 'focus', data); }); @@ -136,6 +136,23 @@ describe('useFocusRing (native)', () => { }); }); + // Native focus events bubble, so a focused Switch inside a List.Item, or a + // TextInput tapped inside a pressable Card, reaches the container's onFocus + // with the descendant as `target`. + it('does not ring when focus bubbles up from a descendant', async () => { + await render(); + + await focus({ + nativeEvent: { target: 0 }, + target: {}, + currentTarget: {}, + }); + + expect(screen.getByTestId('probe')).not.toHaveStyle({ + outlineWidth: thickness, + }); + }); + // `disabled` goes to the hook only, never to the Pressable: RNTL will not // dispatch to a disabled element, so that would pass for free. it('never rings a disabled control, even if a focus event arrives', async () => { diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index dcfb52630c..54fcc92c6f 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -106,13 +106,17 @@ const webNoOutlineStyle = { outline: 'none' } as unknown as ViewStyle; * track): `target` also suppresses the browser's default outline on the * focused element itself on web, so only the ring shows. * - * iOS: `onFocus`/`onBlur` never reach here today. Fabric's view does call - * `-becomeFirstResponder`/`-resignFirstResponder` for hardware-keyboard/Full - * Keyboard Access navigation, but only emits the JS event when the - * `enableImperativeFocus` feature flag is on, and it defaults off (old - * architecture has no equivalent path at all). Pre-existing, not something - * this hook introduces - the library's older FAB, Checkbox, and Switch rings - * were equally inert on iOS. + * iOS: a ringed element never gets its own `onFocus`/`onBlur` today. Fabric's + * view does call `-becomeFirstResponder`/`-resignFirstResponder` for + * hardware-keyboard/Full Keyboard Access navigation, but only emits the JS + * event when the `enableImperativeFocus` feature flag is on, and it defaults + * off. Pre-existing, not something this hook introduces: the library's older + * FAB, Checkbox, and Switch rings were equally inert on iOS. + * + * Native focus events bubble, on iOS too (a TextInput's focus after a tap + * reaches every ancestor's `onFocus`). The native `onFocus` ignores any event + * whose target isn't the element it is attached to, so a focused descendant + * never lights an ancestor's ring. */ export function useFocusRing( disabled: boolean | undefined, @@ -128,9 +132,13 @@ export function useFocusRing( const onFocus = React.useCallback( (e: NativeSyntheticEvent) => { - if (!suppressed) { - setFocused(isKeyboardFocusEvent(e)); + // Native focus events bubble: a focused descendant (a Switch in a + // List.Item, a TextInput tapped inside a pressable Card) reaches this + // handler too. Only the element's own focus draws its ring. + if (suppressed || e.target !== e.currentTarget) { + return; } + setFocused(isKeyboardFocusEvent(e)); }, [suppressed] ); From 42c3f363125515696011992dcd305c1af8aaaa76 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:47:36 +0200 Subject: [PATCH 30/50] fix: clear a stale focus ring on Card and the Chip close button --- src/components/Card/Card.tsx | 11 +-- src/components/Chip/Chip.tsx | 4 +- .../__tests__/focusRingWiring.test.tsx | 68 +++++++++++++++++++ src/utils/useFocusRing.ts | 6 +- 4 files changed, 82 insertions(+), 7 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 863008b7d9..9e909e999b 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -166,10 +166,6 @@ const Card = ({ ...rest }: (OutlinedCardProps | ElevatedCardProps | ContainedCardProps) & Props) => { const theme = useInternalTheme(themeOverrides); - const { target: focusTarget, ring: focusRing } = useFocusRing( - disabled, - theme.colors.secondary - ); const isMode = React.useCallback( (modeToCompare: Mode) => { return cardMode === modeToCompare; @@ -184,6 +180,13 @@ const Card = ({ onPressOut, }); + // Off without a touch handler too: the `Pressable` unmounts then, and a + // focused one sends no blur, so the ring would come back with the handler. + const { target: focusTarget, ring: focusRing } = useFocusRing( + disabled || !hasPassedTouchHandler, + theme.colors.secondary + ); + const [pressed, setPressed] = React.useState(false); const elevation = isMode('elevated') ? (pressed ? 2 : cardElevation) : 0; diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index 37121d2d86..2107b42396 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -258,8 +258,10 @@ const Chip = ({ // round shape, so it goes on a circle inside it (`'descendant'`). The // circle is a childless overlay on the glyph: Android drew the ring square // when it sat on the view holding the icon, ignoring its border radius. + // Off without `onClose` too: the close `Pressable` unmounts then, and a + // focused one sends no blur, so the ring would come back with `onClose`. const { target: closeFocusTarget, ring: closeFocusRing } = useFocusRing( - disabled, + disabled || !onClose, theme.colors.secondary, 'outward', 'descendant' diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 760bfda5a5..06437c2ff3 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -2,6 +2,7 @@ The node carrying the ring is an unnamed internal view (Card's Pressable, Switch's track, FAB's clip view). There is no testID to query it by, and which node it is IS the thing under test, so the tree has to be walked. */ +import type { ReactElement } from 'react'; import { Platform, StyleSheet, Text } from 'react-native'; import type { ViewStyle } from 'react-native'; @@ -345,6 +346,73 @@ describe('focus ring wiring', () => { }); }); +// A focused Pressable that unmounts sends no blur, so each of these resets its +// ring state when the handler goes away. Otherwise the new Pressable is drawn +// ringed when the handler comes back, with nothing focused. +describe('focus ring after the handler goes away and comes back', () => { + const dropAndRestore = async ( + withHandler: ReactElement, + withoutHandler: ReactElement + ) => { + const { rerender } = await render(withHandler); + await focusFirstFocusable(); + expect(ringOffset()).toBeDefined(); + + await act(async () => { + await rerender(withoutHandler); + }); + expect(ringOffset()).toBeUndefined(); + + await act(async () => { + await rerender(withHandler); + }); + }; + + it('Card shows no ring until it is focused again', async () => { + await dropAndRestore( + {}}> + card + , + + card + + ); + + expect(ringOffset()).toBeUndefined(); + }); + + it('Chip close button shows no ring until it is focused again', async () => { + await dropAndRestore( + {}}>chip, + chip + ); + + expect(ringOffset()).toBeUndefined(); + }); + + it('TouchableRipple shows no ring until it is focused again', async () => { + await dropAndRestore( + {}}> + ripple + , + + ripple + + ); + + expect(ringOffset()).toBeUndefined(); + }); + + it('FAB shows no ring until it is focused again', async () => { + await dropAndRestore( + {}} />, + + ); + + expect(ringOffset()).toBeUndefined(); + }); +}); + describe('focus ring wiring (web)', () => { const original = Platform.OS; beforeEach(() => { diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index 54fcc92c6f..b48b71476c 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -145,8 +145,10 @@ export function useFocusRing( const onBlur = React.useCallback(() => setFocused(false), []); - // The focusable node can unmount while this hook stays mounted, and neither - // the DOM nor React fires blur for that, so clear rather than only masking. + // A focused node that unmounts sends no blur, so `focused` would outlive it. + // This clears it whenever the ring is suppressed, rather than only masking + // it, so a caller whose focusable node can unmount keys `disabled` off that + // too (no handler, no `onClose`) and the state resets with it. React.useEffect(() => { if (suppressed) { setFocused(false); From 4b5aa140961515ed16b085bac0979a2c22cf8665 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:49:14 +0200 Subject: [PATCH 31/50] fix: draw the focus ring in a component's theme prop color --- .../BottomNavigation/BottomNavigationBar.tsx | 3 + src/components/DataTable/DataTableRow.tsx | 1 + src/components/IconButton/IconButton.tsx | 1 + src/components/Menu/MenuItem.tsx | 1 + src/components/TextInput/TextInputIcon.tsx | 1 + .../__tests__/focusRingWiring.test.tsx | 71 +++++++++++++++++++ 6 files changed, 78 insertions(+) diff --git a/src/components/BottomNavigation/BottomNavigationBar.tsx b/src/components/BottomNavigation/BottomNavigationBar.tsx index 154f872a91..6e86348c3a 100644 --- a/src/components/BottomNavigation/BottomNavigationBar.tsx +++ b/src/components/BottomNavigation/BottomNavigationBar.tsx @@ -214,6 +214,7 @@ const Touchable = ({ centered, rippleColor, focusRing, + theme, ...rest }: TouchableProps) => TouchableRipple.supported ? ( @@ -224,6 +225,7 @@ const Touchable = ({ centered={centered} rippleColor={rippleColor} focusRing={focusRing} + theme={theme} style={style} > {children} @@ -580,6 +582,7 @@ const BottomNavigationBar = ({ // (`overflow: 'hidden'`), so an outward ring would lose its top // and bottom and read as two vertical lines between tabs. focusRing: 'inward', + theme, onPress: () => onTabPress(eventForIndex(index)), onLongPress: () => onTabLongPress?.(eventForIndex(index)), testID: getTestID({ route }), diff --git a/src/components/DataTable/DataTableRow.tsx b/src/components/DataTable/DataTableRow.tsx index 24a6627004..c1232b8c8c 100644 --- a/src/components/DataTable/DataTableRow.tsx +++ b/src/components/DataTable/DataTableRow.tsx @@ -75,6 +75,7 @@ const DataTableRow = ({ focusRing="inward" {...rest} onPress={onPress} + theme={theme} style={[styles.container, { borderBottomColor }, style]} > diff --git a/src/components/IconButton/IconButton.tsx b/src/components/IconButton/IconButton.tsx index 91ffbe35e2..4bf54c324d 100644 --- a/src/components/IconButton/IconButton.tsx +++ b/src/components/IconButton/IconButton.tsx @@ -221,6 +221,7 @@ const IconButton = ({ borderless centered onPress={onPress} + theme={theme} aria-label={ariaLabel} style={[ styles.touchable, diff --git a/src/components/Menu/MenuItem.tsx b/src/components/Menu/MenuItem.tsx index 561bb02800..b3707e20db 100644 --- a/src/components/Menu/MenuItem.tsx +++ b/src/components/Menu/MenuItem.tsx @@ -185,6 +185,7 @@ const MenuItem = ({ // Items fill the menu's scroll view edge to edge with no gap, which // clips an outward ring and runs it into the neighbouring items. focusRing="inward" + theme={theme} style={[ styles.container, { paddingHorizontal: containerPadding }, diff --git a/src/components/TextInput/TextInputIcon.tsx b/src/components/TextInput/TextInputIcon.tsx index d4631d10c1..b75b5dd658 100644 --- a/src/components/TextInput/TextInputIcon.tsx +++ b/src/components/TextInput/TextInputIcon.tsx @@ -110,6 +110,7 @@ const TextInputIcon = ({ icon={icon} iconColor={color} size={iconSize} + theme={themeOverride} style={[ styles.icon, style, diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 06437c2ff3..95af9327c5 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -30,11 +30,13 @@ import DataTableTitle from '../DataTable/DataTableTitle'; import DrawerCollapsedItem from '../Drawer/DrawerCollapsedItem'; import FAB from '../FAB/FAB'; import FABMenu from '../FAB/Menu'; +import IconButton from '../IconButton/IconButton'; import ListAccordion from '../List/ListAccordion'; import ListItem from '../List/ListItem'; import MenuItem from '../Menu/MenuItem'; import SegmentedButtons from '../SegmentedButtons/SegmentedButtons'; import Switch from '../Switch/Switch'; +import TextInputIcon from '../TextInput/TextInputIcon'; import TouchableRipple from '../TouchableRipple/TouchableRipple.native'; const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; @@ -346,6 +348,75 @@ describe('focus ring wiring', () => { }); }); +// A component's `theme` prop sets its ring color, not only the provider's. +describe('focus ring color follows the theme prop', () => { + const theme = { colors: { secondary: 'rgb(255, 0, 0)' } }; + + const ringColor = () => { + const root = (screen as unknown as { root: Node }).root; + const [ringed] = walk(root, (n) => style(n).outlineStyle === 'solid'); + return ringed ? style(ringed).outlineColor : undefined; + }; + + it.each([ + [ + 'IconButton', + {}} + theme={theme} + />, + ], + [ + 'TextInput.Icon', + {}} + style={undefined} + multiline={false} + disabled={false} + error={false} + theme={theme} + />, + ], + [ + 'Menu.Item', + {}} theme={theme} />, + ], + [ + 'DataTable.Row', + {}} theme={theme}> + cell + , + ], + [ + 'BottomNavigation.Bar', + {}} + renderTouchable={({ key, route: _route, ...props }) => ( + + )} + theme={theme} + />, + ], + ])('%s', async (_name, element) => { + await render(element); + + await focusFirstFocusable(); + + expect(ringColor()).toBe('rgb(255, 0, 0)'); + }); +}); + // A focused Pressable that unmounts sends no blur, so each of these resets its // ring state when the handler goes away. Otherwise the new Pressable is drawn // ringed when the handler comes back, with nothing focused. From 13ed02e3ddd486d7e525d0aff6603ca4d3385e2d Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:50:18 +0200 Subject: [PATCH 32/50] fix: let a caller's focusRing and android_ripple override the defaults --- src/components/DataTable/DataTableTitle.tsx | 8 ++-- src/components/List/ListItem.tsx | 3 +- .../__tests__/focusRingWiring.test.tsx | 40 ++++++++++++++++++- 3 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/components/DataTable/DataTableTitle.tsx b/src/components/DataTable/DataTableTitle.tsx index c132a53ad6..76daec7f8b 100644 --- a/src/components/DataTable/DataTableTitle.tsx +++ b/src/components/DataTable/DataTableTitle.tsx @@ -221,6 +221,11 @@ const DataTableTitle = ({ return ( { focusTarget.onFocus?.(e); onFocus?.(e); diff --git a/src/components/List/ListItem.tsx b/src/components/List/ListItem.tsx index 5e6069b924..659abf9774 100644 --- a/src/components/List/ListItem.tsx +++ b/src/components/List/ListItem.tsx @@ -231,9 +231,10 @@ const ListItem = ({ return ( { expect(onFocus).toHaveBeenCalledTimes(1); }); + it("List.Item takes a caller's focusRing over its inward default", async () => { + await render( + {}} focusRing="outward" /> + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + }); + // Without a touch handler or `disabled` the title is a plain View, a column // heading and not a control. It keeps a caller's onFocus, but even a focus // that reaches it draws no ring. @@ -484,6 +494,34 @@ describe('focus ring after the handler goes away and comes back', () => { }); }); +describe('focus ring wiring (Android)', () => { + const original = Platform.OS; + beforeEach(() => { + Platform.OS = 'android'; + }); + afterEach(() => { + Platform.OS = original; + }); + + // The transparent ripple only keeps Android's grey focus highlight away, and + // any ripple does that, so a caller's own ripple stays. + it("DataTable.Title keeps a caller's android_ripple", async () => { + await render( + {}} + android_ripple={{ color: 'red' }} + > + title + + ); + + expect( + screen.getByTestId('title').props.nativeBackgroundAndroid + ).toMatchObject({ type: 'RippleAndroid', color: processColor('red') }); + }); +}); + describe('focus ring wiring (web)', () => { const original = Platform.OS; beforeEach(() => { From 59f1e2e97add485d7232a423f2d8116aa6eae928 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:50:53 +0200 Subject: [PATCH 33/50] fix(drawer): draw Drawer.Item's focus ring inside the item --- docs/6.x/docs/guides/migration.md | 2 +- src/components/Drawer/DrawerItem.tsx | 3 +++ src/components/__tests__/focusRingWiring.test.tsx | 9 +++++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 8cd1e74dcd..333cf9366f 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -364,7 +364,7 @@ In a disabled `TextInput`, every `TextInput.Icon` takes the disabled color, also Interactive components now draw the Material Design 3 keyboard focus indicator: a 3dp ring in `theme.colors.secondary`, 2dp outside the component. On web it shows when an element gets focus from the keyboard (`:focus-visible`), and on Android when it gets focus from a hardware keyboard or D-pad. Clicking or touching an element shows no ring. iOS shows no ring. -Components that fill a clipping container or touch their neighbours draw the ring 3dp inside their edge instead: `List.Item`, `List.Accordion`, `Checkbox.Item`, `RadioButton.Item`, `Menu.Item`, the `FAB.Menu` items, `Drawer.CollapsedItem`, the `BottomNavigation` tabs, `DataTable.Row`, `DataTable.Cell`, `DataTable.Title` and `SegmentedButtons`. `FAB` and `Switch` draw this ring instead of their own, and `Checkbox` keeps its circular ring around the state layer. +Components that fill a clipping container or touch their neighbours draw the ring 3dp inside their edge instead: `List.Item`, `List.Accordion`, `Checkbox.Item`, `RadioButton.Item`, `Menu.Item`, the `FAB.Menu` items, `Drawer.Item`, `Drawer.CollapsedItem`, the `BottomNavigation` tabs, `DataTable.Row`, `DataTable.Cell`, `DataTable.Title` and `SegmentedButtons`. `FAB` and `Switch` draw this ring instead of their own, and `Checkbox` keeps its circular ring around the state layer. A `TouchableRipple`, and every component built on it, rings only while it can be pressed. A disabled one shows no ring. One with no touch handler and no `disabled` is the plain view described in [TouchableRipple without a press handler](#touchableripple-without-a-press-handler): it isn't a keyboard stop, so it never rings. This applies to `TouchableRipple` only: a `Switch` or `Drawer.CollapsedItem` without a handler is still a keyboard stop and rings. diff --git a/src/components/Drawer/DrawerItem.tsx b/src/components/Drawer/DrawerItem.tsx index 50086bbe71..0b9250d232 100644 --- a/src/components/Drawer/DrawerItem.tsx +++ b/src/components/Drawer/DrawerItem.tsx @@ -120,6 +120,9 @@ const DrawerItem = ({ { // MD3 rings a navigation rail item as a whole, inside the rail. The // Pressable also spans the gap below the item, so the ring is on the item. + it('Drawer.Item rings inward, clear of the items above and below', async () => { + await render( {}} />); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + it('Drawer.CollapsedItem rings the item inward, not the Pressable', async () => { await render( Date: Sun, 15 Nov 2026 20:51:36 +0200 Subject: [PATCH 34/50] docs(touchable-ripple): clarify when the focusRing ring shows --- src/components/TouchableRipple/TouchableRipple.native.tsx | 8 +++++--- src/components/TouchableRipple/TouchableRipple.tsx | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/components/TouchableRipple/TouchableRipple.native.tsx b/src/components/TouchableRipple/TouchableRipple.native.tsx index 42bf0bad01..4325f13d37 100644 --- a/src/components/TouchableRipple/TouchableRipple.native.tsx +++ b/src/components/TouchableRipple/TouchableRipple.native.tsx @@ -37,10 +37,12 @@ export type Props = PressableProps & { * - `outward` - just outside the bounds. The MD3 default. * - `inward` - just inside, for controls a clipping ancestor would trim or * that sit flush against a neighbour. - * - `none` - no indicator. Only for a control that draws its own. + * - `none` - no indicator. On web the browser's own focus outline still + * shows, so a control that draws its own indicator also needs + * `outline: 'none'` there. * - * Has no effect on iOS today - see `useFocusRing`'s doc comment for why - * (`enableImperativeFocus`, off by default). + * The ring shows only while the touchable can be pressed: not when it is + * disabled or has no touch handler. There is no ring on iOS. */ focusRing?: FocusRingPlacement; onPress?: (e: GestureResponderEvent) => void | null; diff --git a/src/components/TouchableRipple/TouchableRipple.tsx b/src/components/TouchableRipple/TouchableRipple.tsx index 0ae285b1c1..f1bb352835 100644 --- a/src/components/TouchableRipple/TouchableRipple.tsx +++ b/src/components/TouchableRipple/TouchableRipple.tsx @@ -51,10 +51,12 @@ export type Props = PressableProps & { * - `outward` - just outside the bounds. The MD3 default. * - `inward` - just inside, for controls a clipping ancestor would trim or * that sit flush against a neighbour. - * - `none` - no indicator. Only for a control that draws its own. + * - `none` - no indicator. On web the browser's own focus outline still + * shows, so a control that draws its own indicator also needs + * `outline: 'none'` there. * - * Has no effect on iOS today - see `useFocusRing`'s doc comment for why - * (`enableImperativeFocus`, off by default). + * The ring shows only while the touchable can be pressed: not when it is + * disabled or has no touch handler. There is no ring on iOS. */ focusRing?: FocusRingPlacement; /** From 4dab82671cf73e1bf053c4b4dd39ce11460b5999 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:53:42 +0200 Subject: [PATCH 35/50] fix: keep the focus ring working when a test fires focus with no event --- src/utils/__tests__/useFocusRing.test.tsx | 14 ++++++++++++++ src/utils/useFocusRing.ts | 8 +++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/utils/__tests__/useFocusRing.test.tsx b/src/utils/__tests__/useFocusRing.test.tsx index 2b07b41251..4ac1060623 100644 --- a/src/utils/__tests__/useFocusRing.test.tsx +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -153,6 +153,20 @@ describe('useFocusRing (native)', () => { }); }); + // `fireEvent(element, 'focus')` without an event calls the handler with + // nothing, as an app's own tests may do. + it('rings when the focus handler gets no event', async () => { + await render(); + + await act(async () => { + await fireEvent(screen.getByTestId('probe'), 'focus'); + }); + + expect(screen.getByTestId('probe')).toHaveStyle({ + outlineWidth: thickness, + }); + }); + // `disabled` goes to the hook only, never to the Pressable: RNTL will not // dispatch to a disabled element, so that would pass for free. it('never rings a disabled control, even if a focus event arrives', async () => { diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index b48b71476c..0ef24e4dea 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -131,14 +131,16 @@ export function useFocusRing( const [focused, setFocused] = React.useState(false); const onFocus = React.useCallback( - (e: NativeSyntheticEvent) => { + // Optional: an app test can call the handler with no event at all + // (`fireEvent(element, 'focus')`), and that has to keep working. + (e?: NativeSyntheticEvent) => { // Native focus events bubble: a focused descendant (a Switch in a // List.Item, a TextInput tapped inside a pressable Card) reaches this // handler too. Only the element's own focus draws its ring. - if (suppressed || e.target !== e.currentTarget) { + if (suppressed || (e && e.target !== e.currentTarget)) { return; } - setFocused(isKeyboardFocusEvent(e)); + setFocused(!e || isKeyboardFocusEvent(e)); }, [suppressed] ); From ad70168d55a1117c82a5788a4782dcfd2a942516 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:55:23 +0200 Subject: [PATCH 36/50] fix: keep the inward ring visible over a row's own background --- src/components/Checkbox/CheckboxItem.tsx | 30 ++++++++- .../RadioButton/RadioButtonItem.tsx | 26 +++++++- .../__snapshots__/CheckboxItem.test.tsx.snap | 48 +++++++++++++- .../RadioButtonItem.test.tsx.snap | 64 +++++++++++++++++-- .../__tests__/focusRingWiring.test.tsx | 49 ++++++++++++++ 5 files changed, 206 insertions(+), 11 deletions(-) diff --git a/src/components/Checkbox/CheckboxItem.tsx b/src/components/Checkbox/CheckboxItem.tsx index a1a4c0e1da..b020376a93 100644 --- a/src/components/Checkbox/CheckboxItem.tsx +++ b/src/components/Checkbox/CheckboxItem.tsx @@ -11,6 +11,8 @@ import Checkbox from './Checkbox'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp, TypescaleKey } from '../../theme/types'; import { getStateLayer } from '../../theme/utils/state'; +import hasTouchHandler from '../../utils/hasTouchHandler'; +import { useFocusRing } from '../../utils/useFocusRing'; import { useSpaceKeyPress } from '../../utils/useSpaceKeyPress'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; @@ -160,18 +162,35 @@ const CheckboxItem = ({ textAlign, }; + // A full-width row: an outward ring would run into the rows around it. Inward, + // the ring goes on a childless overlay painted last (`'descendant'`), like + // Drawer.CollapsedItem's: drawn on the row itself, it would sit under the + // content view, and a background set through `style` would hide it. Off + // whenever the row can't be pressed, as on TouchableRipple. + const { target: focusTarget, ring: focusRing } = useFocusRing( + disabled || !hasTouchHandler({ onPress, onLongPress }), + theme.colors.secondary, + 'inward', + 'descendant' + ); + return ( { + handleSpaceKeyBlur(e); + focusTarget.onBlur?.(); + }} {...spaceKeyHandlers} + {...focusTarget.dataSetProps} + style={focusTarget.style} testID={testID} disabled={disabled} theme={theme} @@ -193,6 +212,11 @@ const CheckboxItem = ({ {!isLeading && checkbox} + ); }; diff --git a/src/components/RadioButton/RadioButtonItem.tsx b/src/components/RadioButton/RadioButtonItem.tsx index cd90157aa9..87c17b75e1 100644 --- a/src/components/RadioButton/RadioButtonItem.tsx +++ b/src/components/RadioButton/RadioButtonItem.tsx @@ -1,3 +1,4 @@ +import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { GestureResponderEvent, @@ -16,6 +17,7 @@ import { handlePress, isChecked } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp, TypescaleKey } from '../../theme/types'; import { getStateLayer } from '../../theme/utils/state'; +import { useFocusRing } from '../../utils/useFocusRing'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; import Text from '../Typography/Text'; @@ -186,6 +188,19 @@ const RadioButtonItem = ({ textAlign, }; + // Rows stack edge to edge, so the ring is inward. It goes on a childless + // overlay painted last (`'descendant'`), like Drawer.CollapsedItem's: drawn + // on the row itself, it would sit under the content view, and a background + // set through `style` would hide it. Off whenever the row can't be pressed, + // as on TouchableRipple. The hook needs the group above the consumer below. + const group = React.useContext(RadioButtonContext); + const { target: focusTarget, ring: focusRing } = useFocusRing( + disabled || !(onPress || group?.onValueChange || onLongPress), + theme.colors.secondary, + 'inward', + 'descendant' + ); + return ( {(context: RadioButtonContextType | null) => { @@ -197,7 +212,11 @@ const RadioButtonItem = ({ }) === 'checked'; return ( {!isLeading && radioButton} + ); }} diff --git a/src/components/__tests__/Checkbox/__snapshots__/CheckboxItem.test.tsx.snap b/src/components/__tests__/Checkbox/__snapshots__/CheckboxItem.test.tsx.snap index 46763401e6..9f4c45c9e5 100644 --- a/src/components/__tests__/Checkbox/__snapshots__/CheckboxItem.test.tsx.snap +++ b/src/components/__tests__/Checkbox/__snapshots__/CheckboxItem.test.tsx.snap @@ -11,7 +11,7 @@ exports[`can render leading checkbox control 1`] = ` style={ [ false, - undefined, + [], ] } > @@ -255,6 +255,20 @@ exports[`can render leading checkbox control 1`] = ` Default with leading control + `; @@ -269,7 +283,7 @@ exports[`renders unchecked 1`] = ` style={ [ false, - undefined, + [], ] } > @@ -513,6 +527,20 @@ exports[`renders unchecked 1`] = ` + `; @@ -527,7 +555,7 @@ exports[`should have maxFontSizeMultiplier set to 1.5 by default 1`] = ` style={ [ false, - undefined, + [], ] } testID="checkbox-item" @@ -770,5 +798,19 @@ exports[`should have maxFontSizeMultiplier set to 1.5 by default 1`] = ` + `; diff --git a/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap b/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap index dc9fea1f58..81713f6cb3 100644 --- a/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap +++ b/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap @@ -10,7 +10,7 @@ exports[`can render leading radio button control 1`] = ` style={ [ false, - undefined, + [], ] } > @@ -123,6 +123,20 @@ exports[`can render leading radio button control 1`] = ` Default with leading control + `; @@ -136,7 +150,7 @@ exports[`can render the Android radio button on different platforms 1`] = ` style={ [ false, - undefined, + [], ] } > @@ -223,6 +237,20 @@ exports[`can render the Android radio button on different platforms 1`] = ` /> + `; @@ -238,7 +266,7 @@ exports[`can render the iOS radio button on different platforms 1`] = ` style={ [ false, - undefined, + [], ] } > @@ -353,6 +381,20 @@ exports[`can render the iOS radio button on different platforms 1`] = ` + `; @@ -366,7 +408,7 @@ exports[`renders unchecked 1`] = ` style={ [ false, - undefined, + [], ] } > @@ -479,5 +521,19 @@ exports[`renders unchecked 1`] = ` + `; diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index e1484dea03..d7d155db1d 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -35,6 +35,7 @@ import IconButton from '../IconButton/IconButton'; import ListAccordion from '../List/ListAccordion'; import ListItem from '../List/ListItem'; import MenuItem from '../Menu/MenuItem'; +import RadioButtonItem from '../RadioButton/RadioButtonItem'; import SegmentedButtons from '../SegmentedButtons/SegmentedButtons'; import Switch from '../Switch/Switch'; import TextInputIcon from '../TextInput/TextInputIcon'; @@ -163,6 +164,54 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(INWARD); }); + const ROW_BACKGROUND = 'lightgrey'; + + // An inward ring on the row would sit under its content view, so a + // background set through `style` would hide it. The ring goes on a childless + // overlay that paints last instead. + it.each([ + [ + 'Checkbox.Item', + {}} + style={{ backgroundColor: ROW_BACKGROUND }} + />, + ], + [ + 'RadioButton.Item', + {}} + style={{ backgroundColor: ROW_BACKGROUND }} + />, + ], + ])( + '%s rings inward above a background set through style', + async (_name, element) => { + await render(element); + + await focusFirstFocusable(); + + const root = (screen as unknown as { root: Node }).root; + const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(ringed).toHaveLength(1); + expect(style(ringed[0])).toMatchObject({ + outlineOffset: INWARD, + position: 'absolute', + }); + expect(ringed[0].children ?? []).toHaveLength(0); + const row = walk(root, (n) => + (n.children ?? []).some((c) => c === ringed[0]) + )[0]; + expect(row.children?.at(-1)).toBe(ringed[0]); + } + ); + it('List.Accordion rings inward, like List.Item', async () => { await render( From dde9e4c96ef95ccdfc3732ebbfabb5e94fb6fc50 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:57:18 +0200 Subject: [PATCH 37/50] fix(button): keep the focus ring 2dp outside an outlined button --- src/components/Button/Button.tsx | 26 +++++++++-- .../__tests__/focusRingWiring.test.tsx | 46 +++++++++++++++++++ 2 files changed, 67 insertions(+), 5 deletions(-) diff --git a/src/components/Button/Button.tsx b/src/components/Button/Button.tsx index 5ba90f16b8..93f5a59e59 100644 --- a/src/components/Button/Button.tsx +++ b/src/components/Button/Button.tsx @@ -32,6 +32,7 @@ import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import { toSpringCurve } from '../../theme/tokens/sys/motion'; import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; +import { useFocusRing } from '../../utils/useFocusRing'; import ActivityIndicator from '../ActivityIndicator'; import Icon from '../Icon'; import type { IconSource } from '../Icon'; @@ -446,9 +447,18 @@ const Button = ({ // The clip carries the same radius transition as the `Surface`, so the // ripple and the disabled overlay follow the morph. // - // The keyboard focus ring is `TouchableRipple`'s default outward one, drawn - // on the ripple itself. Neither this view nor the `Surface` sets `overflow`, - // so nothing here trims it. + // The keyboard focus ring goes on the clip (`scope: 'within'`, as on FAB), + // not on the ripple that takes focus: the ripple sits inside the outline's + // border, so a ring measured from it would lose the border width from its + // 2dp gap, and overlap a thick outline. Neither this view nor the `Surface` + // sets `overflow`, so nothing here trims it. Off whenever the button can't + // be pressed, as on TouchableRipple. + const { target: focusTarget, ring: focusRing } = useFocusRing( + disabled || !hasPassedTouchHandler, + theme.colors.secondary, + 'outward', + 'within' + ); const shapeTransitionStyle = { transitionProperty: 'borderRadius', transitionDuration: shapeTransitionDuration, @@ -491,7 +501,10 @@ const Button = ({ shapeTransitionTimingFunction={shapeTimingFunction} style={[styles.button, style]} > - + {backgroundOpacity < 1 && ( { expect(ringOffset()).toBe(OUTWARD); }); + // The ring goes on the view that draws the outline, so the 2dp gap is + // measured from the outline's outer edge, not from inside it. + it.each(['small', 'extra-large'] as const)( + 'outlined Button (%s) keeps the 2dp gap outside its outline', + async (size) => { + await render( + + ); + + await focusFirstFocusable(); + + const root = (screen as unknown as { root: Node }).root; + const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(ringed).toHaveLength(1); + expect(style(ringed[0]).outlineOffset).toBe(OUTWARD); + expect(style(ringed[0]).borderWidth).toBeGreaterThan(0); + } + ); + it('DataTable.Row rings inward, clear of the rows above and below', async () => { await render( {}}> @@ -661,6 +682,31 @@ describe('focus ring wiring (web)', () => { ).toBe('inward'); }); + it('Button rings the view that draws its outline, not the button inside it', async () => { + await render( + + ); + + const button = screen.getByRole('button'); + expect(style(button)).toMatchObject({ outline: 'none' }); + + const root = (screen as unknown as { root: Node }).root; + const ringed = walk( + root, + (n) => + (n.props?.dataSet as Record | undefined) + ?.focusRingWithin !== undefined + ); + expect(ringed).toHaveLength(1); + expect( + (ringed[0].props?.dataSet as Record).focusRingWithin + ).toBe('outward'); + expect(style(ringed[0]).borderWidth).toBeGreaterThan(0); + expect(walk(ringed[0], (n) => n === button)).toHaveLength(1); + }); + it('Chip marks its close button as the focus target and rings the glyph circle inside it', async () => { await render( {}} onClose={() => {}}> From 04a0a3e73cc8869962d6314ea132fac6116a857f Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 20:59:31 +0200 Subject: [PATCH 38/50] fix(drawer): keep the collapsed item's ring clear of its indicator --- src/components/Drawer/DrawerCollapsedItem.tsx | 32 +-- .../DrawerCollapsedItem.test.tsx.snap | 183 ++++++++++-------- .../__tests__/focusRingWiring.test.tsx | 57 +++++- 3 files changed, 175 insertions(+), 97 deletions(-) diff --git a/src/components/Drawer/DrawerCollapsedItem.tsx b/src/components/Drawer/DrawerCollapsedItem.tsx index 15e51e3331..4e4b6e93cd 100644 --- a/src/components/Drawer/DrawerCollapsedItem.tsx +++ b/src/components/Drawer/DrawerCollapsedItem.tsx @@ -127,7 +127,8 @@ const DrawerCollapsedItem = ({ // children, and the active indicator would cover its top edge. The overlay // starts above the item, so the ring clears the indicator by the usual 2dp // gap instead of cutting into it; the 12dp gap below the item above it - // leaves room. + // leaves room. Without a label it ends below the item the same way, in the + // item's own 12dp gap. const { target: focusTarget, ring: focusRing } = useFocusRing( disabled, theme.colors.secondary, @@ -219,6 +220,20 @@ const DrawerCollapsedItem = ({ ]} /> + {/* After the indicator, so the indicator doesn't cover the ring, but + before the icon and label, so a text badge above the indicator + and a second label line stay readable over it. */} + + {badge !== false && ( @@ -246,16 +261,6 @@ const DrawerCollapsedItem = ({ {label} ) : null} - - @@ -275,6 +280,11 @@ const styles = StyleSheet.create({ right: 0, bottom: 0, }, + // Without a label the indicator is a circle as tall as the item, so the ring + // reaches into the gap below the item too, with the same 2dp clearance. + focusRingIconOnly: { + bottom: -(focusOuterOffset + focusThickness), + }, wrapper: { width: 80, marginBottom: 12, diff --git a/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap b/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap index 184365e685..f990b0165c 100644 --- a/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap +++ b/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap @@ -73,6 +73,26 @@ exports[`DrawerCollapsedItem should display focused icon in active state 1`] = ` ] } /> + - @@ -210,6 +213,26 @@ exports[`DrawerCollapsedItem should display focused icon in inactive state, if u ] } /> + - @@ -347,6 +353,26 @@ exports[`DrawerCollapsedItem should display unfocused icon in inactive state, if ] } /> + - @@ -482,6 +491,24 @@ exports[`DrawerCollapsedItem should have regular outline if label is specified 1 ] } /> + starred - @@ -662,6 +672,26 @@ exports[`DrawerCollapsedItem should have rounded outline if label is not specifi ] } /> + - diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index a3a549f155..2a23f24f87 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -338,13 +338,68 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(INWARD); // An inward ring is painted under its own element's children, where the - // active indicator would cover it, so it is on an overlay drawn last. + // active indicator would cover it, so it is on an overlay drawn after the + // indicator. const root = (screen as unknown as { root: Node }).root; const [ringed] = walk(root, (n) => style(n).outlineStyle === 'solid'); expect(style(ringed).position).toBe('absolute'); expect(ringed.children ?? []).toHaveLength(0); }); + // The ring stays 2dp clear of the active indicator. Without a label the + // indicator is a circle as tall as the item, so the ring reaches below it. + it.each([ + ['with a label', 'Inbox', 0], + ['without a label', undefined, -(outerOffset + thickness)], + ])( + 'Drawer.CollapsedItem %s clears the active indicator', + async (_name, label, bottom) => { + await render( + {}} + /> + ); + + await focusFirstFocusable(); + + const root = (screen as unknown as { root: Node }).root; + const [ringed] = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(style(ringed)).toMatchObject({ + top: -(outerOffset + thickness), + bottom, + }); + } + ); + + // A text badge pokes above the indicator, across the ring's top edge, so it + // has to paint over the ring to stay readable. + it('Drawer.CollapsedItem paints its badge over the ring', async () => { + await render( + {}} + /> + ); + + await focusFirstFocusable(); + + const root = (screen as unknown as { root: Node }).root; + const [ringed] = walk(root, (n) => style(n).outlineStyle === 'solid'); + const wrapper = walk(root, (n) => + (n.children ?? []).some((c) => c === ringed) + )[0]; + const siblings = wrapper.children ?? []; + const badgeBox = siblings.findIndex( + (c) => walk(c as Node, (n) => n === screen.getByText('3')).length > 0 + ); + expect(badgeBox).toBeGreaterThan(siblings.indexOf(ringed)); + }); + it('Appbar.Content with onPress rings outward, and keeps its own onFocus', async () => { const onFocus = jest.fn(); await render( From 76e4ce00b466db67c48bd64c32473535bc1ef86a Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 21:00:29 +0200 Subject: [PATCH 39/50] fix(card): ring and press the whole card when it outgrows its content --- docs/6.x/docs/guides/migration.md | 4 ++++ src/components/Card/Card.tsx | 7 ++++++- .../__tests__/focusRingWiring.test.tsx | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 333cf9366f..a56976850a 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -1092,6 +1092,10 @@ The `borderColor` in `style` no longer changes the outline color in `outlined` m ``` +#### Press area + +A pressable `Card` that is taller than its content, such as one with a fixed `height` or one stretched by its row, now takes the press over its whole area, not only over its content. Its keyboard focus ring follows the card's edge the same way. + #### `Card.Cover` The `style` prop of `Card.Cover` is now typed as a `View` style. Image style properties such as `resizeMode` or `tintColor` were never applied, so pass them as `Image` props instead: diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 9e909e999b..a45ea7b8f2 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -280,7 +280,9 @@ const Card = ({ onFocus={focusTarget.onFocus} onBlur={focusTarget.onBlur} {...focusRing.dataSetProps} - style={[{ borderRadius }, ...focusRing.style]} + // Grows to fill a card that is taller than its content, so the ring + // follows the card's edge and the whole card takes the press. + style={[styles.pressable, { borderRadius }, ...focusRing.style]} > {content} @@ -303,6 +305,9 @@ Card.Cover = CardCover; Card.Title = CardTitle; const styles = StyleSheet.create({ + pressable: { + flexGrow: 1, + }, content: { flexShrink: 1, overflow: 'hidden', diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 2a23f24f87..2c5512338a 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -451,6 +451,22 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(OUTWARD); }); + // The caller's `style` sizes the card, around the ringed Pressable, so the + // Pressable has to grow with it or the ring stops at the content's height. + it('Card rings its whole box when it is taller than its content', async () => { + await render( + {}} style={{ height: 200 }}> + card + + ); + + await focusFirstFocusable(); + + const root = (screen as unknown as { root: Node }).root; + const [ringed] = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(style(ringed).flexGrow).toBe(1); + }); + it('FAB rings outward on its clip view', async () => { await render( {}} />); From 92583a911a821684d2259c66d996553e22c1ec2d Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 21:43:13 +0200 Subject: [PATCH 40/50] fix(appbar): draw Appbar.Action's focus ring in its theme color --- src/components/Appbar/AppbarAction.tsx | 1 + .../__tests__/focusRingWiring.test.tsx | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx index cf95f9e50e..bd0296c8a3 100644 --- a/src/components/Appbar/AppbarAction.tsx +++ b/src/components/Appbar/AppbarAction.tsx @@ -100,6 +100,7 @@ const AppbarAction = ({ disabled={disabled} aria-label={ariaLabel} animated + theme={theme} ref={ref} {...rest} /> diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 2c5512338a..fefb166ab7 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -18,6 +18,8 @@ import { act, fireEvent } from '@testing-library/react-native'; import { ownFocusEvent, render, screen } from '../../test-utils'; import { tokens } from '../../theme/tokens'; +import AppbarAction from '../Appbar/AppbarAction'; +import AppbarBackAction from '../Appbar/AppbarBackAction'; import AppbarContent from '../Appbar/AppbarContent'; import BottomNavigation from '../BottomNavigation/BottomNavigation'; import Button from '../Button/Button'; @@ -519,6 +521,20 @@ describe('focus ring color follows the theme prop', () => { }; it.each([ + [ + 'Appbar.Action', + {}} + theme={theme} + />, + ], + [ + 'Appbar.BackAction', + {}} theme={theme} />, + ], [ 'IconButton', Date: Sun, 15 Nov 2026 21:44:56 +0200 Subject: [PATCH 41/50] fix(card): ring the card's edge instead of growing its press area --- docs/6.x/docs/guides/migration.md | 4 -- src/components/Card/Card.tsx | 22 +++++----- .../__tests__/focusRingWiring.test.tsx | 43 ++++++++++++++++--- 3 files changed, 49 insertions(+), 20 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index a56976850a..333cf9366f 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -1092,10 +1092,6 @@ The `borderColor` in `style` no longer changes the outline color in `outlined` m ``` -#### Press area - -A pressable `Card` that is taller than its content, such as one with a fixed `height` or one stretched by its row, now takes the press over its whole area, not only over its content. Its keyboard focus ring follows the card's edge the same way. - #### `Card.Cover` The `style` prop of `Card.Cover` is now typed as a `View` style. Image style properties such as `resizeMode` or `tintColor` were never applied, so pass them as `Image` props instead: diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index a45ea7b8f2..876ba099c0 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -19,7 +19,7 @@ import { getCardColors } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; -import { useFocusRing } from '../../utils/useFocusRing'; +import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; @@ -180,11 +180,18 @@ const Card = ({ onPressOut, }); + // The ring goes on the Surface, the card's visible box (`scope: 'within'`), + // not on the `Pressable` that takes focus: the caller's `style` sizes and + // pads the Surface, so a ring on the content-sized `Pressable` would stop + // short of a taller card's edge or sit inside its padding. + // // Off without a touch handler too: the `Pressable` unmounts then, and a // focused one sends no blur, so the ring would come back with the handler. const { target: focusTarget, ring: focusRing } = useFocusRing( disabled || !hasPassedTouchHandler, - theme.colors.secondary + theme.colors.secondary, + 'outward', + 'within' ); const [pressed, setPressed] = React.useState(false); @@ -244,11 +251,12 @@ const Card = ({ ref={ref} borderRadius={borderRadius} backgroundColor={!isMode('elevated') ? backgroundColor : undefined} - style={style} + style={[style, ...focusRing.style]} theme={theme} elevation={elevation} testID={hasPassedTouchHandler ? undefined : testID} {...rest} + {...mergeDataSetProps(rest, focusRing.dataSetProps)} > {isMode('outlined') && ( {content} @@ -305,9 +310,6 @@ Card.Cover = CardCover; Card.Title = CardTitle; const styles = StyleSheet.create({ - pressable: { - flexGrow: 1, - }, content: { flexShrink: 1, overflow: 'hidden', diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index fefb166ab7..216c283085 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -453,11 +453,12 @@ describe('focus ring wiring', () => { expect(ringOffset()).toBe(OUTWARD); }); - // The caller's `style` sizes the card, around the ringed Pressable, so the - // Pressable has to grow with it or the ring stops at the content's height. - it('Card rings its whole box when it is taller than its content', async () => { + // The caller's `style` sizes and pads the card around the Pressable that + // takes focus, so the ring goes on the card's own box: a ring on the + // Pressable would stop at the content's height and sit inside the padding. + it('Card rings its own box, whatever its size and padding', async () => { await render( - {}} style={{ height: 200 }}> + {}} style={{ height: 200, padding: 12 }}> card ); @@ -465,8 +466,13 @@ describe('focus ring wiring', () => { await focusFirstFocusable(); const root = (screen as unknown as { root: Node }).root; - const [ringed] = walk(root, (n) => style(n).outlineStyle === 'solid'); - expect(style(ringed).flexGrow).toBe(1); + const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(ringed).toHaveLength(1); + expect(style(ringed[0])).toMatchObject({ + height: 200, + padding: 12, + outlineOffset: OUTWARD, + }); }); it('FAB rings outward on its clip view', async () => { @@ -769,6 +775,31 @@ describe('focus ring wiring (web)', () => { ).toBe('inward'); }); + it('Card marks its own box as the ring and keeps the browser outline off the Pressable', async () => { + await render( + {}} style={{ height: 200 }}> + card + + ); + + const pressable = screen.getByTestId('card'); + expect(style(pressable)).toMatchObject({ outline: 'none' }); + + const root = (screen as unknown as { root: Node }).root; + const ringed = walk( + root, + (n) => + (n.props?.dataSet as Record | undefined) + ?.focusRingWithin !== undefined + ); + expect(ringed).toHaveLength(1); + expect( + (ringed[0].props?.dataSet as Record).focusRingWithin + ).toBe('outward'); + expect(style(ringed[0]).height).toBe(200); + expect(walk(ringed[0], (n) => n === pressable)).toHaveLength(1); + }); + it('Button rings the view that draws its outline, not the button inside it', async () => { await render( , + ], + [ + 'Card', + {}}> + card + , + ], + ])( + '%s holds its focusable element directly inside its ring', + async (_name, element) => { + await render(element); + + const rings = withinRings(); + expect(rings).toHaveLength(1); + expect(rings[0].children).toContain(screen.getByTestId('focusable')); + } + ); + + it('FAB.Menu holds each item directly inside its ring', async () => { + await render( + {}} + trigger={{ icon: 'plus' }} + items={[ + { label: 'first', onPress: () => {}, testID: 'item-0' }, + { label: 'second', onPress: () => {}, testID: 'item-1' }, + ]} + /> + ); + + const item = screen.getByTestId('item-0'); + expect(withinRings().some((r) => r.children?.includes(item))).toBe(true); + }); + + // A Button or TextInput inside a pressable Card is focused on its own, so it + // must not light the Card's ring as well. + it("does not hold a Card's nested controls directly inside the Card's ring", async () => { + await render( + {}}> + + + + + + ); + + const [cardRing] = withinRings(); + expect(cardRing.children).toContain(screen.getByTestId('card')); + expect(cardRing.children).not.toContain(screen.getByTestId('input')); + expect(cardRing.children).not.toContain( + screen.getByRole('button', { name: 'OK' }) + ); + }); + it('Button rings the view that draws its outline, not the button inside it', async () => { await render( , - ], - [ - 'Card', - {}}> - card - , - ], - ])( - '%s holds its focusable element directly inside its ring', - async (_name, element) => { - await render(element); - - const rings = withinRings(); - expect(rings).toHaveLength(1); - expect(rings[0].children).toContain(screen.getByTestId('focusable')); - } - ); - - it('FAB.Menu holds each item directly inside its ring', async () => { - await render( - {}} - trigger={{ icon: 'plus' }} - items={[ - { label: 'first', onPress: () => {}, testID: 'item-0' }, - { label: 'second', onPress: () => {}, testID: 'item-1' }, - ]} - /> - ); - - const item = screen.getByTestId('item-0'); - expect(withinRings().some((r) => r.children?.includes(item))).toBe(true); - }); - - // A Button or TextInput inside a pressable Card is focused on its own, so it - // must not light the Card's ring as well. - it("does not hold a Card's nested controls directly inside the Card's ring", async () => { - await render( - {}}> - - - - - - ); - - const [cardRing] = withinRings(); - expect(cardRing.children).toContain(screen.getByTestId('card')); - expect(cardRing.children).not.toContain(screen.getByTestId('input')); - expect(cardRing.children).not.toContain( - screen.getByRole('button', { name: 'OK' }) - ); - }); - it('Button rings the view that draws its outline, not the button inside it', async () => { await render( , + ], + [ + 'Card', + {}}> + card + , + ], + ])( + '%s holds its focusable element directly inside its ring', + async (_name, element) => { + await render(element); + + const rings = withinRings(); + expect(rings).toHaveLength(1); + expect(rings[0].children).toContain(screen.getByTestId('focusable')); + } + ); + + // The trigger's ring view also holds the menu's overlay views, ahead of the + // trigger itself. + it('FAB.Menu holds its trigger and each item directly inside their rings', async () => { + await render( + {}} + trigger={{ icon: 'plus', testID: 'trigger' }} + items={[ + { label: 'first', onPress: () => {}, testID: 'item-0' }, + { label: 'second', onPress: () => {}, testID: 'item-1' }, + ]} + /> + ); + + const rings = withinRings(); + for (const testID of ['trigger', 'item-0', 'item-1']) { + const focusable = screen.getByTestId(testID); + expect(rings.some((r) => r.children?.includes(focusable))).toBe(true); + } + }); + + // A Button or TextInput inside a pressable Card is focused on its own, so it + // must not light the Card's ring as well. + it("does not hold a Card's nested controls directly inside the Card's ring", async () => { + await render( + {}}> + + + + + + ); + + const [cardRing] = withinRings(); + expect(cardRing.children).toContain(screen.getByTestId('card')); + expect(cardRing.children).not.toContain(screen.getByTestId('input')); + expect(cardRing.children).not.toContain( + screen.getByRole('button', { name: 'OK' }) + ); + }); +}); diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index 556359ffae..95691baa49 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -103,7 +103,7 @@ const webNoOutlineStyle = { outline: 'none' } as unknown as ViewStyle; * color passed through as a CSS custom property. Nothing here tracks focus in * JS on web - the browser drives it. * - * `scope: 'within'` is for a control whose ring belongs on an ancestor of the + * `scope: 'within'` is for a control whose ring belongs on the parent of the * element that actually receives focus (FAB's clip view), and * `scope: 'descendant'` for one whose ring belongs on a child of it (Switch's * track): `target` also suppresses the browser's default outline on the From d877c8ff6830bb0a18cd8ec07a0c8c94b1ced463 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 22:21:53 +0200 Subject: [PATCH 46/50] test(appbar): cover a leading action in the themed Appbar test --- src/components/__tests__/focusRingWiring.test.tsx | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 85d89f7745..a4f51aef5a 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -609,6 +609,7 @@ describe('focus ring color follows the theme prop', () => { await render( {}} /> + {}} /> {}} /> {}} /> @@ -619,7 +620,7 @@ describe('focus ring color follows the theme prop', () => { root, (n) => typeof n.props?.onFocus === 'function' ); - expect(focusables).toHaveLength(3); + expect(focusables).toHaveLength(4); for (const node of focusables) { await act(async () => { await fireEvent(node as never, 'focus', ownFocusEvent()); @@ -627,12 +628,10 @@ describe('focus ring color follows the theme prop', () => { } const rings = walk(root, (n) => style(n).outlineStyle === 'solid'); - expect(rings).toHaveLength(3); - expect(rings.map((n) => style(n).outlineColor)).toEqual([ - 'rgb(255, 0, 0)', - 'rgb(255, 0, 0)', - 'rgb(255, 0, 0)', - ]); + expect(rings).toHaveLength(4); + expect(rings.map((n) => style(n).outlineColor)).toEqual( + Array(4).fill('rgb(255, 0, 0)') + ); } ); }); From 5ff6547a4522e7ebb0251e9257658888e531b94c Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Sun, 15 Nov 2026 22:22:06 +0200 Subject: [PATCH 47/50] docs(migration): scope the medium and large Appbar theme note --- docs/6.x/docs/guides/migration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index dc98b3e58a..adaa030306 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -429,7 +429,7 @@ To keep the height of the content row when setting `height` in `style`, add the ``` -In `medium` and `large` mode, `Appbar` now passes its `theme` to `Appbar.BackAction`, `Appbar.Action` and `Appbar.Content`, as the `small` and `center-aligned` modes already did. A medium or large bar with its own `theme` now takes the color of its icons, its title and their focus rings from that theme, not from the app's. In 5.x, a dark-themed bar in a light app drew dark icons and a dark title on its dark background. +In `medium` and `large` mode, `Appbar` now passes its `theme` to `Appbar.BackAction`, `Appbar.Action` and `Appbar.Content`, as the `small` and `center-aligned` modes already did. These children of a medium or large bar with its own `theme` now take their colors, the title's font and their focus rings from that theme, not from the app's. In 5.x, a dark-themed bar in a light app drew dark icons and a dark title on its dark background. ### Avatar From c1848af009887047d74229df0858aa90034d2162 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Mon, 16 Nov 2026 00:40:28 +0200 Subject: [PATCH 48/50] fix(chip): draw the body focus ring on the chip's own box On Android and iOS the ripple keeps its own height at the top of a chip that style makes taller, so a ring drawn on it sat high. It also sat inside the chip's 1dp border, so its gap to the visible edge was 1dp, not 2dp. The ring now goes on the Surface, as on Card, and the ripple only takes focus. --- src/components/Chip/Chip.tsx | 41 +++++++-- .../__tests__/focusRingWiring.test.tsx | 90 +++++++++++++++++++ .../__tests__/focusRingWithinWeb.test.tsx | 38 ++++++++ 3 files changed, 160 insertions(+), 9 deletions(-) diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index 2107b42396..1e6946e1d3 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -21,7 +21,7 @@ import { tokens } from '../../theme/tokens'; import type { ThemeProp } from '../../theme/types'; import getMinInteractiveSizeHitSlop from '../../utils/getMinInteractiveSizeHitSlop'; import hasTouchHandler from '../../utils/hasTouchHandler'; -import { useFocusRing } from '../../utils/useFocusRing'; +import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; import type { IconSource } from '../Icon'; import Icon from '../Icon'; import MaterialCommunityIcon from '../MaterialCommunityIcon'; @@ -252,12 +252,11 @@ const Chip = ({ }: Props) => { const theme = useInternalTheme(themeOverrides); // The close affordance is a plain `Pressable`, not a `TouchableRipple` - // (see below), so it calls `useFocusRing` directly instead of going - // through `TouchableRipple`'s `focusRing` prop like the body does. The - // `Pressable` is the whole close column, but the ring follows the glyph's - // round shape, so it goes on a circle inside it (`'descendant'`). The - // circle is a childless overlay on the glyph: Android drew the ring square - // when it sat on the view holding the icon, ignoring its border radius. + // (see below). The `Pressable` is the whole close column, but the ring + // follows the glyph's round shape, so it goes on a circle inside it + // (`'descendant'`). The circle is a childless overlay on the glyph: Android + // drew the ring square when it sat on the view holding the icon, ignoring + // its border radius. // Off without `onClose` too: the close `Pressable` unmounts then, and a // focused one sends no blur, so the ring would come back with `onClose`. const { target: closeFocusTarget, ring: closeFocusRing } = useFocusRing( @@ -277,6 +276,20 @@ const Chip = ({ onPressOut, }); + // The body's ring goes on the Surface, the chip's visible box + // (`scope: 'within'`), not on the ripple that takes focus. The ripple sits + // inside the Surface's border, so a ring measured from it would lose the + // border width from its 2dp gap. And on Android and iOS the ripple keeps its + // own height at the top of a chip that `style` makes taller, so a ring on it + // would sit high. Off whenever the body can't be pressed, as on + // TouchableRipple. + const { target: bodyFocusTarget, ring: bodyFocusRing } = useFocusRing( + disabled || !hasPassedTouchHandler, + theme.colors.secondary, + 'outward', + 'within' + ); + const isOutlined = mode === 'outlined'; const handlePressIn = useLatestCallback((e: GestureResponderEvent) => { @@ -336,16 +349,26 @@ const Chip = ({ { expect(ringOffset()).toBe(OUTWARD); }); + // The caller's `style` sizes the chip around the ripple that takes focus, + // and on Android and iOS the ripple keeps its own height at the top of a + // taller chip. So the ring goes on the chip's own box, and the 2dp gap is + // measured from its border, the visible edge. + it('Chip rings its own box, whatever its height', async () => { + await render( + {}} style={{ height: 40 }}> + chip + + ); + + await focusFirstFocusable(); + + const root = (screen as unknown as { root: Node }).root; + const ringed = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(ringed).toHaveLength(1); + expect(style(ringed[0])).toMatchObject({ + height: 40, + borderWidth: 1, + outlineOffset: OUTWARD, + }); + }); + + it('Chip drops its ring when it is disabled while focused', async () => { + const { rerender } = await render( {}}>chip); + await focusFirstFocusable(); + expect(ringOffset()).toBe(OUTWARD); + + await act(async () => { + await rerender( + {}}> + chip + + ); + }); + expect(ringOffset()).toBeUndefined(); + + // No focus event in between, so nothing is ringed after re-enabling. + await act(async () => { + await rerender( {}}>chip); + }); + expect(ringOffset()).toBeUndefined(); + }); + // The bar clips (`overflow: 'hidden'`) and tabs fill it edge to edge, so an // outward ring loses its top and bottom. Rendered through a custom // `renderTouchable` so the test runs the ring path on every platform. @@ -572,6 +616,12 @@ describe('focus ring color follows the theme prop', () => { 'Menu.Item', {}} theme={theme} />, ], + [ + 'Chip', + {}} theme={theme}> + chip + , + ], [ 'DataTable.Row', {}} theme={theme}> @@ -671,6 +721,15 @@ describe('focus ring after the handler goes away and comes back', () => { expect(ringOffset()).toBeUndefined(); }); + it('Chip shows no ring until it is focused again', async () => { + await dropAndRestore( + {}}>chip, + chip + ); + + expect(ringOffset()).toBeUndefined(); + }); + it('Chip close button shows no ring until it is focused again', async () => { await dropAndRestore( {}}>chip, @@ -862,6 +921,37 @@ describe('focus ring wiring (web)', () => { expect(walk(ringed[0], (n) => n === button)).toHaveLength(1); }); + it("Chip marks its own box as the ring, keeps the caller's dataSet and keeps the browser outline off the ripple", async () => { + await render( + {}} + style={{ height: 40 }} + {...{ dataSet: { qa: 'chip' } }} + > + chip + + ); + + const ripple = screen.getByTestId('chip'); + expect(style(ripple)).toMatchObject({ outline: 'none' }); + + const root = (screen as unknown as { root: Node }).root; + const ringed = walk( + root, + (n) => + (n.props?.dataSet as Record | undefined) + ?.focusRingWithin !== undefined + ); + expect(ringed).toHaveLength(1); + expect(ringed[0].props?.dataSet).toEqual({ + qa: 'chip', + focusRingWithin: 'outward', + }); + expect(style(ringed[0])).toMatchObject({ height: 40, borderWidth: 1 }); + expect(walk(ringed[0], (n) => n === ripple)).toHaveLength(1); + }); + it('Chip marks its close button as the focus target and rings the glyph circle inside it', async () => { await render( {}} onClose={() => {}}> diff --git a/src/components/__tests__/focusRingWithinWeb.test.tsx b/src/components/__tests__/focusRingWithinWeb.test.tsx index e1c9126d7f..9fafd4b75c 100644 --- a/src/components/__tests__/focusRingWithinWeb.test.tsx +++ b/src/components/__tests__/focusRingWithinWeb.test.tsx @@ -15,6 +15,7 @@ import { import { render, screen } from '../../test-utils'; import Button from '../Button/Button'; import Card from '../Card/Card'; +import Chip from '../Chip/Chip'; import FAB from '../FAB/FAB'; import FABMenu from '../FAB/Menu'; @@ -71,6 +72,12 @@ describe('focus ring `within` structure (web)', () => { card , ], + [ + 'Chip', + {}}> + chip + , + ], ])( '%s holds its focusable element directly inside its ring', async (_name, element) => { @@ -123,4 +130,35 @@ describe('focus ring `within` structure (web)', () => { screen.getByRole('button', { name: 'OK' }) ); }); + + // The chip's box draws the ring, so a ring on the ripple inside it would + // show a second one. + it("Chip's ripple carries no ring of its own", async () => { + await render( + {}}> + chip + + ); + + expect(screen.getByTestId('chip').props.dataSet).toBeUndefined(); + }); + + // The close button is focused on its own and rings its glyph, so it must not + // light the chip's ring as well. + it("does not hold a Chip's close button directly inside the Chip's ring", async () => { + await render( + {}} + onClose={() => {}} + > + chip + + ); + + const [chipRing] = withinRings(); + expect(chipRing.children).toContain(screen.getByTestId('chip')); + expect(chipRing.children).not.toContain(screen.getByTestId('close')); + }); }); From 83c8211d80a9f813fd20c62046dc6ce0d6b9ca56 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Mon, 16 Nov 2026 12:35:58 +0200 Subject: [PATCH 49/50] fix(snackbar): ring the action and close button in inversePrimary secondary has 2.04:1 contrast on the snackbar's inverseSurface in the light theme and 1.32:1 in the dark one, below the 3:1 a focus indicator needs. inversePrimary, the action label's color, has 7.73:1 and 4.97:1. An internal context sets the ring color for those two controls only, so there is no new prop and nothing else changes color. --- docs/6.x/docs/guides/migration.md | 2 + src/components/Snackbar.tsx | 89 ++++++++++--------- .../__tests__/focusRingWiring.test.tsx | 62 +++++++++++++ src/utils/__tests__/focusRingContrast.test.ts | 24 +++-- src/utils/__tests__/useFocusRing.test.tsx | 28 ++++++ src/utils/useFocusRing.ts | 24 ++++- 6 files changed, 176 insertions(+), 53 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index adaa030306..27e27fc62a 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -364,6 +364,8 @@ In a disabled `TextInput`, every `TextInput.Icon` takes the disabled color, also Interactive components now draw the Material Design 3 keyboard focus indicator: a 3dp ring in `theme.colors.secondary`, 2dp outside the component. On web it shows when an element gets focus from the keyboard (`:focus-visible`), and on Android when it gets focus from a hardware keyboard or D-pad. Clicking or touching an element shows no ring. iOS shows no ring. +`Snackbar` rings its action and close button in `theme.colors.inversePrimary`, the color of its action label, because `secondary` barely shows on its `inverseSurface` background. If a component's background is the ring color, such as an `Appbar` with a `secondary` background, the rings of the controls on it don't show: give those controls a `theme` with a contrasting `secondary`. An `Appbar` passes its own `theme` on to the `Appbar.Action`, `Appbar.BackAction` and `Appbar.Content` placed directly in it. + Components that fill a clipping container or touch their neighbours draw the ring 3dp inside their edge instead: `List.Item`, `List.Accordion`, `Checkbox.Item`, `RadioButton.Item`, `Menu.Item`, the `FAB.Menu` items, `Drawer.Item`, the `BottomNavigation` tabs, `DataTable.Row`, `DataTable.Cell`, `DataTable.Title` and `SegmentedButtons`. `Drawer.CollapsedItem` draws it around its icon and label, 2dp clear of the active indicator. `FAB` and `Switch` draw this ring instead of their own, and `Checkbox` keeps its circular ring around the state layer. A `TouchableRipple`, and every component built on it, rings only while it can be pressed. A disabled one shows no ring. One with no touch handler and no `disabled` is the plain view described in [TouchableRipple without a press handler](#touchableripple-without-a-press-handler): it isn't a keyboard stop, so it never rings. This applies to `TouchableRipple` only: a `Switch` or `Drawer.CollapsedItem` without a handler is still a keyboard stop and rings. diff --git a/src/components/Snackbar.tsx b/src/components/Snackbar.tsx index 0729052044..ca485c0c0a 100644 --- a/src/components/Snackbar.tsx +++ b/src/components/Snackbar.tsx @@ -25,6 +25,7 @@ import Text from './Typography/Text'; import { useLocale } from '../core/locale'; import { useInternalTheme } from '../core/theming'; import type { Elevation, ThemeProp } from '../theme/types'; +import { FocusRingColorContext } from '../utils/useFocusRing'; export type Props = Omit & { /** @@ -305,48 +306,52 @@ const Snackbar = ({ > {content} {(action || isIconButton) && ( - - {action ? ( - - ) : null} - {isIconButton ? ( - { - return ( - - ); - }) - } - aria-label={iconAccessibilityLabel} - style={styles.icon} - testID={iconTestID} - /> - ) : null} - + // `secondary` barely shows on `inverseSurface`, so the action and + // close button ring in `inversePrimary`, the action label's color. + + + {action ? ( + + ) : null} + {isIconButton ? ( + { + return ( + + ); + }) + } + aria-label={iconAccessibilityLabel} + style={styles.icon} + testID={iconTestID} + /> + ) : null} + + )} diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 7c204dba73..a02dbdb6b9 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -17,6 +17,7 @@ import { import { act, fireEvent } from '@testing-library/react-native'; import { ownFocusEvent, render, screen } from '../../test-utils'; +import { DarkTheme, LightTheme } from '../../theme/schemes'; import { tokens } from '../../theme/tokens'; import Appbar from '../Appbar/Appbar'; import AppbarAction from '../Appbar/AppbarAction'; @@ -40,6 +41,7 @@ import ListItem from '../List/ListItem'; import MenuItem from '../Menu/MenuItem'; import RadioButtonItem from '../RadioButton/RadioButtonItem'; import SegmentedButtons from '../SegmentedButtons/SegmentedButtons'; +import Snackbar from '../Snackbar'; import Switch from '../Switch/Switch'; import TextInputIcon from '../TextInput/TextInputIcon'; import TouchableRipple from '../TouchableRipple/TouchableRipple.native'; @@ -686,6 +688,66 @@ describe('focus ring color follows the theme prop', () => { ); }); +// `secondary` barely shows on the snackbar's `inverseSurface` (2.04:1 in the +// light theme, 1.32:1 in the dark), so its action and close button ring in +// `inversePrimary`, the action label's color. Only those two: a control the +// app puts in the message keeps `secondary`. +describe.each([ + ['light', LightTheme], + ['dark', DarkTheme], +])('Snackbar focus ring (%s)', (_name, theme) => { + const renderSnackbar = () => + render( + {}} + action={{ label: 'Undo', onPress: () => {} }} + onIconPress={() => {}} + iconAccessibilityLabel="Close" + theme={theme} + > + + + ); + + const ringColors = () => { + const root = (screen as unknown as { root: Node }).root; + return walk(root, (n) => style(n).outlineStyle === 'solid').map( + (n) => style(n).outlineColor + ); + }; + + it.each(['Undo', 'Close'])('rings %s in inversePrimary', async (name) => { + await renderSnackbar(); + + await act(async () => { + await fireEvent( + screen.getByRole('button', { name }), + 'focus', + ownFocusEvent() + ); + }); + + expect(ringColors()).toEqual([theme.colors.inversePrimary]); + }); + + it('rings a control in the message in secondary', async () => { + await renderSnackbar(); + + await act(async () => { + await fireEvent( + screen.getByRole('button', { name: 'Details' }), + 'focus', + ownFocusEvent() + ); + }); + + expect(ringColors()).toEqual([theme.colors.secondary]); + }); +}); + // A focused Pressable that unmounts sends no blur, so each of these resets its // ring state when the handler goes away. Otherwise the new Pressable is drawn // ringed when the handler comes back, with nothing focused. diff --git a/src/utils/__tests__/focusRingContrast.test.ts b/src/utils/__tests__/focusRingContrast.test.ts index 5ff9e9cf6f..f7167b98e9 100644 --- a/src/utils/__tests__/focusRingContrast.test.ts +++ b/src/utils/__tests__/focusRingContrast.test.ts @@ -32,16 +32,24 @@ describe.each([ ])('focus ring contrast (%s)', (_name, theme) => { const ring = String(theme.colors.secondary); - // Surfaces an outward ring actually lands on. - const landsOn: (keyof typeof theme.colors)[] = [ - 'background', - 'surface', - 'surfaceVariant', - 'secondaryContainer', + type Role = keyof typeof theme.colors; + + // Surfaces an outward ring actually lands on, with the role that colors the + // ring there. Snackbar's action and close button sit on `inverseSurface`, + // so Snackbar rings them in `inversePrimary`. + const landsOn: [ring: Role, surface: Role][] = [ + ['secondary', 'background'], + ['secondary', 'surface'], + ['secondary', 'surfaceVariant'], + ['secondary', 'secondaryContainer'], + ['inversePrimary', 'inverseSurface'], ]; - it.each(landsOn)('has 3:1 against %s', (role) => { + it.each(landsOn)('a %s ring has 3:1 against %s', (ringRole, surfaceRole) => { expect( - contrastRatio(ring, String(theme.colors[role])) + contrastRatio( + String(theme.colors[ringRole]), + String(theme.colors[surfaceRole]) + ) ).toBeGreaterThanOrEqual(MIN_RATIO); }); diff --git a/src/utils/__tests__/useFocusRing.test.tsx b/src/utils/__tests__/useFocusRing.test.tsx index f9dc10b4f0..61a14d6eee 100644 --- a/src/utils/__tests__/useFocusRing.test.tsx +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -16,6 +16,7 @@ import { tokens } from '../../theme/tokens'; import type { FocusRingPlacement, FocusRingScope } from '../useFocusRing'; import { buildFocusRingStylesheet, + FocusRingColorContext, mergeDataSetProps, useFocusRing, } from '../useFocusRing'; @@ -170,6 +171,20 @@ describe('useFocusRing (native)', () => { }); }); + it('takes its color from FocusRingColorContext when one is set', async () => { + await render( + + + + ); + + await focus(); + + expect(screen.getByTestId('probe')).toHaveStyle({ + outlineColor: 'seagreen', + }); + }); + // `disabled` goes to the hook only, never to the Pressable: RNTL will not // dispatch to a disabled element, so that would pass for free. it('never rings a disabled control, even if a focus event arrives', async () => { @@ -313,6 +328,19 @@ describe('useFocusRing (web)', () => { expect(screen.getByTestId('target').props.style).toEqual([]); }); + it('takes the color variable from FocusRingColorContext when one is set', async () => { + await render( + + + + ); + + expect(screen.getByTestId('probe')).toHaveStyle( + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + { '--rnp-focus-ring-color': 'seagreen' } as unknown as ViewStyle + ); + }); + it('emits nothing when disabled or when the ring is turned off', async () => { await render(); diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index 95691baa49..173aec6dfc 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -80,6 +80,15 @@ export const mergeDataSetProps = ( : {}; }; +/** + * Replaces the ring color of every control inside it, for a component that + * puts controls on a surface where `secondary` doesn't stand out: Snackbar's + * action and close button sit on `inverseSurface`. Internal, not exported + * from the package. + */ +export const FocusRingColorContext: React.Context = + React.createContext(undefined); + const EMPTY: FocusRingResult = { target: { style: [], dataSetProps: {} }, ring: { style: [], dataSetProps: {} }, @@ -128,6 +137,7 @@ export function useFocusRing( scope: FocusRingScope = 'self' ): FocusRingResult { const suppressed = disabled || placement === 'none'; + const ringColor = React.useContext(FocusRingColorContext) ?? color; // Rules of hooks: called unconditionally regardless of platform. Cheap - // native's is a no-op until focus/blur actually fires, web's is stateless. @@ -188,7 +198,7 @@ export function useFocusRing( // by the shared stylesheet below. Not reactive to focus - the // browser's own `:focus-visible`/`:has()` shows the ring. // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - { ['--rnp-focus-ring-color']: color } as unknown as ViewStyle, + { ['--rnp-focus-ring-color']: ringColor } as unknown as ViewStyle, ], dataSetProps: toDataSetProps({ [dataKey]: placement }), }, @@ -202,7 +212,7 @@ export function useFocusRing( ? [ { outlineWidth: thickness, - outlineColor: color, + outlineColor: ringColor, outlineStyle: 'solid' as const, outlineOffset: placement === 'inward' ? -thickness : outerOffset, @@ -212,7 +222,15 @@ export function useFocusRing( dataSetProps: {}, }, }; - }, [suppressed, scope, color, placement, isNativeFocused, onFocus, onBlur]); + }, [ + suppressed, + scope, + ringColor, + placement, + isNativeFocused, + onFocus, + onBlur, + ]); } const STYLE_ELEMENT_ATTR = 'data-rnp-focus-ring-styles'; From 352fa2fbbcadc0ebefecf23ea6b5cf1546c8a937 Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Mon, 16 Nov 2026 12:43:17 +0200 Subject: [PATCH 50/50] fix: keep the browser focus outline where :has() is unsupported Button, Card, the Chip body, FAB, FAB.Extended and the FAB.Menu trigger and items draw their ring on a parent with a :has() rule, and hid the browser outline on the focused element with an inline style. In a browser without :has() (Chrome before 105, Safari before 15.4, Firefox before 121) they showed no focus indicator at all. The shared stylesheet now hides that outline, inside a supports block that tests for :has(), so those browsers keep their own outline. It is important, as the inline style was, so an app's own outline rules still don't add a second indicator. The outline is drawn inside the edge, so the FAB clip views don't cut it off. --- docs/6.x/docs/guides/migration.md | 2 ++ src/components/FAB/Shell.tsx | 6 ++-- .../__tests__/focusRingWiring.test.tsx | 13 +++++--- .../__tests__/focusRingWithinWeb.test.tsx | 14 +++++++-- src/utils/__tests__/useFocusRing.test.tsx | 31 ++++++++++++++++--- src/utils/useFocusRing.ts | 30 +++++++++++++++--- 6 files changed, 75 insertions(+), 21 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 27e27fc62a..30cbc45a6a 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -386,6 +386,8 @@ An outward ring sits outside the component, so a scroll view or a container with On web the ring comes from a stylesheet that Paper adds to the page, and on these elements it takes precedence over your own `:focus-visible` outline styles. There is no app-wide switch to turn the ring off. Its color follows `theme.colors.secondary`, from the theme or a component's `theme` prop. +On web, `Button`, `Card`, the `Chip` body, `FAB`, `FAB.Extended` and the `FAB.Menu` trigger and items draw the ring with the CSS `:has()` selector. A browser without it (Chrome before 105, Safari before 15.4, Firefox before 121) shows its own focus outline just inside their edge instead. + ### Libraries built on Paper Libraries built on Paper may not support 6.x yet. For example, `react-native-paper-dates` 0.24.1 still uses `HelperText`, the 5.x theme exports and `theme.roundness`, so its `DatePickerInput` crashes when it shows a validation error. diff --git a/src/components/FAB/Shell.tsx b/src/components/FAB/Shell.tsx index 959414ec97..e7c45cd50c 100644 --- a/src/components/FAB/Shell.tsx +++ b/src/components/FAB/Shell.tsx @@ -299,9 +299,9 @@ const Shell = ({ ); // `scope: 'within'`: the ring is drawn on the clip view below, not the - // inner `TouchableRipple` that actually receives focus - `target.style` - // suppresses the browser's own outline there on web, so only the clip - // view's ring shows. + // inner `TouchableRipple` that actually receives focus. On web the shared + // stylesheet hides the browser's own outline there, so only the clip view's + // ring shows, or only the outline in a browser without `:has()`. // // Off when `disabled` or without `onPress`: the inner TouchableRipple is // then a plain View, and a focused one unmounts without a blur reaching the diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index a02dbdb6b9..80817b0281 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -933,7 +933,7 @@ describe('focus ring wiring (web)', () => { ).toBe('inward'); }); - it('Card marks its own box as the ring and keeps the browser outline off the Pressable', async () => { + it("Card marks its own box as the ring and leaves the Pressable's outline to the stylesheet", async () => { await render( {}} style={{ height: 200 }}> card @@ -941,7 +941,8 @@ describe('focus ring wiring (web)', () => { ); const pressable = screen.getByTestId('card'); - expect(style(pressable)).toMatchObject({ outline: 'none' }); + // The stylesheet hides its outline, and only where `:has()` works. + expect(style(pressable)).not.toHaveProperty('outline'); const root = (screen as unknown as { root: Node }).root; const ringed = walk( @@ -966,7 +967,8 @@ describe('focus ring wiring (web)', () => { ); const button = screen.getByRole('button'); - expect(style(button)).toMatchObject({ outline: 'none' }); + // The stylesheet hides its outline, and only where `:has()` works. + expect(style(button)).not.toHaveProperty('outline'); const root = (screen as unknown as { root: Node }).root; const ringed = walk( @@ -983,7 +985,7 @@ describe('focus ring wiring (web)', () => { expect(walk(ringed[0], (n) => n === button)).toHaveLength(1); }); - it("Chip marks its own box as the ring, keeps the caller's dataSet and keeps the browser outline off the ripple", async () => { + it("Chip marks its own box as the ring, keeps the caller's dataSet and leaves the ripple's outline to the stylesheet", async () => { await render( { ); const ripple = screen.getByTestId('chip'); - expect(style(ripple)).toMatchObject({ outline: 'none' }); + // The stylesheet hides its outline, and only where `:has()` works. + expect(style(ripple)).not.toHaveProperty('outline'); const root = (screen as unknown as { root: Node }).root; const ringed = walk( diff --git a/src/components/__tests__/focusRingWithinWeb.test.tsx b/src/components/__tests__/focusRingWithinWeb.test.tsx index 9fafd4b75c..6323d3de56 100644 --- a/src/components/__tests__/focusRingWithinWeb.test.tsx +++ b/src/components/__tests__/focusRingWithinWeb.test.tsx @@ -1,7 +1,8 @@ /* eslint-disable testing-library/no-node-access, @typescript-eslint/no-unsafe-type-assertion, no-restricted-syntax -- The ring view is an unnamed internal view (a clip view, a card's box), so the tree has to be walked to find it and its children. */ -import { Platform, Text, TextInput } from 'react-native'; +import { Platform, StyleSheet, Text, TextInput } from 'react-native'; +import type { ViewStyle } from 'react-native'; import { afterEach, @@ -45,7 +46,8 @@ const withinRings = () => // On web a `within` ring lights only for a focused direct child // (`:has(> :focus-visible)`), so each ring view has to hold its own focusable -// element directly, and must not hold a control nested deeper inside it. +// element directly, and must not hold a control nested deeper inside it. The +// stylesheet also hides the browser's outline on that direct child. describe('focus ring `within` structure (web)', () => { const original = Platform.OS; beforeEach(() => { @@ -85,7 +87,13 @@ describe('focus ring `within` structure (web)', () => { const rings = withinRings(); expect(rings).toHaveLength(1); - expect(rings[0].children).toContain(screen.getByTestId('focusable')); + const focusable = screen.getByTestId('focusable'); + expect(rings[0].children).toContain(focusable); + // No inline `outline: 'none'`: the stylesheet hides the browser's + // outline, and only where `:has()` draws the ring instead. + expect( + StyleSheet.flatten(focusable.props.style as ViewStyle) ?? {} + ).not.toHaveProperty('outline'); } ); diff --git a/src/utils/__tests__/useFocusRing.test.tsx b/src/utils/__tests__/useFocusRing.test.tsx index 61a14d6eee..2527b2bccf 100644 --- a/src/utils/__tests__/useFocusRing.test.tsx +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -83,6 +83,29 @@ describe('buildFocusRingStylesheet', () => { ); }); + // The `within` ring replaces the browser's outline on the focused child, but + // only a browser that supports `:has()` draws it. One without keeps its own + // outline, so the control still shows focus. + it('hides the browser outline on a `within` target only where :has() works', () => { + expect(css).toMatch( + /@supports selector\(:has\(> :focus-visible\)\) \{\s*\[data-focus-ring-within\] > :focus \{\s*outline: none !important;\s*\}\s*\}/ + ); + // Nowhere else: the `descendant` target hides its outline inline. + expect(css.match(/outline: none/g)).toHaveLength(1); + }); + + // The ring view often clips (FAB's clip view, a FAB.Menu item's pill), so a + // browser without `:has()` draws its own outline inside the edge. + it('insets the browser outline on a `within` target, outside the :has() check', () => { + const { thickness } = tokens.md.sys.state.focusIndicator; + + expect(css).toMatch( + new RegExp( + `\\}\\n\\[data-focus-ring-within\\] > :focus \\{\\s*outline-offset: ${-thickness}px;\\s*\\}` + ) + ); + }); + // Values must come from the design tokens, not be hardcoded here, or the // token is decorative. Derive the expectation from the token itself. it('takes its thickness and offsets from the focusIndicator tokens', () => { @@ -278,17 +301,15 @@ describe('useFocusRing (web)', () => { ); }); - it('emits data-focus-ring-within for scope "within", and suppresses the target element\'s own outline', async () => { + it('emits data-focus-ring-within for scope "within", and leaves the target element\'s own outline to the stylesheet', async () => { await render(); // eslint-disable-next-line no-restricted-syntax expect(screen.getByTestId('probe').props.dataSet).toEqual({ focusRingWithin: 'inward', }); - expect(screen.getByTestId('target')).toHaveStyle( - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - { outline: 'none' } as unknown as ViewStyle - ); + // eslint-disable-next-line no-restricted-syntax + expect(screen.getByTestId('target').props.style).toEqual([]); }); it('marks the focused element and its ringed child for scope "descendant", and suppresses the target element\'s own outline', async () => { diff --git a/src/utils/useFocusRing.ts b/src/utils/useFocusRing.ts index 173aec6dfc..762f70e5cb 100644 --- a/src/utils/useFocusRing.ts +++ b/src/utils/useFocusRing.ts @@ -95,8 +95,8 @@ const EMPTY: FocusRingResult = { }; /** - * Suppresses the browser's own focus ring, for `scope: 'within'` and - * `scope: 'descendant'` on web. + * Suppresses the browser's own focus ring, for `scope: 'descendant'` on web. + * `scope: 'within'` leaves that to the stylesheet below instead. */ // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion const webNoOutlineStyle = { outline: 'none' } as unknown as ViewStyle; @@ -115,8 +115,11 @@ const webNoOutlineStyle = { outline: 'none' } as unknown as ViewStyle; * `scope: 'within'` is for a control whose ring belongs on the parent of the * element that actually receives focus (FAB's clip view), and * `scope: 'descendant'` for one whose ring belongs on a child of it (Switch's - * track): `target` also suppresses the browser's default outline on the - * focused element itself on web, so only the ring shows. + * track). On web only the ring shows, not the browser's default outline on + * the focused element too. For `'descendant'`, `target` hides that outline. + * For `'within'`, the stylesheet hides it, and only in a browser that + * supports `:has()`: one that doesn't can't draw the ring, so it shows its + * own focus outline instead. * * iOS: a ringed element never gets its own `onFocus`/`onBlur` today. Fabric's * view does call `-becomeFirstResponder`/`-resignFirstResponder` for @@ -186,7 +189,7 @@ export function useFocusRing( : 'focusRing'; return { target: { - style: scope === 'self' ? [] : [webNoOutlineStyle], + style: scope === 'descendant' ? [webNoOutlineStyle] : [], dataSetProps: toDataSetProps( scope === 'descendant' ? { focusRingTarget: 'true' } : undefined ), @@ -259,6 +262,23 @@ export const buildFocusRingStylesheet = (): string => focusRingRule( (p) => `[data-focus-ring-within="${p}"]:has(> :focus-visible)` ), + // The `within` ring replaces the browser's own outline on the focused + // child, but only where the rule above works. A browser without `:has()` + // drops that rule, skips the block, and keeps its own outline, so the + // control still shows focus. `:focus` and `!important` match the inline + // `outline: 'none'` this replaces, which also beat an app's own outline + // rules in every state. + // + // The ring view often clips (FAB's clip view, a FAB.Menu item's pill), + // so the outline a browser without `:has()` draws goes inside the edge. + `@supports selector(:has(> :focus-visible)) { + [data-focus-ring-within] > :focus { + outline: none !important; + } +} +[data-focus-ring-within] > :focus { + outline-offset: ${-thickness}px; +}`, focusRingRule( (p) => `[data-focus-ring-target]:focus-visible [data-focus-ring-descendant="${p}"]`