diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md
index 4004b584d8..30cbc45a6a 100644
--- a/docs/6.x/docs/guides/migration.md
+++ b/docs/6.x/docs/guides/migration.md
@@ -360,6 +360,34 @@ 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.
+
+`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.
+
+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.
+
+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.
@@ -405,6 +433,8 @@ 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. 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
The `style` prop for `Avatar.Icon`, `Avatar.Image` and `Avatar.Text` no longer configures the background color. Use the `backgroundColor` prop instead. The text or icon color is still derived from the background color unless `color` is specified.
@@ -673,6 +703,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.
diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx
index 68156c6327..b3107d33bc 100644
--- a/src/components/Appbar/Appbar.tsx
+++ b/src/components/Appbar/Appbar.tsx
@@ -258,12 +258,14 @@ const Appbar = ({
{renderAppbarContent({
children,
isDark,
+ theme,
renderOnly: ['Appbar.BackAction'],
mode,
})}
{renderAppbarContent({
children: filterAppbarActions(children, true),
isDark,
+ theme,
renderOnly: ['Appbar.Action'],
mode,
})}
@@ -272,6 +274,7 @@ const Appbar = ({
{renderAppbarContent({
children: filterAppbarActions(children),
isDark,
+ theme,
renderExcept: [
'Appbar',
'Appbar.BackAction',
@@ -285,6 +288,7 @@ const Appbar = ({
{renderAppbarContent({
children,
isDark,
+ theme,
renderOnly: ['Appbar.Content'],
mode,
})}
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/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx
index 37c3b28e2c..a7ed41f2d9 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 { mergeDataSetProps, 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,19 @@ 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);
+ }}
+ onBlur={(e) => {
+ focusTarget.onBlur?.();
+ rest.onBlur?.(e);
+ }}
+ {...mergeDataSetProps(rest, focusRing.dataSetProps)}
+ style={[...contentWrapperProps.style, ...focusRing.style]}
>
{content}
diff --git a/src/components/BottomNavigation/BottomNavigationBar.tsx b/src/components/BottomNavigation/BottomNavigationBar.tsx
index 99ee8591d9..6e86348c3a 100644
--- a/src/components/BottomNavigation/BottomNavigationBar.tsx
+++ b/src/components/BottomNavigation/BottomNavigationBar.tsx
@@ -213,6 +213,8 @@ const Touchable = ({
borderless,
centered,
rippleColor,
+ focusRing,
+ theme,
...rest
}: TouchableProps) =>
TouchableRipple.supported ? (
@@ -222,6 +224,8 @@ const Touchable = ({
borderless={borderless}
centered={centered}
rippleColor={rippleColor}
+ focusRing={focusRing}
+ theme={theme}
style={style}
>
{children}
@@ -574,6 +578,11 @@ 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',
+ theme,
onPress: () => onTabPress(eventForIndex(index)),
onLongPress: () => onTabLongPress?.(eventForIndex(index)),
testID: getTestID({ route }),
diff --git a/src/components/Button/Button.tsx b/src/components/Button/Button.tsx
index 37cd23a29d..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,14 +447,18 @@ 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 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,
@@ -496,7 +501,10 @@ const Button = ({
shapeTransitionTimingFunction={shapeTimingFunction}
style={[styles.button, style]}
>
-
+
{backgroundOpacity < 1 && (
{
const theme = useInternalTheme(themeOverrides);
-
const isMode = React.useCallback(
(modeToCompare: Mode) => {
return cardMode === modeToCompare;
@@ -180,6 +180,20 @@ 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,
+ 'outward',
+ 'within'
+ );
+
const [pressed, setPressed] = React.useState(false);
const elevation = isMode('elevated') ? (pressed ? 2 : cardElevation) : 0;
@@ -237,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}
diff --git a/src/components/Checkbox/Checkbox.tsx b/src/components/Checkbox/Checkbox.tsx
index 51ab74f600..f8d8115b40 100644
--- a/src/components/Checkbox/Checkbox.tsx
+++ b/src/components/Checkbox/Checkbox.tsx
@@ -499,6 +499,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/Checkbox/CheckboxItem.tsx b/src/components/Checkbox/CheckboxItem.tsx
index e924f0c07a..3dabdd2de9 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,16 +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'`): 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}
@@ -191,6 +212,11 @@ const CheckboxItem = ({
{!isLeading && checkbox}
+
);
};
diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx
index bfdebbaa52..1e6946e1d3 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';
@@ -24,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 { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent';
+import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing';
import type { IconSource } from '../Icon';
import Icon from '../Icon';
import MaterialCommunityIcon from '../MaterialCommunityIcon';
@@ -175,6 +172,16 @@ 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, 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 - 2 * tokens.md.sys.state.focusIndicator.outerOffset;
+
/**
* 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
@@ -188,13 +195,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 +251,22 @@ const Chip = ({
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);
+ // The close affordance is a plain `Pressable`, not a `TouchableRipple`
+ // (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(
+ disabled || !onClose,
+ theme.colors.secondary,
+ 'outward',
+ 'descendant'
+ );
const [pressed, setPressed] = React.useState(false);
- const [closeFocused, setCloseFocused] = React.useState(false);
const elevation = elevated ? (pressed ? 2 : 1) : 0;
const hasPassedTouchHandler = hasTouchHandler({
@@ -263,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) => {
@@ -275,18 +302,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;
@@ -334,16 +349,26 @@ const Chip = ({
{/* react-native-web removed `hitSlop` in 0.13.0,
so web needs a real element the browser can
@@ -465,16 +493,14 @@ const Chip = ({
{Platform.OS === 'web' && !disabled && (
)}
-
- {closeFocused && !disabled ? (
-
- ) : null}
+
{closeIcon ? (
) : (
@@ -485,6 +511,15 @@ const Chip = ({
direction="ltr"
/>
)}
+
@@ -562,21 +597,21 @@ 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: {
- 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,
+ width: CLOSE_FOCUS_RING_SIZE,
+ height: CLOSE_FOCUS_RING_SIZE,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ closeFocusRingShape: {
+ borderRadius: CLOSE_FOCUS_RING_SIZE / 2,
},
closeButtonWebTouchTarget: {
position: 'absolute',
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 (
diff --git a/src/components/DataTable/DataTableTitle.tsx b/src/components/DataTable/DataTableTitle.tsx
index 3f2c13909b..76daec7f8b 100644
--- a/src/components/DataTable/DataTableTitle.tsx
+++ b/src/components/DataTable/DataTableTitle.tsx
@@ -23,6 +23,7 @@ import type { ThemeProp } from '../../theme/types';
import hasTouchHandler, {
getNonControlA11yProps,
} from '../../utils/hasTouchHandler';
+import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing';
import MaterialCommunityIcon from '../MaterialCommunityIcon';
import Text from '../Typography/Text';
@@ -110,6 +111,8 @@ const DataTableTitle = ({
numberOfLines = 1,
maxFontSizeMultiplier,
hitSlop,
+ onFocus,
+ onBlur,
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);
@@ -176,6 +179,17 @@ const DataTableTitle = ({
const isControl = hasPassedTouchHandler || Boolean(disabledProp);
const isInteractive = hasPassedTouchHandler && !disabledProp;
+ // A title with a touch handler is a control, so it gets the keyboard focus
+ // ring. It is a plain `Pressable`, not a `TouchableRipple`, so it calls the
+ // hook directly, above the early return below. Off whenever the title can't
+ // be pressed.
+ // Inward: titles sit side by side in the header row, like the rows below.
+ const { target: focusTarget, ring: focusRing } = useFocusRing(
+ !isInteractive,
+ theme.colors.secondary,
+ 'inward'
+ );
+
const content = (
<>
{icon}
@@ -194,6 +208,9 @@ const DataTableTitle = ({
return (
@@ -204,6 +221,11 @@ const DataTableTitle = ({
return (
{
+ focusTarget.onFocus?.(e);
+ onFocus?.(e);
+ }}
+ onBlur={(e) => {
+ focusTarget.onBlur?.();
+ onBlur?.(e);
+ }}
+ {...mergeDataSetProps(rest, focusRing.dataSetProps)}
+ style={[...containerStyle, style, ...focusRing.style]}
>
{content}
diff --git a/src/components/Drawer/DrawerCollapsedItem.tsx b/src/components/Drawer/DrawerCollapsedItem.tsx
index dc9211bf0f..65ade3fa40 100644
--- a/src/components/Drawer/DrawerCollapsedItem.tsx
+++ b/src/components/Drawer/DrawerCollapsedItem.tsx
@@ -17,7 +17,9 @@ 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';
import Icon from '../Icon';
import type { IconSource } from '../Icon';
@@ -117,6 +119,24 @@ 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 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. It ends below the item the same way, in the item's own 12dp
+ // gap, so it clears an icon-only item's round indicator and a label that
+ // sets the item's height (two lines, or a large font scale) by 2dp too.
+ 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,6 +202,13 @@ 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}
+ style={focusTarget.style}
>
+ {/* After the indicator, so the indicator doesn't cover the ring, but
+ before the icon, so a text badge that pokes above the indicator
+ stays readable over it. */}
+
+
{badge !== false && (
@@ -229,7 +269,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: -(focusOuterOffset + focusThickness),
+ },
wrapper: {
width: 80,
marginBottom: 12,
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 = ({
({
- opacity: focusedSV.value ? 1 : 0,
- }));
+ // `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,
+ 'inward',
+ 'within'
+ );
return (
@@ -260,19 +265,19 @@ const MenuItem = ({
style={[
styles.menuItem,
{ height, borderRadius, backgroundColor: colors.container },
+ ...focusRing.style,
]}
+ {...focusRing.dataSetProps}
>
-
);
};
@@ -692,15 +687,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 aca8afd1c8..e7c45cd50c 100644
--- a/src/components/FAB/Shell.tsx
+++ b/src/components/FAB/Shell.tsx
@@ -17,20 +17,15 @@ 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 { useFocusRing } from '../../utils/useFocusRing';
import type { IconSource } from '../Icon';
import Surface from '../Surface';
import TouchableRipple from '../TouchableRipple/TouchableRipple';
@@ -262,7 +257,7 @@ const Shell = ({
// Fallback shared values track the static size-driven dimensions. Consumers
// that don't supply their own animated shared values get these. Keeping
// everything as a shared value means there's exactly one animated style
- // per view — no static-vs-animated merge surprises.
+ // per view: no static-vs-animated merge surprises.
const fallbackWidth = useSharedValue(dimensions.width);
const fallbackHeight = useSharedValue(dimensions.height);
const fallbackBorderRadius = useSharedValue(dimensions.borderRadius);
@@ -303,7 +298,21 @@ const Shell = ({
[borderRadius, containerBg]
);
- const { focusedSV, onFocus, onBlur } = useFocusRing();
+ // `scope: 'within'`: the ring is drawn on the clip view below, not the
+ // 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
+ // hook. The public FAB has no `disabled`, so dropping `onPress` is how an app
+ // turns it off.
+ const { target: focusTarget, ring: focusRing } = useFocusRing(
+ disabled || !onPress,
+ theme.colors.secondary,
+ 'outward',
+ 'within'
+ );
// Without a handler the touchable drops the button role, and on web that
// renders role="presentation", which can't carry a name. A labelled
@@ -317,14 +326,6 @@ const Shell = ({
ariaLabel !== undefined &&
ariaChecked === undefined;
- const focusRingStyle = useAnimatedStyle(
- () => ({
- opacity: focusedSV.value ? 1 : 0,
- borderRadius: borderRadius.value + FOCUS_RING_INSET,
- }),
- [borderRadius]
- );
-
return (
-
+
{overlay}
{children ?? (
-
);
};
@@ -408,15 +403,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/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/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 = ({
{(context: RadioButtonContextType | null) => {
@@ -197,6 +212,11 @@ const RadioButtonItem = ({
}) === 'checked';
return (
{!isLeading && radioButton}
+
);
}}
diff --git a/src/components/SegmentedButtons/SegmentedButtonItem.tsx b/src/components/SegmentedButtons/SegmentedButtonItem.tsx
index 10bf51f638..c0df4c8b7a 100644
--- a/src/components/SegmentedButtons/SegmentedButtonItem.tsx
+++ b/src/components/SegmentedButtons/SegmentedButtonItem.tsx
@@ -212,6 +212,11 @@ const SegmentedButtonItem = ({
& {
/**
@@ -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/Switch/Switch.tsx b/src/components/Switch/Switch.tsx
index 2c86f8d963..1631c84119 100644
--- a/src/components/Switch/Switch.tsx
+++ b/src/components/Switch/Switch.tsx
@@ -31,6 +31,7 @@ import { toRawSpring } from '../../theme/tokens/sys/motion';
import { cornerFull } from '../../theme/tokens/sys/shape';
import type { StateOpacityKey, ThemeProp } from '../../theme/types';
import { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent';
+import { useFocusRing } from '../../utils/useFocusRing';
import Icon, { type IconSource } from '../Icon';
export type Props = {
@@ -83,10 +84,6 @@ const {
const { state: stateTokens } = tokens.md.sys;
const stateOpacity = stateTokens.opacity;
-const { thickness: FOCUS_THICKNESS, outerOffset: FOCUS_OUTER_OFFSET } =
- stateTokens.focusIndicator;
-const FOCUS_RING_INSET = -(FOCUS_OUTER_OFFSET + FOCUS_THICKNESS);
-const OVERLAY_TOP = (STATE_LAYER_SIZE - TRACK_HEIGHT) / 2;
// Hold-then-grow: a brief delay before snapping to PRESSED_HANDLE so a quick
// tap doesn't flash the press-grow visual.
@@ -154,6 +151,12 @@ const Switch = ({
const pressedSV = useSharedValue(0);
const hoveredSV = useSharedValue(0);
const focusedSV = useSharedValue(0);
+
+ React.useEffect(() => {
+ 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);
@@ -166,6 +169,16 @@ const Switch = ({
const colors = React.useMemo(() => getDefaultSwitchColors(theme), [theme]);
+ // `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',
+ 'descendant'
+ );
+
const reanimatedReduceMotion = reduceMotion
? ReduceMotion.Always
: ReduceMotion.Never;
@@ -323,10 +336,6 @@ const Switch = ({
],
}));
- const focusRingAnimatedStyle = useAnimatedStyle(() => ({
- opacity: focusedSV.value,
- }));
-
const paint = resolveSwitchPaint(colors, isEnabled, checked);
const stateLayerColor = checked
? colors.checkedStateLayerColor
@@ -363,10 +372,14 @@ const Switch = ({
hoveredSV.value = 0;
}}
onFocus={(e) => {
- if (!isKeyboardFocusEvent(e)) return;
- focusedSV.value = 1;
+ // 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={() => {
+ focusTarget.onBlur?.();
focusedSV.value = 0;
}}
android_ripple={{ color: 'transparent' }}
@@ -375,16 +388,16 @@ const Switch = ({
aria-checked={checked}
aria-label={ariaLabel}
testID={testID}
- style={[
- styles.touchable,
- Platform.OS === 'web' ? webNoOutline : undefined,
- ]}
+ style={[styles.touchable, ...focusTarget.style]}
+ {...focusTarget.dataSetProps}
>
{showOutline ? (
@@ -446,22 +459,6 @@ const Switch = ({
) : null}
-
-
);
};
@@ -525,10 +522,6 @@ const styles = StyleSheet.create({
height: SELECTED_ICON,
pointerEvents: 'none',
},
- focusRing: {
- position: 'absolute',
- pointerEvents: 'none',
- },
absoluteFill: {
position: 'absolute',
top: 0,
@@ -538,8 +531,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/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/TouchableRipple/TouchableRipple.native.tsx b/src/components/TouchableRipple/TouchableRipple.native.tsx
index 1034c17261..4325f13d37 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';
@@ -18,6 +20,8 @@ import type { ThemeProp } from '../../theme/types';
import hasTouchHandler, {
getNonControlA11yProps,
} from '../../utils/hasTouchHandler';
+import type { FocusRingPlacement } from '../../utils/useFocusRing';
+import { useFocusRing } from '../../utils/useFocusRing';
const ANDROID_VERSION_LOLLIPOP = 21;
const ANDROID_VERSION_PIE = 28;
@@ -27,6 +31,20 @@ 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. On web the browser's own focus outline still
+ * shows, so a control that draws its own indicator also needs
+ * `outline: 'none'` there.
+ *
+ * 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;
onLongPress?: (e: GestureResponderEvent) => void;
onPressIn?: (e: GestureResponderEvent) => void;
@@ -46,6 +64,9 @@ const TouchableRipple = ({
underlayColor,
children,
theme: themeOverrides,
+ focusRing = 'outward',
+ onFocus,
+ onBlur,
hitSlop,
ref,
...rest
@@ -74,6 +95,26 @@ const TouchableRipple = ({
// View would take touches in its slop on both.
const effectiveHitSlop = isInteractive ? hitSlop : undefined;
+ // Called above the non-control early return, so the hook runs on every
+ // render. Keyed off `!isInteractive`: on the Pressable that is `disabled`,
+ // and when the touchable drops to the plain View it resets the focus state.
+ // A focused Pressable that unmounts sends no blur here, so without the reset
+ // the ring would come back with the handler. The plain View takes neither
+ // the ring's focus handlers nor its style.
+ const { target, ring } = useFocusRing(
+ !isInteractive,
+ theme.colors.secondary,
+ focusRing
+ );
+ const handleFocus = (e: NativeSyntheticEvent) => {
+ onFocus?.(e);
+ target.onFocus?.(e);
+ };
+ const handleBlur = (e: NativeSyntheticEvent) => {
+ onBlur?.(e);
+ target.onBlur?.();
+ };
+
const { calculatedRippleColor, calculatedUnderlayColor } =
getTouchableRippleColors({
theme,
@@ -95,8 +136,8 @@ const TouchableRipple = ({
baseStyle: StyleProp
): PressableProps['style'] =>
typeof style === 'function'
- ? (state) => [baseStyle, style(state)]
- : [baseStyle, style];
+ ? (state) => [baseStyle, style(state), ...ring.style]
+ : [baseStyle, style, ...ring.style];
if (!isControl) {
const baseStyle = TouchableRipple.supported
@@ -107,6 +148,9 @@ const TouchableRipple = ({
@@ -150,6 +196,8 @@ const TouchableRipple = ({
ref={ref}
disabled={Boolean(disabledProp)}
hitSlop={effectiveHitSlop}
+ 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 d9890eca76..f1bb352835 100644
--- a/src/components/TouchableRipple/TouchableRipple.tsx
+++ b/src/components/TouchableRipple/TouchableRipple.tsx
@@ -19,6 +19,8 @@ import type { ThemeProp } from '../../theme/types';
import hasTouchHandler, {
getNonControlA11yProps,
} from '../../utils/hasTouchHandler';
+import type { FocusRingPlacement } from '../../utils/useFocusRing';
+import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing';
export type Props = PressableProps & {
/**
@@ -43,6 +45,20 @@ 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. On web the browser's own focus outline still
+ * shows, so a control that draws its own indicator also needs
+ * `outline: 'none'` there.
+ *
+ * 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;
/**
* Function to execute on press. Without it, `onLongPress`, `onPressIn`,
* `onPressOut` and `disabled`, the touchable renders as a plain view that
@@ -128,6 +144,7 @@ const TouchableRipple = ({
children,
theme: themeOverrides,
hitSlop,
+ focusRing = 'outward',
ref,
...rest
}: Props) => {
@@ -295,6 +312,21 @@ const TouchableRipple = ({
[onPressOut, rippleEffectEnabled]
);
+ // 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
+ // onto the Pressable below. `onFocus`/`onBlur` reach the caller unmodified
+ // via `rest`, nothing to intercept.
+ //
+ // Called above the non-control early return, so the hook runs on every
+ // render. Keyed off `!isInteractive`, which on the Pressable is the same as
+ // `disabled`. Web keeps no focus state, so this only mirrors the native
+ // file. The plain View below takes none of the ring props.
+ const { ring } = useFocusRing(
+ !isInteractive,
+ theme.colors.secondary,
+ focusRing
+ );
+
if (!isControl) {
// No cursor of its own: inside a clickable parent, the parent's applies
return (
@@ -319,13 +351,16 @@ const TouchableRipple = ({
onPressIn={handlePressIn}
onPressOut={handlePressOut}
disabled={Boolean(disabledProp)}
+ {...mergeDataSetProps(rest, ring.dataSetProps)}
style={(state) => [
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, which is
+ // exactly the distinction `:focus-visible` exists to make.
+ // https://github.com/necolas/react-native-web/issues/1849
state.hovered && isInteractive && { backgroundColor: hoverColor },
!isInteractive && styles.disabled,
typeof style === 'function' ? style(state) : style,
+ ...ring.style,
]}
>
{(state) => {
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__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap b/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap
index 1bdc1cec4f..dd763a873c 100644
--- a/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap
+++ b/src/components/__tests__/Drawer/__snapshots__/DrawerCollapsedItem.test.tsx.snap
@@ -33,6 +33,7 @@ exports[`DrawerCollapsedItem should display focused icon in active state 1`] = `
onResponderTerminationRequest={[Function]}
onStartShouldSetResponder={[Function]}
role="button"
+ style={[]}
>
+
+
+
+
+
@@ -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__/TouchableRipple.test.tsx b/src/components/__tests__/TouchableRipple.test.tsx
index d9ebbcfa2e..c29d1b7db5 100644
--- a/src/components/__tests__/TouchableRipple.test.tsx
+++ b/src/components/__tests__/TouchableRipple.test.tsx
@@ -12,9 +12,9 @@ import {
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 { ownFocusEvent, render, screen } from '../../test-utils';
import TouchableRipple from '../TouchableRipple/TouchableRipple.native';
describe('TouchableRipple', () => {
@@ -540,3 +540,91 @@ describe('TouchableRipple', () => {
});
});
});
+
+describe('TouchableRipple focus ring', () => {
+ const focus = async () => {
+ await act(async () => {
+ await fireEvent(screen.getByTestId('ripple'), 'focus', ownFocusEvent());
+ });
+ };
+
+ 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 disabled case is covered in useFocusRing's own tests. RNTL's focus()
+ // won't dispatch to a disabled element, so asserting it here would mean
+ // calling the host's onFocus directly.
+ 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();
+ });
+
+ // Without a touch handler it renders a plain View, which keeps the caller's
+ // focus handlers but takes none of the ring.
+ it('keeps caller focus handlers and draws no ring without a touch handler', async () => {
+ const onFocus = jest.fn();
+ const onBlur = jest.fn();
+ await render(
+
+ Not a button
+
+ );
+
+ // Checked on the host view: `fireEvent` would also find them on the
+ // TouchableRipple element itself, so calling them proves nothing.
+ expect(screen.getByTestId('ripple')).toHaveProp('onFocus', onFocus);
+ expect(screen.getByTestId('ripple')).toHaveProp('onBlur', onBlur);
+
+ await focus();
+ expect(screen.getByTestId('ripple')).not.toHaveStyle({ outlineWidth: 3 });
+ });
+});
diff --git a/src/components/__tests__/TouchableRippleFocusWeb.test.tsx b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx
new file mode 100644
index 0000000000..287308d1c0
--- /dev/null
+++ b/src/components/__tests__/TouchableRippleFocusWeb.test.tsx
@@ -0,0 +1,119 @@
+import { Platform, Text } 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';
+// 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';
+
+// 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}>
+ Button
+
+ );
+
+describe('TouchableRipple focus ring (web implementation)', () => {
+ const original = Platform.OS;
+ beforeEach(() => {
+ Platform.OS = 'web';
+ });
+ afterEach(() => {
+ Platform.OS = original;
+ });
+
+ it('emits data-focus-ring="outward" and the secondary colour by default', async () => {
+ await renderRipple();
+
+ // 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('emits data-focus-ring="inward" when asked', async () => {
+ await renderRipple({ focusRing: 'inward' });
+
+ // eslint-disable-next-line no-restricted-syntax
+ expect(screen.getByTestId('ripple').props.dataSet).toEqual({
+ focusRing: 'inward',
+ });
+ });
+
+ it('emits no attribute when the ring is turned off', async () => {
+ await renderRipple({ focusRing: 'none' });
+
+ // eslint-disable-next-line no-restricted-syntax
+ expect(screen.getByTestId('ripple').props.dataSet).toBeUndefined();
+ });
+
+ 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();
+ });
+
+ // 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 act(async () => {
+ await fireEvent(screen.getByTestId('ripple'), 'focus');
+ });
+ await act(async () => {
+ await fireEvent(screen.getByTestId('ripple'), 'blur');
+ });
+
+ 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__/__snapshots__/Chip.test.tsx.snap b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap
index b228fda895..fbc4a1035a 100644
--- a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap
+++ b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap
@@ -235,11 +235,12 @@ exports[`renders chip with close button 1`] = `
@@ -309,6 +311,12 @@ exports[`renders chip with close button 1`] = `
"marginRight": 0,
"padding": 0,
},
+ {
+ "alignItems": "center",
+ "height": 20,
+ "justifyContent": "center",
+ "width": 20,
+ },
]
}
>
@@ -341,6 +349,23 @@ exports[`renders chip with close button 1`] = `
>
close
+
@@ -582,11 +607,12 @@ exports[`renders chip with custom close button 1`] = `
@@ -656,6 +683,12 @@ exports[`renders chip with custom close button 1`] = `
"marginRight": 0,
"padding": 0,
},
+ {
+ "alignItems": "center",
+ "height": 20,
+ "justifyContent": "center",
+ "width": 20,
+ },
]
}
>
@@ -688,6 +721,23 @@ exports[`renders chip with custom close button 1`] = `
>
arrow-down
+
diff --git a/src/components/__tests__/__snapshots__/FAB.test.tsx.snap b/src/components/__tests__/__snapshots__/FAB.test.tsx.snap
index 1783f44076..f469bb2d57 100644
--- a/src/components/__tests__/__snapshots__/FAB.test.tsx.snap
+++ b/src/components/__tests__/__snapshots__/FAB.test.tsx.snap
@@ -120,8 +120,6 @@ exports[`renders FAB large size 1`] = `
>
-
`;
@@ -333,8 +307,6 @@ exports[`renders FAB medium size 1`] = `
>
-
`;
@@ -546,8 +494,6 @@ exports[`renders FAB transitioning to not visible 1`] = `
>
-
`;
@@ -759,8 +681,6 @@ exports[`renders FAB transitioning to visible 1`] = `
>
-
`;
@@ -973,8 +869,6 @@ exports[`renders FAB with aria-label 1`] = `
-
`;
@@ -1186,8 +1056,6 @@ exports[`renders FAB with containerColor and contentColor overrides 1`] = `
>
-
`;
@@ -1399,8 +1243,6 @@ exports[`renders FAB with containerColor override 1`] = `
>
-
`;
@@ -1612,8 +1430,6 @@ exports[`renders FAB with default props 1`] = `
>
-
`;
@@ -1825,8 +1617,6 @@ exports[`renders FAB with primary variant 1`] = `
>
-
`;
@@ -2038,8 +1804,6 @@ exports[`renders FAB with secondary variant 1`] = `
>
-
`;
@@ -2251,8 +1991,6 @@ exports[`renders FAB with tertiary variant 1`] = `
>
-
`;
@@ -2464,8 +2178,6 @@ exports[`renders FAB with tonalSecondary variant 1`] = `
>
-
`;
@@ -2677,8 +2365,6 @@ 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 5de216dad3..1a53afc39e 100644
--- a/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap
+++ b/src/components/__tests__/__snapshots__/FABExtended.test.tsx.snap
@@ -122,8 +122,6 @@ exports[`renders extended FAB collapsed 1`] = `
-
-
-
-
-
-
-
-
@@ -622,7 +574,6 @@ exports[`renders FAB.Menu closed 1`] = `
{
"flex": 1,
},
- null,
],
]
}
@@ -748,29 +699,6 @@ exports[`renders FAB.Menu closed 1`] = `
-
@@ -916,7 +844,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = `
{
"borderRadius": 9999,
},
- null,
],
]
}
@@ -981,29 +908,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = `
-
-
@@ -1399,7 +1279,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = `
{
"flex": 1,
},
- null,
],
]
}
@@ -1525,29 +1404,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = `
-
@@ -1693,7 +1549,6 @@ exports[`renders FAB.Menu open 1`] = `
{
"borderRadius": 9999,
},
- null,
],
]
}
@@ -1758,29 +1613,6 @@ exports[`renders FAB.Menu open 1`] = `
-
-
@@ -2176,7 +1984,6 @@ exports[`renders FAB.Menu open 1`] = `
{
"flex": 1,
},
- null,
],
]
}
@@ -2302,29 +2109,6 @@ exports[`renders FAB.Menu open 1`] = `
-
@@ -2470,7 +2254,6 @@ exports[`renders FAB.Menu with 6 items 1`] = `
{
"borderRadius": 9999,
},
- null,
],
]
}
@@ -2535,29 +2318,6 @@ exports[`renders FAB.Menu with 6 items 1`] = `
-
-
-
-
-
-
@@ -3657,7 +3297,6 @@ exports[`renders FAB.Menu with 6 items 1`] = `
{
"flex": 1,
},
- null,
],
]
}
@@ -3783,29 +3422,6 @@ exports[`renders FAB.Menu with 6 items 1`] = `
-
@@ -3952,7 +3568,6 @@ exports[`renders FAB.Menu with center alignment 1`] = `
{
"borderRadius": 9999,
},
- null,
],
]
}
@@ -4017,29 +3632,6 @@ exports[`renders FAB.Menu with center alignment 1`] = `
-
-
@@ -4435,7 +4003,6 @@ exports[`renders FAB.Menu with center alignment 1`] = `
{
"flex": 1,
},
- null,
],
]
}
@@ -4561,29 +4128,6 @@ exports[`renders FAB.Menu with center alignment 1`] = `
-
@@ -4729,7 +4273,6 @@ exports[`renders FAB.Menu with items having icons 1`] = `
{
"borderRadius": 9999,
},
- null,
],
]
}
@@ -4824,29 +4367,6 @@ exports[`renders FAB.Menu with items having icons 1`] = `
-
-
@@ -5272,7 +4768,6 @@ exports[`renders FAB.Menu with items having icons 1`] = `
{
"flex": 1,
},
- null,
],
]
}
@@ -5398,29 +4893,6 @@ exports[`renders FAB.Menu with items having icons 1`] = `
-
@@ -5566,7 +5038,6 @@ exports[`renders FAB.Menu with start alignment 1`] = `
{
"borderRadius": 9999,
},
- null,
],
]
}
@@ -5631,29 +5102,6 @@ exports[`renders FAB.Menu with start alignment 1`] = `
-
-
@@ -6049,7 +5473,6 @@ exports[`renders FAB.Menu with start alignment 1`] = `
{
"flex": 1,
},
- null,
],
]
}
@@ -6175,29 +5598,6 @@ exports[`renders FAB.Menu with start alignment 1`] = `
-
diff --git a/src/components/__tests__/__snapshots__/Switch.test.tsx.snap b/src/components/__tests__/__snapshots__/Switch.test.tsx.snap
index e38a5145e1..d94d99fffa 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,
]
}
>
@@ -189,29 +188,6 @@ exports[`Switch render renders disabled off 1`] = `
}
/>
-
`;
@@ -269,7 +245,6 @@ exports[`Switch render renders disabled on 1`] = `
"justifyContent": "center",
"width": 52,
},
- undefined,
]
}
>
@@ -384,29 +359,6 @@ exports[`Switch render renders disabled on 1`] = `
}
/>
-
`;
@@ -464,7 +416,6 @@ exports[`Switch render renders off 1`] = `
"justifyContent": "center",
"width": 52,
},
- undefined,
]
}
>
@@ -582,29 +533,6 @@ exports[`Switch render renders off 1`] = `
}
/>
-
`;
@@ -662,7 +590,6 @@ exports[`Switch render renders on 1`] = `
"justifyContent": "center",
"width": 52,
},
- undefined,
]
}
>
@@ -760,29 +687,6 @@ exports[`Switch render renders on 1`] = `
}
/>
-
`;
@@ -840,7 +744,6 @@ exports[`Switch render renders with checked icon 1`] = `
"justifyContent": "center",
"width": 52,
},
- undefined,
]
}
>
@@ -1009,29 +912,6 @@ exports[`Switch render renders with checked icon 1`] = `
-
`;
@@ -1089,7 +969,6 @@ exports[`Switch render renders with per-state icons 1`] = `
"justifyContent": "center",
"width": 52,
},
- undefined,
]
}
>
@@ -1258,28 +1137,5 @@ exports[`Switch render renders with per-state icons 1`] = `
-
`;
diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx
new file mode 100644
index 0000000000..80817b0281
--- /dev/null
+++ b/src/components/__tests__/focusRingWiring.test.tsx
@@ -0,0 +1,1045 @@
+/* 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 type { ReactElement } from 'react';
+import { Platform, processColor, StyleSheet, Text } 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 { 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';
+import AppbarBackAction from '../Appbar/AppbarBackAction';
+import AppbarContent from '../Appbar/AppbarContent';
+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';
+import DataTableCell from '../DataTable/DataTableCell';
+import DataTableRow from '../DataTable/DataTableRow';
+import DataTableTitle from '../DataTable/DataTableTitle';
+import DrawerCollapsedItem from '../Drawer/DrawerCollapsedItem';
+import DrawerItem from '../Drawer/DrawerItem';
+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 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';
+
+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', ownFocusEvent());
+ });
+};
+
+/**
+ * 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);
+ });
+
+ // 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(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.
+ it('BottomNavigation.Bar rings its tabs inward', async () => {
+ await render(
+ {}}
+ renderTouchable={({ key, route: _route, ...props }) => (
+
+ )}
+ />
+ );
+
+ await focusFirstFocusable();
+
+ 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', ownFocusEvent());
+ });
+
+ 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 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,
+ 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 () => {
+ await render(
+ {}} />
+ );
+
+ await focusFirstFocusable();
+
+ 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(
+
+
+
+ );
+
+ await focusFirstFocusable();
+
+ expect(ringOffset()).toBe(INWARD);
+ });
+
+ it("Menu.Item rings inward, inside the menu's scroll view", async () => {
+ await render(