diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index bb5821f1bb..a960315a3c 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -42,6 +42,34 @@ const MyComponent = () => { }; ``` +### Reduce motion + +The `animation` theme key and its `scale` were removed. The new `reduceMotion` prop of `PaperProvider` turns Paper's animations on or off instead: + +- `'auto'` (default): follows the reduce motion setting of the device. +- `'on'`: turns Paper's animations off. +- `'off'`: keeps Paper's animations on, even when the device setting is on. + +In 5.x, `PaperProvider` set the `scale` itself and replaced any `scale` in the theme passed to it, so a `scale` of `0` only turned animations off in a nested `ThemeProvider` or a component's `theme` prop. To turn animations off, for example in tests, remove that `scale` and pass `reduceMotion="on"` to `PaperProvider`: + +```diff +- +- +- +- ++ ++ + +``` + +If your app was written for a 6.0 alpha build, which also read a `scale` set on `PaperProvider`, remove it from that theme too. + +Other `scale` values, which made animations slower or faster, have no replacement in 6.0. A `scale` in a component's `theme` prop, such as `theme={{ animation: { scale: 2 } }}`, does nothing now, and it can no longer turn animations back on while reduce motion is on. Paper ignores an `animation` left in your theme. TypeScript reports it in a theme object written inline in the `theme` prop of `PaperProvider` or a component, or typed as `Theme`, but not in the `theme` prop of `ThemeProvider`, which accepts any value, or in an untyped variable that also holds other theme keys. + +In 5.x, `PaperProvider` also followed the device setting only when you passed no `theme`. In 6.x, `'auto'` follows the device setting with every theme, so if your app passes a custom theme, Paper's animations now stop when the user turns on reduce motion. 6.x also reads the setting when the app starts, while 5.x only reacted when it changed. + +To follow the same preference in your own components, use the `useReduceMotion()` hook, which returns `true` when reduce motion is on. See [Reduce motion](./theming#reduce-motion) in the theming guide. + ### Elevation The `elevation` prop no longer accepts a React Native `Animated.Value` in the following components: @@ -226,7 +254,7 @@ If you import it from Paper's type declarations instead, the path changed: #### `roundness` -The `roundness` theme property was removed. Corner radii are now set in `theme.shapes.corner`, a scale of roles from `extraSmall` (4) to `extraExtraLarge` (48), and each component uses one fixed role. Paper ignores a `roundness` left in your theme, and TypeScript only reports it in a theme object written inline in a `theme` prop or typed as `Theme`. +The `roundness` theme property was removed. Corner radii are now set in `theme.shapes.corner`, a scale of roles from `extraSmall` (4) to `extraExtraLarge` (48), and each component uses one fixed role. Paper ignores a `roundness` left in your theme. TypeScript reports it in a theme object written inline in the `theme` prop of `PaperProvider` or a component, or typed as `Theme`, but not in the `theme` prop of `ThemeProvider`, which accepts any value, or in an untyped variable that also holds other theme keys. In 5.x, each of these components multiplied `roundness` by a fixed number, and the 6.x defaults match the 5.x corners with the default `roundness` of 4. To port a custom `roundness`, set each role to your `roundness` times its multiplier: @@ -278,7 +306,7 @@ A component's `theme` prop is merged deeply, so you can set only the role you ne #### Removed keys -The 6.x theme has no `version`, `isV3`, `mode` or `animation.defaultAnimationDuration` keys. Paper 6 only supports Material Design 3, so `version` and `isV3` have nothing to select, and `mode` and `defaultAnimationDuration` have no replacement. Remove `version: 3` and `isV3` from your custom theme objects: +The 6.x theme has no `version`, `isV3`, `mode` or `animation` keys. Paper 6 only supports Material Design 3, so `version` and `isV3` have nothing to select. `mode` and `animation.defaultAnimationDuration` have no replacement, and `animation.scale` is replaced by the `reduceMotion` prop of `PaperProvider`, see [Reduce motion](#reduce-motion). Remove `version: 3` and `isV3` from your custom theme objects: ```diff const theme = { @@ -292,7 +320,7 @@ The 6.x theme has no `version`, `isV3`, `mode` or `animation.defaultAnimationDur }; ``` -As with `roundness`, Paper ignores these keys, and TypeScript only reports them in a theme object written inline in a `theme` prop or typed as `Theme`. Code that reads `theme.isV3` gets `undefined` once the key is gone, so a check like `theme.isV3 ? a : b` takes the Material Design 2 branch. Keep only the Material Design 3 branch. +As with `roundness`, Paper ignores these keys, and TypeScript reports them in the same cases. Code that reads `theme.isV3` gets `undefined` once the key is gone, so a check like `theme.isV3 ? a : b` takes the Material Design 2 branch. Keep only the Material Design 3 branch. #### `configureFonts` @@ -390,6 +418,8 @@ On web, `Button`, `Card`, the `Chip` body, `FAB`, `FAB.Extended` and the `FAB.Me 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. +A library that reads `theme.animation.scale` to turn its own animations off should read `useReduceMotion()` instead. The 6.x theme has no `animation` key, so `theme.animation.scale` throws. + ## Components ### Appbar diff --git a/docs/6.x/docs/guides/theming.mdx b/docs/6.x/docs/guides/theming.mdx index 30d946875b..ac8f12b2b2 100644 --- a/docs/6.x/docs/guides/theming.mdx +++ b/docs/6.x/docs/guides/theming.mdx @@ -134,16 +134,58 @@ A theme usually contains the following properties: - `fontWeight` - `lineHeight` - `fontSize` -- `animation` (`object`) - - `scale` - scale for all animations When creating a custom theme, you only need to provide the properties you change. `PaperProvider` merges your theme deeply with the default one, so a nested object such as `shapes` or `motion` keeps every key you leave out. Paper merges a custom theme onto `DarkTheme` when it sets `dark: true`, and onto `LightTheme` otherwise. The examples on this page still spread `LightTheme` or `DarkTheme`: that sets `dark`, and in TypeScript it gives the theme object the full `Theme` shape. Without TypeScript, nested spreads such as `...LightTheme.colors` are optional. -If you don't use a custom theme, Paper will automatically turn animations on/off, depending on device settings. +## Reduce motion -Otherwise, your custom theme will need to handle it manually, using React Native's [AccessibilityInfo API](https://reactnative.dev/docs/accessibilityinfo). +`PaperProvider` takes a `reduceMotion` prop, typed `ReduceMotionPreference`, that turns Paper's animations on or off: + +- `'auto'` (default): follows the reduce motion setting of the device, read with React Native's [AccessibilityInfo API](https://reactnative.dev/docs/accessibilityinfo). +- `'on'`: turns Paper's animations off. +- `'off'`: keeps Paper's animations on, even when the device setting is on. + +It works the same whether or not you pass a custom `theme`. With `'auto'`, Paper starts from the setting the device had when the app launched and follows every change after that. + +When reduce motion is on, Paper's components skip their animations. A few still move: the `ActivityIndicator` rotation, the indeterminate `ProgressBar` and the `TouchableRipple` ripple on web. The `TextInput` label and active indicator follow only the device setting: they don't read the `reduceMotion` prop. + +To turn Paper's animations off in tests and screenshots, whatever the device setting, pass `reduceMotion="on"`: + +```js +import * as React from 'react'; +import { PaperProvider } from 'react-native-paper'; +import App from './src/App'; + +export default function Main() { + return ( + + + + ); +} +``` + +To follow the same preference in your own components, use the `useReduceMotion()` hook. It returns `true` when reduce motion is on. Reanimated's animations follow the device setting on their own too, so give them `ReduceMotion.Never` to leave the choice to the hook: + +```js +import * as React from 'react'; +import { useReduceMotion } from 'react-native-paper'; +import Animated, { ReduceMotion, SlideInDown } from 'react-native-reanimated'; + +const slideIn = SlideInDown.reduceMotion(ReduceMotion.Never); + +export default function Toast({ children }) { + const reduceMotion = useReduceMotion(); + + return ( + + {children} + + ); +} +``` ## Extending the theme diff --git a/src/components/ActivityIndicator.tsx b/src/components/ActivityIndicator.tsx index 294f7e986e..c8a3e295a0 100644 --- a/src/components/ActivityIndicator.tsx +++ b/src/components/ActivityIndicator.tsx @@ -4,6 +4,7 @@ import { Animated, Easing, Platform, StyleSheet, View } from 'react-native'; import type { ColorValue, StyleProp, ViewProps, ViewStyle } from 'react-native'; import { useInternalTheme } from '../core/theming'; +import { useMotionDuration } from '../theme/accessibility/ReduceMotionContext'; import type { ThemeProp } from '../theme/types'; export type Props = ViewProps & { @@ -69,14 +70,12 @@ const ActivityIndicator = ({ undefined ); - const { - animation: { scale }, - } = theme; + const getDuration = useMotionDuration(); const startRotation = React.useCallback(() => { // Show indicator Animated.timing(fade, { - duration: 200 * scale, + duration: getDuration(200), toValue: 1, isInteraction: false, useNativeDriver: true, @@ -88,7 +87,7 @@ const ActivityIndicator = ({ // $FlowFixMe Animated.loop(rotation.current).start(); } - }, [scale, fade, timer]); + }, [getDuration, fade, timer]); const stopRotation = () => { if (rotation.current) { @@ -114,7 +113,7 @@ const ActivityIndicator = ({ } else if (hidesWhenStopped) { // Hide indicator first and then stop rotation Animated.timing(fade, { - duration: 200 * scale, + duration: getDuration(200), toValue: 0, useNativeDriver: true, isInteraction: false, @@ -122,7 +121,7 @@ const ActivityIndicator = ({ } else { stopRotation(); } - }, [animating, fade, hidesWhenStopped, startRotation, scale, timer]); + }, [animating, fade, hidesWhenStopped, startRotation, getDuration, timer]); const color = indicatorColor || theme.colors?.primary; const size = diff --git a/src/components/Badge.tsx b/src/components/Badge.tsx index cbe7e8d0b5..590c2d70f0 100644 --- a/src/components/Badge.tsx +++ b/src/components/Badge.tsx @@ -4,6 +4,7 @@ import { StyleSheet } from 'react-native'; import Animated, { type AnimatedStyle } from 'react-native-reanimated'; import { useInternalTheme } from '../core/theming'; +import { useReduceMotion } from '../theme/accessibility/ReduceMotionContext'; import { cornerFull } from '../theme/tokens/sys/shape'; import type { ThemeProp } from '../theme/types'; @@ -56,10 +57,7 @@ const Badge = ({ ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); - - const { - animation: { scale }, - } = theme; + const reduceMotion = useReduceMotion(); const textColor = theme.colors.onError; @@ -69,7 +67,7 @@ const Badge = ({ const transitionStyle = { opacity: visible ? 1 : 0, - transitionDuration: 150 * scale, + transitionDuration: reduceMotion ? 0 : 150, transitionProperty: 'opacity', }; diff --git a/src/components/Banner.tsx b/src/components/Banner.tsx index a9a2cf6977..4b51b5f953 100644 --- a/src/components/Banner.tsx +++ b/src/components/Banner.tsx @@ -26,6 +26,7 @@ import Surface from './Surface'; import type { SurfaceStyle } from './Surface'; import Text from './Typography/Text'; import { useInternalTheme } from '../core/theming'; +import { useMotionDuration } from '../theme/accessibility/ReduceMotionContext'; import type { Elevation, ThemeProp } from '../theme/types'; const DEFAULT_MAX_WIDTH = 960; @@ -165,8 +166,7 @@ const Banner = ({ const showCallback = useLatestCallback(onShowAnimationFinished); const hideCallback = useLatestCallback(onHideAnimationFinished); - const { scale } = theme.animation; - const animationDuration = (visible ? 250 : 200) * scale; + const getDuration = useMotionDuration(); React.useEffect(() => { const callback = visible ? showCallback : hideCallback; @@ -174,13 +174,13 @@ const Banner = ({ position.value = withTiming( visible ? 1 : 0, { - duration: animationDuration, + duration: getDuration(visible ? 250 : 200), easing: Easing.inOut(Easing.ease), reduceMotion: ReduceMotion.Never, }, (finished) => scheduleOnRN(callback, { finished: finished ?? false }) ); - }, [animationDuration, hideCallback, position, showCallback, visible]); + }, [getDuration, hideCallback, position, showCallback, visible]); const surfaceStyle = useAnimatedStyle(() => ({ opacity: interpolate(position.value, [0, 0.1, 1], [0, 1, 1]), diff --git a/src/components/BottomNavigation/BottomNavigation.tsx b/src/components/BottomNavigation/BottomNavigation.tsx index 62a8d07ea2..b391336256 100644 --- a/src/components/BottomNavigation/BottomNavigation.tsx +++ b/src/components/BottomNavigation/BottomNavigation.tsx @@ -13,6 +13,7 @@ import useLatestCallback from 'use-latest-callback'; import BottomNavigationBar from './BottomNavigationBar'; import BottomNavigationRouteScreen from './BottomNavigationRouteScreen'; import { useInternalTheme } from '../../core/theming'; +import { useMotionDuration } from '../../theme/accessibility/ReduceMotionContext'; import type { ThemeProp } from '../../theme/types'; import useAnimatedValueArray from '../../utils/useAnimatedValueArray'; import type { IconSource } from '../Icon'; @@ -342,7 +343,7 @@ const BottomNavigation = ({ getLazy = ({ route }: { route: Route }) => route.lazy, }: Props) => { const theme = useInternalTheme(themeOverrides); - const { scale } = theme.animation; + const getDuration = useMotionDuration(); const compact = compactProp ?? false; let shifting = shiftingProp ?? false; @@ -393,7 +394,7 @@ const BottomNavigation = ({ ...navigationState.routes.map((_, i) => Animated.timing(tabsPositionAnims[i], { toValue: i === index ? 0 : i >= index ? 1 : -1, - duration: 150 * scale, + duration: getDuration(150), useNativeDriver: true, easing: sceneAnimationEasing, }) @@ -415,7 +416,7 @@ const BottomNavigation = ({ [ navigationState.routes, offsetsAnims, - scale, + getDuration, tabsPositionAnims, sceneAnimationEasing, ] diff --git a/src/components/BottomNavigation/BottomNavigationBar.tsx b/src/components/BottomNavigation/BottomNavigationBar.tsx index 6e86348c3a..e2ba52677c 100644 --- a/src/components/BottomNavigation/BottomNavigationBar.tsx +++ b/src/components/BottomNavigation/BottomNavigationBar.tsx @@ -16,6 +16,7 @@ import { getLabelColor, } from './utils'; import { useInternalTheme } from '../../core/theming'; +import { useMotionDuration } from '../../theme/accessibility/ReduceMotionContext'; import type { ThemeProp } from '../../theme/types'; import useAnimatedValue from '../../utils/useAnimatedValue'; import useAnimatedValueArray from '../../utils/useAnimatedValueArray'; @@ -334,7 +335,7 @@ const BottomNavigationBar = ({ const theme = useInternalTheme(themeOverrides); const { colors } = theme; const { bottom, left, right } = useSafeAreaInsets(); - const { scale } = theme.animation; + const getDuration = useMotionDuration(); const compact = compactProp ?? false; let shifting = shiftingProp ?? false; @@ -374,20 +375,20 @@ const BottomNavigationBar = ({ setKeyboardVisible(true); Animated.timing(visibleAnim, { toValue: 0, - duration: 150 * scale, + duration: getDuration(150), useNativeDriver: true, }).start(); - }, [scale, visibleAnim]); + }, [getDuration, visibleAnim]); const handleKeyboardHide = React.useCallback(() => { Animated.timing(visibleAnim, { toValue: 1, - duration: 100 * scale, + duration: getDuration(100), useNativeDriver: true, }).start(() => { setKeyboardVisible(false); }); - }, [scale, visibleAnim]); + }, [getDuration, visibleAnim]); const animateToIndex = React.useCallback( (index: number) => { @@ -395,7 +396,7 @@ const BottomNavigationBar = ({ navigationState.routes.map((_, i) => Animated.timing(tabsAnims[i], { toValue: i === index ? 1 : 0, - duration: 150 * scale, + duration: getDuration(150), useNativeDriver: true, easing: animationEasing, }) @@ -405,7 +406,7 @@ const BottomNavigationBar = ({ tabsAnims.map((tab, i) => tab.setValue(i === index ? 1 : 0)); }); }, - [scale, navigationState.routes, tabsAnims, animationEasing] + [getDuration, navigationState.routes, tabsAnims, animationEasing] ); React.useEffect(() => { diff --git a/src/components/Button/Button.tsx b/src/components/Button/Button.tsx index 93f5a59e59..0e7365f953 100644 --- a/src/components/Button/Button.tsx +++ b/src/components/Button/Button.tsx @@ -86,7 +86,9 @@ export type Props = Omit & { * `false` the shape still changes, it just snaps instead of animating, and * there is no press morph at all. * - * The press morph is skipped when the OS reduce-motion setting is on. + * Under reduce motion the shape behaves as with `false`. Reduce motion + * comes from the `reduceMotion` prop of `PaperProvider`, which follows the + * OS setting by default. */ animateShape?: boolean; /** @@ -348,9 +350,7 @@ const Button = ({ () => toSpringCurve(theme.motion.spring.fast.spatial), [theme.motion.spring.fast.spatial] ); - const shapeTransitionDuration = animatesShape - ? shapeSpring.duration * theme.animation.scale - : 0; + const shapeTransitionDuration = animatesShape ? shapeSpring.duration : 0; const tracksPress = animatesShape || isElevationEntitled; @@ -422,6 +422,7 @@ const Button = ({ const surfaceTransitionDuration = getButtonTransitionDuration({ theme, pressed, + reduceMotion, containerColor, previousContainerColor: committedContainerColor, }); diff --git a/src/components/Button/utils.tsx b/src/components/Button/utils.tsx index 5765714b6b..1844654478 100644 --- a/src/components/Button/utils.tsx +++ b/src/components/Button/utils.tsx @@ -122,20 +122,24 @@ export const getButtonShapeRadius = ({ /** * Duration of `Surface`'s background and elevation transition. * - * Snaps when either color is transparent or not a plain string. + * Snaps under reduce motion, or when either color is transparent or not a + * plain string. */ export const getButtonTransitionDuration = ({ theme, pressed, + reduceMotion, containerColor, previousContainerColor, }: { theme: InternalTheme; pressed: boolean; + reduceMotion: boolean; containerColor: ColorValue; previousContainerColor: ColorValue; }): number => { if ( + reduceMotion || typeof containerColor !== 'string' || typeof previousContainerColor !== 'string' || containerColor === 'transparent' || @@ -144,9 +148,7 @@ export const getButtonTransitionDuration = ({ return 0; } - return ( - theme.motion.duration[pressed ? 'short4' : 'short3'] * theme.animation.scale - ); + return theme.motion.duration[pressed ? 'short4' : 'short3']; }; /** diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx index 1e6946e1d3..68fb7b70ca 100644 --- a/src/components/Chip/Chip.tsx +++ b/src/components/Chip/Chip.tsx @@ -16,6 +16,7 @@ import { getChipColors } from './helpers'; import type { ChipAvatarProps } from './helpers'; import { ChipTokens } from './tokens'; import { useInternalTheme } from '../../core/theming'; +import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import { white } from '../../theme/colors'; import { tokens } from '../../theme/tokens'; import type { ThemeProp } from '../../theme/types'; @@ -302,9 +303,10 @@ const Chip = ({ setPressed(false); }); - const elevationTransitionDuration = - theme.motion.duration[pressed ? 'short4' : 'short3'] * - theme.animation.scale; + const reduceMotion = useReduceMotion(); + const elevationTransitionDuration = reduceMotion + ? 0 + : theme.motion.duration[pressed ? 'short4' : 'short3']; const opacity = 0.38; const defaultBorderRadius = theme.shapes.corner.small; diff --git a/src/components/CrossFadeIcon.tsx b/src/components/CrossFadeIcon.tsx index d1e3ab25ab..1f67aa7843 100644 --- a/src/components/CrossFadeIcon.tsx +++ b/src/components/CrossFadeIcon.tsx @@ -14,6 +14,7 @@ import Animated, { import Icon, { isEqualIcon, isValidIcon } from './Icon'; import type { IconSource } from './Icon'; import { useInternalTheme } from '../core/theming'; +import { useMotionDuration } from '../theme/accessibility/ReduceMotionContext'; import type { ThemeProp } from '../theme/types'; type Props = { @@ -57,6 +58,8 @@ const CrossFadeIcon = ({ const fade = useSharedValue(1); + const getDuration = useMotionDuration(); + if (currentIcon !== source) { setPreviousIcon(() => currentIcon); setCurrentIcon(() => source); @@ -67,12 +70,12 @@ const CrossFadeIcon = ({ fade.value = 1; fade.value = withTiming(0, { - duration: theme.animation.scale * 200, + duration: getDuration(200), easing: Easing.inOut(Easing.ease), reduceMotion: ReduceMotion.Never, }); } - }, [currentIcon, fade, previousIcon, theme.animation.scale]); + }, [currentIcon, fade, previousIcon, getDuration]); const hasPreviousIcon = Boolean(previousIcon); diff --git a/src/components/Drawer/DrawerCollapsedItem.tsx b/src/components/Drawer/DrawerCollapsedItem.tsx index 355cfebfba..257a6a3e54 100644 --- a/src/components/Drawer/DrawerCollapsedItem.tsx +++ b/src/components/Drawer/DrawerCollapsedItem.tsx @@ -18,6 +18,7 @@ import Animated, { import useLatestCallback from 'use-latest-callback'; import { useInternalTheme } from '../../core/theming'; +import { useMotionDuration } from '../../theme/accessibility/ReduceMotionContext'; import { tokens } from '../../theme/tokens'; import type { ThemeProp } from '../../theme/types'; import { useFocusRing } from '../../utils/useFocusRing'; @@ -118,7 +119,7 @@ const DrawerCollapsedItem = ({ ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); - const { scale } = theme.animation; + const getDuration = useMotionDuration(); // 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 @@ -144,7 +145,7 @@ const DrawerCollapsedItem = ({ const expandOutline = useLatestCallback(() => { outlineScale.value = withTiming(1, { - duration: 150 * scale, + duration: getDuration(150), easing: Easing.inOut(Easing.ease), reduceMotion: ReduceMotion.Never, }); diff --git a/src/components/Menu/Menu.tsx b/src/components/Menu/Menu.tsx index 268246b5a0..f83cec3a47 100644 --- a/src/components/Menu/Menu.tsx +++ b/src/components/Menu/Menu.tsx @@ -32,6 +32,7 @@ import useLatestCallback from 'use-latest-callback'; import MenuItem from './MenuItem'; import { useLocale } from '../../core/locale'; import { useInternalTheme } from '../../core/theming'; +import { useMotionDuration } from '../../theme/accessibility/ReduceMotionContext'; import type { Elevation, ThemeProp } from '../../theme/types'; import { addEventListener } from '../../utils/addEventListener'; import { useOverlayDismiss } from '../../utils/useOverlayDismiss'; @@ -330,6 +331,8 @@ const Menu = ({ focusFirstDOMNode(anchorRef.current); }); + const getDuration = useMotionDuration(); + const show = React.useCallback(async () => { const windowLayoutResult = Dimensions.get('window'); const [menuLayoutResult, anchorLayoutResult] = await Promise.all([ @@ -385,10 +388,8 @@ const Menu = ({ return; } - const { animation } = theme; - const config = { - duration: ANIMATION_DURATION * animation.scale, + duration: getDuration(ANIMATION_DURATION), easing: EASING, reduceMotion: ReduceMotion.Never, }; @@ -403,30 +404,28 @@ const Menu = ({ }, [ anchor, attachListeners, + getDuration, handleShowAnimationFinished, measureAnchorLayout, opacity, scaleX, scaleY, - theme, ]); const hide = React.useCallback(() => { removeListeners(); isShownRef.current = false; - const { animation } = theme; - opacity.value = withTiming( 0, { - duration: ANIMATION_DURATION * animation.scale, + duration: getDuration(ANIMATION_DURATION), easing: EASING, reduceMotion: ReduceMotion.Never, }, (finished) => scheduleOnRN(handleHideAnimationFinished, finished ?? false) ); - }, [handleHideAnimationFinished, opacity, removeListeners, theme]); + }, [getDuration, handleHideAnimationFinished, opacity, removeListeners]); const updateVisibility = React.useCallback( async (display: boolean) => { diff --git a/src/components/Modal.tsx b/src/components/Modal.tsx index e96612b2b7..fa0c7eea6c 100644 --- a/src/components/Modal.tsx +++ b/src/components/Modal.tsx @@ -13,6 +13,10 @@ import Portal from './Portal/Portal'; import Surface from './Surface'; import type { Props as SurfaceProps, SurfaceStyle } from './Surface'; import { useInternalTheme } from '../core/theming'; +import { + useMotionDuration, + useReduceMotion, +} from '../theme/accessibility/ReduceMotionContext'; import { tokens } from '../theme/tokens'; import type { Elevation, ThemeProp } from '../theme/types'; import { useOverlayDismiss } from '../utils/useOverlayDismiss'; @@ -208,7 +212,9 @@ function Modal({ setVisibleInternal(true); } - const { scale } = theme.animation; + const reduceMotion = useReduceMotion(); + const duration = reduceMotion ? 0 : DEFAULT_DURATION; + const getDuration = useMotionDuration(); const contentRef = React.useRef>(null); @@ -232,11 +238,11 @@ function Modal({ const timeout = setTimeout( () => setVisibleInternal(false), - scale * DEFAULT_DURATION + getDuration(DEFAULT_DURATION) ); return () => clearTimeout(timeout); - }, [scale, visible, visibleInternal]); + }, [getDuration, visible, visibleInternal]); React.useEffect(() => { if (!visibleInternal) { @@ -257,15 +263,18 @@ function Modal({ // Transparent views are not in the accessibility tree, so focus has to // wait for the fade to finish. - const timeout = setTimeout(focusInitialTarget, scale * DEFAULT_DURATION); + const timeout = setTimeout( + focusInitialTarget, + getDuration(DEFAULT_DURATION) + ); return () => clearTimeout(timeout); - }, [animatedVisible, focusInitialTarget, scale]); + }, [animatedVisible, focusInitialTarget, getDuration]); const transitionTimingFunction = cubicBezier(1 / 3, 1, 2 / 3, 1); const backdropTransitionStyle: AnimatedStyle = { - transitionDuration: scale * DEFAULT_DURATION, + transitionDuration: duration, transitionProperty: 'opacity', transitionTimingFunction, }; @@ -338,7 +347,7 @@ function Modal({ contentContainerStyle, ]} elevation={contentElevation} - transitionDuration={scale * DEFAULT_DURATION} + transitionDuration={duration} > {children} {dismissable ? ( diff --git a/src/components/ProgressBar.tsx b/src/components/ProgressBar.tsx index 0618e70b88..b34d3144f2 100644 --- a/src/components/ProgressBar.tsx +++ b/src/components/ProgressBar.tsx @@ -10,6 +10,7 @@ import type { import { useLocale } from '../core/locale'; import { useInternalTheme } from '../core/theming'; +import { useMotionDuration } from '../theme/accessibility/ReduceMotionContext'; import type { ThemeProp } from '../theme/types'; export type Props = ViewProps & { @@ -95,7 +96,7 @@ const ProgressBar = ({ const indeterminateAnimation = React.useRef(null); - const { scale } = theme.animation; + const getDuration = useMotionDuration(); React.useEffect(() => { passedAnimatedValue.current = animatedValue; @@ -104,7 +105,7 @@ const ProgressBar = ({ const startAnimation = React.useCallback(() => { // Show progress bar Animated.timing(fade, { - duration: 200 * scale, + duration: getDuration(200), toValue: 1, useNativeDriver: true, isInteraction: false, @@ -142,13 +143,13 @@ const ProgressBar = ({ Animated.loop(indeterminateAnimation.current).start(); } else { Animated.timing(timer, { - duration: 200 * scale, + duration: getDuration(200), toValue: progress ? progress : 0, useNativeDriver: true, isInteraction: false, }).start(); } - }, [fade, scale, indeterminate, timer, progress]); + }, [fade, getDuration, indeterminate, timer, progress]); const stopAnimation = React.useCallback(() => { // Stop indeterminate animation @@ -157,12 +158,12 @@ const ProgressBar = ({ } Animated.timing(fade, { - duration: 200 * scale, + duration: getDuration(200), toValue: 0, useNativeDriver: true, isInteraction: false, }).start(); - }, [fade, scale]); + }, [fade, getDuration]); React.useEffect(() => { if (visible) startAnimation(); diff --git a/src/components/RadioButton/RadioButtonAndroid.tsx b/src/components/RadioButton/RadioButtonAndroid.tsx index 68d6370884..b840d9ac3f 100644 --- a/src/components/RadioButton/RadioButtonAndroid.tsx +++ b/src/components/RadioButton/RadioButtonAndroid.tsx @@ -6,6 +6,7 @@ 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'; @@ -79,7 +80,7 @@ const RadioButtonAndroid = ({ const isFirstRendering = React.useRef(true); - const { scale } = theme.animation; + const getDuration = useMotionDuration(); React.useEffect(() => { // Do not run animation on very first rendering @@ -93,7 +94,7 @@ const RadioButtonAndroid = ({ Animated.timing(radioAnim, { toValue: 1, - duration: 150 * scale, + duration: getDuration(150), useNativeDriver: true, }).start(); } else { @@ -101,11 +102,11 @@ const RadioButtonAndroid = ({ Animated.timing(borderAnim, { toValue: BORDER_WIDTH, - duration: 150 * scale, + duration: getDuration(150), useNativeDriver: false, }).start(); } - }, [status, borderAnim, radioAnim, scale]); + }, [status, borderAnim, radioAnim, getDuration]); return ( diff --git a/src/components/Snackbar.tsx b/src/components/Snackbar.tsx index ca485c0c0a..6d41b15556 100644 --- a/src/components/Snackbar.tsx +++ b/src/components/Snackbar.tsx @@ -24,6 +24,7 @@ import type { SurfaceStyle } from './Surface'; import Text from './Typography/Text'; import { useLocale } from '../core/locale'; import { useInternalTheme } from '../core/theming'; +import { useMotionDuration } from '../theme/accessibility/ReduceMotionContext'; import type { Elevation, ThemeProp } from '../theme/types'; import { FocusRingColorContext } from '../utils/useFocusRing'; @@ -183,7 +184,7 @@ const Snackbar = ({ const [hidden, setHidden] = React.useState(!visible); - const { scale } = theme.animation; + const getDuration = useMotionDuration(); if (visible && hidden) { setHidden(false); @@ -212,7 +213,7 @@ const Snackbar = ({ opacity.value = withTiming( visible ? 1 : 0, { - duration: (visible ? 200 : 100) * scale, + duration: getDuration(visible ? 200 : 100), easing: visible ? Easing.out(Easing.ease) : Easing.inOut(Easing.ease), reduceMotion: ReduceMotion.Never, }, @@ -224,7 +225,7 @@ const Snackbar = ({ } } ); - }, [handleShowAnimationFinished, opacity, scale, visible]); + }, [getDuration, handleShowAnimationFinished, opacity, visible]); React.useEffect(() => { isMounted.current = true; diff --git a/src/components/Surface.tsx b/src/components/Surface.tsx index 5f47146296..d1a4e07e99 100644 --- a/src/components/Surface.tsx +++ b/src/components/Surface.tsx @@ -11,6 +11,7 @@ import Animated, { } from 'react-native-reanimated'; import { useInternalTheme } from '../core/theming'; +import { useReduceMotion } from '../theme/accessibility/ReduceMotionContext'; import { androidElevationLevels, shadow } from '../theme/tokens/sys/elevation'; import type { Elevation, ThemeProp } from '../theme/types'; @@ -214,6 +215,7 @@ const Surface = ({ ...rest }: Props) => { const theme = useInternalTheme(overriddenTheme); + const reduceMotion = useReduceMotion(); const { colors } = theme; @@ -253,7 +255,7 @@ const Surface = ({ const transitionDuration = customTransitionDuration ?? - theme.motion.duration.short3 * theme.animation.scale; + (reduceMotion ? 0 : theme.motion.duration.short3); const transitionTimingFunction = cubicBezier(...theme.motion.easing.standard); const colorTransitionProperty = // FIXME: Reanimated can't animate PlatformColor and DynamicColorIOS diff --git a/src/components/__tests__/ActivityIndicator.test.tsx b/src/components/__tests__/ActivityIndicator.test.tsx index 076e60effa..c70d6cd3d1 100644 --- a/src/components/__tests__/ActivityIndicator.test.tsx +++ b/src/components/__tests__/ActivityIndicator.test.tsx @@ -1,8 +1,16 @@ -import { expect, it } from '@jest/globals'; +// eslint-disable-next-line no-restricted-imports -- ActivityIndicator animates with React Native's Animated. +import { AccessibilityInfo, Animated } from 'react-native'; -import { render } from '../../test-utils'; +import { afterEach, describe, expect, it, jest } from '@jest/globals'; + +import PaperProvider from '../../core/PaperProvider'; +import { act, render, screen } from '../../test-utils'; import ActivityIndicator from '../ActivityIndicator'; +afterEach(() => { + jest.restoreAllMocks(); +}); + it('renders indicator', async () => { const tree = (await render()).toJSON(); @@ -28,3 +36,60 @@ it('renders colored indicator', async () => { expect(tree).toMatchSnapshot(); }); + +describe('with reduce motion', () => { + it.each([ + { reduceMotion: 'off', fade: 200 }, + { reduceMotion: 'on', fade: 0 }, + ] as const)( + 'fades in and out in $fade ms and keeps rotating when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, fade }) => { + const timing = jest.spyOn(Animated, 'timing'); + const loop = jest.spyOn(Animated, 'loop'); + const makeIndicator = (animating: boolean) => ( + + + + ); + + await render(makeIndicator(true)); + expect(loop).toHaveBeenCalledTimes(1); + + await screen.rerender(makeIndicator(false)); + + // The 2400 ms rotation, then the fade in and the fade out. + expect(timing.mock.calls.map(([, config]) => config.duration)).toEqual([ + 2400, + fade, + fade, + ]); + } + ); + + it('does not restart the rotation when the OS setting changes', async () => { + const listeners: Array<(enabled: boolean) => void> = []; + jest + .spyOn(AccessibilityInfo, 'addEventListener') + .mockImplementation((_eventName, listener) => { + listeners.push(listener); + return { remove: jest.fn() }; + }); + const loop = jest.spyOn(Animated, 'loop'); + + await render( + + + + ); + expect(loop).toHaveBeenCalledTimes(1); + expect(listeners).not.toHaveLength(0); + + for (const enabled of [true, false]) { + await act(() => { + listeners.forEach((listener) => listener(enabled)); + }); + } + + expect(loop).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/components/__tests__/Badge.test.tsx b/src/components/__tests__/Badge.test.tsx index 2b2ff26ca2..b2005c6f65 100644 --- a/src/components/__tests__/Badge.test.tsx +++ b/src/components/__tests__/Badge.test.tsx @@ -1,5 +1,7 @@ -import { expect, it } from '@jest/globals'; +import { describe, expect, it } from '@jest/globals'; +import { getAnimatedStyle } from 'react-native-reanimated'; +import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; import { red500 } from '../../theme/colors'; import Badge from '../Badge'; @@ -65,3 +67,23 @@ it('does not apply typography or padding to dot badge', async () => { expect(screen.getByTestId('badge')).not.toHaveStyle({ paddingHorizontal: 4 }); expect(screen.getByTestId('badge')).not.toHaveStyle({ fontSize: 11 }); }); + +describe('with reduce motion', () => { + it.each([ + { reduceMotion: 'off', duration: 150 }, + { reduceMotion: 'on', duration: 0 }, + ] as const)( + 'fades in and out in $duration ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, duration }) => { + await render( + + 3 + + ); + + expect(getAnimatedStyle(screen.getByTestId('badge'))).toMatchObject({ + transitionDuration: duration, + }); + } + ); +}); diff --git a/src/components/__tests__/Banner.test.tsx b/src/components/__tests__/Banner.test.tsx index 5cbd07b387..a1fa3da99a 100644 --- a/src/components/__tests__/Banner.test.tsx +++ b/src/components/__tests__/Banner.test.tsx @@ -1,4 +1,4 @@ -import { Image } from 'react-native'; +import { AccessibilityInfo, Image } from 'react-native'; import { afterAll, @@ -10,10 +10,25 @@ import { jest, } from '@jest/globals'; import { act } from '@testing-library/react-native'; +import * as Reanimated from 'react-native-reanimated'; +import PaperProvider from '../../core/PaperProvider'; import { render } from '../../test-utils'; import Banner from '../Banner'; +jest.mock('react-native-reanimated', () => { + const ReanimatedModule = jest.requireActual< + typeof import('react-native-reanimated') + >('react-native-reanimated'); + + return { + __esModule: true, + ...ReanimatedModule, + default: ReanimatedModule.default, + withTiming: jest.fn(ReanimatedModule.withTiming), + }; +}); + it('renders hidden banner, without action buttons and without image', async () => { const tree = ( await render( @@ -356,4 +371,79 @@ describe('animations', () => { expect(nextHideCallback).toHaveBeenCalledTimes(1); }); }); + + describe('with reduce motion', () => { + it.each([ + { reduceMotion: 'off', show: 250, hide: 200 }, + { reduceMotion: 'on', show: 0, hide: 0 }, + ] as const)( + 'should open in $show ms and close in $hide ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, show, hide }) => { + const withTiming = jest.mocked(Reanimated.withTiming); + const makeBanner = (visible: boolean) => ( + + Text + + ); + + const view = await render(makeBanner(false)); + withTiming.mockClear(); + + await view.rerender(makeBanner(true)); + await view.rerender(makeBanner(false)); + + expect( + withTiming.mock.calls.map(([, config]) => config?.duration) + ).toEqual([show, hide]); + } + ); + + it.each([ + { state: 'visible', visible: true }, + { state: 'hidden', visible: false }, + ])( + 'should not call the callbacks of a $state banner again when the OS setting changes', + async ({ visible }) => { + const addEventListener = jest.mocked( + AccessibilityInfo.addEventListener + ); + const reduceMotionListeners = () => + addEventListener.mock.calls + .filter(([eventName]) => eventName === 'reduceMotionChanged') + .map(([, listener]) => listener); + addEventListener.mockClear(); + + await render( + + + Text + + + ); + + await act(() => { + jest.runAllTimers(); + }); + expect(showCallback).toHaveBeenCalledTimes(visible ? 1 : 0); + expect(hideCallback).toHaveBeenCalledTimes(visible ? 0 : 1); + expect(reduceMotionListeners()).not.toHaveLength(0); + + for (const enabled of [true, false]) { + await act(() => { + reduceMotionListeners().forEach((listener) => listener(enabled)); + }); + await act(() => { + jest.runAllTimers(); + }); + } + + expect(showCallback).toHaveBeenCalledTimes(visible ? 1 : 0); + expect(hideCallback).toHaveBeenCalledTimes(visible ? 0 : 1); + } + ); + }); }); diff --git a/src/components/__tests__/Button.test.tsx b/src/components/__tests__/Button.test.tsx index 4f2ea92e5b..61b23afe0e 100644 --- a/src/components/__tests__/Button.test.tsx +++ b/src/components/__tests__/Button.test.tsx @@ -5,6 +5,7 @@ import { fireEvent } from '@testing-library/react-native'; import color from 'color'; import { LocaleProvider } from '../../core/locale'; +import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; import { ReduceMotionContext } from '../../theme/accessibility/ReduceMotionContext'; import { pink500, white } from '../../theme/colors'; @@ -811,18 +812,17 @@ describe('getButtonShapeCurvePoints', () => { describe('getButtonTransitionDuration', () => { const theme = LightTheme; const opaque = theme.colors.primary; - const scaled = (key: 'short3' | 'short4') => - theme.motion.duration[key] * theme.animation.scale; it('cross-fades between two opaque containers', () => { expect( getButtonTransitionDuration({ theme, pressed: false, + reduceMotion: false, containerColor: opaque, previousContainerColor: theme.colors.secondaryContainer, }) - ).toBe(scaled('short3')); + ).toBe(theme.motion.duration.short3); }); it('uses the longer duration while pressed', () => { @@ -830,17 +830,34 @@ describe('getButtonTransitionDuration', () => { getButtonTransitionDuration({ theme, pressed: true, + reduceMotion: false, containerColor: opaque, previousContainerColor: opaque, }) - ).toBe(scaled('short4')); + ).toBe(theme.motion.duration.short4); }); + it.each([false, true])( + 'snaps under reduce motion (pressed: %s)', + (pressed) => { + expect( + getButtonTransitionDuration({ + theme, + pressed, + reduceMotion: true, + containerColor: opaque, + previousContainerColor: theme.colors.secondaryContainer, + }) + ).toBe(0); + } + ); + it('snaps when the container becomes transparent', () => { expect( getButtonTransitionDuration({ theme, pressed: false, + reduceMotion: false, containerColor: 'transparent', previousContainerColor: opaque, }) @@ -852,6 +869,7 @@ describe('getButtonTransitionDuration', () => { getButtonTransitionDuration({ theme, pressed: false, + reduceMotion: false, containerColor: opaque, previousContainerColor: 'transparent', }) @@ -868,6 +886,7 @@ describe('getButtonTransitionDuration', () => { getButtonTransitionDuration({ theme, pressed: false, + reduceMotion: false, containerColor, previousContainerColor, }) @@ -1420,3 +1439,62 @@ describe('shape morph animation', () => { expect(screen.getByTestId('button')).toHaveStyle({ borderRadius: 48 }); }); }); + +describe('with reduce motion', () => { + const { short3, short4 } = LightTheme.motion.duration; + const shapeDuration = toSpringCurve( + LightTheme.motion.spring.fast.spatial + ).duration; + + // The touchable sits in the clip, which sits in the container. + const containerOf = () => + parentOf( + parentOf(screen.getByTestId('button'), 'the touchable'), + 'the clip' + ); + + // Reanimated's Jest setup keeps CSS transitions out of `style`, and + // `getAnimatedStyle` can't read the container's nested style arrays. The + // container transitions its background and three shadow properties, then + // its corner. + const containerTransitionDuration = () => + // eslint-disable-next-line no-restricted-syntax -- see the comment above. + StyleSheet.flatten(containerOf().props.jestInlineStyle).transitionDuration; + + const renderButton = (reduceMotion: 'on' | 'off') => + render( + + + + ); + + it('transitions the container and morphs its corner when reduceMotion is "off"', async () => { + await renderButton('off'); + expect(containerTransitionDuration()).toEqual([ + short3, + short3, + short3, + short3, + shapeDuration, + ]); + + await fireEvent(screen.getByTestId('button'), 'onPressIn'); + expect(containerTransitionDuration()).toEqual([ + short4, + short4, + short4, + short4, + shapeDuration, + ]); + }); + + it('snaps the container and its corner when reduceMotion is "on"', async () => { + await renderButton('on'); + expect(containerTransitionDuration()).toEqual([0, 0, 0, 0, 0]); + + await fireEvent(screen.getByTestId('button'), 'onPressIn'); + expect(containerTransitionDuration()).toEqual([0, 0, 0, 0, 0]); + }); +}); diff --git a/src/components/__tests__/Chip.test.tsx b/src/components/__tests__/Chip.test.tsx index cd8562325b..821bb3062f 100644 --- a/src/components/__tests__/Chip.test.tsx +++ b/src/components/__tests__/Chip.test.tsx @@ -1,10 +1,11 @@ -import { Pressable } from 'react-native'; +import { Pressable, StyleSheet } from 'react-native'; import type { GestureResponderEvent } from 'react-native'; import { describe, expect, it, jest } from '@jest/globals'; -import { userEvent } from '@testing-library/react-native'; +import { fireEvent, userEvent } from '@testing-library/react-native'; import color from 'color'; +import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; import { DarkTheme, LightTheme } from '../../theme/schemes'; import { tokens } from '../../theme/tokens'; @@ -400,3 +401,37 @@ describe('hitSlop', () => { expect(screen.getByTestId('chip')).not.toHaveProp('hitSlop'); }); }); + +describe('with reduce motion', () => { + // Reanimated's Jest setup keeps CSS transitions out of `style`, and + // `getAnimatedStyle` can't read the chip's nested style arrays. The chip's + // container is the touchable's parent. + const elevationTransitionDuration = () => { + const { parent } = screen.getByTestId('chip'); + if (!parent) { + throw new Error('Expected the touchable to be inside the container.'); + } + // eslint-disable-next-line no-restricted-syntax -- see the comment above. + return StyleSheet.flatten(parent.props.jestInlineStyle).transitionDuration; + }; + + it.each([ + { reduceMotion: 'off', rest: 150, pressed: 200 }, + { reduceMotion: 'on', rest: 0, pressed: 0 }, + ] as const)( + 'moves its elevation in $rest ms, and $pressed ms while pressed, when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, rest, pressed }) => { + await render( + + {}} testID="chip"> + Example Chip + + + ); + expect(elevationTransitionDuration()).toBe(rest); + + await fireEvent(screen.getByTestId('chip'), 'pressIn'); + expect(elevationTransitionDuration()).toBe(pressed); + } + ); +}); diff --git a/src/components/__tests__/CrossFadeIcon.test.tsx b/src/components/__tests__/CrossFadeIcon.test.tsx new file mode 100644 index 0000000000..3e148541d3 --- /dev/null +++ b/src/components/__tests__/CrossFadeIcon.test.tsx @@ -0,0 +1,79 @@ +import { AccessibilityInfo } from 'react-native'; + +import { beforeEach, expect, it, jest } from '@jest/globals'; +import * as Reanimated from 'react-native-reanimated'; + +import PaperProvider from '../../core/PaperProvider'; +import { act, render, screen } from '../../test-utils'; +import CrossFadeIcon from '../CrossFadeIcon'; + +jest.mock('react-native-reanimated', () => { + const ReanimatedModule = jest.requireActual< + typeof import('react-native-reanimated') + >('react-native-reanimated'); + + return { + __esModule: true, + ...ReanimatedModule, + default: ReanimatedModule.default, + withTiming: jest.fn(ReanimatedModule.withTiming), + }; +}); + +const withTiming = jest.mocked(Reanimated.withTiming); + +beforeEach(() => { + withTiming.mockClear(); +}); + +it.each([ + { reduceMotion: 'off', duration: 200 }, + { reduceMotion: 'on', duration: 0 }, +] as const)( + 'cross-fades to a new icon in $duration ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, duration }) => { + const makeIcon = (source: string) => ( + + + + ); + + await render(makeIcon('plus')); + expect(withTiming).not.toHaveBeenCalled(); + + await screen.rerender(makeIcon('minus')); + expect(withTiming.mock.calls.map(([, config]) => config?.duration)).toEqual( + [duration] + ); + } +); + +it('does not replay the last icon change 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 makeIcon = (source: string) => ( + + + + ); + + await render(makeIcon('plus')); + await screen.rerender(makeIcon('minus')); + await act(() => { + jest.runAllTimers(); + }); + expect(withTiming).toHaveBeenCalledTimes(1); + expect(reduceMotionListeners()).not.toHaveLength(0); + + for (const enabled of [true, false]) { + await act(() => { + reduceMotionListeners().forEach((listener) => listener(enabled)); + }); + } + + expect(withTiming).toHaveBeenCalledTimes(1); +}); diff --git a/src/components/__tests__/Menu.test.tsx b/src/components/__tests__/Menu.test.tsx index 1d6d9fb0f0..7fced51b87 100644 --- a/src/components/__tests__/Menu.test.tsx +++ b/src/components/__tests__/Menu.test.tsx @@ -10,8 +10,9 @@ import { jest, } from '@jest/globals'; import { act, screen, waitFor } from '@testing-library/react-native'; -import { getAnimatedStyle } from 'react-native-reanimated'; +import * as Reanimated from 'react-native-reanimated'; +import PaperProvider from '../../core/PaperProvider'; import { render } from '../../test-utils'; import { LightTheme } from '../../theme/schemes'; import type { Elevation } from '../../theme/types'; @@ -19,6 +20,19 @@ import Button from '../Button/Button'; import Menu from '../Menu/Menu'; import Portal from '../Portal/Portal'; +jest.mock('react-native-reanimated', () => { + const ReanimatedModule = jest.requireActual< + typeof import('react-native-reanimated') + >('react-native-reanimated'); + + return { + __esModule: true, + ...ReanimatedModule, + default: ReanimatedModule.default, + withTiming: jest.fn(ReanimatedModule.withTiming), + }; +}); + describe('web focus', () => { const PAST_ANIMATION_MS = 300; const focus = jest.fn(); @@ -485,7 +499,7 @@ it('scales in again when reopened at the same anchor', async () => { await screen.rerender(makeMenu(true)); }); await act(() => jest.advanceTimersByTimeAsync(100)); - const style = getAnimatedStyle(screen.getByTestId(testID)); + const style = Reanimated.getAnimatedStyle(screen.getByTestId(testID)); await act(() => jest.advanceTimersByTimeAsync(500)); return style; }; @@ -511,3 +525,64 @@ it('scales in again when reopened at the same anchor', async () => { measureSpy.mockRestore(); } }); + +it.each([ + { reduceMotion: 'off', duration: 250 }, + { reduceMotion: 'on', duration: 0 }, +] as const)( + 'opens and closes in $duration ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, duration }) => { + const withTiming = jest.mocked(Reanimated.withTiming); + const durations = () => + withTiming.mock.calls.map(([, config]) => config?.duration); + const measureSpy = jest + .spyOn(ViewPrototype, 'measureInWindow') + .mockImplementation((fn) => fn(100, 100, 80, 32)); + + function makeMenu(visible: boolean) { + return ( + + Open menu} + > + + + + ); + } + + try { + const { rerender } = await render(makeMenu(false)); + // Earlier tests can leave a menu waiting for an animation frame to open. + await act(async () => { + await jest.runOnlyPendingTimersAsync(); + }); + withTiming.mockClear(); + + await act(async () => { + await rerender(makeMenu(true)); + // Menu waits a tick for Portal refs to be up-to-date. + await Promise.resolve(); + }); + // The open animation starts on the next animation frame. + await act(async () => { + await jest.advanceTimersByTimeAsync(50); + }); + + // Width, height and opacity. + expect(durations()).toEqual([duration, duration, duration]); + + withTiming.mockClear(); + await act(async () => { + await rerender(makeMenu(false)); + await Promise.resolve(); + }); + + expect(durations()).toEqual([duration]); + } finally { + measureSpy.mockRestore(); + } + } +); diff --git a/src/components/__tests__/Modal.test.tsx b/src/components/__tests__/Modal.test.tsx index c6e723b60c..4a9a5f4dbb 100644 --- a/src/components/__tests__/Modal.test.tsx +++ b/src/components/__tests__/Modal.test.tsx @@ -17,6 +17,7 @@ import { } from '@jest/globals'; import { act, fireEvent, userEvent } from '@testing-library/react-native'; +import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; import { LightTheme } from '../../theme/schemes'; import { tokens } from '../../theme/tokens'; @@ -28,6 +29,9 @@ import type { TextInputHandles } from '../TextInput/TextInput'; const scrimAlpha = tokens.md.sys.scrim.alpha; jest.mock('react-native-safe-area-context', () => ({ + ...jest.requireActual( + 'react-native-safe-area-context' + ), useSafeAreaInsets: () => ({ bottom: 44, left: 0, right: 0, top: 37 }), })); @@ -979,4 +983,89 @@ describe('Modal', () => { expect(screen.queryByTestId('modal')).not.toBeOnTheScreen(); }); + + it('stays on the screen while it fades out when reduceMotion is "off"', async () => { + const makeModal = (visible: boolean) => ( + + + {null} + + + ); + + const { rerender } = await render(makeModal(true)); + await settle(); + + await rerender(makeModal(false)); + await act(() => { + jest.advanceTimersByTime(219); + }); + + expect(screen.getByTestId('modal')).toBeOnTheScreen(); + + await act(() => { + jest.advanceTimersByTime(1); + }); + + expect(screen.queryByTestId('modal')).not.toBeOnTheScreen(); + }); + + it('leaves the screen at once when reduceMotion is "on"', async () => { + const makeModal = (visible: boolean) => ( + + + {null} + + + ); + + const { rerender } = await render(makeModal(true)); + await settle(); + + await rerender(makeModal(false)); + await act(() => { + jest.advanceTimersByTime(0); + }); + + expect(screen.queryByTestId('modal')).not.toBeOnTheScreen(); + }); + + it('keeps its close timer when the OS reduce motion setting changes while it closes', async () => { + const addEventListener = jest.mocked(AccessibilityInfo.addEventListener); + const reduceMotionListeners = () => + addEventListener.mock.calls + .filter(([eventName]) => eventName === 'reduceMotionChanged') + .map(([, listener]) => listener); + addEventListener.mockClear(); + const makeModal = (visible: boolean) => ( + + + {null} + + + ); + + const { rerender } = await render(makeModal(true)); + await settle(); + expect(reduceMotionListeners()).not.toHaveLength(0); + + await rerender(makeModal(false)); + await act(() => { + jest.advanceTimersByTime(100); + }); + + for (const enabled of [true, false]) { + await act(() => { + reduceMotionListeners().forEach((listener) => listener(enabled)); + }); + } + + expect(screen.getByTestId('modal')).toBeOnTheScreen(); + + await act(() => { + jest.advanceTimersByTime(120); + }); + + expect(screen.queryByTestId('modal')).not.toBeOnTheScreen(); + }); }); diff --git a/src/components/__tests__/Portal.test.tsx b/src/components/__tests__/Portal.test.tsx index 999355ba74..f619119952 100644 --- a/src/components/__tests__/Portal.test.tsx +++ b/src/components/__tests__/Portal.test.tsx @@ -37,7 +37,7 @@ it('portal content reflects theme, direction, and reduced motion changes', async const reduceMotion = useReduceMotion(); return ( - {`${theme.animation.scale} ${direction} ${reduceMotion}`} + {`${theme.shapes.corner.small} ${direction} ${reduceMotion}`} ); }; @@ -45,7 +45,7 @@ it('portal content reflects theme, direction, and reduced motion changes', async - + @@ -59,7 +59,7 @@ it('portal content reflects theme, direction, and reduced motion changes', async - + diff --git a/src/components/__tests__/ProgressBar.test.tsx b/src/components/__tests__/ProgressBar.test.tsx index afd95f664b..d3b595854b 100644 --- a/src/components/__tests__/ProgressBar.test.tsx +++ b/src/components/__tests__/ProgressBar.test.tsx @@ -1,11 +1,17 @@ import * as React from 'react'; -// eslint-disable-next-line no-restricted-imports -- TODO: remove after ProgressBar migrates to Reanimated. -import { Animated, Platform, StyleSheet } from 'react-native'; - -import { afterEach, expect, it } from '@jest/globals'; +import { + AccessibilityInfo, + // eslint-disable-next-line no-restricted-imports -- TODO: remove after ProgressBar migrates to Reanimated. + Animated, + Platform, + StyleSheet, +} from 'react-native'; + +import { afterEach, describe, expect, it, jest } from '@jest/globals'; import { fireEvent } from '@testing-library/react-native'; -import { render, screen } from '../../test-utils'; +import PaperProvider from '../../core/PaperProvider'; +import { act, render, screen } from '../../test-utils'; import ProgressBar from '../ProgressBar'; import type { Props } from '../ProgressBar'; @@ -38,6 +44,7 @@ const AnimatedProgressBar = Animated.createAnimatedComponent(ClassProgressBar); afterEach(() => { Platform.OS = 'ios'; + jest.restoreAllMocks(); }); it('renders progress bar with animated value', async () => { @@ -101,3 +108,55 @@ it('renders progress bar with custom style of filled part', async () => { expect(view.toJSON()).toMatchSnapshot(); }); + +describe('with reduce motion', () => { + it.each([ + { reduceMotion: 'off', fade: 200 }, + { reduceMotion: 'on', fade: 0 }, + ] as const)( + 'fades out in $fade ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, fade }) => { + const makeProgressBar = (visible: boolean) => ( + + + + ); + + await render(makeProgressBar(true)); + const timing = jest.spyOn(Animated, 'timing'); + + await screen.rerender(makeProgressBar(false)); + + expect(timing.mock.calls.map(([, config]) => config.duration)).toEqual([ + fade, + ]); + } + ); + + it('does not restart the indeterminate animation 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 loop = jest.spyOn(Animated, 'loop'); + + await render( + + + + ); + const loopCount = loop.mock.calls.length; + expect(loopCount).toBeGreaterThan(0); + expect(reduceMotionListeners()).not.toHaveLength(0); + + for (const enabled of [true, false]) { + await act(() => { + reduceMotionListeners().forEach((listener) => listener(enabled)); + }); + } + + expect(loop).toHaveBeenCalledTimes(loopCount); + }); +}); diff --git a/src/components/__tests__/RadioButton/RadioButtonAndroid.test.tsx b/src/components/__tests__/RadioButton/RadioButtonAndroid.test.tsx new file mode 100644 index 0000000000..c94fbd9b3c --- /dev/null +++ b/src/components/__tests__/RadioButton/RadioButtonAndroid.test.tsx @@ -0,0 +1,70 @@ +// 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__/Snackbar.test.tsx b/src/components/__tests__/Snackbar.test.tsx index 5c30f7cc6e..37550f28a1 100644 --- a/src/components/__tests__/Snackbar.test.tsx +++ b/src/components/__tests__/Snackbar.test.tsx @@ -1,8 +1,10 @@ -import { StyleSheet, Text, View } from 'react-native'; +import { AccessibilityInfo, StyleSheet, Text, View } from 'react-native'; import { expect, it, jest } from '@jest/globals'; +import * as Reanimated from 'react-native-reanimated'; -import { render } from '../../test-utils'; +import PaperProvider from '../../core/PaperProvider'; +import { act, render } from '../../test-utils'; import { red200, white } from '../../theme/colors'; import Snackbar from '../Snackbar'; @@ -19,9 +21,25 @@ const styles = StyleSheet.create({ }); jest.mock('react-native-safe-area-context', () => ({ + ...jest.requireActual( + 'react-native-safe-area-context' + ), useSafeAreaInsets: () => ({ bottom: 34, left: 0, right: 0, top: 47 }), })); +jest.mock('react-native-reanimated', () => { + const ReanimatedModule = jest.requireActual< + typeof import('react-native-reanimated') + >('react-native-reanimated'); + + return { + __esModule: true, + ...ReanimatedModule, + default: ReanimatedModule.default, + withTiming: jest.fn(ReanimatedModule.withTiming), + }; +}); + it('renders snackbar with content', async () => { const tree = ( await render( @@ -91,3 +109,68 @@ it('renders snackbar with View & Text as a child', async () => { expect(tree).toMatchSnapshot(); }); + +it.each([ + { reduceMotion: 'off', show: 200, hide: 100 }, + { reduceMotion: 'on', show: 0, hide: 0 }, +] as const)( + 'appears in $show ms and disappears in $hide ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, show, hide }) => { + const withTiming = jest.mocked(Reanimated.withTiming); + const makeSnackbar = (visible: boolean) => ( + + + Snackbar content + + + ); + + const { rerender } = await render(makeSnackbar(false)); + withTiming.mockClear(); + + await rerender(makeSnackbar(true)); + await rerender(makeSnackbar(false)); + + expect(withTiming.mock.calls.map(([, config]) => config?.duration)).toEqual( + [show, hide] + ); + } +); + +it('keeps its dismiss timer when the OS reduce motion setting changes', async () => { + const addEventListener = jest.mocked(AccessibilityInfo.addEventListener); + const reduceMotionListeners = () => + addEventListener.mock.calls + .filter(([eventName]) => eventName === 'reduceMotionChanged') + .map(([, listener]) => listener); + addEventListener.mockClear(); + const onDismiss = jest.fn(); + + await render( + + + Snackbar content + + + ); + + // The snackbar appears in 200 ms and is dismissed 1000 ms later. + await act(() => { + jest.advanceTimersByTime(800); + }); + expect(reduceMotionListeners()).not.toHaveLength(0); + + for (const enabled of [true, false]) { + await act(() => { + reduceMotionListeners().forEach((listener) => listener(enabled)); + }); + } + + expect(onDismiss).not.toHaveBeenCalled(); + + await act(() => { + jest.advanceTimersByTime(500); + }); + + expect(onDismiss).toHaveBeenCalledTimes(1); +}); diff --git a/src/components/__tests__/Surface.test.tsx b/src/components/__tests__/Surface.test.tsx index 96ed707ae1..cb568ad767 100644 --- a/src/components/__tests__/Surface.test.tsx +++ b/src/components/__tests__/Surface.test.tsx @@ -20,6 +20,7 @@ import { useSharedValue, } from 'react-native-reanimated'; +import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; import { LightTheme } from '../../theme/schemes'; import Surface from '../Surface'; @@ -86,6 +87,26 @@ describe('Surface', () => { expect(getAnimatedStyle(surface)).toMatchObject({ opacity: 1 }); }); + describe('with reduce motion', () => { + it.each([ + { reduceMotion: 'off', duration: 150 }, + { reduceMotion: 'on', duration: 0 }, + ] as const)( + 'transitions its background and elevation in $duration ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, duration }) => { + await render( + + {null} + + ); + + expect( + getAnimatedStyle(screen.getByTestId('surface-test')) + ).toMatchObject({ transitionDuration: duration }); + } + ); + }); + describe('on iOS', () => { beforeEach(() => { jest.replaceProperty(Platform, 'OS', 'ios'); diff --git a/src/components/__tests__/__snapshots__/ListSection.test.tsx.snap b/src/components/__tests__/__snapshots__/ListSection.test.tsx.snap index bf5edb0f2d..8933cc1b95 100644 --- a/src/components/__tests__/__snapshots__/ListSection.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/ListSection.test.tsx.snap @@ -12,9 +12,6 @@ exports[`renders list section with custom title style 1`] = ` } theme={ { - "animation": { - "scale": 1, - }, "colors": { "background": "rgba(254, 247, 255, 1)", "elevation": { @@ -716,9 +713,6 @@ exports[`renders list section with subheader 1`] = ` } theme={ { - "animation": { - "scale": 1, - }, "colors": { "background": "rgba(254, 247, 255, 1)", "elevation": { @@ -1418,9 +1412,6 @@ exports[`renders list section without subheader 1`] = ` } theme={ { - "animation": { - "scale": 1, - }, "colors": { "background": "rgba(254, 247, 255, 1)", "elevation": { diff --git a/src/core/PaperProvider.tsx b/src/core/PaperProvider.tsx index 6c2394bd7c..be023ae268 100644 --- a/src/core/PaperProvider.tsx +++ b/src/core/PaperProvider.tsx @@ -21,6 +21,20 @@ export type Props = { theme?: ThemeProp; settings?: Settings; direction?: Direction; + /** + * Whether Paper's components reduce motion. With reduce motion on, their + * transitions jump to the end state instead of animating. The theming guide + * lists the few animations that don't follow it. + * + * - `'auto'` (default): follows the reduce motion setting of the OS, whether + * or not a `theme` is passed. It starts from the setting the OS had when + * the app launched, then follows every change, as reported by + * `AccessibilityInfo`. + * - `'on'`: reduces motion, whatever the OS setting. + * - `'off'`: doesn't reduce motion, whatever the OS setting. + * + * Components read the resolved value with `useReduceMotion()`. + */ reduceMotion?: ReduceMotionPreference; }; @@ -33,13 +47,8 @@ const PaperProvider = (props: Props) => { const theme = React.useMemo(() => { const isDark = props.theme?.dark ?? colorScheme === 'dark'; const base = isDark ? DarkTheme : LightTheme; - const scale = resolvedReduceMotion - ? 0 - : (props.theme?.animation?.scale ?? 1); - const merged = safeMerge(base, props.theme); - - return { ...merged, animation: { ...merged.animation, scale } }; - }, [colorScheme, props.theme, resolvedReduceMotion]); + return safeMerge(base, props.theme); + }, [colorScheme, props.theme]); const { children, settings } = props; diff --git a/src/core/__tests__/PaperProvider.test.tsx b/src/core/__tests__/PaperProvider.test.tsx index 6234315df8..7a3e2baa8e 100644 --- a/src/core/__tests__/PaperProvider.test.tsx +++ b/src/core/__tests__/PaperProvider.test.tsx @@ -1,4 +1,10 @@ -import { Appearance, AccessibilityInfo, Platform, View } from 'react-native'; +import { + Appearance, + AccessibilityInfo, + Platform, + Text, + View, +} from 'react-native'; import type { ColorSchemeName } from 'react-native'; import { @@ -34,7 +40,6 @@ declare module 'react-native' { interface ViewProps { theme?: object; - reduceMotion?: boolean; } } @@ -111,6 +116,11 @@ const FakeChild = () => { return ; }; +const ReduceMotionProbe = () => { + const reduceMotion = useReduceMotion(); + return {`reduceMotion: ${reduceMotion}`}; +}; + type ThemeReaderProps = { onTheme: (theme: Theme) => void; }; @@ -140,9 +150,6 @@ const createProvider = (theme?: ThemeProp) => { ); }; -const ExtendedLightTheme: ThemeProp = { ...LightTheme }; -const ExtendedDarkTheme: ThemeProp = { ...DarkTheme }; - const defaultPlatform = Platform.OS; describe('PaperProvider', () => { @@ -156,62 +163,78 @@ describe('PaperProvider', () => { await render(createProvider()); // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. expect(screen.getByTestId('provider-child-view').props.theme).toStrictEqual( - ExtendedLightTheme + LightTheme ); await act(() => Appearance.__internalListeners[0]({ colorScheme: 'dark' })); // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. expect(screen.getByTestId('provider-child-view').props.theme).toStrictEqual( - ExtendedDarkTheme + DarkTheme ); }); - it('subscribes to AccessibilityInfo and adapts theme.animation.scale when OS reduce-motion is enabled (auto mode)', async () => { + it.each([ + { label: 'without a theme', theme: undefined }, + { label: 'with a custom theme', theme: DarkTheme }, + ])( + 'follows the OS reduce-motion setting in "auto" mode $label', + async ({ theme }) => { + mockAppearance(); + mockAccessibilityInfo(); + + await render( + + + + ); + + expect(AccessibilityInfo.addEventListener).toHaveBeenCalled(); + expect(screen.getByText('reduceMotion: false')).toBeOnTheScreen(); + + await act(() => + getMockedAccessibilityInfo().__internalListeners[0](true) + ); + expect(screen.getByText('reduceMotion: true')).toBeOnTheScreen(); + + await act(() => + getMockedAccessibilityInfo().__internalListeners[0](false) + ); + expect(screen.getByText('reduceMotion: false')).toBeOnTheScreen(); + } + ); + + it('follows the OS reduce-motion setting from its first answer when reduceMotion is not set', async () => { mockAppearance(); mockAccessibilityInfo(); + mockJest + .mocked(AccessibilityInfo.isReduceMotionEnabled) + .mockResolvedValue(true); await render( - - + + ); - expect(AccessibilityInfo.addEventListener).toHaveBeenCalled(); - await act(() => getMockedAccessibilityInfo().__internalListeners[0](true)); - - expect( - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - screen.getByTestId('provider-child-view').props.theme.animation.scale - ).toStrictEqual(0); + expect(await screen.findByText('reduceMotion: true')).toBeOnTheScreen(); }); it('exposes the resolved reduce-motion boolean via useReduceMotion to children', async () => { mockAppearance(); mockAccessibilityInfo(); - const Probe = () => { - const reduceMotion = useReduceMotion(); - return ; - }; - const { rerender } = await render( - + ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(screen.getByTestId('reduce-motion-probe').props.reduceMotion).toBe( - true - ); + expect(screen.getByText('reduceMotion: true')).toBeOnTheScreen(); await rerender( - + ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(screen.getByTestId('reduce-motion-probe').props.reduceMotion).toBe( - false - ); + expect(screen.getByText('reduceMotion: false')).toBeOnTheScreen(); }); it('removes the AccessibilityInfo listener when reduceMotion switches from "auto" to "off"', async () => { @@ -244,32 +267,43 @@ describe('PaperProvider', () => { mockAppearance(); mockAccessibilityInfo(); await render( - - + + ); expect(AccessibilityInfo.addEventListener).not.toHaveBeenCalled(); - expect( - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - screen.getByTestId('provider-child-view').props.theme.animation.scale - ).toStrictEqual(1); + expect(screen.getByText('reduceMotion: false')).toBeOnTheScreen(); }); - it('forces animation.scale to 0 when reduceMotion is "on" without subscribing', async () => { + it('reduces motion when reduceMotion is "on" without subscribing to AccessibilityInfo', async () => { mockAppearance(); mockAccessibilityInfo(); await render( - + ); expect(AccessibilityInfo.addEventListener).not.toHaveBeenCalled(); - expect( - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - screen.getByTestId('provider-child-view').props.theme.animation.scale - ).toStrictEqual(0); + expect(screen.getByText('reduceMotion: true')).toBeOnTheScreen(); + }); + + it('keeps the same theme object when the OS reduce-motion setting changes', async () => { + mockAppearance(); + mockAccessibilityInfo(); + const onTheme = mockJest.fn<(theme: Theme) => void>(); + + await render( + + + + ); + const themeBefore = onTheme.mock.lastCall?.[0]; + + await act(() => getMockedAccessibilityInfo().__internalListeners[0](true)); + + expect(onTheme.mock.lastCall?.[0]).toBe(themeBefore); }); it('DynamicLightTheme falls back to LightTheme on non-Android platforms', () => { @@ -285,19 +319,19 @@ describe('PaperProvider', () => { await act(() => Appearance.__internalListeners[0]({ colorScheme: 'dark' })); // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. expect(screen.getByTestId('provider-child-view').props.theme).toStrictEqual( - ExtendedDarkTheme + DarkTheme ); }); it('should not set Appearance listeners, if the theme is passed', async () => { mockAppearance(); - await render(createProvider(ExtendedLightTheme)); + await render(createProvider(LightTheme)); expect(Appearance.addChangeListener).not.toHaveBeenCalled(); expect(Appearance.removeChangeListener).not.toHaveBeenCalled(); // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. expect(screen.getByTestId('provider-child-view').props.theme).toStrictEqual( - ExtendedLightTheme + LightTheme ); }); @@ -309,19 +343,19 @@ describe('PaperProvider', () => { expect(Appearance).toEqual(null); // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. expect(screen.getByTestId('provider-child-view').props.theme).toStrictEqual( - ExtendedLightTheme + LightTheme ); }); it.each([ { label: 'default theme', - theme: ExtendedLightTheme, + theme: LightTheme, colorScheme: 'light', }, { label: 'dark theme', - theme: ExtendedDarkTheme, + theme: DarkTheme, colorScheme: 'dark', }, ] satisfies Array<{ @@ -344,9 +378,9 @@ describe('PaperProvider', () => { it('uses provided custom theme', async () => { mockAppearance(); const customTheme: ThemeProp = { - ...ExtendedLightTheme, + ...LightTheme, colors: { - ...ExtendedLightTheme.colors, + ...LightTheme.colors, primary: 'tomato', }, }; @@ -377,7 +411,7 @@ describe('PaperProvider', () => { 'drops prototype keys from a theme parsed from JSON, read with $label', async ({ Reader, secondary }) => { const theme: ThemeProp = JSON.parse( - '{"__proto__": {"polluted": "yes"}, "colors": {"__proto__": {"polluted": "yes"}, "primary": "red"}, "animation": {"__proto__": {"polluted": "yes"}}}' + '{"__proto__": {"polluted": "yes"}, "colors": {"__proto__": {"polluted": "yes"}, "primary": "red"}}' ); const onTheme = mockJest.fn<(theme: Theme) => void>(); @@ -389,7 +423,7 @@ describe('PaperProvider', () => { expect(onTheme).toHaveBeenCalled(); const [received] = onTheme.mock.calls[0]; - for (const value of [received, received.colors, received.animation]) { + for (const value of [received, received.colors]) { expect(Object.getPrototypeOf(value)).toBe(Object.prototype); expect(Object.prototype.hasOwnProperty.call(value, '__proto__')).toBe( false @@ -399,7 +433,6 @@ describe('PaperProvider', () => { expect(received.colors.primary).toBe('red'); expect(received.colors.secondary).toBe(secondary); expect(received.colors.tertiary).toBe(LightTheme.colors.tertiary); - expect(received.animation.scale).toBe(1); expect(received.fonts).toEqual(LightTheme.fonts); expect({}).not.toHaveProperty('polluted'); } diff --git a/src/core/__tests__/reduceMotionThemeOverride.test.tsx b/src/core/__tests__/reduceMotionThemeOverride.test.tsx new file mode 100644 index 0000000000..f5620d11e3 --- /dev/null +++ b/src/core/__tests__/reduceMotionThemeOverride.test.tsx @@ -0,0 +1,68 @@ +import { StyleSheet } from 'react-native'; + +import { describe, expect, it } from '@jest/globals'; + +import Chip from '../../components/Chip/Chip'; +import Surface from '../../components/Surface'; +import { render, screen } from '../../test-utils'; +import { LightTheme } from '../../theme/schemes'; +import PaperProvider from '../PaperProvider'; + +// Reanimated's jest setup keeps CSS transition props off `style`, on the host +// view's `jestInlineStyle` prop. +const getTransitionDuration = ( + element: ReturnType | null +) => + // eslint-disable-next-line no-restricted-syntax -- CSS transitions are only readable from this Reanimated test prop. + StyleSheet.flatten(element?.props.jestInlineStyle)?.transitionDuration; + +// A full theme passed to a component, such as a built-in scheme, overrides +// what PaperProvider puts in the theme, so reduce motion has to reach the +// component another way. A theme written for an early 6.x build may also still +// set `animation.scale`, which Paper no longer reads. +const LegacyLightTheme = { ...LightTheme, animation: { scale: 1 } }; + +describe.each([ + { label: 'a built-in scheme', theme: LightTheme }, + { label: 'a theme that still sets animation.scale', theme: LegacyLightTheme }, +])('given $label', ({ theme }) => { + const cases = [ + { reduceMotion: 'on', duration: 0 }, + { reduceMotion: 'off', duration: LightTheme.motion.duration.short3 }, + ] as const; + + it.each(cases)( + 'transitions the elevation of a Surface in $duration ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, duration }) => { + await render( + + + {null} + + + ); + + expect(getTransitionDuration(screen.getByTestId('surface'))).toBe( + duration + ); + } + ); + + it.each(cases)( + 'transitions the elevation of a Chip in $duration ms when reduceMotion is "$reduceMotion"', + async ({ reduceMotion, duration }) => { + await render( + + {}} theme={theme}> + Chip + + + ); + + // The Chip's Surface is the container of its pressable body. + expect(getTransitionDuration(screen.getByRole('button').parent)).toBe( + duration + ); + } + ); +}); diff --git a/src/core/__tests__/useResolvedReduceMotion.test.tsx b/src/core/__tests__/useResolvedReduceMotion.test.tsx new file mode 100644 index 0000000000..3e02adeb03 --- /dev/null +++ b/src/core/__tests__/useResolvedReduceMotion.test.tsx @@ -0,0 +1,78 @@ +import { AccessibilityInfo, Text } from 'react-native'; + +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest, +} from '@jest/globals'; +import { act, render, screen } from '@testing-library/react-native'; + +import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; +import PaperProvider from '../PaperProvider'; + +let mockReducedMotionAtLaunch = false; + +jest.mock('react-native-reanimated', () => ({ + ...jest.requireActual('react-native-reanimated'), + useReducedMotion: () => mockReducedMotionAtLaunch, +})); + +const ReduceMotionProbe = () => { + const reduceMotion = useReduceMotion(); + return {`reduceMotion: ${reduceMotion}`}; +}; + +describe('reduce motion on the first render', () => { + let answer: (enabled: boolean) => void; + + beforeEach(() => { + jest + .spyOn(AccessibilityInfo, 'isReduceMotionEnabled') + .mockReturnValue(new Promise((resolve) => (answer = resolve))); + }); + + afterEach(() => { + mockReducedMotionAtLaunch = false; + jest.restoreAllMocks(); + }); + + it('reduces motion from the first render when the device setting was on at launch', async () => { + mockReducedMotionAtLaunch = true; + + await render( + + + + ); + + expect(screen.getByText('reduceMotion: true')).toBeOnTheScreen(); + }); + + it('follows the asynchronous answer when it differs from the setting at launch', async () => { + mockReducedMotionAtLaunch = true; + + await render( + + + + ); + await act(() => answer(false)); + + expect(screen.getByText('reduceMotion: false')).toBeOnTheScreen(); + }); + + it('ignores the setting at launch when reduceMotion is "off"', async () => { + mockReducedMotionAtLaunch = true; + + await render( + + + + ); + + expect(screen.getByText('reduceMotion: false')).toBeOnTheScreen(); + }); +}); diff --git a/src/core/useResolvedReduceMotion.ts b/src/core/useResolvedReduceMotion.ts index fe264e54fd..3cee7bd36d 100644 --- a/src/core/useResolvedReduceMotion.ts +++ b/src/core/useResolvedReduceMotion.ts @@ -1,6 +1,8 @@ import * as React from 'react'; import { AccessibilityInfo } from 'react-native'; +import { useReducedMotion } from 'react-native-reanimated'; + import { addEventListener } from '../utils/addEventListener'; export type ReduceMotionPreference = 'auto' | 'on' | 'off'; @@ -9,16 +11,19 @@ export type ReduceMotionPreference = 'auto' | 'on' | 'off'; * Resolves a reduce-motion preference into a boolean. * * - `'on'` / `'off'` are explicit overrides. - * - `'auto'` subscribes to `AccessibilityInfo.reduceMotionChanged` and follows - * the OS-level setting. - * - * `AccessibilityInfo.isReduceMotionEnabled()` is async, so the first render - * returns `false` for one frame regardless of OS state. + * - `'auto'` follows the OS-level setting. It starts from the value Reanimated + * reads synchronously when the app launches, so animations that start on the + * first render already see it. It then asks + * `AccessibilityInfo.isReduceMotionEnabled()`, which answers asynchronously, + * and subscribes to `AccessibilityInfo.reduceMotionChanged`. */ export function useResolvedReduceMotion( preference: ReduceMotionPreference ): boolean { - const [osReduceMotion, setOsReduceMotion] = React.useState(false); + const reducedMotionAtLaunch = useReducedMotion(); + const [osReduceMotion, setOsReduceMotion] = React.useState( + reducedMotionAtLaunch + ); React.useEffect(() => { if (preference !== 'auto') return; diff --git a/src/index.tsx b/src/index.tsx index 13e1918695..6945d219e6 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -9,6 +9,8 @@ export { export { useLocale, LocaleProvider } from './core/locale'; +export { useReduceMotion } from './theme/accessibility/ReduceMotionContext'; + export * from './theme/schemes'; export { default as Provider } from './core/PaperProvider'; @@ -142,3 +144,4 @@ export type { Props as ListImageProps } from './components/List/ListImage'; export type { Props as TooltipProps } from './components/Tooltip/Tooltip'; export { type TypescaleKey, type Theme, type Elevation } from './theme/types'; +export type { ReduceMotionPreference } from './core/useResolvedReduceMotion'; diff --git a/src/theme/__tests__/useMotionDuration.test.tsx b/src/theme/__tests__/useMotionDuration.test.tsx new file mode 100644 index 0000000000..729e720e3d --- /dev/null +++ b/src/theme/__tests__/useMotionDuration.test.tsx @@ -0,0 +1,64 @@ +import * as React from 'react'; + +import { describe, expect, it } from '@jest/globals'; +import { render, renderHook } from '@testing-library/react-native'; + +import PaperProvider from '../../core/PaperProvider'; +import type { ReduceMotionPreference } from '../../core/useResolvedReduceMotion'; +import { useMotionDuration } from '../accessibility/ReduceMotionContext'; + +const withProvider = + (reduceMotion: ReduceMotionPreference) => + ({ children }: { children: React.ReactNode }) => ( + {children} + ); + +describe('useMotionDuration', () => { + it('keeps the duration when reduceMotion is "off"', async () => { + const { result } = await renderHook(() => useMotionDuration(), { + wrapper: withProvider('off'), + }); + + expect(result.current(200)).toBe(200); + }); + + it('returns 0 when reduceMotion is "on"', async () => { + const { result } = await renderHook(() => useMotionDuration(), { + wrapper: withProvider('on'), + }); + + expect(result.current(200)).toBe(0); + }); + + it('keeps the duration outside a PaperProvider', async () => { + const { result } = await renderHook(() => useMotionDuration()); + + expect(result.current(150)).toBe(150); + }); + + it('keeps its identity and reads the latest preference when it changes', async () => { + const getDurations: ((duration: number) => number)[] = []; + const Probe = () => { + getDurations.push(useMotionDuration()); + return null; + }; + const makeTree = (reduceMotion: ReduceMotionPreference) => ( + + + + ); + + const { rerender } = await render(makeTree('off')); + const [getDuration] = getDurations; + expect(getDuration(200)).toBe(200); + + await rerender(makeTree('on')); + expect(getDuration(200)).toBe(0); + + await rerender(makeTree('off')); + expect(getDuration(200)).toBe(200); + + expect(getDurations.length).toBeGreaterThan(1); + expect(new Set(getDurations).size).toBe(1); + }); +}); diff --git a/src/theme/accessibility/ReduceMotionContext.tsx b/src/theme/accessibility/ReduceMotionContext.tsx index 34ad809060..a62767ba8e 100644 --- a/src/theme/accessibility/ReduceMotionContext.tsx +++ b/src/theme/accessibility/ReduceMotionContext.tsx @@ -1,15 +1,53 @@ import * as React from 'react'; +import useLatestCallback from 'use-latest-callback'; + export const ReduceMotionContext = React.createContext(false); /** - * Returns `true` when the user has requested reduced motion, either via the - * `reduceMotion` prop on `PaperProvider` (`"on"` | `"off"`) or, in `"auto"` - * mode (the default), via the OS-level setting reported by `AccessibilityInfo`. + * Returns `true` when motion should be reduced, and `false` otherwise. + * + * The value comes from the `reduceMotion` prop of the nearest `PaperProvider`: + * `'on'` and `'off'` set it, and `'auto'` (the default) follows the OS setting + * reported by `AccessibilityInfo`. Outside a `PaperProvider` it is `false`. + * Paper's own components read it too: when it is `true`, their transitions + * jump to the end state instead of animating. + * + * Use it to keep your own components in line with the user's choice. Reduce + * motion is about movement, so when it is `true`, skip animations that slide, + * scale, zoom or spin content, and show their end state instead. Opacity and + * color changes don't move anything on screen, so you can choose to keep them. + * Reanimated also follows the OS setting on its own, so give a Reanimated + * animation that this value gates `reduceMotion: ReduceMotion.Never`, or it + * still skips while the OS setting is on, even under `reduceMotion="off"`. * - * Use this in component code to gate motion-specific animations (translation, - * scale, transforms) while keeping non-motion animations (opacity, color) intact. + * @example + * const reduceMotion = useReduceMotion(); + * const duration = reduceMotion ? 0 : theme.motion.duration.medium2; */ export function useReduceMotion(): boolean { return React.useContext(ReduceMotionContext); } + +/** + * Returns a function that gives back the duration it is passed, or `0` when + * motion should be reduced. + * + * The function keeps its identity and reads the latest value of + * `useReduceMotion()` when it is called, so an effect that lists it doesn't + * run again, replaying an animation or restarting a timer, when the + * preference changes. Call it when an animation starts, not during render: + * there it can still return the previous render's value. + * + * @example + * const getDuration = useMotionDuration(); + * // In an effect or an event handler: + * opacity.value = withTiming(1, { + * duration: getDuration(200), + * reduceMotion: ReduceMotion.Never, + * }); + */ +export function useMotionDuration(): (duration: number) => number { + const reduceMotion = useReduceMotion(); + return useLatestCallback((duration: number) => (reduceMotion ? 0 : duration)); +} diff --git a/src/theme/schemes/base.ts b/src/theme/schemes/base.ts index 180ec1c155..4031914242 100644 --- a/src/theme/schemes/base.ts +++ b/src/theme/schemes/base.ts @@ -7,9 +7,6 @@ import type { Theme } from '../types'; type ThemeDefaults = Omit; export const themeDefaults: ThemeDefaults = { - animation: { - scale: 1.0, - }, fonts: defaultFonts, shapes: defaultShapes, motion: expressiveMotion, diff --git a/src/theme/tokens/sys/motion.ts b/src/theme/tokens/sys/motion.ts index f9e6dee79c..522dc1333b 100644 --- a/src/theme/tokens/sys/motion.ts +++ b/src/theme/tokens/sys/motion.ts @@ -120,11 +120,12 @@ const SPRING_SAMPLE_COUNT = 30; * with the time the spring takes to settle in milliseconds. * * @example + * const reduceMotion = useReduceMotion(); * const { points, duration } = toSpringCurve(theme.motion.spring.fast.spatial); * * const style = { * transitionProperty: 'borderRadius', - * transitionDuration: duration * theme.animation.scale, + * transitionDuration: reduceMotion ? 0 : duration, * transitionTimingFunction: linear(...points), * }; */ diff --git a/src/theme/types/theme.ts b/src/theme/types/theme.ts index a4ce2288ae..ba17a04910 100644 --- a/src/theme/types/theme.ts +++ b/src/theme/types/theme.ts @@ -8,9 +8,6 @@ import type { Typescale } from './typography'; export type Theme = { dark: boolean; - animation: { - scale: number; - }; colors: ThemeColors; fonts: Typescale; shapes: ThemeShapes;