diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md
index e8e5ec373a..121105af66 100644
--- a/docs/6.x/docs/guides/migration.md
+++ b/docs/6.x/docs/guides/migration.md
@@ -394,7 +394,7 @@ On web, an `IconButton` or icon-only `FAB` labelled with `aria-label`, with no h
`hitSlop` applies only to a touchable that can be pressed. Without a handler, or with `disabled`, a touchable takes no touches outside its bounds, so it doesn't take them from its neighbors.
-`RadioButton`, `RadioButton.Android`, `RadioButton.IOS` and `RadioButton.Item` with no press handler and no `RadioButton.Group` no longer take the press. They stay read-only radios, a row around them gets the press, and on web they're no longer a tab stop.
+`RadioButton` and `RadioButton.Item` with no press handler and no `RadioButton.Group` no longer take the press. They stay read-only radios, a row around them gets the press, and on web they're no longer a tab stop.
To have something look and announce disabled, pass `disabled`, which keeps the control and its role. Pass it to switch interactivity off at runtime too, instead of removing `onPress`. A touchable renders another element whenever it goes between having a handler or `disabled` and having neither, so its children remount and lose their state and focus. That includes toggling `disabled` on a touchable with no handler. `FAB.Menu` does this for its trigger: a trigger without `onPress` is a disabled button while the menu is closed, so it keeps its element when the menu opens.
@@ -905,6 +905,28 @@ On web, a menu now closes on the Escape key when it is pressed down, instead of
On Android, an open menu now also keeps the back press: it calls `onDismiss`, and the screen behind no longer goes back. Previously the press reached that screen as well. Without an `onDismiss`, the menu leaves the press to whatever is underneath, so pass one to close the menu on back.
+### RadioButton
+
+`RadioButton` renders one Material 3 circular radio control on every platform. The platform-specific components and their prop types are gone. On iOS checked controls no longer render a checkmark; they use the same ring-and-dot indicator as other platforms. `RadioButton` now also forwards `TouchableRipple` props (`accessible`, `onFocus`, `onBlur`, `borderless`, `rippleColor`, ...).
+
+The control now occupies a 48×48dp layout box instead of 36×36dp, so rows containing it may become 12dp taller. The 20dp radio indicator is unchanged. `RadioButton.Item` rows grow from 52dp to 64dp.
+
+#### Interaction state colors
+
+Interaction states are now painted as a Material Design 3 state layer on every platform, so the tint follows the spec: hover & focus fill a flat 40dp layer behind the indicator with `primary` when checked and `onSurface` when not, and press inverts the two. An `error` radio stays on `error` throughout and `color`/`uncheckedColor` replace the role they already override on the ring, so custom radio no longer picks up `primary` halo. The platform ripple is turned off to make room for it; passing `rippleColor` on any platform, `background` on Android or `underlayColor` on iOS turns it back on and disables the built-in press. Setting `rippleEffectEnabled: false` on the `settings` prop of `PaperProvider` still suppresses both.
+
+| v5 | v6 |
+| ------------------------------------------------ | ------------------------------------------------------------------------ |
+| `RadioButton.Android`, `RadioButton.IOS` | `RadioButton` |
+| `RadioButtonAndroidProps`, `RadioButtonIOSProps` | `RadioButtonProps` |
+| `RadioButton.Item` `mode="android" \| "ios"` | `mode` removed; `RadioButton.Item` always renders `RadioButton` |
+| n/a | new `error` (uses `theme.colors.error`) and `style` (touch-target style) |
+
+```diff
+-
++
+```
+
### Searchbar
The misspelled `traileringIcon` props have been renamed:
diff --git a/docs/component-docs.config.ts b/docs/component-docs.config.ts
index 73ebb3b3b2..77c74769ff 100644
--- a/docs/component-docs.config.ts
+++ b/docs/component-docs.config.ts
@@ -120,9 +120,7 @@ const pages = {
ProgressBar: 'ProgressBar',
RadioButton: {
RadioButton: 'RadioButton/RadioButton',
- RadioButtonAndroid: 'RadioButton/RadioButtonAndroid',
RadioButtonGroup: 'RadioButton/RadioButtonGroup',
- RadioButtonIOS: 'RadioButton/RadioButtonIOS',
RadioButtonItem: 'RadioButton/RadioButtonItem',
},
Searchbar: 'Searchbar',
diff --git a/docs/src/data/screenshots.ts b/docs/src/data/screenshots.ts
index e18135fc49..2014d9ae2a 100644
--- a/docs/src/data/screenshots.ts
+++ b/docs/src/data/screenshots.ts
@@ -114,24 +114,11 @@ export const screenshots = {
Modal: 'screenshots/modal.gif',
ProgressBar: 'screenshots/progress-bar.png',
RadioButton: {
- 'Android (enabled)': 'screenshots/radio-enabled.android.png',
- 'Android (disabled)': 'screenshots/radio-disabled.android.png',
- 'iOS (enabled)': 'screenshots/radio-enabled.ios.png',
- 'iOS (disabled)': 'screenshots/radio-disabled.ios.png',
- },
- 'RadioButton.Android': {
enabled: 'screenshots/radio-enabled.android.png',
disabled: 'screenshots/radio-disabled.android.png',
},
- 'RadioButton.Group': {
- Android: 'screenshots/radio-button-group-android.gif',
- iOS: 'screenshots/radio-button-group-ios.gif',
- },
- 'RadioButton.IOS': {
- enabled: 'screenshots/radio-enabled.ios.png',
- disabled: 'screenshots/radio-disabled.ios.png',
- },
- 'RadioButton.Item': 'screenshots/radio-item.ios.png',
+ // The iOS radio assets show a checkmark that 6.x no longer draws.
+ 'RadioButton.Group': 'screenshots/radio-button-group-android.gif',
Searchbar: {
bar: 'screenshots/searchbar.png',
view: 'screenshots/searchbar-view.png',
diff --git a/example/src/Examples/RadioButtonExample.tsx b/example/src/Examples/RadioButtonExample.tsx
index 6ab1869dd9..c30e49e00f 100644
--- a/example/src/Examples/RadioButtonExample.tsx
+++ b/example/src/Examples/RadioButtonExample.tsx
@@ -10,7 +10,7 @@ import {
import ScreenWrapper from '../ScreenWrapper';
-type State = 'normal' | 'normal-ios' | 'normal-item' | 'custom';
+type State = 'normal' | 'normal-item' | 'custom';
const RadioButtonExample = () => {
const [checked, setChecked] = React.useState('normal');
@@ -19,26 +19,15 @@ const RadioButtonExample = () => {
setChecked('normal')}>
- Normal - Material Design
+ Normal
-
- setChecked('normal-ios')}>
-
- Normal 2 - IOS
-
-
-
-
-
setChecked('custom')}>
Custom
@@ -58,11 +47,31 @@ const RadioButtonExample = () => {
onPress={() => setChecked('normal-item')}
/>
- Checked (Disabled)
+ Error (Checked)
+
+
+
+ Error (Unchecked)
+
+
+
+
+
+ Checked (Disabled)
- Unchecked (Disabled)
+ Unchecked (Disabled)
{
Second
-
+
Third
-
+
diff --git a/example/src/Examples/RadioButtonItemExample.tsx b/example/src/Examples/RadioButtonItemExample.tsx
index e640a1dd0a..efd4eee32a 100644
--- a/example/src/Examples/RadioButtonItemExample.tsx
+++ b/example/src/Examples/RadioButtonItemExample.tsx
@@ -7,55 +7,47 @@ import ScreenWrapper from '../ScreenWrapper';
const RadioButtonItemExample = () => {
const [checkedDefault, setCheckedDefault] = React.useState(true);
- const [checkedAndroid, setCheckedAndroid] = React.useState(true);
- const [checkedIOS, setCheckedIOS] = React.useState(true);
const [checkedLeadingControl, setCheckedLeadingControl] =
React.useState(true);
const [checkedDisabled, setCheckedDisabled] = React.useState(true);
+ const [checkedError, setCheckedError] = React.useState(true);
const [checkedLabelVariant, setCheckedLabelVariant] = React.useState(true);
return (
setCheckedDefault(!checkedDefault)}
value="default"
/>
setCheckedAndroid(!checkedAndroid)}
- value="android"
- />
- setCheckedIOS(!checkedIOS)}
- value="iOS"
- />
- setCheckedLeadingControl(!checkedLeadingControl)}
- value="iOS"
+ value="leading"
position="leading"
/>
setCheckedError(!checkedError)}
+ value="error"
+ error
+ />
+ setCheckedDisabled(!checkedDisabled)}
- value="iOS"
+ value="disabled"
disabled
/>
setCheckedLabelVariant(!checkedLabelVariant)}
- value="default"
+ value="variant"
/>
);
diff --git a/src/components/RadioButton/RadioButton.tsx b/src/components/RadioButton/RadioButton.tsx
index 4f114b1bca..c89962f2ec 100644
--- a/src/components/RadioButton/RadioButton.tsx
+++ b/src/components/RadioButton/RadioButton.tsx
@@ -1,12 +1,39 @@
-import { Platform } from 'react-native';
-import type { GestureResponderEvent } from 'react-native';
+import * as React from 'react';
+import { Platform, StyleSheet, View } from 'react-native';
+import type {
+ GestureResponderEvent,
+ MouseEvent,
+ NativeSyntheticEvent,
+ TargetedEvent,
+ ViewStyle,
+} from 'react-native';
-import RadioButtonAndroid from './RadioButtonAndroid';
-import RadioButtonIOS from './RadioButtonIOS';
+import Animated, { cubicBezier, type CSSStyle } from 'react-native-reanimated';
+
+import { RadioButtonContext } from './RadioButtonGroup';
+import { RadioButtonTokens } from './tokens';
+import {
+ getSelectionControlColor,
+ getSelectionStateLayer,
+ handlePress,
+ isChecked,
+ getInteraction,
+} from './utils';
+import { SettingsContext } from '../../core/settings';
import { useInternalTheme } from '../../core/theming';
+import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext';
import type { ThemeProp } from '../../theme/types';
+import hasTouchHandler from '../../utils/hasTouchHandler';
+import { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent';
+import { useSpaceKeyPress } from '../../utils/useSpaceKeyPress';
+import type { PressableStateCallbackType } from '../TouchableRipple/Pressable';
+import TouchableRipple from '../TouchableRipple/TouchableRipple';
+import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple';
-export type Props = {
+export type Props = Omit<
+ React.PropsWithoutRef,
+ 'children'
+> & {
/**
* Value of the radio button
*/
@@ -33,6 +60,12 @@ export type Props = {
* Custom color for radio.
*/
color?: string;
+ /**
+ * Whether the radio button is in an error state. When true, the ring
+ * (unchecked) and dot (selected) use `theme.colors.error`. `disabled`
+ * and explicit `color`/`uncheckedColor` overrides take precedence.
+ */
+ error?: boolean;
/**
* @optional
*/
@@ -43,6 +76,14 @@ export type Props = {
testID?: string;
};
+const {
+ ringSize,
+ dotSize,
+ outlineWidth: OUTLINE_WIDTH,
+ stateLayerSize,
+ touchTargetSize,
+} = RadioButtonTokens;
+
/**
* Radio buttons allow the selection a single option from a set.
*
@@ -73,16 +114,304 @@ export type Props = {
*
* export default MyComponent;
* ```
+ *
+ * @extends TouchableRipple props https://callstack.github.io/react-native-paper/docs/components/TouchableRipple
*/
-const RadioButton = ({ theme: themeOverrides, ...props }: Props) => {
+const RadioButton = ({
+ disabled,
+ onPress,
+ theme: themeOverrides,
+ value,
+ status,
+ testID,
+ error,
+ color,
+ uncheckedColor,
+ onFocus,
+ onBlur,
+ onHoverIn,
+ onHoverOut,
+ onPressIn,
+ onPressOut,
+ rippleColor,
+ background,
+ underlayColor,
+ ...rest
+}: Props) => {
const theme = useInternalTheme(themeOverrides);
+ const context = React.useContext(RadioButtonContext);
+ const { rippleEffectEnabled } = React.useContext(SettingsContext);
+
+ const checked =
+ isChecked({
+ contextValue: context?.value,
+ status,
+ value,
+ }) === 'checked';
+
+ const reduceMotion = useReduceMotion();
+
+ const [focused, setFocused] = React.useState(false);
+ const [hovered, setHovered] = React.useState(false);
+ const [pressed, setPressed] = React.useState(false);
+
+ const { selectionControlColor, selectionControlOpacity } =
+ getSelectionControlColor({
+ theme,
+ disabled,
+ checked,
+ error,
+ customColor: color,
+ customUncheckedColor: uncheckedColor,
+ });
+
+ const dotStyle: CSSStyle = {
+ backgroundColor: selectionControlColor,
+ transform: [{ scale: checked ? 1 : 0 }],
+ transitionProperty: 'transform',
+ transitionDuration: reduceMotion ? 0 : theme.motion.duration.short3,
+ transitionTimingFunction: cubicBezier(...theme.motion.easing.standard),
+ };
+
+ const platformOwnsPress =
+ rippleColor != null ||
+ (Platform.OS === 'android' && background != null) ||
+ (Platform.OS === 'ios' && underlayColor != null);
+
+ // Without `onPress` and a `RadioButton.Group` there is nothing to select.
+ const isPressable = Boolean(onPress || context?.onValueChange);
+ // A handler-less radio would claim the touch and do nothing with it, so the
+ // press handlers stay off unless there is something to call.
+ const hasHandler =
+ isPressable ||
+ hasTouchHandler({ onLongPress: rest.onLongPress, onPressIn, onPressOut });
+ const isInteractive = !disabled && hasHandler;
+
+ const ownsPress =
+ isInteractive && !platformOwnsPress && Boolean(rippleEffectEnabled);
+
+ const platformPressProps = {
+ background,
+ underlayColor,
+ rippleColor: platformOwnsPress ? rippleColor : 'transparent',
+ };
+
+ // A read-only or disabled radio can't be pressed, so it shows no state.
+ const interaction = isInteractive
+ ? getInteraction({
+ pressed: pressed && ownsPress,
+ focused,
+ hovered,
+ })
+ : null;
- const Button = Platform.select({
- default: RadioButtonAndroid,
- ios: RadioButtonIOS,
+ const stateLayerProps = {
+ theme,
+ checked,
+ disabled,
+ error,
+ customColor: color,
+ customUncheckedColor: uncheckedColor,
+ };
+
+ const stateLayer = getSelectionStateLayer({
+ ...stateLayerProps,
+ interaction,
});
- return ;
+ const stateLayerColor = getSelectionStateLayer({
+ ...stateLayerProps,
+ interaction: interaction ?? 'hovered',
+ }).color;
+
+ const stateLayerStyle: CSSStyle = {
+ backgroundColor: stateLayerColor,
+ opacity: stateLayer.opacity,
+ transitionProperty: 'opacity',
+ transitionDuration: reduceMotion ? 0 : theme.motion.duration.short2,
+ transitionTimingFunction: cubicBezier(...theme.motion.easing.standard),
+ };
+
+ const handleFocus = React.useCallback(
+ (e: NativeSyntheticEvent) => {
+ if (!disabled && isKeyboardFocusEvent(e)) {
+ setFocused(true);
+ }
+ onFocus?.(e);
+ },
+ [disabled, onFocus]
+ );
+
+ const handleHoverIn = React.useCallback(
+ (e: MouseEvent) => {
+ setHovered(true);
+ onHoverIn?.(e);
+ },
+ [onHoverIn]
+ );
+
+ const handleHoverOut = React.useCallback(
+ (e: MouseEvent) => {
+ setHovered(false);
+ onHoverOut?.(e);
+ },
+ [onHoverOut]
+ );
+
+ const handlePressIn = React.useCallback(
+ (e: GestureResponderEvent) => {
+ if (ownsPress) {
+ setPressed(true);
+ }
+ onPressIn?.(e);
+ },
+ [onPressIn, ownsPress]
+ );
+
+ const handlePressOut = React.useCallback(
+ (e: GestureResponderEvent) => {
+ setPressed(false);
+ onPressOut?.(e);
+ },
+ [onPressOut]
+ );
+
+ const handleRadioPress = isPressable
+ ? (event: GestureResponderEvent) => {
+ handlePress({
+ onPress,
+ onValueChange: context?.onValueChange,
+ value,
+ event,
+ });
+ }
+ : undefined;
+
+ // React Native Web presses on Space only for `role="button"`, so the radio
+ // handles Space itself.
+ const { keyHandlers: spaceKeyHandlers, onBlur: handleSpaceKeyBlur } =
+ useSpaceKeyPress({
+ onPress: disabled ? undefined : handleRadioPress,
+ onPressIn: handlePressIn,
+ onPressOut: handlePressOut,
+ });
+
+ const handleBlur = React.useCallback(
+ (e: NativeSyntheticEvent) => {
+ setFocused(false);
+ handleSpaceKeyBlur(e);
+ onBlur?.(e);
+ },
+ [handleSpaceKeyBlur, onBlur]
+ );
+
+ // When `accessible={false}` is passed (typically by `RadioButton.Item`,
+ // which owns the a11y tree for the wrapped row), suppress our own role and
+ // state so the same logical control doesn't expose two `checked` states to
+ // assistive tech.
+ const accessibilityProps =
+ rest.accessible === false
+ ? {}
+ : {
+ role: 'radio' as const,
+ 'aria-disabled': !!disabled,
+ 'aria-checked': checked,
+ // Announces a `status` change that comes from outside the radio,
+ // such as a `RadioButton.Group` value set elsewhere.
+ 'aria-live': 'polite' as const,
+ };
+
+ const { style: restStyle, ...restProps } = rest;
+ const combinedStyle =
+ typeof restStyle === 'function'
+ ? (state: PressableStateCallbackType) => [
+ styles.container,
+ restStyle(state),
+ ]
+ : [styles.container, restStyle];
+
+ return (
+
+
+
+
+
+
+
+
+ );
};
+RadioButton.displayName = 'RadioButton';
+
+const styles = StyleSheet.create({
+ container: {
+ width: touchTargetSize,
+ height: touchTargetSize,
+ borderRadius: touchTargetSize / 2,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ stateLayer: {
+ width: stateLayerSize,
+ height: stateLayerSize,
+ borderRadius: stateLayerSize / 2,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ stateLayerFill: {
+ position: 'absolute',
+ width: stateLayerSize,
+ height: stateLayerSize,
+ borderRadius: stateLayerSize / 2,
+ },
+ radio: {
+ height: ringSize,
+ width: ringSize,
+ borderRadius: ringSize / 2,
+ borderWidth: OUTLINE_WIDTH,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ dot: {
+ height: dotSize,
+ width: dotSize,
+ borderRadius: dotSize / 2,
+ },
+});
+
export default RadioButton;
diff --git a/src/components/RadioButton/RadioButtonAndroid.tsx b/src/components/RadioButton/RadioButtonAndroid.tsx
deleted file mode 100644
index b840d9ac3f..0000000000
--- a/src/components/RadioButton/RadioButtonAndroid.tsx
+++ /dev/null
@@ -1,215 +0,0 @@
-import * as React from 'react';
-// eslint-disable-next-line no-restricted-imports -- TODO: migrate RadioButtonAndroid to Reanimated.
-import { Animated, StyleSheet, View } from 'react-native';
-
-import { RadioButtonContext } from './RadioButtonGroup';
-import type { RadioButtonContextType } from './RadioButtonGroup';
-import { getSelectionControlColor, handlePress, isChecked } from './utils';
-import { useInternalTheme } from '../../core/theming';
-import { useMotionDuration } from '../../theme/accessibility/ReduceMotionContext';
-import type { ThemeProp } from '../../theme/types';
-import TouchableRipple from '../TouchableRipple/TouchableRipple';
-import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple';
-
-export type Props = Omit<
- React.PropsWithoutRef,
- 'children'
-> & {
- /**
- * Value of the radio button
- */
- value: string;
- /**
- * Status of radio button.
- */
- status?: 'checked' | 'unchecked';
- /**
- * Whether radio is disabled.
- */
- disabled?: boolean;
- /**
- * Function to execute on press. Without it, and outside a
- * `RadioButton.Group`, the radio is read only: it can't be pressed, and a
- * press goes to its parent.
- */
- onPress?: (param?: any) => void;
- /**
- * Custom color for unchecked radio.
- */
- uncheckedColor?: string;
- /**
- * Custom color for radio.
- */
- color?: string;
- /**
- * @optional
- */
- theme?: ThemeProp;
- /**
- * testID to be used on tests.
- */
- testID?: string;
-};
-
-const BORDER_WIDTH = 2;
-
-/**
- * Radio buttons allow the selection a single option from a set.
- * This component follows platform guidelines for Android, but can be used
- * on any platform.
- *
- * @extends TouchableRipple props https://callstack.github.io/react-native-paper/docs/components/TouchableRipple
- */
-const RadioButtonAndroid = ({
- disabled,
- onPress,
- theme: themeOverrides,
- value,
- status,
- testID,
- ...rest
-}: Props) => {
- const theme = useInternalTheme(themeOverrides);
- const { current: borderAnim } = React.useRef(
- new Animated.Value(BORDER_WIDTH)
- );
-
- const { current: radioAnim } = React.useRef(
- new Animated.Value(1)
- );
-
- const isFirstRendering = React.useRef(true);
-
- const getDuration = useMotionDuration();
-
- React.useEffect(() => {
- // Do not run animation on very first rendering
- if (isFirstRendering.current) {
- isFirstRendering.current = false;
- return;
- }
-
- if (status === 'checked') {
- radioAnim.setValue(1.2);
-
- Animated.timing(radioAnim, {
- toValue: 1,
- duration: getDuration(150),
- useNativeDriver: true,
- }).start();
- } else {
- borderAnim.setValue(10);
-
- Animated.timing(borderAnim, {
- toValue: BORDER_WIDTH,
- duration: getDuration(150),
- useNativeDriver: false,
- }).start();
- }
- }, [status, borderAnim, radioAnim, getDuration]);
-
- return (
-
- {(context: RadioButtonContextType | null) => {
- const checked =
- isChecked({
- contextValue: context?.value,
- status,
- value,
- }) === 'checked';
-
- const { selectionControlColor } = getSelectionControlColor({
- theme,
- disabled,
- checked,
- customColor: rest.color,
- customUncheckedColor: rest.uncheckedColor,
- });
-
- return (
- {
- handlePress({
- onPress,
- onValueChange: context?.onValueChange,
- value,
- event,
- });
- }
- : undefined
- }
- disabled={disabled}
- role="radio"
- aria-disabled={disabled}
- aria-checked={checked}
- aria-live="polite"
- style={styles.container}
- testID={testID}
- theme={theme}
- >
-
- {checked ? (
-
-
-
- ) : null}
-
-
- );
- }}
-
- );
-};
-
-RadioButtonAndroid.displayName = 'RadioButton.Android';
-
-const styles = StyleSheet.create({
- container: {
- borderRadius: 18,
- },
- radioContainer: {
- alignItems: 'center',
- justifyContent: 'center',
- },
- radio: {
- height: 20,
- width: 20,
- borderRadius: 10,
- margin: 8,
- },
- dot: {
- height: 10,
- width: 10,
- borderRadius: 5,
- },
-});
-
-export default RadioButtonAndroid;
-
-// @component-docs ignore-next-line
-export { RadioButtonAndroid };
diff --git a/src/components/RadioButton/RadioButtonGroup.tsx b/src/components/RadioButton/RadioButtonGroup.tsx
index ef76cd30aa..c413ff0a05 100644
--- a/src/components/RadioButton/RadioButtonGroup.tsx
+++ b/src/components/RadioButton/RadioButtonGroup.tsx
@@ -1,6 +1,8 @@
import * as React from 'react';
import { View } from 'react-native';
+import useLatestCallback from 'use-latest-callback';
+
export type Props = {
/**
* Function to execute on selection change.
@@ -53,11 +55,21 @@ export const RadioButtonContext =
* export default MyComponent;
*```
*/
-const RadioButtonGroup = ({ value, onValueChange, children }: Props) => (
-
- {children}
-
-);
+const RadioButtonGroup = ({ value, onValueChange, children }: Props) => {
+ // Stabilize the callback so the memoized context value only changes when
+ // `value` changes — not on every parent render.
+ const stableOnValueChange = useLatestCallback(onValueChange);
+ const context = React.useMemo(
+ () => ({ value, onValueChange: stableOnValueChange }),
+ [value, stableOnValueChange]
+ );
+
+ return (
+
+ {children}
+
+ );
+};
RadioButtonGroup.displayName = 'RadioButton.Group';
export default RadioButtonGroup;
diff --git a/src/components/RadioButton/RadioButtonIOS.tsx b/src/components/RadioButton/RadioButtonIOS.tsx
deleted file mode 100644
index 9a2a9dfec7..0000000000
--- a/src/components/RadioButton/RadioButtonIOS.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import type * as React from 'react';
-import { StyleSheet, View } from 'react-native';
-import type { GestureResponderEvent } from 'react-native';
-
-import { RadioButtonContext } from './RadioButtonGroup';
-import type { RadioButtonContextType } from './RadioButtonGroup';
-import { handlePress, isChecked } from './utils';
-import { getSelectionControlIOSColor } from './utils';
-import { useInternalTheme } from '../../core/theming';
-import type { ThemeProp } from '../../theme/types';
-import MaterialCommunityIcon from '../MaterialCommunityIcon';
-import TouchableRipple from '../TouchableRipple/TouchableRipple';
-import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple';
-
-export type Props = Omit<
- React.PropsWithoutRef,
- 'children'
-> & {
- /**
- * Value of the radio button
- */
- value: string;
- /**
- * Status of radio button.
- */
- status?: 'checked' | 'unchecked';
- /**
- * Whether radio is disabled.
- */
- disabled?: boolean;
- /**
- * Function to execute on press. Without it, and outside a
- * `RadioButton.Group`, the radio is read only: it can't be pressed, and a
- * press goes to its parent.
- */
- onPress?: (e: GestureResponderEvent) => void;
- /**
- * Custom color for radio.
- */
- color?: string;
- /**
- * @optional
- */
- theme?: ThemeProp;
- /**
- * testID to be used on tests.
- */
- testID?: string;
-};
-
-/**
- * Radio buttons allow the selection a single option from a set.
- * This component follows platform guidelines for iOS, but can be used
- * on any platform.
- *
- * @extends TouchableRipple props https://callstack.github.io/react-native-paper/docs/components/TouchableRipple
- */
-const RadioButtonIOS = ({
- disabled,
- onPress,
- theme: themeOverrides,
- status,
- value,
- testID,
- ...rest
-}: Props) => {
- const theme = useInternalTheme(themeOverrides);
-
- return (
-
- {(context: RadioButtonContextType | null) => {
- const checked =
- isChecked({
- contextValue: context?.value,
- status,
- value,
- }) === 'checked';
-
- const { checkedColor } = getSelectionControlIOSColor({
- theme,
- disabled,
- customColor: rest.color,
- });
- const opacity = checked ? 1 : 0;
-
- return (
- {
- handlePress({
- onPress,
- value,
- onValueChange: context?.onValueChange,
- event,
- });
- }
- : undefined
- }
- disabled={disabled}
- role="radio"
- aria-disabled={disabled}
- aria-checked={checked}
- aria-live="polite"
- style={styles.container}
- testID={testID}
- theme={theme}
- >
-
-
-
-
- );
- }}
-
- );
-};
-
-RadioButtonIOS.displayName = 'RadioButton.IOS';
-
-const styles = StyleSheet.create({
- container: {
- borderRadius: 18,
- padding: 6,
- },
-});
-
-export default RadioButtonIOS;
-
-// @component-docs ignore-next-line
-export { RadioButtonIOS };
diff --git a/src/components/RadioButton/RadioButtonItem.tsx b/src/components/RadioButton/RadioButtonItem.tsx
index f99def9b96..f5e81ca065 100644
--- a/src/components/RadioButton/RadioButtonItem.tsx
+++ b/src/components/RadioButton/RadioButtonItem.tsx
@@ -9,15 +9,13 @@ import type {
} from 'react-native';
import RadioButton from './RadioButton';
-import RadioButtonAndroid from './RadioButtonAndroid';
import { RadioButtonContext } from './RadioButtonGroup';
-import type { RadioButtonContextType } from './RadioButtonGroup';
-import RadioButtonIOS from './RadioButtonIOS';
import { handlePress, isChecked } from './utils';
import { useInternalTheme } from '../../core/theming';
import type { ThemeProp, TypescaleKey } from '../../theme/types';
import { getStateLayer } from '../../theme/utils/state';
import { useFocusRing } from '../../utils/useFocusRing';
+import { useSpaceKeyPress } from '../../utils/useSpaceKeyPress';
import TouchableRipple from '../TouchableRipple/TouchableRipple';
import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple';
import Text from '../Typography/Text';
@@ -66,6 +64,11 @@ export type Props = {
* Status of radio button.
*/
status?: 'checked' | 'unchecked';
+ /**
+ * Whether the radio button is in an error state. When true, the control
+ * uses `theme.colors.error`.
+ */
+ error?: boolean;
/**
* Additional styles for container View.
*/
@@ -103,11 +106,6 @@ export type Props = {
* testID to be used on tests.
*/
testID?: string;
- /**
- * Whether `` or `` should be used.
- * Left undefined `` will be used.
- */
- mode?: 'android' | 'ios';
/**
* Radio button control position.
*/
@@ -151,17 +149,18 @@ const RadioButtonItem = ({
color,
uncheckedColor,
status,
+ error,
theme: themeOverrides,
background,
'aria-label': ariaLabel = label,
testID,
- mode,
position = 'trailing',
labelVariant = 'bodyLarge',
- labelMaxFontSizeMultiplier,
+ labelMaxFontSizeMultiplier = 1.5,
hitSlop,
}: Props) => {
const theme = useInternalTheme(themeOverrides);
+ const context = React.useContext(RadioButtonContext);
const radioButtonProps = {
value,
disabled,
@@ -169,17 +168,20 @@ const RadioButtonItem = ({
color,
theme,
uncheckedColor,
+ error,
};
const isLeading = position === 'leading';
- let radioButton: any;
-
- if (mode === 'android') {
- radioButton = ;
- } else if (mode === 'ios') {
- radioButton = ;
- } else {
- radioButton = ;
- }
+ // The outer TouchableRipple is the interactable element + a11y radio; the
+ // inner control is purely visual, so exclude it from the a11y tree to
+ // avoid duplicate `checked` states.
+ const radioButton = (
+
+ );
const textAlign = isLeading ? 'right' : 'left';
@@ -188,83 +190,88 @@ const RadioButtonItem = ({
textAlign,
};
+ const checked =
+ isChecked({
+ contextValue: context?.value,
+ status,
+ value,
+ }) === 'checked';
+
// Rows stack edge to edge, so the ring is inward. It 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.
- // The hook needs the group above the consumer below.
- const group = React.useContext(RadioButtonContext);
const { target: focusTarget, ring: focusRing } = useFocusRing(
- disabled || !(onPress || group?.onValueChange || onLongPress),
+ disabled || !(onPress || context?.onValueChange || onLongPress),
theme.colors.secondary,
'inward',
'descendant'
);
- return (
-
- {(context: RadioButtonContextType | null) => {
- const checked =
- isChecked({
- contextValue: context?.value,
- status,
+ const handleRowPress =
+ onPress || context?.onValueChange
+ ? (event: GestureResponderEvent) =>
+ handlePress({
+ onPress,
+ onValueChange: context?.onValueChange,
value,
- }) === 'checked';
- return (
-
- handlePress({
- onPress: onPress,
- onValueChange: context?.onValueChange,
- value,
- event,
- })
- : undefined
- }
- onLongPress={onLongPress}
- aria-label={ariaLabel}
- role="radio"
- aria-checked={checked}
- aria-disabled={disabled}
- testID={testID}
- disabled={disabled}
- background={background}
- theme={theme}
- hitSlop={hitSlop}
- >
-
- {isLeading && radioButton}
-
- {label}
-
- {!isLeading && radioButton}
-
-
-
- );
+ event,
+ })
+ : undefined;
+
+ // The row is the focusable radio, so it takes the Space key itself.
+ const { keyHandlers: spaceKeyHandlers, onBlur: handleSpaceKeyBlur } =
+ useSpaceKeyPress({ onPress: disabled ? undefined : handleRowPress });
+
+ return (
+ {
+ handleSpaceKeyBlur(e);
+ focusTarget.onBlur?.();
}}
-
+ {...spaceKeyHandlers}
+ {...focusTarget.dataSetProps}
+ style={focusTarget.style}
+ // A row with nothing to call (no `onPress` and no `RadioButton.Group`)
+ // is read only and gets no handler, so it never takes a press meant for
+ // its parent. A live row is turned off with `disabled`, which keeps the
+ // same element instead of remounting it.
+ onPress={handleRowPress}
+ onLongPress={onLongPress}
+ aria-label={ariaLabel}
+ role="radio"
+ aria-checked={checked}
+ aria-disabled={disabled}
+ testID={testID}
+ disabled={disabled}
+ background={background}
+ theme={theme}
+ hitSlop={hitSlop}
+ >
+
+ {isLeading && radioButton}
+
+ {label}
+
+ {!isLeading && radioButton}
+
+
+
);
};
diff --git a/src/components/RadioButton/index.ts b/src/components/RadioButton/index.ts
index 6ba5b8b873..7373ad4328 100644
--- a/src/components/RadioButton/index.ts
+++ b/src/components/RadioButton/index.ts
@@ -1,7 +1,5 @@
import RadioButtonComponent from './RadioButton';
-import RadioButtonAndroid from './RadioButtonAndroid';
import RadioButtonGroup from './RadioButtonGroup';
-import RadioButtonIOS from './RadioButtonIOS';
import RadioButtonItem from './RadioButtonItem';
const RadioButton = Object.assign(
@@ -10,10 +8,6 @@ const RadioButton = Object.assign(
{
// @component ./RadioButtonGroup.tsx
Group: RadioButtonGroup,
- // @component ./RadioButtonAndroid.tsx
- Android: RadioButtonAndroid,
- // @component ./RadioButtonIOS.tsx
- IOS: RadioButtonIOS,
// @component ./RadioButtonItem.tsx
Item: RadioButtonItem,
}
diff --git a/src/components/RadioButton/tokens.ts b/src/components/RadioButton/tokens.ts
new file mode 100644
index 0000000000..876bab8692
--- /dev/null
+++ b/src/components/RadioButton/tokens.ts
@@ -0,0 +1,30 @@
+import type { ColorRole } from '../../theme/types';
+
+/**
+ * MD3 Radio button spec dimensions and color-role tokens.
+ * @see https://m3.material.io/components/radio-button/specs
+ */
+const sizes = {
+ ringSize: 20,
+ dotSize: 10,
+ outlineWidth: 2,
+ stateLayerSize: 40,
+ touchTargetSize: 48,
+} as const;
+
+const colors = {
+ checkedColor: 'primary',
+ uncheckedColor: 'onSurfaceVariant',
+ disabledColor: 'onSurface',
+ errorColor: 'error',
+ // hover & focus tint by selection; pressing inverts it
+ checkedHoverStateLayerColor: 'primary',
+ checkedFocusStateLayerColor: 'primary',
+ checkedPressedStateLayerColor: 'onSurface',
+ uncheckedHoverStateLayerColor: 'onSurface',
+ uncheckedFocusStateLayerColor: 'onSurface',
+ uncheckedPressedStateLayerColor: 'primary',
+ errorStateLayerColor: 'error',
+} as const satisfies Record;
+
+export const RadioButtonTokens = { ...sizes, ...colors };
diff --git a/src/components/RadioButton/utils.ts b/src/components/RadioButton/utils.ts
index 55fa981840..b0abcc2b33 100644
--- a/src/components/RadioButton/utils.ts
+++ b/src/components/RadioButton/utils.ts
@@ -1,7 +1,9 @@
import type { ColorValue, GestureResponderEvent } from 'react-native';
+import { RadioButtonTokens } from './tokens';
import { tokens } from '../../theme/tokens';
-import type { InternalTheme } from '../../theme/types';
+import type { ColorRole, InternalTheme, StateLayer } from '../../theme/types';
+import { getStateLayer } from '../../theme/utils/state';
const stateOpacity = tokens.md.sys.state.opacity;
@@ -41,59 +43,6 @@ export const isChecked = ({
}
};
-const getIOSCheckedColor = ({
- theme,
- disabled,
- customColor,
- error,
-}: {
- theme: InternalTheme;
- customColor?: ColorValue;
- disabled?: boolean;
- error?: boolean;
-}) => {
- if (disabled) {
- return theme.colors.primary;
- }
-
- if (customColor) {
- return customColor;
- }
-
- if (error) {
- return theme.colors.error;
- }
-
- return theme.colors.primary;
-};
-
-export const getSelectionControlIOSColor = ({
- theme,
- disabled,
- customColor,
- error,
-}: {
- theme: InternalTheme;
- disabled?: boolean;
- customColor?: ColorValue;
- error?: boolean;
-}): { checkedColor: ColorValue; checkedColorOpacity: number } => {
- const checkedColor = getIOSCheckedColor({
- theme,
- disabled,
- customColor,
- error,
- });
- const checkedColorOpacity = disabled
- ? stateOpacity.disabled
- : stateOpacity.enabled;
-
- return {
- checkedColor,
- checkedColorOpacity,
- };
-};
-
export const getSelectionControlColor = ({
theme,
disabled,
@@ -113,17 +62,96 @@ export const getSelectionControlColor = ({
const checkedColor = customColor
? customColor
: error
- ? theme.colors.error
- : theme.colors.primary;
+ ? theme.colors[RadioButtonTokens.errorColor]
+ : theme.colors[RadioButtonTokens.checkedColor];
const uncheckedColor = customUncheckedColor
? customUncheckedColor
: error
- ? theme.colors.error
- : theme.colors.onSurfaceVariant;
+ ? theme.colors[RadioButtonTokens.errorColor]
+ : theme.colors[RadioButtonTokens.uncheckedColor];
const color = disabled
- ? theme.colors.onSurface
+ ? theme.colors[RadioButtonTokens.disabledColor]
: checked
? checkedColor
: uncheckedColor;
return { selectionControlColor: color, selectionControlOpacity: opacity };
};
+
+export type RadioButtonInteraction = 'hovered' | 'focused' | 'pressed';
+
+const stateLayerRoles: Record<
+ RadioButtonInteraction,
+ Record<'checked' | 'unchecked', ColorRole>
+> = {
+ hovered: {
+ checked: RadioButtonTokens.checkedHoverStateLayerColor,
+ unchecked: RadioButtonTokens.uncheckedHoverStateLayerColor,
+ },
+ focused: {
+ checked: RadioButtonTokens.checkedFocusStateLayerColor,
+ unchecked: RadioButtonTokens.uncheckedFocusStateLayerColor,
+ },
+ pressed: {
+ checked: RadioButtonTokens.checkedPressedStateLayerColor,
+ unchecked: RadioButtonTokens.uncheckedPressedStateLayerColor,
+ },
+};
+
+export const getInteraction = ({
+ pressed,
+ focused,
+ hovered,
+}: {
+ pressed: boolean;
+ focused: boolean;
+ hovered: boolean;
+}): RadioButtonInteraction | null => {
+ if (pressed) return 'pressed';
+ if (focused) return 'focused';
+ if (hovered) return 'hovered';
+ return null;
+};
+
+export const getSelectionStateLayer = ({
+ theme,
+ checked,
+ disabled,
+ error,
+ interaction,
+ customColor,
+ customUncheckedColor,
+}: {
+ theme: InternalTheme;
+ checked: boolean;
+ disabled?: boolean;
+ error?: boolean;
+ interaction: RadioButtonInteraction | null;
+ customColor?: ColorValue;
+ customUncheckedColor?: ColorValue;
+}): StateLayer => {
+ if (interaction === null || disabled) {
+ return { color: 'transparent', opacity: 0 };
+ }
+
+ // press previews the state being moved to, so the layer takes the opposite selection's color
+ const followsChecked = interaction === 'pressed' ? !checked : checked;
+ const custom = followsChecked ? customColor : customUncheckedColor;
+
+ if (custom) {
+ return { color: custom, opacity: stateOpacity[interaction] };
+ }
+
+ if (error) {
+ return getStateLayer(
+ theme,
+ RadioButtonTokens.errorStateLayerColor,
+ interaction
+ );
+ }
+
+ return getStateLayer(
+ theme,
+ stateLayerRoles[interaction][checked ? 'checked' : 'unchecked'],
+ interaction
+ );
+};
diff --git a/src/components/__tests__/RadioButton/RadioButton.test.tsx b/src/components/__tests__/RadioButton/RadioButton.test.tsx
index f34f67ed56..481850ff13 100644
--- a/src/components/__tests__/RadioButton/RadioButton.test.tsx
+++ b/src/components/__tests__/RadioButton/RadioButton.test.tsx
@@ -1,63 +1,59 @@
-import type { GestureResponderEvent } from 'react-native';
+import { type GestureResponderEvent, Platform } from 'react-native';
import {
- beforeAll,
+ afterEach,
describe,
expect,
it,
jest as mockJest,
} from '@jest/globals';
import { userEvent } from '@testing-library/react-native';
+import { getAnimatedStyle } from 'react-native-reanimated';
-import { render, screen } from '../../../test-utils';
+import PaperProvider from '../../../core/PaperProvider';
+import { fireEvent, render, screen } from '../../../test-utils';
+import { LightTheme } from '../../../theme/schemes';
+import { tokens } from '../../../theme/tokens';
import RadioButton from '../../RadioButton';
+import type { Props as RadioButtonProps } from '../../RadioButton/RadioButton';
import { RadioButtonContext } from '../../RadioButton/RadioButtonGroup';
describe('RadioButton', () => {
- describe('on default platform', () => {
- beforeAll(() => {
- mockJest.mock('react-native', () => {
- const RN =
- mockJest.requireActual('react-native');
-
- return {
- ...RN,
- Platform: {
- ...RN.Platform,
- select: (objs: { default: object }) => objs.default,
- },
- };
- });
- });
+ it('renders properly', async () => {
+ const tree = (await render()).toJSON();
- it('renders properly', async () => {
- const tree = (await render()).toJSON();
+ expect(tree).toMatchSnapshot();
+ });
- expect(tree).toMatchSnapshot();
+ it('provides a 48dp touch target in its layout', async () => {
+ await render();
+
+ expect(screen.getByRole('radio')).toHaveStyle({
+ width: 48,
+ height: 48,
+ borderRadius: 24,
});
});
- describe('on ios platform', () => {
- beforeAll(() => {
- mockJest.mock('react-native', () => {
- const RN =
- mockJest.requireActual('react-native');
+ it('preserves consumer layout styles on the touch target', async () => {
+ await render(
+
+ );
- return {
- ...RN,
- Platform: {
- ...RN.Platform,
- select: (objs: { ios: object }) => objs.ios,
- },
- };
- });
+ expect(screen.getByRole('radio')).toHaveStyle({
+ margin: 8,
+ width: 56,
+ height: 56,
});
+ });
- it('renders properly', async () => {
- const tree = (await render()).toJSON();
+ it('announces status changes politely', async () => {
+ await render( {}} />);
- expect(tree).toMatchSnapshot();
- });
+ expect(screen.getByRole('radio')).toHaveProp(
+ 'accessibilityLiveRegion',
+ 'polite'
+ );
});
describe('when RadioButton is wrapped by RadioButtonContext.Provider', () => {
@@ -86,15 +82,10 @@ describe('RadioButton', () => {
});
});
- // Both variants are reached through their own component, so neither depends on
- // which platform the file mocking `Platform.select` above runs on.
- describe.each([
- { label: 'RadioButton.Android', Button: RadioButton.Android },
- { label: 'RadioButton.IOS', Button: RadioButton.IOS },
- ])('$label', ({ Button }) => {
+ describe('press handling', () => {
it('calls onPress when pressed', async () => {
const onPress = mockJest.fn<(e: GestureResponderEvent) => void>();
- await render();
+ await render();
await userEvent.press(screen.getByRole('radio'));
@@ -103,7 +94,7 @@ describe('RadioButton', () => {
it('is a disabled control and ignores presses when disabled', async () => {
const onPress = mockJest.fn<(e: GestureResponderEvent) => void>();
- await render();
+ await render();
const radio = screen.getByRole('radio');
@@ -117,14 +108,14 @@ describe('RadioButton', () => {
it('keeps the same element when it gets disabled', async () => {
const onPress = mockJest.fn<(e: GestureResponderEvent) => void>();
const { rerender } = await render(
-
+
);
const enabled = screen.getByRole('radio');
// a disabled radio that switched element would drop focus and any state a
// child holds, so `disabled` has to be what switches it off
- await rerender();
+ await rerender();
const disabled = screen.getByRole('radio');
@@ -133,3 +124,227 @@ describe('RadioButton', () => {
});
});
});
+
+describe('RadioButton state layer', () => {
+ const { colors } = LightTheme;
+ const { hovered, focused, pressed } = tokens.md.sys.state.opacity;
+
+ const stateLayer = () => screen.getByTestId('radio-state-layer');
+ const radio = () => screen.getByRole('radio');
+
+ const renderRadio = (props: Partial = {}) =>
+ render(
+ {}}
+ {...props}
+ />
+ );
+
+ it('is idle until the radio is interacted with', async () => {
+ await renderRadio();
+
+ expect(stateLayer()).toHaveStyle({ opacity: 0 });
+ });
+
+ it('is 40dp, not the 48dp touch target', async () => {
+ await renderRadio();
+
+ expect(stateLayer()).toHaveStyle({ width: 40, height: 40 });
+ });
+
+ it('tints hover with onSurface when unchecked', async () => {
+ await renderRadio();
+
+ await fireEvent(radio(), 'hoverIn');
+
+ expect(stateLayer()).toHaveStyle({
+ backgroundColor: colors.onSurface,
+ opacity: hovered,
+ });
+ });
+
+ it('tints hover with primary when checked', async () => {
+ await renderRadio({ status: 'checked' });
+
+ await fireEvent(radio(), 'hoverIn');
+
+ expect(stateLayer()).toHaveStyle({
+ backgroundColor: colors.primary,
+ opacity: hovered,
+ });
+ });
+
+ it('tints focus the same way as hover', async () => {
+ await renderRadio({ status: 'checked' });
+
+ await fireEvent(radio(), 'focus');
+
+ expect(stateLayer()).toHaveStyle({
+ backgroundColor: colors.primary,
+ opacity: focused,
+ });
+ });
+
+ it('inverts the color on press, previewing the next state', async () => {
+ await renderRadio();
+
+ await fireEvent(radio(), 'pressIn');
+
+ expect(stateLayer()).toHaveStyle({
+ backgroundColor: colors.primary,
+ opacity: pressed,
+ });
+
+ await fireEvent(radio(), 'hoverIn');
+ await fireEvent(radio(), 'pressOut');
+
+ expect(stateLayer()).toHaveStyle({
+ backgroundColor: colors.onSurface,
+ opacity: hovered,
+ });
+ });
+
+ it('stays on error for every interaction', async () => {
+ await renderRadio({ status: 'checked', error: true });
+
+ await fireEvent(radio(), 'hoverIn');
+ expect(stateLayer()).toHaveStyle({ backgroundColor: colors.error });
+
+ await fireEvent(radio(), 'focus');
+ expect(stateLayer()).toHaveStyle({ backgroundColor: colors.error });
+ });
+
+ it('tints with a custom color instead of the token role', async () => {
+ await renderRadio({ status: 'checked', color: 'teal' });
+
+ await fireEvent(radio(), 'hoverIn');
+
+ expect(stateLayer()).toHaveStyle({
+ backgroundColor: 'teal',
+ opacity: hovered,
+ });
+ });
+
+ it('stays idle on a disabled radio', async () => {
+ await renderRadio({ disabled: true });
+
+ await fireEvent(radio(), 'hoverIn');
+
+ expect(stateLayer()).toHaveStyle({ opacity: 0 });
+ });
+
+ it('stays idle on a read-only radio', async () => {
+ await renderRadio({ onPress: undefined });
+
+ await fireEvent(radio(), 'hoverIn');
+
+ expect(stateLayer()).toHaveStyle({ opacity: 0 });
+ });
+
+ it('fades out by opacity and keeps its color', async () => {
+ await renderRadio();
+
+ await fireEvent(radio(), 'hoverIn');
+ await fireEvent(radio(), 'hoverOut');
+
+ expect(stateLayer()).toHaveStyle({
+ backgroundColor: colors.onSurface,
+ opacity: 0,
+ });
+ });
+
+ it('transitions opacity only', async () => {
+ await renderRadio();
+
+ // Interpolating a themed `PlatformColor` is not possible, so the layer
+ // fades by opacity alone and its color is left to snap. Read the style off
+ // the element rather than `toHaveStyle`, which only knows layout props.
+ // `toHaveStyle` reads the props Reanimated leaves on the host node, which
+ // drops CSS-transition-only keys -- `getAnimatedStyle` mirrors how
+ // Surface.test.tsx asserts `transitionProperty` for the same reason.
+ expect(getAnimatedStyle(stateLayer())).toMatchObject({
+ transitionProperty: 'opacity',
+ });
+ });
+});
+
+describe('RadioButton with reduce motion', () => {
+ it.each([
+ { reduceMotion: 'off', duration: LightTheme.motion.duration.short2 },
+ { reduceMotion: 'on', duration: 0 },
+ ] as const)(
+ 'fades the state layer in $duration ms when reduceMotion is "$reduceMotion"',
+ async ({ reduceMotion, duration }) => {
+ await render(
+
+ {}} />
+
+ );
+
+ expect(
+ getAnimatedStyle(screen.getByTestId('radio-state-layer'))
+ ).toMatchObject({ transitionDuration: duration });
+ }
+ );
+});
+
+describe('RadioButton Space key on web', () => {
+ afterEach(() => {
+ mockJest.restoreAllMocks();
+ });
+
+ it('presses the radio once on Space release', async () => {
+ mockJest.replaceProperty(Platform, 'OS', 'web');
+ const onPress = mockJest.fn<(e: GestureResponderEvent) => void>();
+ const preventDefault = mockJest.fn();
+ await render();
+ const radio = screen.getByRole('radio');
+
+ await fireEvent(radio, 'keyDown', {
+ nativeEvent: { key: ' ' },
+ preventDefault,
+ });
+
+ expect(preventDefault).toHaveBeenCalled();
+ expect(onPress).not.toHaveBeenCalled();
+
+ await fireEvent(radio, 'keyUp', {
+ nativeEvent: { key: ' ' },
+ preventDefault,
+ });
+
+ expect(onPress).toHaveBeenCalledTimes(1);
+ });
+
+ it('selects its value in a group on Space release', async () => {
+ mockJest.replaceProperty(Platform, 'OS', 'web');
+ const onValueChange = mockJest.fn<(value: string) => void>();
+ const space = { nativeEvent: { key: ' ' }, preventDefault: mockJest.fn() };
+ await render(
+
+
+
+ );
+ const radio = screen.getByRole('radio');
+
+ await fireEvent(radio, 'keyDown', space);
+ await fireEvent(radio, 'keyUp', space);
+
+ expect(onValueChange).toHaveBeenCalledWith('second');
+ });
+
+ it('leaves Space to the page on a read-only radio', async () => {
+ mockJest.replaceProperty(Platform, 'OS', 'web');
+ const space = { nativeEvent: { key: ' ' }, preventDefault: mockJest.fn() };
+ await render();
+ const radio = screen.getByRole('radio');
+
+ await fireEvent(radio, 'keyDown', space);
+ await fireEvent(radio, 'keyUp', space);
+
+ expect(space.preventDefault).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/components/__tests__/RadioButton/RadioButtonAndroid.test.tsx b/src/components/__tests__/RadioButton/RadioButtonAndroid.test.tsx
deleted file mode 100644
index c94fbd9b3c..0000000000
--- a/src/components/__tests__/RadioButton/RadioButtonAndroid.test.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-// eslint-disable-next-line no-restricted-imports -- RadioButtonAndroid animates with React Native's Animated.
-import { AccessibilityInfo, Animated } from 'react-native';
-
-import { afterEach, describe, expect, it, jest } from '@jest/globals';
-
-import PaperProvider from '../../../core/PaperProvider';
-import { act, render, screen } from '../../../test-utils';
-import RadioButtonAndroid from '../../RadioButton/RadioButtonAndroid';
-
-type Status = 'checked' | 'unchecked';
-
-afterEach(() => {
- jest.restoreAllMocks();
-});
-
-describe('with reduce motion', () => {
- it.each([
- { reduceMotion: 'off', duration: 150 },
- { reduceMotion: 'on', duration: 0 },
- ] as const)(
- 'checks and unchecks in $duration ms when reduceMotion is "$reduceMotion"',
- async ({ reduceMotion, duration }) => {
- const makeRadio = (status: Status) => (
-
-
-
- );
-
- await render(makeRadio('unchecked'));
- const timing = jest.spyOn(Animated, 'timing');
-
- await screen.rerender(makeRadio('checked'));
- await screen.rerender(makeRadio('unchecked'));
-
- expect(timing.mock.calls.map(([, config]) => config.duration)).toEqual([
- duration,
- duration,
- ]);
- }
- );
-
- it('does not replay the last check when the OS setting changes', async () => {
- const addEventListener = jest.mocked(AccessibilityInfo.addEventListener);
- const reduceMotionListeners = () =>
- addEventListener.mock.calls
- .filter(([eventName]) => eventName === 'reduceMotionChanged')
- .map(([, listener]) => listener);
- addEventListener.mockClear();
- const makeRadio = (status: Status) => (
-
-
-
- );
-
- await render(makeRadio('unchecked'));
- const timing = jest.spyOn(Animated, 'timing');
-
- await screen.rerender(makeRadio('checked'));
- expect(timing).toHaveBeenCalledTimes(1);
- expect(reduceMotionListeners()).not.toHaveLength(0);
-
- for (const enabled of [true, false]) {
- await act(() => {
- reduceMotionListeners().forEach((listener) => listener(enabled));
- });
- }
-
- expect(timing).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/src/components/__tests__/RadioButton/RadioButtonGroup.test.tsx b/src/components/__tests__/RadioButton/RadioButtonGroup.test.tsx
index 15bf4aa442..d3e7c7bb18 100644
--- a/src/components/__tests__/RadioButton/RadioButtonGroup.test.tsx
+++ b/src/components/__tests__/RadioButton/RadioButtonGroup.test.tsx
@@ -1,6 +1,7 @@
-import { describe, expect, it } from '@jest/globals';
+import { describe, expect, it, jest } from '@jest/globals';
+import { userEvent } from '@testing-library/react-native';
-import { render } from '../../../test-utils';
+import { render, screen } from '../../../test-utils';
import RadioButton from '../../RadioButton';
describe('RadioButtonGroup', () => {
@@ -15,4 +16,26 @@ describe('RadioButtonGroup', () => {
expect(tree).toMatchSnapshot();
});
+
+ it('calls the latest onValueChange after the parent re-renders', async () => {
+ const first = jest.fn();
+ const second = jest.fn();
+
+ const { rerender } = await render(
+
+
+
+ );
+
+ await rerender(
+
+
+
+ );
+
+ await userEvent.press(screen.getByRole('radio', { name: 'Second' }));
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledWith('second');
+ });
});
diff --git a/src/components/__tests__/RadioButton/RadioButtonItem.test.tsx b/src/components/__tests__/RadioButton/RadioButtonItem.test.tsx
index 821d9ebc5b..512ca5ab2f 100644
--- a/src/components/__tests__/RadioButton/RadioButtonItem.test.tsx
+++ b/src/components/__tests__/RadioButton/RadioButtonItem.test.tsx
@@ -1,11 +1,15 @@
import { Platform } from 'react-native';
-import { expect, it, jest } from '@jest/globals';
+import { afterEach, expect, it, jest } from '@jest/globals';
import { userEvent } from '@testing-library/react-native';
-import { render, screen } from '../../../test-utils';
+import { fireEvent, render, screen } from '../../../test-utils';
import RadioButton from '../../RadioButton';
+afterEach(() => {
+ jest.restoreAllMocks();
+});
+
it('renders unchecked', async () => {
const tree = (
await render(
@@ -20,40 +24,7 @@ it('renders unchecked', async () => {
expect(tree).toMatchSnapshot();
});
-it('can render the iOS radio button on different platforms', async () => {
- Platform.OS = 'android';
- const tree = (
- await render(
-
- )
- ).toJSON();
-
- expect(tree).toMatchSnapshot();
-});
-
-it('can render the Android radio button on different platforms', async () => {
- Platform.OS = 'ios';
- const tree = (
- await render(
-
- )
- ).toJSON();
-
- expect(tree).toMatchSnapshot();
-});
-
it('can render leading radio button control', async () => {
- Platform.OS = 'ios';
const tree = (
await render(
{
expect(tree).toMatchSnapshot();
});
+it('exposes a single radio a11y node per item', async () => {
+ await render(
+
+ );
+
+ // The inner control is visual-only, so only the row is a radio.
+ expect(screen.queryAllByRole('radio')).toHaveLength(1);
+});
+
it('should execute onLongPress', async () => {
const onLongPress = jest.fn();
@@ -84,3 +64,47 @@ it('should execute onLongPress', async () => {
expect(onLongPress).toHaveBeenCalledTimes(1);
});
+
+it('selects the row in a group on Space release on web', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ const onValueChange = jest.fn<(value: string) => void>();
+ const preventDefault = jest.fn();
+ await render(
+
+
+
+
+ );
+ const row = screen.getByRole('radio', { name: 'Second' });
+
+ await fireEvent(row, 'keyDown', {
+ nativeEvent: { key: ' ' },
+ preventDefault,
+ });
+
+ expect(preventDefault).toHaveBeenCalled();
+ expect(onValueChange).not.toHaveBeenCalled();
+
+ await fireEvent(row, 'keyUp', { nativeEvent: { key: ' ' }, preventDefault });
+
+ expect(onValueChange).toHaveBeenCalledTimes(1);
+ expect(onValueChange).toHaveBeenCalledWith('second');
+});
+
+it('ignores Space on a disabled row on web', async () => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ const onValueChange = jest.fn<(value: string) => void>();
+ const space = { nativeEvent: { key: ' ' }, preventDefault: jest.fn() };
+ await render(
+
+
+
+ );
+ const row = screen.getByRole('radio', { name: 'Second' });
+
+ await fireEvent(row, 'keyDown', space);
+ await fireEvent(row, 'keyUp', space);
+
+ expect(space.preventDefault).not.toHaveBeenCalled();
+ expect(onValueChange).not.toHaveBeenCalled();
+});
diff --git a/src/components/__tests__/RadioButton/RadioButtonReadOnly.test.tsx b/src/components/__tests__/RadioButton/RadioButtonReadOnly.test.tsx
index 97bae1fe46..1a9472dd81 100644
--- a/src/components/__tests__/RadioButton/RadioButtonReadOnly.test.tsx
+++ b/src/components/__tests__/RadioButton/RadioButtonReadOnly.test.tsx
@@ -15,21 +15,17 @@ type RadioProps = {
onPress?: (event: GestureResponderEvent) => void;
};
-// `RadioButton.Item` is a row: it wraps a radio of its own, so it exposes two
-// radio nodes and the queries below take the first one, which is the row. The
-// other two variants render a single node, which makes it the row as well.
-// `Item` names its row, hence the label only it takes.
+// `RadioButton.Item` is a row. Its inner radio is hidden from assistive tech,
+// so it exposes one radio node, which is the row. `RadioButton` renders a single
+// node, which makes it the row as well. `Item` names its row, hence the label
+// only it takes.
const radios: {
label: string;
Radio: (props: RadioProps) => React.ReactElement;
}[] = [
{
- label: 'RadioButton.Android',
- Radio: (props) => ,
- },
- {
- label: 'RadioButton.IOS',
- Radio: (props) => ,
+ label: 'RadioButton',
+ Radio: (props) => ,
},
{
label: 'RadioButton.Item',
diff --git a/src/components/__tests__/RadioButton/__snapshots__/RadioButton.test.tsx.snap b/src/components/__tests__/RadioButton/__snapshots__/RadioButton.test.tsx.snap
index c03a4639d9..fdc3d1de02 100644
--- a/src/components/__tests__/RadioButton/__snapshots__/RadioButton.test.tsx.snap
+++ b/src/components/__tests__/RadioButton/__snapshots__/RadioButton.test.tsx.snap
@@ -4,179 +4,206 @@ exports[`RadioButton RadioButton with custom testID renders properly 1`] = `
-
- check
-
-
-
-`;
-
-exports[`RadioButton on default platform renders properly 1`] = `
-
-
-
+
+
- check
-
+ ]
+ }
+ />
+
`;
-exports[`RadioButton on ios platform renders properly 1`] = `
+exports[`RadioButton renders properly 1`] = `
-
+
+
- check
-
+ ]
+ }
+ />
+
`;
@@ -219,50 +246,88 @@ exports[`RadioButton when RadioButton is wrapped by RadioButtonContext.Provider
{
"overflow": "hidden",
},
- {
- "borderRadius": 18,
- "padding": 6,
- },
+ [
+ {
+ "alignItems": "center",
+ "borderRadius": 24,
+ "height": 48,
+ "justifyContent": "center",
+ "width": 48,
+ },
+ undefined,
+ ],
]
}
>
-
+
+
- check
-
+ ]
+ }
+ />
+
`;
diff --git a/src/components/__tests__/RadioButton/__snapshots__/RadioButtonGroup.test.tsx.snap b/src/components/__tests__/RadioButton/__snapshots__/RadioButtonGroup.test.tsx.snap
index 1ae7f560be..9e4b728a03 100644
--- a/src/components/__tests__/RadioButton/__snapshots__/RadioButtonGroup.test.tsx.snap
+++ b/src/components/__tests__/RadioButton/__snapshots__/RadioButtonGroup.test.tsx.snap
@@ -41,50 +41,88 @@ exports[`RadioButtonGroup renders properly 1`] = `
{
"overflow": "hidden",
},
- {
- "borderRadius": 18,
- "padding": 6,
- },
+ [
+ {
+ "alignItems": "center",
+ "borderRadius": 24,
+ "height": 48,
+ "justifyContent": "center",
+ "width": 48,
+ },
+ undefined,
+ ],
]
}
>
-
+
+
- check
-
+ ]
+ }
+ />
+
diff --git a/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap b/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap
index 81713f6cb3..81d154d99c 100644
--- a/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap
+++ b/src/components/__tests__/RadioButton/__snapshots__/RadioButtonItem.test.tsx.snap
@@ -6,6 +6,7 @@ exports[`can render leading radio button control 1`] = `
aria-checked={false}
aria-label="Default with leading control"
focusable={false}
+ onBlur={[Function]}
role="radio"
style={
[
@@ -15,6 +16,7 @@ exports[`can render leading radio button control 1`] = `
}
>
-
+
+
- check
-
+ ]
+ }
+ />
+
`;
-exports[`can render the Android radio button on different platforms 1`] = `
+exports[`renders unchecked 1`] = `
- iOS Checkbox
+ Unchecked Button
-
-
-
-
-
-`;
-
-exports[`can render the iOS radio button on different platforms 1`] = `
-
-
-
- iOS Radio button
-
-
-
- check
-
-
-
-
-
-
-`;
-
-exports[`renders unchecked 1`] = `
-
-
-
+
- Unchecked Button
-
-
-
-
+
- check
-
+ ]
+ }
+ />
+
diff --git a/src/components/__tests__/RadioButton/utils.test.tsx b/src/components/__tests__/RadioButton/utils.test.tsx
index be3cbc97d8..0b2cc27015 100644
--- a/src/components/__tests__/RadioButton/utils.test.tsx
+++ b/src/components/__tests__/RadioButton/utils.test.tsx
@@ -2,88 +2,118 @@ import { describe, expect, it } from '@jest/globals';
import { DarkTheme, LightTheme } from '../../../theme/schemes';
import { tokens } from '../../../theme/tokens';
-import { getSelectionControlIOSColor } from '../../RadioButton/utils';
+import { getSelectionControlColor } from '../../RadioButton/utils';
const stateOpacity = tokens.md.sys.state.opacity;
-describe('getSelectionControlIOSColor - checked color', () => {
- it('should return correct disabled color, for theme version 3', () => {
+describe('getSelectionControlColor', () => {
+ it('should return disabled color', () => {
expect(
- getSelectionControlIOSColor({
+ getSelectionControlColor({
theme: LightTheme,
disabled: true,
+ checked: true,
})
).toMatchObject({
- checkedColor: LightTheme.colors.primary,
- checkedColorOpacity: stateOpacity.disabled,
+ selectionControlColor: LightTheme.colors.onSurface,
+ selectionControlOpacity: stateOpacity.disabled,
});
});
it('should return custom color, checked', () => {
expect(
- getSelectionControlIOSColor({
+ getSelectionControlColor({
theme: LightTheme,
+ checked: true,
customColor: 'purple',
})
).toMatchObject({
- checkedColor: 'purple',
+ selectionControlColor: 'purple',
});
});
- it('should return theme color, for theme version 3, checked', () => {
+ it('should return primary color, checked', () => {
expect(
- getSelectionControlIOSColor({
+ getSelectionControlColor({
theme: LightTheme,
+ checked: true,
})
).toMatchObject({
- checkedColor: LightTheme.colors.primary,
+ selectionControlColor: LightTheme.colors.primary,
});
});
- it('should return error color when error is true', () => {
+ it('should return onSurfaceVariant color, unchecked', () => {
expect(
- getSelectionControlIOSColor({
+ getSelectionControlColor({
theme: LightTheme,
+ checked: false,
+ })
+ ).toMatchObject({
+ selectionControlColor: LightTheme.colors.onSurfaceVariant,
+ });
+ });
+
+ it('should return error color when error is true, checked', () => {
+ expect(
+ getSelectionControlColor({
+ theme: LightTheme,
+ checked: true,
+ error: true,
+ })
+ ).toMatchObject({
+ selectionControlColor: LightTheme.colors.error,
+ });
+ });
+
+ it('should return error color when error is true, unchecked', () => {
+ expect(
+ getSelectionControlColor({
+ theme: LightTheme,
+ checked: false,
error: true,
})
).toMatchObject({
- checkedColor: LightTheme.colors.error,
+ selectionControlColor: LightTheme.colors.error,
});
});
it('should return error color, dark mode, when error is true', () => {
expect(
- getSelectionControlIOSColor({
+ getSelectionControlColor({
theme: DarkTheme,
+ checked: true,
error: true,
})
).toMatchObject({
- checkedColor: DarkTheme.colors.error,
+ selectionControlColor: DarkTheme.colors.error,
});
});
it('should return disabled color when both disabled and error are true (disabled wins)', () => {
expect(
- getSelectionControlIOSColor({
+ getSelectionControlColor({
theme: LightTheme,
+ checked: true,
disabled: true,
error: true,
})
).toMatchObject({
- checkedColor: LightTheme.colors.primary,
- checkedColorOpacity: stateOpacity.disabled,
+ selectionControlColor: LightTheme.colors.onSurface,
+ selectionControlOpacity: stateOpacity.disabled,
});
});
it('should return custom color when both customColor and error are true (customColor wins)', () => {
expect(
- getSelectionControlIOSColor({
+ getSelectionControlColor({
theme: LightTheme,
+ checked: true,
customColor: 'purple',
error: true,
})
).toMatchObject({
- checkedColor: 'purple',
+ selectionControlColor: 'purple',
});
});
});
diff --git a/src/index.tsx b/src/index.tsx
index 2b0614c8cc..be3db1a75e 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -125,9 +125,7 @@ export type { Props as PortalHostProps } from './components/Portal/PortalHost';
export type { Props as ProgressBarProps } from './components/ProgressBar';
export type { Props as ProviderProps } from './core/PaperProvider';
export type { Props as RadioButtonProps } from './components/RadioButton/RadioButton';
-export type { Props as RadioButtonAndroidProps } from './components/RadioButton/RadioButtonAndroid';
export type { Props as RadioButtonGroupProps } from './components/RadioButton/RadioButtonGroup';
-export type { Props as RadioButtonIOSProps } from './components/RadioButton/RadioButtonIOS';
export type { Props as RadioButtonItemProps } from './components/RadioButton/RadioButtonItem';
export type { Props as SearchbarProps } from './components/Searchbar';
export type { Props as SnackbarProps } from './components/Snackbar';