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( {}} />); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(INWARD); + }); + + it('Button rings outward', async () => { + await render(); + + await focusFirstFocusable(); + + 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( + {}}> + cell + + ); + + await focusFirstFocusable(); + + 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); + }); + + 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. + it('DataTable.Title draws no ring when it is not pressable', async () => { + const onFocus = jest.fn(); + await render(title); + + await focusFirstFocusable(); + + expect(onFocus).toHaveBeenCalledTimes(1); + 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.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( + {}} + /> + ); + + const pressable = screen.getByRole('button'); + await act(async () => { + await fireEvent(pressable, 'focus', ownFocusEvent()); + }); + + 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 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 item above and below. Without a label the + // indicator is a circle as tall as the item, and a two-line label sets the + // item's height, so the ring reaches below the item in both cases. + it.each([ + ['with a label', 'Inbox'], + ['with a two-line label', 'Inbox and other mail'], + ['without a label', undefined], + ])( + 'Drawer.CollapsedItem %s clears the active indicator and the label', + async (_name, label) => { + 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: -(outerOffset + thickness), + }); + } + ); + + // 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( + {}} onFocus={onFocus} /> + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + 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('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( + {}}> + card + + ); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + }); + + // 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, padding: 12 }}> + card + + ); + + 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: 200, + padding: 12, + outlineOffset: 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. + // 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', ownFocusEvent()); + }); + + expect(ringOffset()).toBe(INWARD); + }); + + it('Switch rings outward on its track, not inside it', async () => { + await render( {}} />); + + await focusFirstFocusable(); + + expect(ringOffset()).toBe(OUTWARD); + }); +}); + +// 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([ + [ + 'Appbar.Action', + {}} + theme={theme} + />, + ], + [ + 'Appbar.BackAction', + {}} theme={theme} />, + ], + [ + 'IconButton', + {}} + theme={theme} + />, + ], + [ + 'TextInput.Icon', + {}} + style={undefined} + multiline={false} + disabled={false} + error={false} + theme={theme} + />, + ], + [ + 'Menu.Item', + {}} theme={theme} />, + ], + [ + 'Chip', + {}} theme={theme}> + chip + , + ], + [ + '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)'); + }); + + // An Appbar hands its theme to its back action, actions and title, in every + // mode, so their rings match the bar. + it.each(['small', 'center-aligned', 'medium', 'large'] as const)( + 'Appbar in %s mode rings its controls in its theme color', + async (mode) => { + await render( + + {}} /> + {}} /> + {}} /> + {}} /> + + ); + + const root = (screen as unknown as { root: Node }).root; + const focusables = walk( + root, + (n) => typeof n.props?.onFocus === 'function' + ); + expect(focusables).toHaveLength(4); + for (const node of focusables) { + await act(async () => { + await fireEvent(node as never, 'focus', ownFocusEvent()); + }); + } + + const rings = walk(root, (n) => style(n).outlineStyle === 'solid'); + expect(rings).toHaveLength(4); + expect(rings.map((n) => style(n).outlineColor)).toEqual( + Array(4).fill('rgb(255, 0, 0)') + ); + } + ); +}); + +// `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. +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 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, + 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 (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(() => { + Platform.OS = 'web'; + }); + afterEach(() => { + Platform.OS = original; + }); + + // The track is a child of the focused Pressable, so it can't be ringed with + // `:has()` (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'); + }); + + // 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( + {}} + /> + ); + + 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("Card marks its own box as the ring and leaves the Pressable's outline to the stylesheet", async () => { + await render( + {}} style={{ height: 200 }}> + card + + ); + + const pressable = screen.getByTestId('card'); + // 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( + 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( + + ); + + const button = screen.getByRole('button'); + // 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( + 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 own box as the ring, keeps the caller's dataSet and leaves the ripple's outline to the stylesheet", async () => { + await render( + {}} + style={{ height: 40 }} + {...{ dataSet: { qa: 'chip' } }} + > + chip + + ); + + const ripple = screen.getByTestId('chip'); + // 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( + 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={() => {}}> + 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({ + position: 'absolute', + borderRadius: 12 - outerOffset, + }); + }); +}); diff --git a/src/components/__tests__/focusRingWithinWeb.test.tsx b/src/components/__tests__/focusRingWithinWeb.test.tsx new file mode 100644 index 0000000000..6323d3de56 --- /dev/null +++ b/src/components/__tests__/focusRingWithinWeb.test.tsx @@ -0,0 +1,172 @@ +/* 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, StyleSheet, Text, TextInput } from 'react-native'; +import type { ViewStyle } from 'react-native'; + +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest, +} from '@jest/globals'; + +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'; + +// A bare import resolves to `.native` under the jest preset. Swap in the web +// TouchableRipple for every component in this file, so the structure checked +// here is the one the browser gets. +jest.mock('../TouchableRipple/TouchableRipple', () => + jest.requireActual('../TouchableRipple/TouchableRipple.tsx') +); + +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 withinRings = () => + walk( + (screen as unknown as { root: Node }).root, + (n) => + (n.props?.dataSet as Record | undefined) + ?.focusRingWithin !== undefined + ); + +// 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. The +// stylesheet also hides the browser's outline on that direct child. +describe('focus ring `within` structure (web)', () => { + const original = Platform.OS; + beforeEach(() => { + Platform.OS = 'web'; + }); + afterEach(() => { + Platform.OS = original; + }); + + it.each([ + [ + 'FAB', + {}} />, + ], + [ + 'Button', + , + ], + [ + 'Card', + {}}> + card + , + ], + [ + 'Chip', + {}}> + chip + , + ], + ])( + '%s holds its focusable element directly inside its ring', + async (_name, element) => { + await render(element); + + const rings = withinRings(); + expect(rings).toHaveLength(1); + 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'); + } + ); + + // 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' }) + ); + }); + + // 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')); + }); +}); 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__/focusRingContrast.test.ts b/src/utils/__tests__/focusRingContrast.test.ts new file mode 100644 index 0000000000..f7167b98e9 --- /dev/null +++ b/src/utils/__tests__/focusRingContrast.test.ts @@ -0,0 +1,71 @@ +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); + + 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)('a %s ring has 3:1 against %s', (ringRole, surfaceRole) => { + expect( + contrastRatio( + String(theme.colors[ringRole]), + String(theme.colors[surfaceRole]) + ) + ).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..2527b2bccf --- /dev/null +++ b/src/utils/__tests__/useFocusRing.test.tsx @@ -0,0 +1,376 @@ +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 { ownFocusEvent, render, screen } from '../../test-utils'; +import { tokens } from '../../theme/tokens'; +import type { FocusRingPlacement, FocusRingScope } from '../useFocusRing'; +import { + buildFocusRingStylesheet, + FocusRingColorContext, + mergeDataSetProps, + useFocusRing, +} from '../useFocusRing'; + +const focus = async (data: unknown = ownFocusEvent()) => { + 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 { target, ring } = useFocusRing(disabled, 'rebeccapurple'); + onRender?.(); + return ( + {}} + onFocus={target.onFocus} + onBlur={target.onBlur} + style={ring.style} + > + probe + + ); +}; + +describe('buildFocusRingStylesheet', () => { + const css = buildFocusRingStylesheet(); + + // `within` matches only a focused direct child, so a focused Button or + // TextInput inside a pressable Card doesn't light the Card's ring as well. + it('rings `self` via :focus-visible and `within` via a focused direct child, 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)' + ); + expect(css).not.toContain(':has(:focus-visible)'); + }); + + // `: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"]' + ); + }); + + // 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', () => { + const { thickness, outerOffset } = tokens.md.sys.state.focusIndicator; + + expect(css).toContain(`outline: ${thickness}px solid`); + expect(css).toContain(`outline-offset: ${outerOffset}px;`); + expect(css).toContain(`outline-offset: ${-thickness}px;`); + }); +}); + +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. + 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: thickness, + }); + + await focus(); + expect(screen.getByTestId('probe')).toHaveStyle({ + outlineWidth: thickness, + outlineColor: 'rebeccapurple', + outlineOffset: outerOffset, + }); + + await blur(); + expect(screen.getByTestId('probe')).not.toHaveStyle({ + outlineWidth: thickness, + }); + }); + + // 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, + }); + }); + + // `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, + }); + }); + + 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 () => { + await render(); + + await focus(); + + expect(screen.getByTestId('probe')).not.toHaveStyle({ + outlineWidth: thickness, + }); + }); + + // 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: thickness, + }); + + 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: 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 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', + }); + // 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 () => { + 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(); + + // eslint-disable-next-line no-restricted-syntax + 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(); + + // 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 new file mode 100644 index 0000000000..762f70e5cb --- /dev/null +++ b/src/utils/useFocusRing.ts @@ -0,0 +1,309 @@ +import * as React from 'react'; +import { + Platform, + type ColorValue, + type NativeSyntheticEvent, + type TargetedEvent, + type 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'; + +/** + * `'self'` - the ring is drawn on the element that receives focus. + * `'within'` - the ring is drawn on the parent of the element that receives + * focus (a clip view, a card's box), because the focusable element's own box + * is the wrong shape or size for it. The focusable element must be a direct + * child: on web, a focused element deeper inside (a Button in a Card) doesn't + * light the parent's ring. + * `'descendant'` - the ring is drawn on a child of the element that receives + * 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'; + +export type FocusRingResult = { + /** Spread onto the element that receives focus. */ + target: { + 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: { + 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 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 } } + : {}; +}; + +/** + * 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: {} }, +}; + +/** + * 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; + +/** + * MD3 keyboard focus indicator, from one hook shared by every component built + * on it. + * + * 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 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). 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 + * 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, + color: ColorValue, + placement: FocusRingPlacement = 'outward', + 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. + const [focused, setFocused] = React.useState(false); + + const onFocus = React.useCallback( + // 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 && e.target !== e.currentTarget)) { + return; + } + setFocused(!e || isKeyboardFocusEvent(e)); + }, + [suppressed] + ); + + const onBlur = React.useCallback(() => setFocused(false), []); + + // 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); + } + }, [suppressed]); + + const isNativeFocused = focused && !suppressed; + + return React.useMemo(() => { + if (suppressed) { + return EMPTY; + } + + if (Platform.OS === 'web') { + const dataKey = + scope === 'within' + ? 'focusRingWithin' + : scope === 'descendant' + ? 'focusRingDescendant' + : 'focusRing'; + return { + target: { + style: scope === 'descendant' ? [webNoOutlineStyle] : [], + dataSetProps: toDataSetProps( + scope === 'descendant' ? { focusRingTarget: 'true' } : undefined + ), + }, + 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']: ringColor } as unknown as ViewStyle, + ], + dataSetProps: toDataSetProps({ [dataKey]: placement }), + }, + }; + } + + return { + target: { onFocus, onBlur, style: [], dataSetProps: {} }, + ring: { + style: isNativeFocused + ? [ + { + outlineWidth: thickness, + outlineColor: ringColor, + outlineStyle: 'solid' as const, + outlineOffset: + placement === 'inward' ? -thickness : outerOffset, + }, + ] + : [], + dataSetProps: {}, + }, + }; + }, [ + suppressed, + scope, + ringColor, + placement, + isNativeFocused, + onFocus, + onBlur, + ]); +} + +const STYLE_ELEMENT_ATTR = 'data-rnp-focus-ring-styles'; + +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; +}`; + +/** + * The shared web stylesheet text, as a pure function of the design tokens - + * exported so its contents can be asserted without a DOM. + */ +export const buildFocusRingStylesheet = (): string => + [ + focusRingRule((p) => `[data-focus-ring="${p}"]:focus-visible`), + // A direct child only: a focused element nested deeper, such as a Button + // or a TextInput inside a Card, must not light the Card's ring too. + 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}"]` + ), + ].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(); +}