Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 20 additions & 38 deletions src/components/Button/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,14 @@ import type {
ViewStyle,
} from 'react-native';

import Reanimated, { linear } from 'react-native-reanimated';
import Reanimated from 'react-native-reanimated';

import {
createIsMode,
getButtonColors,
getButtonContentBoxStyle,
getButtonHitSlop,
getButtonPressedRadius,
getButtonRippleColor,
getButtonShapeCurvePoints,
getButtonShapeRadius,
getButtonSizeStyle,
getButtonTransitionDuration,
Expand All @@ -29,17 +27,18 @@ 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';
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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -405,7 +398,7 @@ const Button = ({
);

const rippleColor = React.useMemo(
() => getButtonRippleColor({ labelColor }),
() => getRippleColorFromContent({ contentColor: labelColor }),
[labelColor]
);

Expand All @@ -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.
Expand All @@ -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]
Expand Down
49 changes: 0 additions & 49 deletions src/components/Button/utils.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}
};
66 changes: 17 additions & 49 deletions src/components/IconButton/IconButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<ViewStyle> = {
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);
Expand Down Expand Up @@ -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<ViewStyle> = {
...radiusStyle,
borderRadius: Math.max(0, borderRadius - borderWidth),
};

return (
<Animated.View
ref={ref}
Expand Down Expand Up @@ -407,6 +373,8 @@ const IconButton = ({
style={[
styles.touchable,
innerRadiusStyle,
// Not on web, where `overflow: 'hidden'` would also clip the hit
// slop target; there the ripple container follows the corner.
Platform.OS !== 'web' && styles.clipToShape,
contentStyle,
]}
Expand Down
30 changes: 30 additions & 0 deletions src/components/TouchableRipple/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import type { ColorValue } from 'react-native';

import color from 'color';

import type { PressableProps, PressableStateCallbackType } from './Pressable';
import { tokens } from '../../theme/tokens';
import type { InternalTheme } from '../../theme/types';

const stateOpacity = tokens.md.sys.state.opacity;

const getUnderlayColor = ({
calculatedRippleColor,
underlayColor,
Expand Down Expand Up @@ -66,3 +71,28 @@ export const resolveChildren = (
children: PressableProps['children'],
state: PressableStateCallbackType
) => (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;
}
};
Loading
Loading