From 6174db11fbc15b984963854401aa7b0770298e3d Mon Sep 17 00:00:00 2001 From: Doberjohn Date: Mon, 23 Nov 2026 18:12:34 +0200 Subject: [PATCH] refactor(button): share the shape morph between Button and IconButton Re-lands #5264, which #5279 reverted to keep it out of 6.0.0-alpha.4. Button and IconButton now share useShapeMorph, which caps the spring curve against the inner corner, as Button already did (IconButton capped against the outer one). With the default spring both caps give the same curve. The ripple color helper moves to TouchableRipple/utils, so IconButton no longer imports from Button. Co-authored-by: Luke Walczak --- src/components/Button/Button.tsx | 58 ++++------- src/components/Button/utils.tsx | 49 ---------- src/components/IconButton/IconButton.tsx | 66 ++++--------- src/components/TouchableRipple/utils.ts | 30 ++++++ src/components/__tests__/Button.test.tsx | 96 +++++++++--------- src/components/__tests__/Chip.test.tsx | 11 +-- src/components/__tests__/IconButton.test.tsx | 62 +++++++++++- .../__tests__/TouchableRippleUtils.test.tsx | 25 +++++ .../reduceMotionThemeOverride.test.tsx | 24 ++--- src/test-utils.tsx | 20 +++- src/utils/__tests__/useShapeMorph.test.ts | 64 ++++++++++++ src/utils/useShapeMorph.ts | 97 +++++++++++++++++++ 12 files changed, 386 insertions(+), 216 deletions(-) create mode 100644 src/components/__tests__/TouchableRippleUtils.test.tsx create mode 100644 src/utils/__tests__/useShapeMorph.test.ts create mode 100644 src/utils/useShapeMorph.ts diff --git a/src/components/Button/Button.tsx b/src/components/Button/Button.tsx index 0e7365f953..dd39a768e7 100644 --- a/src/components/Button/Button.tsx +++ b/src/components/Button/Button.tsx @@ -11,7 +11,7 @@ import type { ViewStyle, } from 'react-native'; -import Reanimated, { linear } from 'react-native-reanimated'; +import Reanimated from 'react-native-reanimated'; import { createIsMode, @@ -19,8 +19,6 @@ import { getButtonContentBoxStyle, getButtonHitSlop, getButtonPressedRadius, - getButtonRippleColor, - getButtonShapeCurvePoints, getButtonShapeRadius, getButtonSizeStyle, getButtonTransitionDuration, @@ -29,10 +27,10 @@ import { import { getDefaultDirection, useLocale } from '../../core/locale'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; -import { toSpringCurve } from '../../theme/tokens/sys/motion'; import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; import { useFocusRing } from '../../utils/useFocusRing'; +import { useShapeMorph } from '../../utils/useShapeMorph'; import ActivityIndicator from '../ActivityIndicator'; import Icon from '../Icon'; import type { IconSource } from '../Icon'; @@ -40,6 +38,7 @@ import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; +import { getRippleColorFromContent } from '../TouchableRipple/utils'; import Text from '../Typography/Text'; // Elevation levels (MD3) used by the `elevated` mode: level 1 at rest, @@ -346,12 +345,6 @@ const Button = ({ animatesShape && pressed ? getButtonPressedRadius({ size, theme }) : restingRadius; - const shapeSpring = React.useMemo( - () => toSpringCurve(theme.motion.spring.fast.spatial), - [theme.motion.spring.fast.spatial] - ); - const shapeTransitionDuration = animatesShape ? shapeSpring.duration : 0; - const tracksPress = animatesShape || isElevationEntitled; const handlePressIn = React.useCallback( @@ -405,7 +398,7 @@ const Button = ({ ); const rippleColor = React.useMemo( - () => getButtonRippleColor({ labelColor }), + () => getRippleColorFromContent({ contentColor: labelColor }), [labelColor] ); @@ -427,23 +420,22 @@ const Button = ({ previousContainerColor: committedContainerColor, }); - const innerRadius = Math.max(0, radius - borderWidth); - const largestRadius = Math.max( - sizeStyle.minHeight / 2, - getButtonShapeRadius({ size, shape: 'square', theme }), - getButtonPressedRadius({ size, theme }) - ); - const shapeTimingFunction = React.useMemo( - () => - linear( - ...getButtonShapeCurvePoints({ - points: shapeSpring.points, - radius: innerRadius, - largestRadius: Math.max(0, largestRadius - borderWidth), - }) - ), - [shapeSpring.points, innerRadius, largestRadius, borderWidth] - ); + const { + duration: shapeTransitionDuration, + timingFunction: shapeTimingFunction, + outerStyle: clipStyle, + innerStyle: innerClipStyle, + } = useShapeMorph({ + theme, + radius, + largestRadius: Math.max( + sizeStyle.minHeight / 2, + getButtonShapeRadius({ size, shape: 'square', theme }), + getButtonPressedRadius({ size, theme }) + ), + borderWidth, + animate: animatesShape, + }); // The clip carries the same radius transition as the `Surface`, so the // ripple and the disabled overlay follow the morph. @@ -460,16 +452,6 @@ const Button = ({ 'outward', 'within' ); - const shapeTransitionStyle = { - transitionProperty: 'borderRadius', - transitionDuration: shapeTransitionDuration, - transitionTimingFunction: shapeTimingFunction, - } as const; - - const clipStyle = { ...shapeTransitionStyle, borderRadius: radius }; - - const innerClipStyle = { ...shapeTransitionStyle, borderRadius: innerRadius }; - const outlineStyle = React.useMemo( () => ({ borderColor, borderWidth }), [borderColor, borderWidth] diff --git a/src/components/Button/utils.tsx b/src/components/Button/utils.tsx index 1844654478..f784225a04 100644 --- a/src/components/Button/utils.tsx +++ b/src/components/Button/utils.tsx @@ -1,7 +1,5 @@ import type { ColorValue, Insets } from 'react-native'; -import color from 'color'; - import { Tokens } from './tokens'; import type { ButtonToggleMode } from './tokens'; import { black, white } from '../../theme/colors'; @@ -151,28 +149,6 @@ export const getButtonTransitionDuration = ({ return theme.motion.duration[pressed ? 'short4' : 'short3']; }; -/** - * Caps the spring curve so the corner can't overshoot below 0 on its way to - * `radius`, from any start up to `largestRadius`. - */ -export const getButtonShapeCurvePoints = ({ - points, - radius, - largestRadius, -}: { - points: number[]; - radius: number; - largestRadius: number; -}): number[] => { - if (largestRadius <= radius) { - return points; - } - - const maxProgress = largestRadius / (largestRadius - radius); - - return points.map((point) => Math.min(point, maxProgress)); -}; - /** Corner the container morphs to while pressed. */ export const getButtonPressedRadius = ({ size, @@ -449,28 +425,3 @@ export const getButtonColors = ({ backgroundOpacity, }; }; - -/** - * Returns the color used for the button's ripple / state layer: the label - * color at the pressed-state opacity (per Material Design 3). - * - * When the label color is not a plain string (e.g. an Android Material You - * `PlatformColor`), or is a string `color` can't parse (e.g. `var(--x)` or - * `currentColor` on web), `undefined` is returned so `TouchableRipple` falls - * back to its own default state-layer color. - */ -export const getButtonRippleColor = ({ - labelColor, -}: { - labelColor: ColorValue; -}): ColorValue | undefined => { - if (typeof labelColor !== 'string') { - return undefined; - } - - try { - return color(labelColor).alpha(stateOpacity.pressed).rgb().string(); - } catch { - return undefined; - } -}; diff --git a/src/components/IconButton/IconButton.tsx b/src/components/IconButton/IconButton.tsx index 82730ced44..a3553503c1 100644 --- a/src/components/IconButton/IconButton.tsx +++ b/src/components/IconButton/IconButton.tsx @@ -9,33 +9,26 @@ import type { ViewStyle, } from 'react-native'; -import Animated, { - type AnimatedStyle, - linear, - type CSSStyle, -} from 'react-native-reanimated'; +import Animated, { type AnimatedStyle } from 'react-native-reanimated'; import type { Mode, Shape, Size, Width } from './tokens'; import { getDimensions, getIconButtonColor } from './utils'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; -import { toSpringCurve } from '../../theme/tokens/sys/motion'; import type { ThemeProp } from '../../theme/types'; import getMinInteractiveSizeHitSlop from '../../utils/getMinInteractiveSizeHitSlop'; import hasTouchHandler, { carriesToggleState, } from '../../utils/hasTouchHandler'; import { useFocusRing } from '../../utils/useFocusRing'; +import { useShapeMorph } from '../../utils/useShapeMorph'; import ActivityIndicator from '../ActivityIndicator'; -import { - getButtonRippleColor, - getButtonShapeCurvePoints, -} from '../Button/utils'; import CrossFadeIcon from '../CrossFadeIcon'; import Icon from '../Icon'; import type { IconSource } from '../Icon'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; +import { getRippleColorFromContent } from '../TouchableRipple/utils'; const AnimatedTouchableRipple = Animated.createAnimatedComponent(TouchableRipple); @@ -242,38 +235,21 @@ const IconButton = ({ const borderRadius = isPressed ? dimensions.pressedRadius : dimensions.restingRadius; - // The morph follows the MD3 fast spatial spring, as on Button. The curve is - // capped so a bouncy spring can't push the corner below 0 on its way back - // from the largest radius (the round one). - const shapeSpring = React.useMemo( - () => toSpringCurve(theme.motion.spring.fast.spatial), - [theme.motion.spring.fast.spatial] - ); - const largestRadius = Math.max( - dimensions.height / 2, - dimensions.restingRadius, - dimensions.pressedRadius - ); - const shapeTimingFunction = React.useMemo( - () => - linear( - ...getButtonShapeCurvePoints({ - points: shapeSpring.points, - radius: borderRadius, - largestRadius, - }) + const { outerStyle: radiusStyle, innerStyle: innerRadiusStyle } = + useShapeMorph({ + theme, + radius: borderRadius, + largestRadius: Math.max( + dimensions.height / 2, + dimensions.restingRadius, + dimensions.pressedRadius ), - [shapeSpring.points, borderRadius, largestRadius] - ); - const radiusStyle: CSSStyle = { - borderRadius, - transitionProperty: ['borderRadius'], - transitionDuration: reduceMotion ? 0 : shapeSpring.duration, - transitionTimingFunction: shapeTimingFunction, - }; + borderWidth, + animate: !reduceMotion, + }); // The state layer takes the icon color, as Button's takes its label color. - const rippleColor = getButtonRippleColor({ labelColor: iconColor }); + const rippleColor = getRippleColorFromContent({ contentColor: iconColor }); const handlePressIn = (e: GestureResponderEvent) => { setPressed(true); @@ -345,16 +321,6 @@ const IconButton = ({ !hasPassedTouchHandler && !carriesToggleState({ ...rest, ...toggleStateProps }); - // The touchable and the disabled layer sit inside the outline, so their - // corner is the container's less the outline, and they morph with it. The - // touchable clips its own ripple to it, though not on web, where - // `overflow: 'hidden'` would also clip the hit slop target; there the ripple - // container follows the touchable's corner. - const innerRadiusStyle: CSSStyle = { - ...radiusStyle, - borderRadius: Math.max(0, borderRadius - borderWidth), - }; - return ( (typeof children === 'function' ? children(state) : children); + +/** + * Returns the ripple / state layer color for a component's content: the + * content color at the pressed-state opacity (per Material Design 3). + * + * When the content color is not a plain string (e.g. an Android Material You + * `PlatformColor`), or is a string `color` can't parse (e.g. `var(--x)` or + * `currentColor` on web), `undefined` is returned so `TouchableRipple` falls + * back to its own default state-layer color. + */ +export const getRippleColorFromContent = ({ + contentColor, +}: { + contentColor: ColorValue; +}): ColorValue | undefined => { + if (typeof contentColor !== 'string') { + return undefined; + } + + try { + return color(contentColor).alpha(stateOpacity.pressed).rgb().string(); + } catch { + return undefined; + } +}; diff --git a/src/components/__tests__/Button.test.tsx b/src/components/__tests__/Button.test.tsx index 61b23afe0e..6295f2eba9 100644 --- a/src/components/__tests__/Button.test.tsx +++ b/src/components/__tests__/Button.test.tsx @@ -2,11 +2,10 @@ import { Platform, PlatformColor, StyleSheet } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; 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 { render, screen, transitionOf } from '../../test-utils'; import { ReduceMotionContext } from '../../theme/accessibility/ReduceMotionContext'; import { pink500, white } from '../../theme/colors'; import { LightTheme } from '../../theme/schemes'; @@ -20,8 +19,6 @@ import { getButtonContentBoxStyle, getButtonHitSlop, getButtonPressedRadius, - getButtonRippleColor, - getButtonShapeCurvePoints, getButtonShapeRadius, getButtonSizeStyle, getButtonTransitionDuration, @@ -630,20 +627,6 @@ describe('getButtonColors - border width', () => { ); }); -describe('getButtonRippleColor', () => { - it('defaults to the label color at the pressed-state opacity', () => { - expect(getButtonRippleColor({ labelColor: '#123456' })).toBe( - color('#123456').alpha(stateOpacity.pressed).rgb().string() - ); - }); - - it('returns undefined when the label color is not a plain string', () => { - expect( - getButtonRippleColor({ labelColor: PlatformColor('?attr/colorPrimary') }) - ).toBeUndefined(); - }); -}); - it('renders with a label color the ripple cannot parse', async () => { await render( + ); + const touchable = screen.getByTestId('button'); + const clip = parentOf(touchable, 'the touchable'); + + expect(transitionOf(touchable)).toEqual(transitionOf(clip)); + + await fireEvent(touchable, 'onPressIn'); + + expect(transitionOf(touchable)).toEqual(transitionOf(clip)); + expect(clip).toHaveStyle({ borderRadius: LightTheme.shapes.corner.large }); + expect(touchable).toHaveStyle({ + borderRadius: + LightTheme.shapes.corner.large - + Tokens.sizes.large.outlinedOutlineWidth, + }); + }); + + it('snaps the corner when animateShape is false', async () => { + await render( + + ); + const touchable = screen.getByTestId('button'); + + expect(transitionOf(touchable).transitionDuration).toBe(0); + expect( + transitionOf(parentOf(touchable, 'the touchable')).transitionDuration + ).toBe(0); + }); + it('still changes the shape when animateShape is false and selected flips', async () => { await render(