diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md
index a495505e74..28e0db29f2 100644
--- a/docs/6.x/docs/guides/migration.md
+++ b/docs/6.x/docs/guides/migration.md
@@ -166,7 +166,7 @@ If you were relying on internal test IDs, update your tests not to rely on inter
Some components now accept explicit `testID` props for their interactable elements:
- `BottomNavigation`: `barTestID` for the internal `BottomNavigation.Bar`, replacing the previous `${testID}-bar` derivation.
-- `Chip`: `closeIconTestID` for the close icon button.
+- `Chip`: `closeIconTestID` for the close icon button and `trailingIconTestID` for the trailing icon button.
- `Dialog` and `Modal`: `overlayTestID` for the overlay displayed behind the content.
- `Menu`: `overlayTestID` for the overlay displayed behind the menu.
- `Searchbar`: `searchTestID`, `clearTestID`, and `trailingTestID` for the search, clear, and trailing icon buttons.
@@ -422,6 +422,52 @@ A library that reads `theme.animation.scale` to turn its own animations off shou
## Components
+### Chip
+
+#### Default mode
+
+- The default **`mode`** changed from **`"flat"`** to **`"outlined"`**.
+
+```tsx
+// Before (v5) - no mode passed, rendered flat
+ {}}>Example Chip
+
+// After (v6) - no mode passed, renders outlined; pass mode="flat" to keep the old look
+ {}}>Example Chip
+```
+
+#### Removed props
+
+- **`compact`** The chip always uses the MD3 32dp height; to change the size, use `style`.
+- **`showSelectedOverlay`** A selected chip shows a check icon (`showSelectedCheck`, on by default). With an `avatar`, the check is drawn over the avatar automatically.
+- **`avatar`** is rendered as is inside a clipped 24dp circle; Chip no longer injects a `style` into it. Size the avatar to 24dp yourself.
+
+#### New props
+
+- **`trailingIcon`** / **`onTrailingIconPress`** / **`trailingIconAccessibilityLabel`** add a trailing action (e.g. a dropdown) independent of the close button. `trailingIcon` takes precedence over `onClose`'s close icon when both are specified.
+- **`backgroundColor`** / **`borderRadius`** replace overriding the chip's background color or border radius through `style`. `style` no longer accepts `backgroundColor` or `borderRadius`.
+
+```tsx
+// Before (v5)
+ {}} style={{ backgroundColor: 'purple', borderRadius: 16 }}>Example Chip
+
+// After (v6)
+ {}} backgroundColor="purple" borderRadius={16}>Example Chip
+```
+
+#### Colors and states
+
+- **`selectedColor`** now also tints the trailing icon and the border of an unselected outlined chip, at full strength (the border used to be at 29% opacity). A disabled chip ignores it.
+- An unselected `flat` chip uses `surfaceContainerLow` instead of `secondaryContainer`, with an `onSurfaceVariant` label and a `primary` leading icon.
+- A selected chip uses the `secondaryContainer` color in both modes (outlined chips used to stay on `surface`), and `elevated` chips use `surfaceContainerLow`.
+- Disabled chips use the `stateLayerPressed` container color.
+
+#### Close button and touch targets
+
+- The close button (`onClose`) is now a 32dp circle flush with the trailing edge of the chip, instead of a column. Its touch target extends to 48dp above, below and past the trailing edge (not over the label), and taps in that area that used to activate the chip's `onPress` now activate `onClose`.
+- The chip's own touch target is 48dp tall by default. A custom **`hitSlop`** replaces that default entirely.
+- A `trailingIcon` without `onTrailingIconPress` is decorative: it is not focusable and not announced as a button.
+
### Appbar
`Appbar.Content` no longer takes `subtitle` or `subtitleStyle`, which were deprecated in 5.x. In 5.x they only rendered with a Material Design 2 theme, so removing them doesn't change how a Material Design 3 app looks.
@@ -772,10 +818,6 @@ The misspelled `traileringIcon` props have been renamed:
/>
```
-### Chip
-
-The close button (`onClose`) now fills the trailing 34dp column reserved for it, instead of only the 26x18 area around its icon, and its touch target extends to 48dp in height. Taps in that column that used to activate the chip's `onPress` now activate `onClose`.
-
### IconButton
Corner radii set through `style` no longer shape the press, hover and disabled feedback.
diff --git a/docs/public/gallery/chip-dark.png b/docs/public/gallery/chip-dark.png
index ac6ea638fe..565e446b82 100644
Binary files a/docs/public/gallery/chip-dark.png and b/docs/public/gallery/chip-dark.png differ
diff --git a/docs/public/gallery/chip.png b/docs/public/gallery/chip.png
index 6613a45bb5..f8537ac640 100644
Binary files a/docs/public/gallery/chip.png and b/docs/public/gallery/chip.png differ
diff --git a/docs/public/screenshots/chip.png b/docs/public/screenshots/chip.png
new file mode 100644
index 0000000000..f8537ac640
Binary files /dev/null and b/docs/public/screenshots/chip.png differ
diff --git a/docs/src/data/screenshots.ts b/docs/src/data/screenshots.ts
index 90f9f0273c..399aa4b162 100644
--- a/docs/src/data/screenshots.ts
+++ b/docs/src/data/screenshots.ts
@@ -51,10 +51,7 @@ export const screenshots = {
enabled: 'screenshots/checkbox-enabled.ios.png',
disabled: 'screenshots/checkbox-disabled.ios.png',
},
- Chip: {
- flat: 'screenshots/chip-1.png',
- outlined: 'screenshots/chip-2.png',
- },
+ Chip: 'screenshots/chip.png',
DataTable: 'screenshots/data-table-full-width.png',
'DataTable.Cell': 'screenshots/data-table-row-cell.png',
'DataTable.Header': 'screenshots/data-table-header.png',
diff --git a/example/src/Examples/ButtonExample.tsx b/example/src/Examples/ButtonExample.tsx
index 554f80cda1..26d6a566f1 100644
--- a/example/src/Examples/ButtonExample.tsx
+++ b/example/src/Examples/ButtonExample.tsx
@@ -54,8 +54,6 @@ function OptionRow({
onChange(option)}
style={styles.chip}
diff --git a/example/src/Examples/ChipExample.tsx b/example/src/Examples/ChipExample.tsx
index c6c817041f..14f493a103 100644
--- a/example/src/Examples/ChipExample.tsx
+++ b/example/src/Examples/ChipExample.tsx
@@ -2,11 +2,14 @@ import * as React from 'react';
import { Image, StyleSheet, View } from 'react-native';
import color from 'color';
-import { Chip, List, Palette, Snackbar, Text } from 'react-native-paper';
+import { Chip, List, Palette, Snackbar } from 'react-native-paper';
import ScreenWrapper from '../ScreenWrapper';
+const filters = ['All', 'Unread', 'Starred'];
+
const ChipExample = () => {
+ const [selectedFilter, setSelectedFilter] = React.useState(filters[0]);
const [snackbarProperties, setSnackbarProperties] = React.useState({
visible: false,
text: '',
@@ -16,171 +19,85 @@ const ChipExample = () => {
return (
<>
-
+
- {}} style={styles.chip}>
- Simple
+ {filters.map((filter) => (
+ setSelectedFilter(filter)}
+ style={styles.chip}
+ >
+ {filter}
+
+ ))}
+ {}} style={styles.chip}>
+ With icon
{}}
style={styles.chip}
>
- With selected overlay
-
- {}} style={styles.chip}>
- Elevated
+ No check
- {}}>
- Compact chip
-
- {}}
- onClose={() =>
- setSnackbarProperties({
- visible: true,
- text: 'Close button pressed',
- })
- }
- style={styles.chip}
- closeIconAccessibilityLabel="Close icon accessibility label"
- >
- Close button
-
- {}}
- onClose={() =>
- setSnackbarProperties({
- visible: true,
- text: 'Heart icon close button pressed',
- })
- }
- style={styles.chip}
- >
- Icon
-
-
- }
- onPress={() => {}}
- onClose={() =>
- setSnackbarProperties({
- visible: true,
- text: 'Avatar close button pressed',
- })
- }
- style={styles.chip}
- >
- Avatar
+
+ Disabled
- }
+ trailingIcon="menu-down"
onPress={() => {}}
- style={styles.chip}
- >
- Avatar (selected)
-
-
+ onTrailingIconPress={() =>
setSnackbarProperties({
visible: true,
- text: 'Disabled heart icon close button pressed',
+ text: 'Filter menu icon pressed',
})
}
+ trailingIconAccessibilityLabel="Open filter menu"
style={styles.chip}
>
- Icon (disabled)
-
-
- }
- style={styles.chip}
- >
- Avatar (disabled)
+ Trailing icon
-
+
+
- {}} style={styles.chip}>
- Simple
+ {}} style={styles.chip}>
+ Outlined
{}}
style={styles.chip}
>
- With selected overlay
+ Flat
{}}
style={styles.chip}
>
Elevated
- {}}
- style={styles.chip}
- >
- Compact chip
-
- {}}
- onClose={() =>
- setSnackbarProperties({
- visible: true,
- text: 'Close button pressed',
- })
- }
- style={styles.chip}
- >
- Close button
-
- {}}
- onClose={() =>
- setSnackbarProperties({
- visible: true,
- text: 'Heart icon close button pressed',
- })
- }
- style={styles.chip}
- >
- Icon
+ {}} style={styles.chip}>
+ No icon
+
+
+
+
+
}
@@ -191,7 +108,6 @@ const ChipExample = () => {
{
onPress={() => {}}
style={styles.chip}
>
- Avatar (selected)
+ Selected avatar
{}}
onClose={() =>
setSnackbarProperties({
visible: true,
- text: 'Disabled close button pressed',
+ text: 'Close button pressed',
})
}
style={styles.chip}
>
- Icon (disabled)
+ Removable
+ closeIcon="arrow-down"
+ onPress={() => {}}
+ onClose={() =>
+ setSnackbarProperties({
+ visible: true,
+ text: 'Custom trailing icon pressed',
+ })
}
style={styles.chip}
+ closeIconAccessibilityLabel="Custom trailing icon accessibility label"
>
- Avatar (disabled)
+ Custom trailing
-
+
+
- {}}
- compact
- avatar={
-
- }
- style={styles.chip}
- theme={{ shapes: { corner: { small: 16 } } }}
- >
- Compact with custom border radius
-
- {}}
- compact
- avatar={
-
- }
- style={styles.chip}
- theme={{ shapes: { corner: { small: 16 } } }}
- >
- Compact with custom border radius
+ {}} style={styles.chip}>
+ Outlined
- {}}
- onLongPress={() =>
- setSnackbarProperties({ visible: true, text: '' })
- }
- style={styles.chip}
- >
- With onLongPress
+ {}} style={styles.chip}>
+ Flat
- {}}
- style={styles.chip}
- theme={{
- colors: {
- secondaryContainer: color(customColor)
- .alpha(0.2)
- .rgb()
- .string(),
- },
- }}
- selectedColor={customColor}
- >
- Flat selected chip with custom color
+ {}} style={styles.chip}>
+ Elevated
- {}}
- style={styles.chip}
- selectedColor={customColor}
- >
- Flat unselected chip with custom color
+ {}} style={styles.chip}>
+ With icon
+
+
+
+
+
{}}
- style={styles.chip}
- theme={{
- colors: {
- surface: color(customColor).alpha(0.2).rgb().string(),
- },
- }}
- selectedColor={customColor}
- >
- Outlined selected chip with custom color
-
- {}}
- style={styles.chip}
selectedColor={customColor}
- >
- Outlined unselected chip with custom color
-
- {}}
+ backgroundColor={color(customColor).alpha(0.2).rgb().string()}
style={styles.chip}
- textStyle={styles.tiny}
- >
- With custom size
-
- {}}
- onClose={() =>
- setSnackbarProperties({
- visible: true,
- text: 'Close button pressed',
- })
- }
- style={styles.bigTextFlex}
- textStyle={styles.bigTextStyle}
- ellipsizeMode="middle"
>
- With a very big text: React Native Paper is a high-quality,
- standard-compliant Material Design library that has you covered in
- all major use-cases.
+ Custom color
- {}}
- onClose={() =>
- setSnackbarProperties({
- visible: true,
- text: 'Custom icon close button pressed',
- })
- }
- closeIcon="arrow-down"
- style={styles.chip}
- closeIconAccessibilityLabel="Custom Close icon accessibility label"
- >
- With custom close icon
+ {}} borderRadius={16} style={styles.chip}>
+ Rounded
- {}}
- style={styles.chip}
- textStyle={styles.tiny}
- >
- With custom text
+ {}} style={styles.fullWidthChip}>
+ Full width chip
- {}} style={styles.fullWidthChip}>
- Full width chip
-
({
onChange(option)}
>
{option}
diff --git a/example/src/Examples/TeamDetails.tsx b/example/src/Examples/TeamDetails.tsx
index cb06e817d6..619e0ba3f8 100644
--- a/example/src/Examples/TeamDetails.tsx
+++ b/example/src/Examples/TeamDetails.tsx
@@ -57,12 +57,7 @@ const News = () => {
style={styles.chipsContainer}
contentContainerStyle={styles.chipsContent}
>
- {}}
- style={styles.chip}
- showSelectedOverlay
- >
+ {}} style={styles.chip}>
Latest
{}} style={styles.chip}>
diff --git a/src/components/Chip/Chip.tsx b/src/components/Chip/Chip.tsx
index 68fb7b70ca..4339387556 100644
--- a/src/components/Chip/Chip.tsx
+++ b/src/components/Chip/Chip.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { Platform, StyleSheet, Pressable, View } from 'react-native';
+import { Platform, StyleSheet, View } from 'react-native';
import type {
ColorValue,
GestureResponderEvent,
@@ -8,35 +8,37 @@ import type {
TextProps,
TextStyle,
ViewProps,
+ ViewStyle,
} from 'react-native';
-import useLatestCallback from 'use-latest-callback';
-
-import { getChipColors } from './helpers';
-import type { ChipAvatarProps } from './helpers';
import { ChipTokens } from './tokens';
+import { getChipColors } from './utils';
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';
-import getMinInteractiveSizeHitSlop from '../../utils/getMinInteractiveSizeHitSlop';
import hasTouchHandler from '../../utils/hasTouchHandler';
+import { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent';
import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing';
import type { IconSource } from '../Icon';
import Icon from '../Icon';
-import MaterialCommunityIcon from '../MaterialCommunityIcon';
import Surface from '../Surface';
-import type { SurfaceStyle } from '../Surface';
import TouchableRipple from '../TouchableRipple/TouchableRipple';
import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple';
import Text from '../Typography/Text';
+// The trailing icon's touch target is a square flush with the chip's
+// top/bottom edges (so its ripple/state layer stays circular per MD3),
+// sized to the chip height rather than a fixed value of its own.
+const TRAILING_ICON_AREA_SIZE = ChipTokens.containerHeight;
+
+// The icon glyph is centered inside that (larger) touch target, so its own
+// edge sits this far in from the touch target's edge.
+const TRAILING_ICON_INSET = (TRAILING_ICON_AREA_SIZE - ChipTokens.iconSize) / 2;
+
export type Props = Omit & {
/**
* Mode of the chip.
- * - `flat` - flat chip without outline.
- * - `outlined` - chip with an outline.
+ * - `flat` - chip with a filled container.
+ * - `outlined` - chip with an outline when unselected.
*/
mode?: 'flat' | 'outlined';
/**
@@ -44,15 +46,34 @@ export type Props = Omit & {
*/
children: React.ReactNode;
/**
- * Icon to display for the `Chip`. Both icon and avatar cannot be specified.
+ * Leading icon to display for the `Chip`. Takes precedence over `avatar` when both are specified.
*/
icon?: IconSource;
/**
- * Avatar to display for the `Chip`. Both icon and avatar cannot be specified.
+ * Leading avatar to display for the `Chip`, rendered as is inside a clipped 24dp circle (size it to 24dp). Ignored when `icon` is also specified.
*/
avatar?: React.ReactNode;
/**
- * Icon to display as the close button for the `Chip`. The icon appears only when the onClose prop is specified.
+ * Trailing icon to display for the `Chip`, independent of the close button (e.g. a dropdown or info icon).
+ * Takes precedence over `onClose`'s close icon when both are specified.
+ */
+ trailingIcon?: IconSource;
+ /**
+ * Function to execute when the trailing icon is pressed. Only called when `trailingIcon` is specified.
+ * Without it the trailing icon is decorative: not focusable and not announced as a button.
+ */
+ onTrailingIconPress?: (e: GestureResponderEvent) => void;
+ /**
+ * Accessibility label for the trailing icon. This is read by the screen reader when the user taps the trailing icon.
+ */
+ trailingIconAccessibilityLabel?: string;
+ /**
+ * testID for the trailing icon button.
+ */
+ trailingIconTestID?: string;
+ /**
+ * Icon to display as the close button for the `Chip`, rendered in the trailing icon slot. The icon appears only
+ * when `onClose` is specified and `trailingIcon` is not.
*/
closeIcon?: IconSource;
/**
@@ -60,16 +81,10 @@ export type Props = Omit & {
*/
selected?: boolean;
/**
- * Whether to style the chip color as selected.
- * Note: With theme version 3 `selectedColor` doesn't apply to the `icon`.
- * If you want specify custom color for the `icon`, render your own `Icon` component.
+ * Custom color to use for the label, leading icon, trailing icon, and outlined border,
+ * overriding the default selected/unselected theme colors. A disabled chip ignores it.
*/
selectedColor?: ColorValue;
- /**
- * @supported Available in v5.x with theme version 3
- * Whether to display overlay on selected chip
- */
- showSelectedOverlay?: boolean;
/**
* Whether to display default check icon on selected chip.
* Note: Check will not be shown if `icon` is specified. If specified, `icon` will be shown regardless of `selected`.
@@ -90,6 +105,7 @@ export type Props = Omit & {
'aria-label'?: string;
/**
* Accessibility label for the close icon. This is read by the screen reader when the user taps the close icon.
+ * Ignored when `trailingIcon` is also specified — use `trailingIconAccessibilityLabel` instead.
*/
closeIconAccessibilityLabel?: string;
/**
@@ -103,7 +119,7 @@ export type Props = Omit & {
/**
* Function to execute on long press.
*/
- onLongPress?: () => void;
+ onLongPress?: (e: GestureResponderEvent) => void;
/**
* Function to execute as soon as the touchable element is pressed and invoked even before onPress.
*/
@@ -113,7 +129,8 @@ export type Props = Omit & {
*/
onPressOut?: (e: GestureResponderEvent) => void;
/**
- * Function to execute on close button press. The close button appears only when this prop is specified.
+ * Function to execute on close button press, indicating the chip should be removed. The close button appears
+ * only when this prop is specified and `trailingIcon` is not.
*/
onClose?: () => void;
/**
@@ -121,22 +138,29 @@ export type Props = Omit & {
*/
delayLongPress?: number;
/**
- * @supported Available in v5.x with theme version 3
- * Sets smaller horizontal paddings `12dp` around label, when there is only label.
+ * Whether the chip should have elevation.
*/
- compact?: boolean;
+ elevated?: boolean;
/**
- * @supported Available in v5.x with theme version 3
- * Whether chip should have the elevation.
+ * Custom background color for the chip, overriding the default background for its mode/selected state.
*/
- elevated?: boolean;
+ backgroundColor?: ColorValue;
/**
- * Style of chip's text
+ * Custom border radius for the chip.
+ */
+ borderRadius?: number;
+ /**
+ * Style of chip's text.
*/
textStyle?: StyleProp;
- style?: StyleProp;
+ /**
+ * Style of the chip's container. Background color and border radius should be specified via
+ * the `backgroundColor`/`borderRadius` props instead.
+ */
+ style?: StyleProp>;
/**
* Sets additional distance outside of element in which a press can be detected.
+ * Defaults to extending the touch target to 48dp tall; a custom value replaces that default.
*/
hitSlop?: TouchableRippleProps['hitSlop'];
/**
@@ -148,7 +172,7 @@ export type Props = Omit & {
*/
testID?: string;
/**
- * Ellipsize Mode for the children text
+ * Ellipsize Mode for the label text.
*/
ellipsizeMode?: TextProps['ellipsizeMode'];
/**
@@ -161,44 +185,9 @@ export type Props = Omit & {
ref?: React.Ref>;
};
-/**
- * Width reserved on the right for the close button.
- */
-const CLOSE_AFFORDANCE_WIDTH = 34;
-
-/**
- * Floor for the clamp below. The 18dp glyph is centered in the column, so at
- * this width it sits 4dp from each side. Any narrower and part of the visible
- * icon would activate the chip instead of removing it.
- */
-const CLOSE_AFFORDANCE_MIN_WIDTH = 26;
-
-/**
- * The close button's focus ring is a circle around the glyph, not around the
- * whole column, matching Material Web's trailing action: a 24dp circle (4/3
- * of the 18dp icon) with the 3dp ring right outside it and no outer offset
- * (`inset: unset`). The shared ring adds the 2dp offset, so the view is that
- * much smaller. The ring ends 30dp across, 2dp clear of the label.
- */
-const CLOSE_FOCUS_RING_SIZE =
- 24 - 2 * tokens.md.sys.state.focusIndicator.outerOffset;
-
-/**
- * The label makes a default chip 32dp tall, so the slop to reach the 48dp
- * minimum is a constant rather than something to measure. Width grows with the
- * label and the whole pill is already the target, so only the vertical axis
- * needs it.
- */
-const { containerHeight: CHIP_BODY_HEIGHT } = ChipTokens;
-const CHIP_BODY_HIT_SLOP = getMinInteractiveSizeHitSlop({
- height: CHIP_BODY_HEIGHT,
-});
-// The close column spans the chip's height, so it gets the same vertical slop.
-const CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET = CHIP_BODY_HIT_SLOP?.top ?? 0;
-
/**
* Chips are compact elements that can represent inputs, attributes, or actions.
- * They can have an icon or avatar on the left, and a close button icon on the right.
+ * They can have a leading icon or avatar, and a trailing icon (a close button or a custom action) on the right.
* They are typically used to:
*
* - Present multiple options
@@ -220,7 +209,7 @@ const CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET = CHIP_BODY_HIT_SLOP?.top ?? 0;
* ```
*/
const Chip = ({
- mode = 'flat',
+ mode = 'outlined',
children,
icon,
avatar,
@@ -238,6 +227,10 @@ const Chip = ({
delayLongPress,
onClose,
closeIcon,
+ trailingIcon,
+ onTrailingIconPress,
+ trailingIconAccessibilityLabel = 'Trailing icon',
+ trailingIconTestID,
textStyle,
style,
theme: themeOverrides,
@@ -245,30 +238,15 @@ const Chip = ({
selectedColor,
showSelectedCheck = true,
ellipsizeMode,
- compact,
elevated = false,
+ backgroundColor: customBackgroundColor,
+ borderRadius: borderRadiusProp,
maxFontSizeMultiplier,
hitSlop,
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);
- // The close affordance is a plain `Pressable`, not a `TouchableRipple`
- // (see below). The `Pressable` is the whole close column, but the ring
- // follows the glyph's round shape, so it goes on a circle inside it
- // (`'descendant'`). The circle is a childless overlay on the glyph: Android
- // drew the ring square when it sat on the view holding the icon, ignoring
- // its border radius.
- // Off without `onClose` too: the close `Pressable` unmounts then, and a
- // focused one sends no blur, so the ring would come back with `onClose`.
- const { target: closeFocusTarget, ring: closeFocusRing } = useFocusRing(
- disabled || !onClose,
- theme.colors.secondary,
- 'outward',
- 'descendant'
- );
-
- const [pressed, setPressed] = React.useState(false);
- const elevation = elevated ? (pressed ? 2 : 1) : 0;
+ const isOutlined = mode === 'outlined';
const hasPassedTouchHandler = hasTouchHandler({
onPress,
@@ -276,90 +254,118 @@ const Chip = ({
onPressIn,
onPressOut,
});
+ const isTouchableDisabled = disabled || !hasPassedTouchHandler;
+
+ const [hovered, setHovered] = React.useState(false);
+ const [focused, setFocused] = React.useState(false);
+
+ // A chip that can't be pressed has no element left to send `onHoverOut` or
+ // `onBlur`, so clear both when it stops being pressable.
+ React.useEffect(() => {
+ if (isTouchableDisabled) {
+ setHovered(false);
+ setFocused(false);
+ }
+ }, [isTouchableDisabled]);
+
+ const borderRadius = borderRadiusProp ?? theme.shapes.corner.small;
// The body's ring goes on the Surface, the chip's visible box
- // (`scope: 'within'`), not on the ripple that takes focus. The ripple sits
- // inside the Surface's border, so a ring measured from it would lose the
- // border width from its 2dp gap. And on Android and iOS the ripple keeps its
- // own height at the top of a chip that `style` makes taller, so a ring on it
- // would sit high. Off whenever the body can't be pressed, as on
- // TouchableRipple.
+ // (`scope: 'within'`), not on the ripple that takes focus, so it follows the
+ // chip's border box. Off whenever the body can't be pressed.
const { target: bodyFocusTarget, ring: bodyFocusRing } = useFocusRing(
- disabled || !hasPassedTouchHandler,
+ isTouchableDisabled,
theme.colors.secondary,
'outward',
'within'
);
- const isOutlined = mode === 'outlined';
-
- const handlePressIn = useLatestCallback((e: GestureResponderEvent) => {
- onPressIn?.(e);
- setPressed(true);
- });
-
- const handlePressOut = useLatestCallback((e: GestureResponderEvent) => {
- onPressOut?.(e);
- setPressed(false);
- });
-
- const reduceMotion = useReduceMotion();
- const elevationTransitionDuration = reduceMotion
- ? 0
- : theme.motion.duration[pressed ? 'short4' : 'short3'];
-
- const opacity = 0.38;
- const defaultBorderRadius = theme.shapes.corner.small;
- const iconSize = 18;
-
- const borderRadius = defaultBorderRadius;
-
const {
borderColor,
textColor,
iconColor,
+ trailingIconColor,
contentOpacity,
- selectedBackgroundColor,
backgroundColor,
+ rippleColor,
+ focusedColor,
+ avatarOverlayColor,
} = getChipColors({
isOutlined,
+ selected,
+ elevated,
theme,
selectedColor,
+ customBackgroundColor,
disabled,
});
- const multiplier = compact ? 1.5 : 2;
+ const hasAvatar = !!avatar && !icon;
+ const showSelectedIcon = selected && showSelectedCheck && !icon;
+ const showLeadingIcon = !!icon || showSelectedIcon;
+ const hasLeading = hasAvatar || showLeadingIcon;
+ const hasTrailingIcon = !!trailingIcon;
+ const hasClose = !hasTrailingIcon && !!onClose;
+ const showTrailingIcon = hasTrailingIcon || hasClose;
+ const onTrailingPress = hasTrailingIcon ? onTrailingIconPress : onClose;
+ const isTrailingInteractive = !!onTrailingPress;
- const labelSpacings = {
- marginRight: onClose ? 0 : 8 * multiplier,
- marginLeft:
- avatar || icon || (selected && showSelectedCheck)
- ? 4 * multiplier
- : 8 * multiplier,
- };
+ // The trailing ripple clips to a circle, so its ring sits on an unclipped
+ // wrapper around it. Off without a trailing control too: a focused node that
+ // unmounts sends no blur.
+ const { target: trailingFocusTarget, ring: trailingFocusRing } = useFocusRing(
+ disabled || !isTrailingInteractive,
+ theme.colors.secondary,
+ 'outward',
+ 'within'
+ );
- const contentSpacings = {
- paddingRight: onClose ? CLOSE_AFFORDANCE_WIDTH : 0,
+ const leftPadding = hasAvatar
+ ? ChipTokens.avatarLeadingPadding
+ : hasLeading
+ ? ChipTokens.iconLeadingPadding
+ : ChipTokens.leadingPadding;
+ const rightPadding = showTrailingIcon
+ ? ChipTokens.trailingIconPadding + ChipTokens.iconSize + TRAILING_ICON_INSET
+ : ChipTokens.trailingPadding;
+ const touchTargetInset =
+ (ChipTokens.minimumTouchTarget - ChipTokens.containerHeight) / 2;
+ const touchTargetHitSlop = {
+ top: touchTargetInset,
+ bottom: touchTargetInset,
};
-
- const labelTextStyle = {
- color: textColor,
- ...theme.fonts.labelLarge,
+ const trailingIconTouchTargetInset =
+ (ChipTokens.minimumTouchTarget - TRAILING_ICON_AREA_SIZE) / 2;
+ // No slop on the left: it would overlap the chip body's touch area, and the
+ // later sibling would take presses meant for the label.
+ const trailingIconHitSlop = {
+ top: trailingIconTouchTargetInset,
+ bottom: trailingIconTouchTargetInset,
+ right: trailingIconTouchTargetInset,
};
+ const trailingIconAndroidRipple =
+ Platform.OS === 'android'
+ ? {
+ color: rippleColor,
+ borderless: true,
+ radius: TRAILING_ICON_AREA_SIZE / 2,
+ }
+ : undefined;
return (
setHovered(true)}
+ onHoverOut={() => setHovered(false)}
+ onFocus={(e) => {
+ bodyFocusTarget.onFocus?.(e);
+ if (e.target !== e.currentTarget || !isKeyboardFocusEvent(e)) return;
+ setFocused(true);
+ }}
+ onBlur={() => {
+ bodyFocusTarget.onBlur?.();
+ setFocused(false);
+ }}
delayLongPress={delayLongPress}
disabled={disabled}
aria-label={ariaLabel}
@@ -383,84 +406,53 @@ const Chip = ({
aria-disabled={disabled}
testID={testID}
theme={theme}
- hitSlop={
- hitSlop !== undefined
- ? hitSlop
- : disabled || !hasPassedTouchHandler
- ? undefined
- : CHIP_BODY_HIT_SLOP
- }
+ hitSlop={hitSlop ?? touchTargetHitSlop}
>
- {avatar && !icon ? (
-
- {React.isValidElement(avatar)
- ? React.cloneElement(avatar, {
- style: [styles.avatar, avatar.props.style],
- })
- : avatar}
+ {hasAvatar ? (
+
+ {avatar}
+ {showSelectedIcon ? (
+
+
+
+ ) : null}
) : null}
- {icon || (selected && showSelectedCheck) ? (
-
- {icon ? (
-
- ) : (
-
- )}
+ {showLeadingIcon && !hasAvatar ? (
+
+
) : null}
@@ -468,62 +460,47 @@ const Chip = ({
- {onClose ? (
-
-
+
- {/* react-native-web removed `hitSlop` in 0.13.0,
- so web needs a real element the browser can
- hit-test instead of a native responder inset. */}
- {Platform.OS === 'web' && !disabled && (
-
- )}
-
- {closeIcon ? (
-
- ) : (
-
- )}
-
-
-
+
+
) : null}
@@ -532,99 +509,64 @@ const Chip = ({
const styles = StyleSheet.create({
container: {
- borderWidth: StyleSheet.hairlineWidth,
+ minHeight: ChipTokens.containerHeight,
+ borderWidth: ChipTokens.outlineWidth,
borderStyle: 'solid',
- flexDirection: Platform.select({ default: 'column', web: 'row' }),
+ justifyContent: 'center',
+ alignSelf: 'flex-start',
},
- md3Container: {
- borderWidth: 1,
+ touchable: {
+ minHeight: ChipTokens.containerHeight,
+ flexShrink: 1,
+ alignSelf: 'stretch',
+ justifyContent: 'center',
},
content: {
+ flexShrink: 1,
flexDirection: 'row',
alignItems: 'center',
- paddingLeft: 4,
position: 'relative',
+ overflow: 'hidden',
},
- md3Content: {
- paddingLeft: 0,
- },
- icon: {
- padding: 4,
- alignSelf: 'center',
- },
- md3Icon: {
- paddingLeft: 8,
- paddingRight: 0,
+ avatarWrapper: {
+ width: ChipTokens.avatarSize,
+ height: ChipTokens.avatarSize,
+ borderRadius: ChipTokens.avatarSize / 2,
+ marginRight: ChipTokens.leadingLabelGap,
+ overflow: 'hidden',
},
- closeIcon: {
- marginRight: 4,
+ avatarSelectedOverlay: {
+ ...StyleSheet.absoluteFill,
+ alignItems: 'center',
+ justifyContent: 'center',
},
- md3CloseIcon: {
- marginRight: 0,
- padding: 0,
+ leadingIcon: {
+ width: ChipTokens.iconSize,
+ height: ChipTokens.iconSize,
+ marginRight: ChipTokens.leadingLabelGap,
+ alignItems: 'center',
+ justifyContent: 'center',
},
- md3LabelText: {
+ labelText: {
textAlignVertical: 'center',
- marginVertical: 6,
+ includeFontPadding: false,
flexShrink: 1,
},
- avatar: {
- width: 24,
- height: 24,
- borderRadius: 12,
- },
- avatarWrapper: {
- marginRight: 4,
- },
- md3AvatarWrapper: {
- marginLeft: 4,
- marginRight: 0,
- },
- md3SelectedIcon: {
- paddingLeft: 4,
- },
- // eslint-disable-next-line react-native/no-color-literals
- avatarSelected: {
+ trailingIconWrapper: {
position: 'absolute',
- top: 4,
- left: 4,
- backgroundColor: 'rgba(0, 0, 0, .29)',
- },
- closeButtonStyle: {
- position: 'absolute',
- right: 0,
- width: CLOSE_AFFORDANCE_WIDTH,
- // A chip narrower than this column would hand the whole thing to the close
- // button. Never more than half, never less than the glyph needs; minWidth
- // wins over maxWidth.
- minWidth: CLOSE_AFFORDANCE_MIN_WIDTH,
- maxWidth: '50%',
top: 0,
bottom: 0,
+ right: 0,
+ width: TRAILING_ICON_AREA_SIZE,
+ borderRadius: TRAILING_ICON_AREA_SIZE / 2,
},
closeButton: {
flex: 1,
- justifyContent: 'center',
- },
- closeFocusRing: {
- width: CLOSE_FOCUS_RING_SIZE,
- height: CLOSE_FOCUS_RING_SIZE,
+ borderRadius: TRAILING_ICON_AREA_SIZE / 2,
+ overflow: 'hidden',
alignItems: 'center',
justifyContent: 'center',
},
- closeFocusRingShape: {
- borderRadius: CLOSE_FOCUS_RING_SIZE / 2,
- },
- closeButtonWebTouchTarget: {
- position: 'absolute',
- top: -CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET,
- bottom: -CLOSE_BUTTON_WEB_TOUCH_TARGET_INSET,
- left: 0,
- right: 0,
- },
- touchable: {
- width: '100%',
- },
});
export default Chip;
diff --git a/src/components/Chip/helpers.tsx b/src/components/Chip/helpers.tsx
deleted file mode 100644
index 44225d3304..0000000000
--- a/src/components/Chip/helpers.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import type { ColorValue, StyleProp, ViewStyle } from 'react-native';
-
-import color from 'color';
-
-import { tokens } from '../../theme/tokens';
-import type { InternalTheme } from '../../theme/types';
-
-const md3 = (theme: InternalTheme) => theme;
-
-const stateOpacity = tokens.md.sys.state.opacity;
-
-export type ChipAvatarProps = {
- style?: StyleProp;
-};
-
-type BaseProps = {
- theme: InternalTheme;
- isOutlined: boolean;
- disabled?: boolean;
-};
-
-const getBorderColor = ({
- theme,
- isOutlined,
- disabled,
- selectedColor,
-}: BaseProps & { selectedColor?: ColorValue }) => {
- const isSelectedColor = selectedColor !== undefined;
- const { colors } = md3(theme);
-
- if (!isOutlined) {
- // If the Chip mode is "flat", set border color to transparent
- return 'transparent';
- }
-
- if (disabled) {
- return colors.surfaceContainer;
- }
-
- if (isSelectedColor) {
- if (typeof selectedColor === 'string') {
- return color(selectedColor).alpha(0.29).rgb().string();
- }
- // PlatformColor / OpaqueColorValue: skip the alpha pass and render opaque.
- return selectedColor;
- }
-
- return colors.outlineVariant;
-};
-
-const getTextColor = ({
- theme,
- isOutlined,
- disabled,
- selectedColor,
-}: BaseProps & {
- selectedColor?: ColorValue;
-}) => {
- const isSelectedColor = selectedColor !== undefined;
- const { colors } = md3(theme);
- if (disabled) {
- return colors.onSurface;
- }
-
- if (isSelectedColor) {
- return selectedColor;
- }
-
- if (isOutlined) {
- return colors.onSurfaceVariant;
- }
-
- return colors.onSecondaryContainer;
-};
-
-const getDefaultBackgroundColor = ({
- theme,
- isOutlined,
-}: Omit) => {
- const { colors } = md3(theme);
- if (isOutlined) {
- return colors.surface;
- }
-
- return colors.secondaryContainer;
-};
-
-const getBackgroundColor = ({ theme, isOutlined, disabled }: BaseProps) => {
- const { colors } = md3(theme);
- if (disabled) {
- if (isOutlined) {
- return 'transparent';
- }
- return colors.surfaceContainerLow;
- }
-
- return getDefaultBackgroundColor({ theme, isOutlined });
-};
-
-const getIconColor = ({
- theme,
- isOutlined,
- disabled,
- selectedColor,
-}: BaseProps & {
- selectedColor?: ColorValue;
-}) => {
- const isSelectedColor = selectedColor !== undefined;
- const { colors } = md3(theme);
- if (disabled) {
- return colors.onSurface;
- }
-
- if (isSelectedColor) {
- return selectedColor;
- }
-
- if (isOutlined) {
- return colors.onSurfaceVariant;
- }
-
- return colors.onSecondaryContainer;
-};
-
-export const getChipColors = ({
- isOutlined,
- theme,
- selectedColor,
- disabled,
-}: BaseProps & {
- disabled?: boolean;
- selectedColor?: ColorValue;
-}): {
- borderColor: ColorValue;
- textColor: ColorValue;
- iconColor: ColorValue;
- contentOpacity: number;
- backgroundColor: ColorValue;
- selectedBackgroundColor: ColorValue;
-} => {
- const baseChipColorProps = { theme, isOutlined, disabled };
-
- const backgroundColor = getBackgroundColor({
- ...baseChipColorProps,
- });
-
- const contentOpacity = disabled
- ? stateOpacity.disabled
- : stateOpacity.enabled;
-
- return {
- borderColor: getBorderColor({
- ...baseChipColorProps,
- selectedColor,
- }),
- textColor: getTextColor({
- ...baseChipColorProps,
- selectedColor,
- }),
- iconColor: getIconColor({
- ...baseChipColorProps,
- selectedColor,
- }),
- contentOpacity,
- backgroundColor,
- selectedBackgroundColor: backgroundColor,
- };
-};
diff --git a/src/components/Chip/tokens.ts b/src/components/Chip/tokens.ts
index 772ef9d0e0..ecfe388793 100644
--- a/src/components/Chip/tokens.ts
+++ b/src/components/Chip/tokens.ts
@@ -1,7 +1,43 @@
+import type { ColorRole, TypescaleKey } from '../../theme/types';
+
/**
- * MD3 Chip spec dimensions.
+ * MD3 Chip component tokens.
* @see https://m3.material.io/components/chips/specs
*/
-export const ChipTokens = {
+const sizes = {
containerHeight: 32,
+ minimumTouchTarget: 48,
+ outlineWidth: 1,
+ iconSize: 18,
+ avatarSize: 24,
+ leadingPadding: 16,
+ trailingPadding: 16,
+ iconLeadingPadding: 8,
+ avatarLeadingPadding: 4,
+ trailingIconPadding: 8,
+ leadingLabelGap: 8,
+ labelTypescale: 'labelLarge' as TypescaleKey,
+
+ disabledContentOpacity: 0.38,
+
+ flatElevation: 0,
+ elevatedElevation: 1,
+ elevatedHoverElevation: 2,
} as const;
+
+const colors = {
+ elevatedContainerColor: 'surfaceContainerLow',
+ flatContainerColor: 'surfaceContainerLow',
+ selectedContainerColor: 'secondaryContainer',
+ outlinedContainerColor: 'surface',
+ labelColor: 'onSurfaceVariant',
+ selectedLabelColor: 'onSecondaryContainer',
+ leadingIconColor: 'primary',
+ selectedIconColor: 'onSecondaryContainer',
+ trailingIconColor: 'onSurfaceVariant',
+ selectedTrailingIconColor: 'onSecondaryContainer',
+ outlineColor: 'outlineVariant',
+ disabledColor: 'onSurface',
+} as const satisfies Record;
+
+export const ChipTokens = { ...sizes, ...colors };
diff --git a/src/components/Chip/utils.ts b/src/components/Chip/utils.ts
new file mode 100644
index 0000000000..8f4f63b24b
--- /dev/null
+++ b/src/components/Chip/utils.ts
@@ -0,0 +1,161 @@
+import type { ColorValue } from 'react-native';
+
+import { ChipTokens } from './tokens';
+import type { ColorRole, InternalTheme } from '../../theme/types';
+
+type BaseProps = {
+ theme: InternalTheme;
+ isOutlined: boolean;
+ selected?: boolean;
+ disabled?: boolean;
+ elevated?: boolean;
+};
+
+export type ChipColors = {
+ borderColor: ColorValue;
+ textColor: ColorValue;
+ iconColor: ColorValue;
+ trailingIconColor: ColorValue;
+ contentOpacity: number;
+ backgroundColor: ColorValue;
+ rippleColor: ColorValue;
+ focusedColor: ColorValue;
+ avatarOverlayColor: ColorValue;
+};
+
+const getContainerColor = ({
+ theme,
+ isOutlined,
+ selected,
+ disabled,
+ elevated,
+ customBackgroundColor,
+}: BaseProps & {
+ customBackgroundColor?: ColorValue;
+}) => {
+ if (disabled) {
+ // A disabled selected chip keeps its filled look (no outline); only a
+ // disabled unselected outlined chip stays unfilled.
+ return isOutlined && !selected
+ ? 'transparent'
+ : theme.colors.stateLayerPressed;
+ }
+
+ if (customBackgroundColor !== undefined) {
+ return customBackgroundColor;
+ }
+
+ if (selected) {
+ return theme.colors[ChipTokens.selectedContainerColor];
+ }
+
+ if (isOutlined) {
+ return theme.colors[ChipTokens.outlinedContainerColor];
+ }
+
+ return elevated
+ ? theme.colors[ChipTokens.elevatedContainerColor]
+ : theme.colors[ChipTokens.flatContainerColor];
+};
+
+const getBorderColor = ({
+ theme,
+ isOutlined,
+ selected,
+ disabled,
+ selectedColor,
+}: BaseProps & {
+ selectedColor?: ColorValue;
+}) => {
+ if (!isOutlined || selected) {
+ return 'transparent';
+ }
+
+ if (disabled) {
+ return theme.colors.outlineVariant;
+ }
+
+ if (selectedColor !== undefined) {
+ return selectedColor;
+ }
+
+ return theme.colors[ChipTokens.outlineColor];
+};
+
+const resolveColor = (
+ {
+ theme,
+ disabled,
+ selected,
+ }: Pick,
+ selectedColor: ColorValue | undefined,
+ selectedToken: ColorRole,
+ defaultToken: ColorRole
+): ColorValue => {
+ if (disabled) {
+ return theme.colors[ChipTokens.disabledColor];
+ }
+
+ if (selectedColor !== undefined) {
+ return selectedColor;
+ }
+
+ return theme.colors[selected ? selectedToken : defaultToken];
+};
+
+export const getChipColors = ({
+ isOutlined,
+ theme,
+ selected,
+ selectedColor,
+ customBackgroundColor,
+ disabled,
+ elevated,
+}: BaseProps & {
+ customBackgroundColor?: ColorValue;
+ disabled?: boolean;
+ selectedColor?: ColorValue;
+}): ChipColors => {
+ const baseChipColorProps = {
+ theme,
+ isOutlined,
+ selected,
+ disabled,
+ elevated,
+ };
+
+ const contentOpacity = disabled ? ChipTokens.disabledContentOpacity : 1;
+
+ return {
+ borderColor: getBorderColor({
+ ...baseChipColorProps,
+ selectedColor,
+ }),
+ textColor: resolveColor(
+ baseChipColorProps,
+ selectedColor,
+ ChipTokens.selectedLabelColor,
+ ChipTokens.labelColor
+ ),
+ iconColor: resolveColor(
+ baseChipColorProps,
+ selectedColor,
+ ChipTokens.selectedIconColor,
+ ChipTokens.leadingIconColor
+ ),
+ trailingIconColor: resolveColor(
+ baseChipColorProps,
+ selectedColor,
+ ChipTokens.selectedTrailingIconColor,
+ ChipTokens.trailingIconColor
+ ),
+ contentOpacity,
+ backgroundColor: getContainerColor({
+ ...baseChipColorProps,
+ customBackgroundColor,
+ }),
+ rippleColor: theme.colors.stateLayerPressed,
+ focusedColor: theme.colors.stateLayerPressed,
+ avatarOverlayColor: theme.colors.stateLayerPressed,
+ };
+};
diff --git a/src/components/__tests__/Chip.test.tsx b/src/components/__tests__/Chip.test.tsx
index 821bb3062f..8217d4ff1e 100644
--- a/src/components/__tests__/Chip.test.tsx
+++ b/src/components/__tests__/Chip.test.tsx
@@ -1,16 +1,21 @@
-import { Pressable, StyleSheet } from 'react-native';
-import type { GestureResponderEvent } from 'react-native';
-
-import { describe, expect, it, jest } from '@jest/globals';
+import { Platform, Text } from 'react-native';
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ jest,
+} from '@jest/globals';
import { fireEvent, userEvent } from '@testing-library/react-native';
-import color from 'color';
-import PaperProvider from '../../core/PaperProvider';
-import { render, screen } from '../../test-utils';
+import { ownFocusEvent, render, screen } from '../../test-utils';
import { DarkTheme, LightTheme } from '../../theme/schemes';
import { tokens } from '../../theme/tokens';
+import * as Avatar from '../Avatar/Avatar';
import Chip from '../Chip/Chip';
-import { getChipColors } from '../Chip/helpers';
+import { getChipColors } from '../Chip/utils';
const stateOpacity = tokens.md.sys.state.opacity;
@@ -22,6 +27,38 @@ it('renders chip with onPress', async () => {
expect(tree).toMatchSnapshot();
});
+it('exposes the label as the accessible name of the chip button', async () => {
+ await render( {}}>Example Chip);
+
+ expect(
+ screen.getByRole('button', { name: 'Example Chip' })
+ ).toBeOnTheScreen();
+});
+
+it('exposes the accessible name for non-string children', async () => {
+ await render(
+ {}}>
+ Example Chip
+
+ );
+
+ expect(
+ screen.getByRole('button', { name: 'Example Chip' })
+ ).toBeOnTheScreen();
+});
+
+it('prefers an explicit aria-label over the derived one', async () => {
+ await render(
+ {}} aria-label="Custom label">
+ Example Chip
+
+ );
+
+ expect(
+ screen.getByRole('button', { name: 'Custom label' })
+ ).toBeOnTheScreen();
+});
+
it('renders chip with icon', async () => {
const tree = (
await render(Example Chip)
@@ -54,6 +91,166 @@ it('renders chip with custom close button', async () => {
expect(tree).toMatchSnapshot();
});
+it('renders chip with a generic trailing icon', async () => {
+ const tree = (
+ await render(
+
+ Example Chip
+
+ )
+ ).toJSON();
+
+ expect(tree).toMatchSnapshot();
+});
+
+it('calls onTrailingIconPress when the trailing icon is pressed', async () => {
+ const onTrailingIconPress = jest.fn();
+ const onClose = jest.fn();
+ await render(
+
+ Example Chip
+
+ );
+
+ await userEvent.press(screen.getByTestId('chip-trailing-icon'));
+
+ expect(onTrailingIconPress).toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+});
+
+it('prefers trailingIcon over the close icon when both trailingIcon and onClose are specified', async () => {
+ const tree = (
+ await render(
+ {}}>
+ Example Chip
+
+ )
+ ).toJSON();
+
+ expect(tree).toMatchSnapshot();
+});
+
+it('renders a trailing icon without a handler as a decorative view', async () => {
+ await render(
+ {}}
+ trailingIcon="menu-down"
+ trailingIconTestID="chip-trailing-icon"
+ >
+ Example Chip
+
+ );
+
+ expect(screen.queryByRole('button', { name: 'Trailing icon' })).toBeNull();
+ expect(screen.getByTestId('chip-trailing-icon')).toBeOnTheScreen();
+});
+
+it('lets touches through a decorative trailing icon to the chip body', async () => {
+ await render(
+ {}}
+ trailingIcon="menu-down"
+ trailingIconTestID="chip-trailing-icon"
+ >
+ Example Chip
+
+ );
+
+ expect(screen.getByTestId('chip-trailing-icon').parent).toHaveProp(
+ 'pointerEvents',
+ 'none'
+ );
+});
+
+it('drops the hover elevation of an elevated chip that stops being pressable while hovered', async () => {
+ const pressable = (
+ {}} testID="chip">
+ Example Chip
+
+ );
+ const { rerender } = await render(pressable);
+ const resting = JSON.stringify(screen.toJSON());
+
+ await fireEvent(screen.getByTestId('chip'), 'hoverIn');
+ expect(JSON.stringify(screen.toJSON())).not.toBe(resting);
+
+ await rerender(
+
+ Example Chip
+
+ );
+ await rerender(pressable);
+
+ expect(JSON.stringify(screen.toJSON())).toBe(resting);
+});
+
+describe('keyboard focus fill (web)', () => {
+ const original = Platform.OS;
+ beforeEach(() => {
+ Platform.OS = 'web';
+ });
+ afterEach(() => {
+ Platform.OS = original;
+ });
+
+ const { focusedColor } = getChipColors({
+ theme: LightTheme,
+ isOutlined: true,
+ });
+
+ it('fills the chip body on keyboard focus and clears it on blur', async () => {
+ await render(
+ {}} testID="chip">
+ Example Chip
+
+ );
+
+ await fireEvent(screen.getByTestId('chip'), 'focus', ownFocusEvent());
+ expect(screen.getByTestId('chip')).toHaveStyle({
+ backgroundColor: focusedColor,
+ });
+
+ await fireEvent(screen.getByTestId('chip'), 'blur');
+ expect(screen.getByTestId('chip')).not.toHaveStyle({
+ backgroundColor: focusedColor,
+ });
+ });
+
+ it('clears the fill when the chip is disabled while focused', async () => {
+ const { rerender } = await render(
+ {}} testID="chip">
+ Example Chip
+
+ );
+
+ await fireEvent(screen.getByTestId('chip'), 'focus', ownFocusEvent());
+ expect(screen.getByTestId('chip')).toHaveStyle({
+ backgroundColor: focusedColor,
+ });
+
+ await rerender(
+ {}} testID="chip">
+ Example Chip
+
+ );
+ await rerender(
+ {}} testID="chip">
+ Example Chip
+
+ );
+
+ expect(screen.getByTestId('chip')).not.toHaveStyle({
+ backgroundColor: focusedColor,
+ });
+ });
+});
+
it('renders outlined disabled chip', async () => {
const tree = (
await render(
@@ -72,68 +269,122 @@ it('renders selected chip', async () => {
expect(tree).toMatchSnapshot();
});
-it('does not mark a chip without a touch handler as disabled', async () => {
- await render(Plain chip);
+it('renders chip with avatar', async () => {
+ const tree = (
+ await render(
+ }>Example Chip
+ )
+ ).toJSON();
+
+ expect(tree).toMatchSnapshot();
+});
+
+it('renders selected chip with avatar and a check overlay', async () => {
+ const tree = (
+ await render(
+ }>
+ Example Chip
+
+ )
+ ).toJSON();
+
+ expect(tree).toMatchSnapshot();
+});
+
+it('prefers icon over avatar when both are specified', async () => {
+ const tree = (
+ await render(
+ }>
+ Example Chip
+
+ )
+ ).toJSON();
+
+ expect(tree).toMatchSnapshot();
+});
+
+it('does not announce a chip without a touch handler as disabled', async () => {
+ await render(Static chip);
- expect(screen.getByTestId('plain-chip')).not.toBeDisabled();
+ expect(screen.getByTestId('static-chip')).not.toBeDisabled();
});
-it('does not announce a chip without a touch handler as a button', async () => {
- const onWrapPress = jest.fn<(e: GestureResponderEvent) => void>();
+it('disables only a chip that is explicitly disabled', async () => {
await render(
-
- Info
-
+ {}} testID="disabled-chip">
+ Disabled chip
+
);
- expect(screen.queryByRole('button')).not.toBeOnTheScreen();
+ expect(screen.getByTestId('disabled-chip')).toBeDisabled();
+});
- await userEvent.press(screen.getByText('Info'));
+it('renders active chip if only onLongPress handler is passed', async () => {
+ await render(
+ {}} testID="active-chip">
+ Active chip
+
+ );
- expect(onWrapPress).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId('active-chip')).toBeEnabled();
});
-// With no handler the chip renders a plain view and is no longer a button. iOS
-// and Android still report a selection whatever the role, so it stays.
-it('still reports the selection of a selected chip without a touch handler', async () => {
+it('applies disabled opacity to the close button', async () => {
await render(
-
- Info
+ {}}
+ testID="disabled-chip"
+ closeIconTestID="disabled-chip-close"
+ >
+ Disabled chip
);
- expect(screen.queryByRole('button')).not.toBeOnTheScreen();
- expect(screen.getByTestId('plain-selected-chip')).toBeSelected();
+ expect(screen.getByTestId('disabled-chip-close')).toHaveStyle({
+ opacity: 0.38,
+ });
});
-it('reports the selected state of a chip with a touch handler', async () => {
+it('overlays the close button on top of the chip so its ripple spans behind it', async () => {
await render(
- {}}>
- Selected chip
+ {}} onClose={() => {}} closeIconTestID="chip-close">
+ Removable chip
);
- expect(screen.getByRole('button', { selected: true })).toBeOnTheScreen();
+ expect(screen.getByTestId('chip-close').parent).toHaveStyle({
+ bottom: 0,
+ position: 'absolute',
+ right: 0,
+ top: 0,
+ });
});
-it('renders disabled chip when the disabled prop is passed', async () => {
+it('clips the ripple to custom chip border radius', async () => {
await render(
- {}} testID="disabled-chip">
- Disabled chip
+ {}} testID="rounded-chip" borderRadius={16}>
+ Rounded chip
);
- expect(screen.getByTestId('disabled-chip')).toBeDisabled();
+ expect(screen.getByTestId('rounded-chip')).toHaveStyle({
+ borderRadius: 16,
+ overflow: 'hidden',
+ });
});
-it('renders active chip if only onLongPress handler is passed', async () => {
+it('renders close button with a circular state layer', async () => {
await render(
- {}} testID="active-chip">
- Active chip
+ {}} closeIconTestID="chip-close">
+ Removable chip
);
- expect(screen.getByTestId('active-chip')).toBeEnabled();
+ expect(screen.getByTestId('chip-close')).toHaveStyle({
+ borderRadius: 16,
+ overflow: 'hidden',
+ });
});
it('renders chip with zero border radius', async () => {
@@ -169,7 +420,7 @@ describe('getChipColors - text color', () => {
isOutlined: false,
})
).toMatchObject({
- textColor: LightTheme.colors.onSecondaryContainer,
+ textColor: LightTheme.colors.onSurfaceVariant,
});
});
@@ -218,7 +469,7 @@ describe('getChipColors - icon color', () => {
isOutlined: false,
})
).toMatchObject({
- iconColor: LightTheme.colors.onSecondaryContainer,
+ iconColor: LightTheme.colors.primary,
});
});
@@ -229,7 +480,7 @@ describe('getChipColors - icon color', () => {
isOutlined: true,
})
).toMatchObject({
- iconColor: LightTheme.colors.onSurfaceVariant,
+ iconColor: LightTheme.colors.primary,
});
});
@@ -246,6 +497,46 @@ describe('getChipColors - icon color', () => {
});
});
+describe('getChipColor - selected background color', () => {
+ it('should return custom color, outlined mode', () => {
+ expect(
+ getChipColors({
+ theme: LightTheme,
+ customBackgroundColor: 'purple',
+ isOutlined: true,
+ selected: true,
+ })
+ ).toMatchObject({
+ backgroundColor: 'purple',
+ });
+ });
+
+ it('should return custom color, flat mode', () => {
+ expect(
+ getChipColors({
+ theme: LightTheme,
+ customBackgroundColor: 'purple',
+ isOutlined: false,
+ selected: true,
+ })
+ ).toMatchObject({
+ backgroundColor: 'purple',
+ });
+ });
+
+ it('should return theme color, for theme version 3, flat mode', () => {
+ expect(
+ getChipColors({
+ theme: LightTheme,
+ isOutlined: false,
+ selected: true,
+ })
+ ).toMatchObject({
+ backgroundColor: LightTheme.colors.secondaryContainer,
+ });
+ });
+});
+
describe('getChipColor - background color', () => {
it('should return theme color, for theme version 3, outlined mode', () => {
expect(
@@ -265,7 +556,73 @@ describe('getChipColor - background color', () => {
isOutlined: false,
})
).toMatchObject({
- backgroundColor: LightTheme.colors.secondaryContainer,
+ backgroundColor: LightTheme.colors.surfaceContainerLow,
+ });
+ });
+
+ it('uses the precomputed state layer color for disabled filled chips', () => {
+ const theme = LightTheme;
+
+ expect(
+ getChipColors({
+ theme,
+ disabled: true,
+ isOutlined: false,
+ })
+ ).toMatchObject({
+ backgroundColor: theme.colors.stateLayerPressed,
+ });
+ });
+
+ it('keeps the filled look for a disabled selected outlined chip', () => {
+ const theme = LightTheme;
+
+ expect(
+ getChipColors({
+ theme,
+ disabled: true,
+ selected: true,
+ isOutlined: true,
+ })
+ ).toMatchObject({
+ backgroundColor: theme.colors.stateLayerPressed,
+ });
+ });
+
+ it('stays unfilled for a disabled unselected outlined chip', () => {
+ const theme = LightTheme;
+
+ expect(
+ getChipColors({
+ theme,
+ disabled: true,
+ selected: false,
+ isOutlined: true,
+ })
+ ).toMatchObject({
+ backgroundColor: 'transparent',
+ });
+ });
+});
+
+describe('getChipColor - ripple color', () => {
+ it('uses the precomputed state layer color', () => {
+ const theme = {
+ ...LightTheme,
+ colors: {
+ ...LightTheme.colors,
+ stateLayerPressed: 'rgba(29, 27, 32, 0.1)',
+ },
+ };
+
+ expect(
+ getChipColors({
+ theme,
+ isOutlined: true,
+ })
+ ).toMatchObject({
+ rippleColor: 'rgba(29, 27, 32, 0.1)',
+ avatarOverlayColor: 'rgba(29, 27, 32, 0.1)',
});
});
});
@@ -314,7 +671,21 @@ describe('getChipColor - border color', () => {
isOutlined: true,
})
).toMatchObject({
- borderColor: color('purple').alpha(0.29).rgb().string(),
+ borderColor: 'purple',
+ });
+ });
+
+ it('uses the tokenized outline color for disabled outlined chips', () => {
+ const theme = LightTheme;
+
+ expect(
+ getChipColors({
+ theme,
+ disabled: true,
+ isOutlined: true,
+ })
+ ).toMatchObject({
+ borderColor: theme.colors.outlineVariant,
});
});
@@ -362,76 +733,3 @@ describe('getChipColor - border color', () => {
});
});
});
-
-describe('close affordance', () => {
- it('is not rendered without onClose', async () => {
- await render( {}}>Example);
-
- expect(screen.queryByLabelText('Close')).not.toBeOnTheScreen();
- });
-});
-
-describe('hitSlop', () => {
- it('expands a pressable chip to a 48dp tall target', async () => {
- await render(
- {}} testID="chip">
- Example
-
- );
-
- expect(screen.getByTestId('chip')).toHaveProp('hitSlop', {
- top: 8,
- bottom: 8,
- left: 0,
- right: 0,
- });
- });
-
- it.each([
- { when: 'it has no touch handler', props: {} },
- { when: 'it only has onClose', props: { onClose: () => {} } },
- { when: 'it is disabled', props: { onPress: () => {}, disabled: true } },
- ])('adds no slop to the chip body when $when', async ({ props }) => {
- await render(
-
- Example
-
- );
-
- 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__/ListItem.test.tsx b/src/components/__tests__/ListItem.test.tsx
index 98e6e0f0fe..e62348394b 100644
--- a/src/components/__tests__/ListItem.test.tsx
+++ b/src/components/__tests__/ListItem.test.tsx
@@ -149,6 +149,7 @@ it('renders with a description with typeof number', async () => {
it('calling onPress on ListItem right component', async () => {
Platform.OS = 'web';
const onPress = jest.fn<(event: GestureResponderEvent) => void>();
+ const user = userEvent.setup();
await render(
{
/>
);
- await userEvent.press(screen.getByTestId('icon-button'));
+ await user.press(screen.getByTestId('icon-button'));
expect(onPress).toHaveBeenCalledTimes(1);
});
diff --git a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap
index fbc4a1035a..f30216a317 100644
--- a/src/components/__tests__/__snapshots__/Chip.test.tsx.snap
+++ b/src/components/__tests__/__snapshots__/Chip.test.tsx.snap
@@ -1,26 +1,25 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
-exports[`renders chip with close button 1`] = `
+exports[`prefers icon over avatar when both are specified 1`] = `
-
-
-
-
- close
-
-
-
-
-
`;
-exports[`renders chip with custom close button 1`] = `
+exports[`prefers trailingIcon over the close icon when both trailingIcon and onClose are specified 1`] = `
-
-
- information
-
-
+
+ menu-down
+
+
+
+
+`;
+
+exports[`renders chip with a generic trailing icon 1`] = `
+
+
+
+
+
+
+ information
+
+
+
+ Example Chip
+
+
+
+
+
+
+ menu-down
+
+
+
+
+`;
+
+exports[`renders chip with avatar 1`] = `
+
+
+
+
+
+
+
+ XD
+
+
+
+
+ Example Chip
+
+
+
+
+`;
+
+exports[`renders chip with close button 1`] = `
+
+
+
+
+
+
+ information
+
+
+
+ Example Chip
+
+
+
+
+
+
+ close
+
+
+
+
+`;
+
+exports[`renders chip with custom close button 1`] = `
+
+
+
+
+
+
+ information
+
+
+
+ Example Chip
+
+
+
+
+
-
+ arrow-down
+
+
+
+
+`;
+
+exports[`renders chip with icon 1`] = `
+
+
+
+
+
- arrow-down
+ information
-
+
-
+ [
+ {
+ "flexShrink": 1,
+ "includeFontPadding": false,
+ "textAlignVertical": "center",
+ },
+ {
+ "color": "rgba(73, 69, 79, 1)",
+ },
+ undefined,
+ ],
+ ],
+ ]
+ }
+ >
+ Example Chip
+
`;
-exports[`renders chip with icon 1`] = `
+exports[`renders chip with onPress 1`] = `
-
+
-
-
- information
-
-
`;
-exports[`renders chip with onPress 1`] = `
+exports[`renders outlined disabled chip 1`] = `
`;
-exports[`renders outlined disabled chip 1`] = `
+exports[`renders selected chip 1`] = `
+
+
+ check
+
+
`;
-exports[`renders selected chip 1`] = `
+exports[`renders selected chip with avatar and a check overlay 1`] = `
-
+
+ XD
+
+
+
- check
-
+
+ check
+
+
{
return ringed.length ? style(ringed[0]).outlineOffset : undefined;
};
+const ringedStyle = () =>
+ style(
+ walk(
+ (screen as unknown as { root: Node }).root,
+ (n) => style(n).outlineStyle === 'solid'
+ )[0]
+ );
+
/** Focus whichever node actually has the handler wired. */
const focusFirstFocusable = async () => {
const root = (screen as unknown as { root: Node }).root;
@@ -94,20 +103,9 @@ describe('focus ring wiring', () => {
});
// Outward like MD3 and Material Web. A scrolling chip row that trims it is
- // the app's container, not the chip's own view.
- it('Chip rings outward', async () => {
- await render( {}}>chip);
-
- await focusFirstFocusable();
-
- expect(ringOffset()).toBe(OUTWARD);
- });
-
- // The caller's `style` sizes the chip around the ripple that takes focus,
- // and on Android and iOS the ripple keeps its own height at the top of a
- // taller chip. So the ring goes on the chip's own box, and the 2dp gap is
- // measured from its border, the visible edge.
- it('Chip rings its own box, whatever its height', async () => {
+ // the app's container, not the chip's own view. The ring goes on the chip's
+ // own box, not the ripple that sits at the top of a taller chip.
+ it('Chip rings its own box outward', async () => {
await render(
{}} style={{ height: 40 }}>
chip
@@ -116,14 +114,8 @@ describe('focus ring wiring', () => {
await focusFirstFocusable();
- const root = (screen as unknown as { root: Node }).root;
- const ringed = walk(root, (n) => style(n).outlineStyle === 'solid');
- expect(ringed).toHaveLength(1);
- expect(style(ringed[0])).toMatchObject({
- height: 40,
- borderWidth: 1,
- outlineOffset: OUTWARD,
- });
+ expect(ringOffset()).toBe(OUTWARD);
+ expect(ringedStyle()).toMatchObject({ height: 40 });
});
it('Chip drops its ring when it is disabled while focused', async () => {
@@ -172,9 +164,7 @@ describe('focus ring wiring', () => {
expect(ringOffset()).toBe(INWARD);
});
- // Material Web rings the remove button with a circle around the glyph, not
- // the whole close column.
- it('Chip rings its close button with a circle around the glyph', async () => {
+ it('Chip rings its close button with a circle', async () => {
await render(
{}} onClose={() => {}}>
chip
@@ -185,22 +175,12 @@ describe('focus ring wiring', () => {
await fireEvent(screen.getByLabelText('Close'), 'focus', ownFocusEvent());
});
- const root = (screen as unknown as { root: Node }).root;
- const ringed = walk(root, (n) => style(n).outlineStyle === 'solid');
- expect(ringed).toHaveLength(1);
- // Material Web: a 24dp circle with the ring right outside it. The shared
- // ring adds the outer offset, so the circle is that much smaller. It is
- // an overlay filling the glyph's box, which sets the size.
- const size = 24 - 2 * outerOffset;
- expect(style(ringed[0])).toMatchObject({
- outlineOffset: OUTWARD,
- position: 'absolute',
- borderRadius: size / 2,
+ // The ring sits on an unclipped wrapper around the close ripple, a circle
+ // as tall as the chip, so the ripple's own clipping can't cut it.
+ expect(ringedStyle()).toMatchObject({
+ width: ChipTokens.containerHeight,
+ borderRadius: ChipTokens.containerHeight / 2,
});
- const box = walk(root, (n) =>
- (n.children ?? []).some((c) => c === ringed[0])
- )[0];
- expect(style(box)).toMatchObject({ width: size, height: size });
});
it('Checkbox.Item rings inward, clear of the rows above and below', async () => {
@@ -793,11 +773,21 @@ describe('focus ring after the handler goes away and comes back', () => {
});
it('Chip close button shows no ring until it is focused again', async () => {
- await dropAndRestore(
- {}}>chip,
- chip
- );
+ // Focus the close button by its label: it is the only focusable node.
+ const { rerender } = await render( {}}>chip);
+ await act(async () => {
+ await fireEvent(screen.getByLabelText('Close'), 'focus', ownFocusEvent());
+ });
+ expect(ringOffset()).toBeDefined();
+ await act(async () => {
+ await rerender(chip);
+ });
+ expect(ringOffset()).toBeUndefined();
+
+ await act(async () => {
+ await rerender( {}}>chip);
+ });
expect(ringOffset()).toBeUndefined();
});
@@ -883,10 +873,13 @@ describe('focus ring wiring (web)', () => {
// These spread the caller's props onto the ringed element, so the ring's
// `data-*` attribute must join the caller's `dataSet`, not replace it.
- it("DataTable.Title and Appbar.Content keep a caller's own dataSet", async () => {
+ it("DataTable.Title, Appbar.Content and Chip keep a caller's own dataSet", async () => {
const dataSet = { qa: 'title' };
await render(
<>
+ {}} {...{ dataSet }}>
+ chip
+
{}} testID="table" {...{ dataSet }}>
title
@@ -907,6 +900,10 @@ describe('focus ring wiring (web)', () => {
qa: 'title',
focusRing: 'outward',
});
+ expect(screen.getByTestId('chip').parent?.props.dataSet).toEqual({
+ qa: 'title',
+ focusRingWithin: 'outward',
+ });
});
it('Drawer.CollapsedItem marks its Pressable as the focus target and rings the item inside it', async () => {
@@ -985,61 +982,14 @@ describe('focus ring wiring (web)', () => {
expect(walk(ringed[0], (n) => n === button)).toHaveLength(1);
});
- it("Chip marks its own box as the ring, keeps the caller's dataSet and leaves the ripple's outline to the stylesheet", async () => {
- await render(
- {}}
- style={{ height: 40 }}
- {...{ dataSet: { qa: 'chip' } }}
- >
- chip
-
- );
-
- const ripple = screen.getByTestId('chip');
- // The stylesheet hides its outline, and only where `:has()` works.
- expect(style(ripple)).not.toHaveProperty('outline');
-
- const root = (screen as unknown as { root: Node }).root;
- const ringed = walk(
- root,
- (n) =>
- (n.props?.dataSet as Record | undefined)
- ?.focusRingWithin !== undefined
- );
- expect(ringed).toHaveLength(1);
- expect(ringed[0].props?.dataSet).toEqual({
- qa: 'chip',
- focusRingWithin: 'outward',
- });
- expect(style(ringed[0])).toMatchObject({ height: 40, borderWidth: 1 });
- expect(walk(ringed[0], (n) => n === ripple)).toHaveLength(1);
- });
-
- it('Chip marks its close button as the focus target and rings the glyph circle inside it', async () => {
+ it('Chip marks the wrapper around its close button as the ring', async () => {
await render(
{}} onClose={() => {}}>
chip
);
- const close = screen.getByLabelText('Close');
- expect(close.props.dataSet).toEqual({ focusRingTarget: 'true' });
-
- const ringed = walk(
- close,
- (n) =>
- (n.props?.dataSet as Record | undefined)
- ?.focusRingDescendant !== undefined
- );
- expect(ringed).toHaveLength(1);
- expect(
- (ringed[0].props?.dataSet as Record).focusRingDescendant
- ).toBe('outward');
- expect(style(ringed[0])).toMatchObject({
- position: 'absolute',
- borderRadius: 12 - outerOffset,
- });
+ const wrapper = screen.getByLabelText('Close').parent;
+ expect(wrapper?.props.dataSet).toEqual({ focusRingWithin: 'outward' });
});
});