From 15858af0e8bba92adb804853b578bfdbd2124c7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 4 Sep 2026 12:26:07 +0200 Subject: [PATCH 01/51] refactor(card): make layout helpers parent-independent BREAKING CHANGE: Card.Content now always applies fixed padding, and Card.Actions no longer assigns button modes or child margins. --- src/components/Card/Card.tsx | 2 +- src/components/Card/CardActions.tsx | 44 ++---- src/components/Card/CardContent.tsx | 11 +- src/components/__tests__/Card/Card.test.tsx | 152 ++++++++++++++------ 4 files changed, 128 insertions(+), 81 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 876ba099c0..e260dd3f20 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -159,7 +159,7 @@ const Card = ({ contentStyle, borderColor: customBorderColor, theme: themeOverrides, - testID, + testID = 'card', accessible, disabled, ref, diff --git a/src/components/Card/CardActions.tsx b/src/components/Card/CardActions.tsx index a126824025..11b38c4ee1 100644 --- a/src/components/Card/CardActions.tsx +++ b/src/components/Card/CardActions.tsx @@ -2,8 +2,6 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { StyleProp, ViewProps, ViewStyle } from 'react-native'; -import { CardContext } from './CardContext'; -import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; export type Props = ViewProps & { @@ -35,37 +33,11 @@ export type Props = ViewProps & { * export default MyComponent; * ``` */ -const CardActions = ({ theme, style, children, ...rest }: Props) => { - useInternalTheme(theme); - const cardContext = React.useContext(CardContext); - - const cardMarginStyle = cardContext - ? cardContext.direction === 'horizontal' - ? { - marginTop: -cardContext.padding, - marginRight: -cardContext.padding, - marginBottom: -cardContext.padding, - } - : { - marginLeft: -cardContext.padding, - marginRight: -cardContext.padding, - marginBottom: -cardContext.padding, - } - : null; - - const containerStyle = [ - styles.container, - cardMarginStyle, - { justifyContent: 'flex-end' } satisfies ViewStyle, - style, - ]; - - return ( - - {children} - - ); -}; +const CardActions = ({ style, children, theme: _theme, ...rest }: Props) => ( + + {children} + +); CardActions.displayName = 'Card.Actions'; @@ -73,9 +45,9 @@ const styles = StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center', - columnGap: 8, - paddingHorizontal: 8, - paddingBottom: 8, + justifyContent: 'flex-end', + padding: 8, + gap: 8, }, }); diff --git a/src/components/Card/CardContent.tsx b/src/components/Card/CardContent.tsx index fea1e519da..4e0208469f 100644 --- a/src/components/Card/CardContent.tsx +++ b/src/components/Card/CardContent.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { View } from 'react-native'; +import { StyleSheet, View } from 'react-native'; import type { StyleProp, ViewProps, ViewStyle } from 'react-native'; export type Props = ViewProps & { @@ -31,9 +31,16 @@ export type Props = ViewProps & { * ``` */ const CardContent = ({ style, ...rest }: Props) => ( - + ); CardContent.displayName = 'Card.Content'; +const styles = StyleSheet.create({ + container: { + paddingHorizontal: 16, + paddingVertical: 16, + }, +}); + export default CardContent; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 6bea220fad..6966afbc87 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1,5 +1,5 @@ -import type { ComponentProps } from 'react'; -import { Platform, StyleSheet, Text } from 'react-native'; +import { Platform, StyleSheet, Text, View } from 'react-native'; +import type { StyleProp, ViewStyle } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; @@ -19,6 +19,9 @@ const styles = StyleSheet.create({ contentStyle: { flexDirection: 'column-reverse', }, + customAction: { + marginRight: 12, + }, }); afterEach(() => { @@ -147,68 +150,133 @@ describe('CardCover', () => { }); }); -describe('CardActions', () => { - it('renders button with passed mode', async () => { - const buttonProps = jest.fn(); - const ProbeButton = (props: ComponentProps) => { - buttonProps(props); +describe('CardContent', () => { + it('uses fixed padding when rendered standalone', async () => { + await render( + + Content + + ); - return ); - expect(buttonProps).toHaveBeenCalledWith( - expect.objectContaining({ mode: 'filled' }) - ); + expect(screen.getByTestId('card-content')).toHaveStyle({ + paddingHorizontal: 16, + paddingVertical: 16, + }); }); - it('does not inject default button props', async () => { - const buttonProps = jest.fn(); - const ProbeButton = (props: ComponentProps) => { - buttonProps(props); - - return - - - + + + + Details + ); expect(screen.getByTestId('card-actions')).toHaveStyle({ flexDirection: 'row', + alignItems: 'center', justifyContent: 'flex-end', - columnGap: 8, + padding: 8, + gap: 8, + }); + expect(screen.getByTestId('custom-action')).toBeOnTheScreen(); + expect(screen.getByText('Details')).toBeOnTheScreen(); + }); + + it('lets consumer styles override the default layout', async () => { + await render( + + Action + + ); + + expect(screen.getByTestId('card-actions')).toHaveStyle({ + justifyContent: 'flex-start', + padding: 4, + gap: 12, + }); + }); + + it('preserves consumer-configured child props', async () => { + const Action = ({ + compact, + mode, + style, + }: { + compact?: boolean; + mode?: string; + style?: StyleProp; + }) => ( + + ); + + await render( + + + + + + ); + + expect(screen.getByLabelText('unset:unset')).toHaveStyle( + styles.customAction + ); + expect(screen.getByLabelText('contained:true')).toHaveStyle( + styles.customAction + ); + expect(screen.getByLabelText('unset:unset')).not.toHaveStyle({ + marginLeft: 8, + }); + expect(screen.getByTestId('custom-action')).not.toHaveStyle({ + marginLeft: 8, }); }); }); From 2704a5d4f1236386e1205ccd3899c4aa0f3b42e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 4 Sep 2026 13:08:03 +0200 Subject: [PATCH 02/51] feat(card)!: introduce slot-first filled card BREAKING CHANGE: Card now accepts media, header, content, and actions slots; arbitrary children composition and the mode prop are removed. --- example/src/Examples/CardExample.tsx | 335 +++++++-------- example/src/Examples/DataTableExample.tsx | 74 ++-- .../SegmentedButtonMultiselectRealCase.tsx | 31 +- .../SegmentedButtonRealCase.tsx | 35 +- example/src/Examples/TeamDetails.tsx | 98 +++-- example/src/Examples/TooltipExample.tsx | 17 +- src/components/Card/Card.tsx | 274 +++++------- src/components/Card/CardActions.tsx | 12 +- src/components/Card/CardContent.tsx | 8 +- src/components/Card/CardCover.tsx | 6 +- src/components/Card/utils.tsx | 59 +-- src/components/__tests__/Card/Card.test.tsx | 224 +++++----- .../Card/__snapshots__/Card.test.tsx.snap | 392 ------------------ 13 files changed, 540 insertions(+), 1025 deletions(-) delete mode 100644 src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index 09b732d9d0..ec48b4c4cc 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -1,11 +1,10 @@ import * as React from 'react'; -import { Alert, Platform, ScrollView, StyleSheet, View } from 'react-native'; +import { Alert, Platform, ScrollView, StyleSheet } from 'react-native'; import { Avatar, Button, Card, - Chip, IconButton, Text, useTheme, @@ -14,147 +13,143 @@ import { import { PreferencesContext } from '../PreferencesContext'; import ScreenWrapper from '../ScreenWrapper'; -type Mode = 'elevated' | 'outlined' | 'contained'; - const CardExample = () => { const { colors } = useTheme(); - const [selectedMode, setSelectedMode] = React.useState('elevated'); const [isSelected, setIsSelected] = React.useState(false); const preferences = React.useContext(PreferencesContext); - const modes: Mode[] = ['elevated', 'outlined', 'contained']; - return ( - - {modes.map((mode) => ( - setSelectedMode(mode)} - style={styles.chip} - > - {mode} - - ))} - - - - - - - The Abandoned Ship is a wrecked ship located on Route 108 in - Hoenn, originally being a ship named the S.S. Cactus. The second - part of the ship can only be accessed by using Dive and contains - the Scanner. - - - - - - - - - This is a card using title and subtitle with specified variants. - - - - - - - - - - - - } - right={(props: any) => ( - {}} /> - )} - /> - - - Dotted around the Hoenn region, you will find loamy soil, many of - which are housing berries. Once you have picked the berries, then - you have the ability to use that loamy soil to grow your own - berries. These can be any berry and will require attention to get - the best crop. - - - - - - - - - - - + } + title="Abandoned Ship" + content={ + + + The Abandoned Ship is a wrecked ship located on Route 108 in + Hoenn, originally being a ship named the S.S. Cactus. The second + part of the ship can only be accessed by using Dive and contains + the Scanner. + + + } + /> + + } + header={ + + } + content={ + + + This is a card using title and subtitle with specified variants. + + + } + /> + + } + actions={ + + + + + } + /> + } + trailing={(props) => ( + {}} /> + )} + content={ + + + Dotted around the Hoenn region, you will find loamy soil, many + of which are housing berries. Once you have picked the berries, + then you have the ability to use that loamy soil to grow your + own berries. These can be any berry and will require attention + to get the best crop. + + + } + /> + + } + title="Custom Button styles" + actions={ + + + + + } + /> + - - - - - - ( - setIsSelected(!isSelected)} - /> - )} - /> - + media={ + + } + title="Custom border radius" + subtitle="... for card and cover" + /> + + } + title="Just Strawberries" + subtitle="... and only Strawberries" + trailing={(props) => ( + setIsSelected(!isSelected)} + /> + )} + /> { @@ -162,16 +157,18 @@ const CardExample = () => { ? alert('The Chameleon is Pressed') : Alert.alert('The Chameleon is Pressed'); }} - mode={selectedMode} - > - - - - - This is a pressable chameleon. If you press me, I will alert. - - - + media={ + + } + title="Pressable Chameleon" + content={ + + + This is a pressable chameleon. If you press me, I will alert. + + + } + /> { @@ -179,37 +176,36 @@ const CardExample = () => { ? alert('The City is Long Pressed') : Alert.alert('The City is Long Pressed'); }} - mode={selectedMode} - > - - } - /> - - - This is a long press only city. If you long press me, I will - alert. - - - + media={ + + } + title="Long Pressable City" + leading={(props) => } + content={ + + + This is a long press only city. If you long press me, I will + alert. + + + } + /> { preferences?.toggleTheme(); }} - mode={selectedMode} - > - } - /> - - - This is pressable card. If you press me, I will switch the theme. - - - + title="Pressable Theme Change" + leading={(props) => } + content={ + + + This is pressable card. If you press me, I will switch the + theme. + + + } + /> ); @@ -227,15 +223,6 @@ const styles = StyleSheet.create({ card: { margin: 4, }, - chip: { - margin: 4, - }, - preference: { - alignItems: 'center', - flexDirection: 'row', - paddingVertical: 12, - paddingHorizontal: 8, - }, customCoverRadius: { borderTopLeftRadius: 0, borderTopRightRadius: 0, diff --git a/example/src/Examples/DataTableExample.tsx b/example/src/Examples/DataTableExample.tsx index 69858746c2..43147cef16 100644 --- a/example/src/Examples/DataTableExample.tsx +++ b/example/src/Examples/DataTableExample.tsx @@ -73,43 +73,47 @@ const DataTableExample = () => { return ( - - - - setSortAscending(!sortAscending)} - style={styles.first} - > - Dessert - - - Calories per piece - - Fat (g) - + + + setSortAscending(!sortAscending)} + style={styles.first} + > + Dessert + + + Calories per piece + + Fat (g) + - {sortedItems.slice(from, to).map((item) => ( - - {item.name} - {item.calories} - {item.fat} - - ))} + {sortedItems.slice(from, to).map((item) => ( + + + {item.name} + + {item.calories} + {item.fat} + + ))} - setPage(page)} - label={`${from + 1}-${to} of ${sortedItems.length}`} - numberOfItemsPerPageList={numberOfItemsPerPageList} - numberOfItemsPerPage={itemsPerPage} - onItemsPerPageChange={onItemsPerPageChange} - showFastPaginationControls - selectPageDropdownLabel={'Rows per page'} - /> - - + setPage(page)} + label={`${from + 1}-${to} of ${sortedItems.length}`} + numberOfItemsPerPageList={numberOfItemsPerPageList} + numberOfItemsPerPage={itemsPerPage} + onItemsPerPageChange={onItemsPerPageChange} + showFastPaginationControls + selectPageDropdownLabel={'Rows per page'} + /> + + } + /> ); }; diff --git a/example/src/Examples/SegmentedButtons/SegmentedButtonMultiselectRealCase.tsx b/example/src/Examples/SegmentedButtons/SegmentedButtonMultiselectRealCase.tsx index 2ba4a69d30..8bfdf35c2d 100644 --- a/example/src/Examples/SegmentedButtons/SegmentedButtonMultiselectRealCase.tsx +++ b/example/src/Examples/SegmentedButtons/SegmentedButtonMultiselectRealCase.tsx @@ -59,16 +59,21 @@ const SegmentedButtonMultiselectRealCase = () => { contentContainerStyle={styles.contentContainer} renderItem={({ item }) => { return ( - - - } - /> - + + + } + /> + + } + /> ); }} /> @@ -88,6 +93,12 @@ const styles = StyleSheet.create({ marginHorizontal: 16, marginTop: 16, }, + content: { + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: 0, + paddingVertical: 0, + }, cover: { width: 72, height: 72, diff --git a/example/src/Examples/SegmentedButtons/SegmentedButtonRealCase.tsx b/example/src/Examples/SegmentedButtons/SegmentedButtonRealCase.tsx index 87c0b74ba9..b1882a4b43 100644 --- a/example/src/Examples/SegmentedButtons/SegmentedButtonRealCase.tsx +++ b/example/src/Examples/SegmentedButtons/SegmentedButtonRealCase.tsx @@ -37,16 +37,21 @@ const SegmentedButtonRealCase = () => { contentContainerStyle={styles.contentContainer} renderItem={({ item }) => { return ( - - - } - /> - + + + } + /> + + } + /> ); }} /> @@ -66,9 +71,15 @@ const styles = StyleSheet.create({ marginHorizontal: 16, marginTop: 16, }, + content: { + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: 0, + paddingVertical: 0, + }, cover: { - width: 84, - height: 84, + width: 72, + height: 72, }, title: { flexShrink: 1, diff --git a/example/src/Examples/TeamDetails.tsx b/example/src/Examples/TeamDetails.tsx index cb06e817d6..d8bbc5c888 100644 --- a/example/src/Examples/TeamDetails.tsx +++ b/example/src/Examples/TeamDetails.tsx @@ -79,49 +79,61 @@ const News = () => { - - - - - - Which soccer players are switching teams? From the Premier - League, La Liga and beyond, here is a list of players on the - move this summer. - - - - - - - - - - - - - Medical tests show that Doe has injured the tendon in his left - hamstring, and in the next few days will... - - - - - - - + + } + header={ + + } + content={ + + + Which soccer players are switching teams? From the Premier + League, La Liga and beyond, here is a list of players on the + move this summer. + + + } + actions={ + + + + + } + /> + + } + header={ + + } + content={ + + + Medical tests show that Doe has injured the tendon in his left + hamstring, and in the next few days will... + + + } + actions={ + + + + + } + /> {}} visible style={styles.fab} /> diff --git a/example/src/Examples/TooltipExample.tsx b/example/src/Examples/TooltipExample.tsx index 4ecbdfe544..b617c94891 100644 --- a/example/src/Examples/TooltipExample.tsx +++ b/example/src/Examples/TooltipExample.tsx @@ -145,15 +145,14 @@ const TooltipExample = () => { - - ( - - )} - /> - + ( + + )} + /> diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index e260dd3f20..787cd5e374 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -1,64 +1,82 @@ import * as React from 'react'; import { StyleSheet, Pressable, View } from 'react-native'; import type { - ColorValue, GestureResponderEvent, StyleProp, ViewProps, ViewStyle, } from 'react-native'; -import useLatestCallback from 'use-latest-callback'; - import CardActions from './CardActions'; import CardContent from './CardContent'; -import { CardContext } from './CardContext'; import CardCover from './CardCover'; import CardTitle from './CardTitle'; -import { getCardColors } from './utils'; +import type { Props as CardTitleProps } from './CardTitle'; import { useInternalTheme } from '../../core/theming'; -import type { Elevation, ThemeProp } from '../../theme/types'; +import type { ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; -import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; -type OutlinedCardProps = { - mode: 'outlined'; - elevation?: never; -}; - -type ElevatedCardProps = { - mode?: 'elevated'; - elevation?: Elevation; +type ConvenienceHeaderProps = { + /** + * Header title. + */ + title?: React.ReactNode; + /** + * Header subtitle. + */ + subtitle?: React.ReactNode; + /** + * Render slot displayed before the title and subtitle. + */ + leading?: CardTitleProps['left']; + /** + * Render slot displayed after the title and subtitle. + */ + trailing?: CardTitleProps['right']; + /** + * A fully custom header cannot be combined with convenience header props. + */ + header?: never; }; -type ContainedCardProps = { - mode?: 'contained'; - elevation?: never; +type CustomHeaderProps = { + /** + * Fully custom header content. + */ + header: React.ReactNode; + /** + * Unavailable when a custom header is supplied. + */ + title?: never; + /** + * Unavailable when a custom header is supplied. + */ + subtitle?: never; + /** + * Unavailable when a custom header is supplied. + */ + leading?: never; + /** + * Unavailable when a custom header is supplied. + */ + trailing?: never; }; -type Mode = 'elevated' | 'outlined' | 'contained'; -type Direction = 'vertical' | 'horizontal'; - -export type Props = Omit & { +type CardBaseProps = Omit & { /** - * Mode of the Card. - * - `elevated` - Card with elevation. - * - `contained` - Card without outline and elevation @supported Available in v5.x with theme version 3 - * - `outlined` - Card with an outline. + * Media rendered at the start of the Card. */ - mode?: Mode; + media?: React.ReactNode; /** - * Direction of the Card's content. - * - `vertical` - * - `horizontal` + * Main Card content. */ - direction?: Direction; + content?: React.ReactNode; /** - * Content of the `Card`. + * Actions rendered at the end of the Card. */ - children: React.ReactNode; + actions?: React.ReactNode; /** * Function to execute on long press. */ @@ -84,15 +102,7 @@ export type Props = Omit & { */ disabled?: boolean; /** - * Changes Card shadow and background on iOS and Android. - */ - elevation?: Elevation; - /** - * Color of the outline in `outlined` mode. - */ - borderColor?: ColorValue; - /** - * Style of card's content. + * Style of card's inner content. */ contentStyle?: StyleProp; style?: StyleProp; @@ -111,67 +121,67 @@ export type Props = Omit & { /** * Reference to the card container. */ - ref?: React.Ref>; + ref?: React.Ref; }; -const DEFAULT_CARD_GAP = 16; -const DEFAULT_CARD_PADDING = 16; +export type Props = CardBaseProps & + (ConvenienceHeaderProps | CustomHeaderProps); /** - * A card is a sheet of material that serves as an entry point to more detailed information. + * A filled Card groups related media, header content, body content, and actions. * * ## Usage * ```js * import * as React from 'react'; * import { Avatar, Button, Card, Text } from 'react-native-paper'; * - * const LeftContent = props => + * const Leading = props => * * const MyComponent = () => ( - * - * - * - * + * } + * title="Card Title" + * subtitle="Card Subtitle" + * leading={Leading} + * content={ * Card title * Card content - * - * - * - * - * - * + * } + * actions={ + * + * + * } + * /> * ); * * export default MyComponent; * ``` */ + const Card = ({ - elevation: cardElevation = 1, delayLongPress, onPress, onLongPress, onPressOut, onPressIn, - mode: cardMode = 'elevated', - direction: cardDirection = 'vertical', - children, + media, + header, + title, + subtitle, + leading, + trailing, + content: cardContent, + actions, style, contentStyle, - borderColor: customBorderColor, theme: themeOverrides, testID = 'card', accessible, disabled, ref, ...rest -}: (OutlinedCardProps | ElevatedCardProps | ContainedCardProps) & Props) => { +}: Props) => { const theme = useInternalTheme(themeOverrides); - const isMode = React.useCallback( - (modeToCompare: Mode) => { - return cardMode === modeToCompare; - }, - [cardMode] - ); const hasPassedTouchHandler = hasTouchHandler({ onPress, @@ -180,97 +190,38 @@ const Card = ({ onPressOut, }); - // The ring goes on the Surface, the card's visible box (`scope: 'within'`), - // not on the `Pressable` that takes focus: the caller's `style` sizes and - // pads the Surface, so a ring on the content-sized `Pressable` would stop - // short of a taller card's edge or sit inside its padding. - // - // Off without a touch handler too: the `Pressable` unmounts then, and a - // focused one sends no blur, so the ring would come back with the handler. - const { target: focusTarget, ring: focusRing } = useFocusRing( - disabled || !hasPassedTouchHandler, - theme.colors.secondary, - 'outward', - 'within' - ); - - const [pressed, setPressed] = React.useState(false); - const elevation = isMode('elevated') ? (pressed ? 2 : cardElevation) : 0; - - const handlePressIn = useLatestCallback((e: GestureResponderEvent) => { - onPressIn?.(e); - - if (isMode('elevated')) { - setPressed(true); - } - }); - - const handlePressOut = useLatestCallback((e: GestureResponderEvent) => { - onPressOut?.(e); - - if (isMode('elevated')) { - setPressed(false); - } - }); - - const { backgroundColor, borderColor: themedBorderColor } = getCardColors({ - theme, - mode: cardMode, - }); - - const borderColor = customBorderColor ?? themedBorderColor; - const borderRadius = theme.shapes.corner.medium; - - const cardContext = React.useMemo( - () => ({ padding: DEFAULT_CARD_PADDING, direction: cardDirection }), - [cardDirection] - ); + const hasConvenienceHeader = + title != null || subtitle != null || leading != null || trailing != null; const content = ( - - - {children} - - + + {media} + {header ?? + (hasConvenienceHeader ? ( + + ) : null)} + {cardContent} + {actions} + ); return ( - {isMode('outlined') && ( - - )} - {hasPassedTouchHandler ? ( {content} @@ -310,22 +254,8 @@ Card.Cover = CardCover; Card.Title = CardTitle; const styles = StyleSheet.create({ - content: { + innerContainer: { flexShrink: 1, - overflow: 'hidden', - }, - horizontal: { - flexDirection: 'row', - }, - vertical: { - flexDirection: 'column', - }, - outline: { - borderWidth: 1, - position: 'absolute', - width: '100%', - height: '100%', - zIndex: 2, }, }); diff --git a/src/components/Card/CardActions.tsx b/src/components/Card/CardActions.tsx index 11b38c4ee1..1d26a6f70d 100644 --- a/src/components/Card/CardActions.tsx +++ b/src/components/Card/CardActions.tsx @@ -22,12 +22,12 @@ export type Props = ViewProps & { * import { Card, Button } from 'react-native-paper'; * * const MyComponent = () => ( - * - * - * - * - * - * + * + * + * + * } + * /> * ); * * export default MyComponent; diff --git a/src/components/Card/CardContent.tsx b/src/components/Card/CardContent.tsx index 4e0208469f..9281390f87 100644 --- a/src/components/Card/CardContent.tsx +++ b/src/components/Card/CardContent.tsx @@ -19,12 +19,12 @@ export type Props = ViewProps & { * import { Card, Text } from 'react-native-paper'; * * const MyComponent = () => ( - * - * + * * Card title * Card content - * - * + * } + * /> * ); * * export default MyComponent; diff --git a/src/components/Card/CardCover.tsx b/src/components/Card/CardCover.tsx index 173cd316c2..0a4acec9c9 100644 --- a/src/components/Card/CardCover.tsx +++ b/src/components/Card/CardCover.tsx @@ -24,9 +24,9 @@ export type Props = Omit & { * import { Card } from 'react-native-paper'; * * const MyComponent = () => ( - * - * - * + * } + * /> * ); * * export default MyComponent; diff --git a/src/components/Card/utils.tsx b/src/components/Card/utils.tsx index ab629378e2..f7fff786a6 100644 --- a/src/components/Card/utils.tsx +++ b/src/components/Card/utils.tsx @@ -1,54 +1,31 @@ -import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; +import type { ViewStyle } from 'react-native'; import type { InternalTheme } from '../../theme/types'; -type CardMode = 'elevated' | 'outlined' | 'contained'; +type BorderRadiusStyles = Pick< + ViewStyle, + Extract +>; -export type CardActionChildProps = { - mode?: string; - style?: StyleProp; -}; - -const getBorderColor = ({ theme }: { theme: InternalTheme }) => { - return theme.colors.outline; -}; - -const getBackgroundColor = ({ +export const getCardCoverStyle = ({ theme, - isMode, + index: _index, + total: _total, + borderRadiusStyles, }: { theme: InternalTheme; - isMode: (mode: CardMode) => boolean; + borderRadiusStyles: BorderRadiusStyles; + index?: number; + total?: number; }) => { - const { colors } = theme; - if (isMode('contained')) { - return colors.surfaceVariant; - } - if (isMode('outlined')) { - return colors.surface; + if (Object.keys(borderRadiusStyles).length > 0) { + return { + borderRadius: theme.shapes.corner.medium, + ...borderRadiusStyles, + }; } - return undefined; -}; - -export const getCardColors = ({ - theme, - mode, -}: { - theme: InternalTheme; - mode: CardMode; -}): { - backgroundColor: ColorValue | undefined; - borderColor: ColorValue; -} => { - const isMode = (modeToCompare: CardMode) => { - return mode === modeToCompare; - }; return { - backgroundColor: getBackgroundColor({ - theme, - isMode, - }), - borderColor: getBorderColor({ theme }), + borderRadius: theme.shapes.corner.medium, }; }; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 6966afbc87..50338091c6 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1,4 +1,5 @@ -import { Platform, StyleSheet, Text, View } from 'react-native'; +import * as React from 'react'; +import { StyleSheet, Text, View } from 'react-native'; import type { StyleProp, ViewStyle } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; @@ -7,7 +8,7 @@ import { render, screen } from '../../../test-utils'; import { LightTheme } from '../../../theme/schemes'; import Button from '../../Button/Button'; import Card from '../../Card/Card'; -import { getCardColors } from '../../Card/utils'; +import { getCardCoverStyle } from '../../Card/utils'; const styles = StyleSheet.create({ customCoverRadius: { @@ -29,90 +30,114 @@ afterEach(() => { }); describe('Card', () => { - it('renders an outlined card', async () => { - const tree = (await render({null})).toJSON(); + it('renders populated slots in deterministic order without rewriting nodes', async () => { + const CustomContent = React.memo(() => ( + + Custom content + + )); - expect(tree).toMatchSnapshot(); - }); - - it('renders an outlined card with a custom outline color', async () => { - const { toJSON } = await render( + await render( - {null} - + media={} + header={} + content={[ + , + null, + , + ]} + actions={ + <> + {null} + + + } + /> ); - expect(toJSON()).toMatchSnapshot(); + expect(screen.getAllByTestId(/^(region-|content-custom-wrapper)/)).toEqual([ + screen.getByTestId('region-media'), + screen.getByTestId('region-header'), + screen.getByTestId('region-content-array'), + screen.getByTestId('content-custom-wrapper'), + screen.getByTestId('region-actions'), + ]); }); - it('renders the outline with the color passed to borderColor prop', async () => { - const { toJSON } = await render( - - {null} - - ); + it('renders omitted slots as a neutral filled grouping container', async () => { + await render(); - expect(toJSON()).toMatchSnapshot(); + expect(screen.getByTestId('card-container')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceVariant, + }); + expect(screen.queryByRole('button')).not.toBeOnTheScreen(); }); - it('renders with a custom theme background color', async () => { - jest.replaceProperty(Platform, 'OS', 'web'); - + it('renders the convenience header inputs', async () => { await render( - {null} - + title="Card title" + subtitle="Card subtitle" + leading={({ size }) => Leading {size}} + trailing={({ size }) => Trailing {size}} + /> ); - expect(screen.getByLabelText('card')).toHaveStyle({ - backgroundColor: '#0000FF', - }); + expect(screen.getByText('Card title')).toBeOnTheScreen(); + expect(screen.getByText('Card subtitle')).toBeOnTheScreen(); + expect(screen.getByText('Leading 40')).toBeOnTheScreen(); + expect(screen.getByText('Trailing 24')).toBeOnTheScreen(); }); it('renders with a content style', async () => { await render( - - Content - + Content} contentStyle={styles.contentStyle} /> ); expect(screen.getByText('Content').parent).toHaveStyle(styles.contentStyle); }); - it('clips inner content to the card shape', async () => { - await render( - - Content - - ); + it('does render a disabled accessibility state', async () => { + await render( {}} disabled />); - expect(screen.getByText('Content').parent).toHaveStyle({ - borderRadius: LightTheme.shapes.corner.medium, - overflow: 'hidden', - }); + expect(screen.getByTestId('card')).toBeDisabled(); }); +}); - it('does not render a disabled accessibility state', async () => { - await render({null}); +describe('Card types', () => { + it('rejects the removed API and mixed header forms', () => { + const typeCases = ( + <> + + } + trailing={({ size }) => } + /> + } /> + Content} + actions={[]} + /> - expect(screen.getByTestId('card')).toBeEnabled(); - }); - it('does render a disabled accessibility state', async () => { - await render( - {}} disabled> - {null} - + {/* @ts-expect-error: Arbitrary children composition was removed. */} + + + + + {/* @ts-expect-error: The old mode prop was removed. */} + + + {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} + } title="Title" /> + + {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} + } leading={() => } /> + ); - expect(screen.getByTestId('card')).toBeDisabled(); + expect(typeCases).toBeDefined(); }); }); @@ -134,13 +159,11 @@ describe('CardCover', () => { it('renders with custom border radius', async () => { await render( - - - + ); // The border radius is applied to the container which clips the image @@ -166,19 +189,17 @@ describe('CardContent', () => { it('uses fixed padding regardless of neighboring card elements', async () => { await render( - + <> - <> - - - Content - - - + + + Content + + - + ); expect(screen.getByTestId('card-content')).toHaveStyle({ @@ -281,60 +302,15 @@ describe('CardActions', () => { }); }); -describe('getCardColors - background color', () => { - it('should return correct theme color, for theme version 3, contained mode', () => { - expect( - getCardColors({ - theme: LightTheme, - mode: 'contained', - }) - ).toMatchObject({ - backgroundColor: LightTheme.colors.surfaceVariant, - }); - }); - - it('should return correct theme color, for theme version 3, outlined mode', () => { - expect( - getCardColors({ - theme: LightTheme, - mode: 'outlined', - }) - ).toMatchObject({ backgroundColor: LightTheme.colors.surface }); - }); - - it('should return undefined, for theme version 3, elevated mode', () => { - expect( - getCardColors({ - theme: LightTheme, - mode: 'elevated', - }) - ).toMatchObject({ backgroundColor: undefined }); - }); -}); - -describe('getCardColors - border color', () => { - it('should return correct theme color, for theme version 3', () => { +describe('getCardCoverStyle - border radius', () => { + it('should return custom border radius', () => { expect( - getCardColors({ + getCardCoverStyle({ theme: LightTheme, - // @ts-expect-error: Verify the runtime fallback when mode is omitted. - mode: undefined, + borderRadiusStyles: styles.customCoverRadius, }) - ).toMatchObject({ borderColor: LightTheme.colors.outline }); + ).toMatchObject(styles.customCoverRadius); }); -}); - -describe('CardContent', () => { - it('uses the Card padding when it follows a cover and a title', async () => { - await render( - - - - - Card content - - - ); expect(screen.getByTestId('card-content').parent).toHaveStyle({ padding: 16, diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap deleted file mode 100644 index c746b6a75b..0000000000 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ /dev/null @@ -1,392 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Card renders an outlined card 1`] = ` - - - - - -`; - -exports[`Card renders an outlined card with a custom outline color 1`] = ` - - - - - -`; - -exports[`Card renders the outline with the color passed to borderColor prop 1`] = ` - - - - - -`; From c9be122e66083533bf77217a986e3775bd630e5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 4 Sep 2026 13:22:31 +0200 Subject: [PATCH 03/51] feat(card): add Material variant token contract --- src/components/Card/Card.tsx | 303 ++++++++++++++---- src/components/Card/tokens.ts | 280 ++++++++++++++++ src/components/__tests__/Card/Card.test.tsx | 201 +++++++++++- .../__tests__/Card/Card.tokens.test.ts | 248 ++++++++++++++ 4 files changed, 974 insertions(+), 58 deletions(-) create mode 100644 src/components/Card/tokens.ts create mode 100644 src/components/__tests__/Card/Card.tokens.test.ts diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 787cd5e374..9785b4e2c4 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -12,8 +12,9 @@ import CardContent from './CardContent'; import CardCover from './CardCover'; import CardTitle from './CardTitle'; import type { Props as CardTitleProps } from './CardTitle'; +import { resolveCardVisuals } from './tokens'; import { useInternalTheme } from '../../core/theming'; -import type { ThemeProp } from '../../theme/types'; +import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; @@ -64,71 +65,169 @@ type CustomHeaderProps = { trailing?: never; }; -type CardBaseProps = Omit & { +type CardShapeProps = { /** - * Media rendered at the start of the Card. + * Radius of every Card corner. */ - media?: React.ReactNode; + borderRadius?: ViewStyle['borderRadius']; /** - * Main Card content. + * Radius of the Card's bottom-end corner. */ - content?: React.ReactNode; + borderBottomEndRadius?: ViewStyle['borderBottomEndRadius']; /** - * Actions rendered at the end of the Card. + * Radius of the Card's bottom-left corner. */ - actions?: React.ReactNode; + borderBottomLeftRadius?: ViewStyle['borderBottomLeftRadius']; /** - * Function to execute on long press. + * Radius of the Card's bottom-right corner. */ - onLongPress?: () => void; + borderBottomRightRadius?: ViewStyle['borderBottomRightRadius']; /** - * Function to execute on press. + * Radius of the Card's bottom-start corner. */ - onPress?: (e: GestureResponderEvent) => void; + borderBottomStartRadius?: ViewStyle['borderBottomStartRadius']; /** - * Function to execute as soon as the touchable element is pressed and invoked even before onPress. + * Radius of the Card's end-end corner. */ - onPressIn?: (e: GestureResponderEvent) => void; + borderEndEndRadius?: ViewStyle['borderEndEndRadius']; /** - * Function to execute as soon as the touch is released even before onPress. + * Radius of the Card's end-start corner. */ - onPressOut?: (e: GestureResponderEvent) => void; + borderEndStartRadius?: ViewStyle['borderEndStartRadius']; /** - * The number of milliseconds a user must touch the element before executing `onLongPress`. + * Radius of the Card's start-end corner. */ - delayLongPress?: number; + borderStartEndRadius?: ViewStyle['borderStartEndRadius']; /** - * If true, disable all interactions for this component. + * Radius of the Card's start-start corner. */ - disabled?: boolean; + borderStartStartRadius?: ViewStyle['borderStartStartRadius']; /** - * Style of card's inner content. + * Radius of the Card's top-end corner. */ - contentStyle?: StyleProp; - style?: StyleProp; + borderTopEndRadius?: ViewStyle['borderTopEndRadius']; /** - * @optional + * Radius of the Card's top-left corner. */ - theme?: ThemeProp; + borderTopLeftRadius?: ViewStyle['borderTopLeftRadius']; /** - * Pass down testID from card props to touchable + * Radius of the Card's top-right corner. */ - testID?: string; + borderTopRightRadius?: ViewStyle['borderTopRightRadius']; /** - * Pass down accessible from card props to touchable + * Radius of the Card's top-start corner. */ - accessible?: boolean; + borderTopStartRadius?: ViewStyle['borderTopStartRadius']; /** - * Reference to the card container. + * Corner curve used by the Card on iOS. */ - ref?: React.Ref; + borderCurve?: ViewStyle['borderCurve']; }; +type FilledCardProps = { + /** + * Filled Card variant (default). + */ + variant?: 'filled'; + /** + * Filled Cards do not support custom elevation. + */ + elevation?: never; +}; + +type ElevatedCardProps = { + /** + * Elevated Card variant. + */ + variant: 'elevated'; + /** + * Resting shadow elevation for an elevated Card. + */ + elevation?: Elevation; +}; + +type OutlinedCardProps = { + /** + * Outlined Card variant. + */ + variant: 'outlined'; + /** + * Outlined Cards do not support custom elevation. + */ + elevation?: never; +}; + +type CardVariantProps = FilledCardProps | ElevatedCardProps | OutlinedCardProps; + +type CardBaseProps = Omit & + CardShapeProps & { + /** + * Media rendered at the start of the Card. + */ + media?: React.ReactNode; + /** + * Main Card content. + */ + content?: React.ReactNode; + /** + * Actions rendered at the end of the Card. + */ + actions?: React.ReactNode; + /** + * Function to execute on long press. + */ + onLongPress?: () => void; + /** + * Function to execute on press. + */ + onPress?: (e: GestureResponderEvent) => void; + /** + * Function to execute as soon as the touchable element is pressed and invoked even before onPress. + */ + onPressIn?: (e: GestureResponderEvent) => void; + /** + * Function to execute as soon as the touch is released even before onPress. + */ + onPressOut?: (e: GestureResponderEvent) => void; + /** + * The number of milliseconds a user must touch the element before executing `onLongPress`. + */ + delayLongPress?: number; + /** + * If true, disable all interactions for this component. + */ + disabled?: boolean; + /** + * Style of card's inner content. + */ + contentStyle?: StyleProp; + style?: StyleProp; + /** + * @optional + */ + theme?: ThemeProp; + /** + * Pass down testID from card props to touchable + */ + testID?: string; + /** + * Pass down accessible from card props to touchable + */ + accessible?: boolean; + /** + * Reference to the card container. + */ + ref?: React.Ref; + }; + export type Props = CardBaseProps & - (ConvenienceHeaderProps | CustomHeaderProps); + (ConvenienceHeaderProps | CustomHeaderProps) & + CardVariantProps; /** - * A filled Card groups related media, header content, body content, and actions. + * A Card groups related media, header content, body content, and actions. + * Use the `filled` (default), `elevated`, or `outlined` variant to select its + * Material 3 emphasis. * * ## Usage * ```js @@ -139,6 +238,7 @@ export type Props = CardBaseProps & * * const MyComponent = () => ( * } * title="Card Title" * subtitle="Card Subtitle" @@ -159,6 +259,8 @@ export type Props = CardBaseProps & */ const Card = ({ + variant: cardVariant = 'filled', + elevation: customElevation, delayLongPress, onPress, onLongPress, @@ -178,11 +280,32 @@ const Card = ({ testID = 'card', accessible, disabled, + borderRadius, + borderBottomEndRadius, + borderBottomLeftRadius, + borderBottomRightRadius, + borderBottomStartRadius, + borderEndEndRadius, + borderEndStartRadius, + borderStartEndRadius, + borderStartStartRadius, + borderTopEndRadius, + borderTopLeftRadius, + borderTopRightRadius, + borderTopStartRadius, + borderCurve = 'continuous', ref, ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); + const visuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + disabled, + }); + const hasPassedTouchHandler = hasTouchHandler({ onPress, onLongPress, @@ -190,12 +313,27 @@ const Card = ({ onPressOut, }); - const borderRadius = theme.shapes.corner.medium; + const shapeStyle = { + borderRadius: borderRadius ?? visuals.shape, + borderBottomEndRadius, + borderBottomLeftRadius, + borderBottomRightRadius, + borderBottomStartRadius, + borderEndEndRadius, + borderEndStartRadius, + borderStartEndRadius, + borderStartStartRadius, + borderTopEndRadius, + borderTopLeftRadius, + borderTopRightRadius, + borderTopStartRadius, + borderCurve, + }; const hasConvenienceHeader = title != null || subtitle != null || leading != null || trailing != null; const content = ( - + {media} {header ?? (hasConvenienceHeader ? ( @@ -214,30 +352,80 @@ const Card = ({ return ( - {hasPassedTouchHandler ? ( - - {content} - - ) : ( - content - )} + + + + {hasPassedTouchHandler ? ( + + {content} + + ) : ( + content + )} + {visuals.outlineWidth > 0 ? ( + + ) : null} + ); }; @@ -254,8 +442,13 @@ Card.Cover = CardCover; Card.Title = CardTitle; const styles = StyleSheet.create({ - innerContainer: { + visual: { + flexShrink: 1, + overflow: 'hidden', + }, + content: { flexShrink: 1, + position: 'relative', }, }); diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts new file mode 100644 index 0000000000..aaa00a2f11 --- /dev/null +++ b/src/components/Card/tokens.ts @@ -0,0 +1,280 @@ +import { tokens as systemTokens } from '../../theme/tokens'; +import type { Elevation, InternalTheme } from '../../theme/types'; + +export const cardVariants = ['filled', 'elevated', 'outlined'] as const; + +export type CardVariant = (typeof cardVariants)[number]; + +export const cardStates = [ + 'enabled', + 'hovered', + 'focused', + 'pressed', + 'dragged', + 'disabled', +] as const; + +export type CardState = (typeof cardStates)[number]; + +type ContainerColorRole = + | 'surfaceContainerLow' + | 'surfaceContainerHighest' + | 'surfaceVariant' + | 'surface'; + +type OutlineColorRole = 'outlineVariant' | 'onSurface' | 'outline'; + +type CardStateTokens = { + containerColor: ContainerColorRole; + containerOpacity: number; + outlineColor: OutlineColorRole; + outlineOpacity: number; + outlineWidth: 0 | 1; + elevation: Elevation; + stateLayerOpacity: number; +}; + +type CardTokenMatrix = Record>; + +const { opacity } = systemTokens.md.sys.state; + +/** + * Material 3 Card variant-by-state tokens. + * + * Rechecked 2026-09-04 against the Material 3 Card specification and the + * current AndroidX generated Card tokens at commit + * 160825094a81825468a95b115bfb1b541e549856: + * https://m3.material.io/components/cards/specs + * - FilledCardTokens v0_210 + * - ElevatedCardTokens v0_210 + * - OutlinedCardTokens v0_192 + * https://github.com/androidx/androidx/tree/160825094a81825468a95b115bfb1b541e549856/compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens + * + * State opacities were rechecked against Material Components Android generated + * token set 34.0.0 at commit 4d3710682140722f48a5965b68109b240e1fe79e. + * https://github.com/material-components/material-components-android/tree/4d3710682140722f48a5965b68109b240e1fe79e/lib/java/com/google/android/material + */ +const cardTokenMatrix = { + filled: { + enabled: { + containerColor: 'surfaceContainerHighest', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 0, + stateLayerOpacity: 0, + }, + hovered: { + containerColor: 'surfaceContainerHighest', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 1, + stateLayerOpacity: opacity.hovered, + }, + focused: { + containerColor: 'surfaceContainerHighest', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 0, + stateLayerOpacity: opacity.focused, + }, + pressed: { + containerColor: 'surfaceContainerHighest', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 0, + stateLayerOpacity: opacity.pressed, + }, + dragged: { + containerColor: 'surfaceContainerHighest', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 3, + stateLayerOpacity: opacity.dragged, + }, + disabled: { + containerColor: 'surfaceVariant', + containerOpacity: opacity.disabled, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 0, + stateLayerOpacity: 0, + }, + }, + elevated: { + enabled: { + containerColor: 'surfaceContainerLow', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 1, + stateLayerOpacity: 0, + }, + hovered: { + containerColor: 'surfaceContainerLow', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 2, + stateLayerOpacity: opacity.hovered, + }, + focused: { + containerColor: 'surfaceContainerLow', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 1, + stateLayerOpacity: opacity.focused, + }, + pressed: { + containerColor: 'surfaceContainerLow', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 1, + stateLayerOpacity: opacity.pressed, + }, + dragged: { + containerColor: 'surfaceContainerLow', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 4, + stateLayerOpacity: opacity.dragged, + }, + disabled: { + containerColor: 'surface', + containerOpacity: opacity.disabled, + outlineColor: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + elevation: 1, + stateLayerOpacity: 0, + }, + }, + outlined: { + enabled: { + containerColor: 'surface', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 1, + outlineWidth: 1, + elevation: 0, + stateLayerOpacity: 0, + }, + hovered: { + containerColor: 'surface', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 1, + outlineWidth: 1, + elevation: 1, + stateLayerOpacity: opacity.hovered, + }, + focused: { + containerColor: 'surface', + containerOpacity: 1, + outlineColor: 'onSurface', + outlineOpacity: 1, + outlineWidth: 1, + elevation: 0, + stateLayerOpacity: opacity.focused, + }, + pressed: { + containerColor: 'surface', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 1, + outlineWidth: 1, + elevation: 0, + stateLayerOpacity: opacity.pressed, + }, + dragged: { + containerColor: 'surface', + containerOpacity: 1, + outlineColor: 'outlineVariant', + outlineOpacity: 1, + outlineWidth: 1, + elevation: 3, + stateLayerOpacity: opacity.dragged, + }, + disabled: { + containerColor: 'surface', + containerOpacity: 1, + outlineColor: 'outline', + outlineOpacity: 0.12, + outlineWidth: 1, + elevation: 0, + stateLayerOpacity: 0, + }, + }, +} as const satisfies CardTokenMatrix; + +export type CardStateFlags = { + disabled?: boolean; + dragged?: boolean; + pressed?: boolean; + focused?: boolean; + hovered?: boolean; +}; + +export type ResolveCardVisualsOptions = CardStateFlags & { + theme: InternalTheme; + variant: CardVariant; + elevation?: Elevation; +}; + +export const resolveCardVisuals = ({ + theme, + variant, + elevation: customElevation, + disabled = false, + dragged = false, + pressed = false, + focused = false, + hovered = false, +}: ResolveCardVisualsOptions) => { + const state: CardState = disabled + ? 'disabled' + : dragged + ? 'dragged' + : pressed + ? 'pressed' + : focused + ? 'focused' + : hovered + ? 'hovered' + : 'enabled'; + const stateTokens = cardTokenMatrix[variant][state]; + + return { + state, + containerColor: theme.colors[stateTokens.containerColor], + containerOpacity: stateTokens.containerOpacity, + outlineColor: theme.colors[stateTokens.outlineColor], + outlineOpacity: stateTokens.outlineOpacity, + outlineWidth: stateTokens.outlineWidth, + elevation: + variant === 'elevated' && state === 'enabled' && customElevation != null + ? customElevation + : stateTokens.elevation, + shape: theme.shapes.corner.medium, + stateLayerColor: theme.colors.onSurface, + stateLayerOpacity: stateTokens.stateLayerOpacity, + }; +}; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 50338091c6..3f6fa97c79 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { StyleSheet, Text, View } from 'react-native'; +import { Platform, StyleSheet, Text, View } from 'react-native'; import type { StyleProp, ViewStyle } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; @@ -30,6 +30,185 @@ afterEach(() => { }); describe('Card', () => { + it.each([ + { + variant: 'filled' as const, + colorRole: 'surfaceContainerHighest' as const, + }, + { + variant: 'elevated' as const, + colorRole: 'surfaceContainerLow' as const, + }, + { variant: 'outlined' as const, colorRole: 'surface' as const }, + ])( + 'renders the enabled $variant appearance in light and dark themes', + async ({ variant, colorRole }) => { + for (const isDark of [false, true] as const) { + const theme = getTheme(isDark); + const card = + variant === 'elevated' ? ( + + ) : variant === 'outlined' ? ( + + ) : ( + + ); + const { unmount } = await render(card); + + expect(screen.getByTestId('card-visual')).toHaveStyle({ + backgroundColor: theme.colors[colorRole], + }); + + await unmount(); + } + } + ); + + it('renders the enabled outlined role in light and dark themes', async () => { + for (const isDark of [false, true] as const) { + const theme = getTheme(isDark); + const { unmount } = await render( + + ); + + expect(screen.getByTestId('card-outline')).toHaveStyle({ + borderColor: theme.colors.outlineVariant, + borderWidth: 1, + opacity: 1, + }); + + await unmount(); + } + }); + + it.each(['filled', 'elevated'] as const)( + 'does not render an outline for the %s variant', + async (variant) => { + const card = + variant === 'elevated' ? ( + + ) : ( + + ); + + await render(card); + + expect(screen.queryByTestId('card-outline')).not.toBeOnTheScreen(); + } + ); + + it('uses filled as the default and resolves deeply merged custom colors', async () => { + await render( + + ); + + expect(screen.getByTestId('card-visual')).toHaveStyle({ + backgroundColor: '#111111', + }); + expect(screen.getByTestId('card-state-layer')).toHaveStyle({ + backgroundColor: '#222222', + opacity: 0, + }); + }); + + it('uses custom theme roles for elevated and outlined variants', async () => { + const { unmount } = await render( + + ); + + expect(screen.getByTestId('card-visual')).toHaveStyle({ + backgroundColor: '#123456', + }); + await unmount(); + + await render( + + ); + + expect(screen.getByTestId('card-visual')).toHaveStyle({ + backgroundColor: '#abcdef', + }); + expect(screen.getByTestId('card-outline')).toHaveStyle({ + borderColor: '#654321', + }); + }); + + it('lets only elevated Cards customize their resting elevation', async () => { + jest.replaceProperty(Platform, 'OS', 'android'); + + await render(); + + expect(screen.getByTestId('card-container')).toHaveStyle({ elevation: 12 }); + }); + + it.each([ + { variant: 'filled' as const, elevation: 0 }, + { variant: 'elevated' as const, elevation: 1 }, + { variant: 'outlined' as const, elevation: 0 }, + ])( + 'renders the enabled $variant elevation', + async ({ variant, elevation }) => { + jest.replaceProperty(Platform, 'OS', 'android'); + const card = + variant === 'elevated' ? ( + + ) : variant === 'outlined' ? ( + + ) : ( + + ); + + await render(card); + + expect(screen.getByTestId('card-container')).toHaveStyle({ elevation }); + expect(screen.getByTestId('card-container')).toHaveStyle({ + backgroundColor: 'transparent', + }); + } + ); + + it('applies the medium shape and asymmetric overrides across the shell', async () => { + await render( + + ); + + const expectedShape = { + borderRadius: getTheme().shapes.corner.medium, + borderTopLeftRadius: 4, + borderTopRightRadius: 8, + borderBottomRightRadius: 16, + borderBottomLeftRadius: 20, + borderCurve: 'continuous', + }; + + expect(screen.getByTestId('card-container')).toHaveStyle(expectedShape); + expect(screen.getByTestId('card-visual')).toHaveStyle(expectedShape); + expect(screen.getByTestId('card-background')).toHaveStyle(expectedShape); + expect(screen.getByTestId('card-state-layer')).toHaveStyle(expectedShape); + expect(screen.getByTestId('card-outline')).toHaveStyle(expectedShape); + }); + it('renders populated slots in deterministic order without rewriting nodes', async () => { const CustomContent = React.memo(() => ( @@ -67,8 +246,8 @@ describe('Card', () => { it('renders omitted slots as a neutral filled grouping container', async () => { await render(); - expect(screen.getByTestId('card-container')).toHaveStyle({ - backgroundColor: getTheme().colors.surfaceVariant, + expect(screen.getByTestId('card-visual')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceContainerHighest, }); expect(screen.queryByRole('button')).not.toBeOnTheScreen(); }); @@ -120,6 +299,10 @@ describe('Card types', () => { content={Content} actions={[]} /> + + + + {/* @ts-expect-error: Arbitrary children composition was removed. */} @@ -129,6 +312,18 @@ describe('Card types', () => { {/* @ts-expect-error: The old mode prop was removed. */} + {/* @ts-expect-error: Contained is not a Card variant. */} + + + {/* @ts-expect-error: The default filled Card cannot be elevated. */} + + + {/* @ts-expect-error: Filled Cards cannot be elevated. */} + + + {/* @ts-expect-error: Outlined Cards cannot be elevated. */} + + {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} } title="Title" /> diff --git a/src/components/__tests__/Card/Card.tokens.test.ts b/src/components/__tests__/Card/Card.tokens.test.ts new file mode 100644 index 0000000000..c89a1d93a5 --- /dev/null +++ b/src/components/__tests__/Card/Card.tokens.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from '@jest/globals'; + +import { LightTheme } from '../../../theme/schemes'; +import { + cardStates, + cardVariants, + resolveCardVisuals, +} from '../../Card/tokens'; +import type { CardState } from '../../Card/tokens'; + +const stateFlags: Record< + CardState, + Partial< + Record<'disabled' | 'dragged' | 'pressed' | 'focused' | 'hovered', boolean> + > +> = { + enabled: {}, + hovered: { hovered: true }, + focused: { focused: true }, + pressed: { pressed: true }, + dragged: { dragged: true }, + disabled: { disabled: true }, +}; + +type ExpectedVisualTokens = { + containerRole: + | 'surfaceContainerLow' + | 'surfaceContainerHighest' + | 'surfaceVariant' + | 'surface'; + containerOpacity: number; + outlineRole: 'outlineVariant' | 'onSurface' | 'outline'; + outlineOpacity: number; + outlineWidth: 0 | 1; + elevation: 0 | 1 | 2 | 3 | 4 | 5; + stateLayerOpacity: number; +}; + +const expectedVisual = ( + tokens: Pick< + ExpectedVisualTokens, + 'containerRole' | 'elevation' | 'stateLayerOpacity' + > & + Partial +): ExpectedVisualTokens => ({ + containerOpacity: 1, + outlineRole: 'outlineVariant', + outlineOpacity: 0, + outlineWidth: 0, + ...tokens, +}); + +const expectedOutlinedVisual = ( + tokens: Pick & + Partial +): ExpectedVisualTokens => + expectedVisual({ + containerRole: 'surface', + outlineOpacity: 1, + outlineWidth: 1, + ...tokens, + }); + +const expectedVisuals: Record< + (typeof cardVariants)[number], + ExpectedVisualTokens[] +> = { + elevated: [ + expectedVisual({ + containerRole: 'surfaceContainerLow', + elevation: 1, + stateLayerOpacity: 0, + }), + expectedVisual({ + containerRole: 'surfaceContainerLow', + elevation: 2, + stateLayerOpacity: 0.08, + }), + expectedVisual({ + containerRole: 'surfaceContainerLow', + elevation: 1, + stateLayerOpacity: 0.1, + }), + expectedVisual({ + containerRole: 'surfaceContainerLow', + elevation: 1, + stateLayerOpacity: 0.1, + }), + expectedVisual({ + containerRole: 'surfaceContainerLow', + elevation: 4, + stateLayerOpacity: 0.16, + }), + expectedVisual({ + containerRole: 'surface', + containerOpacity: 0.38, + elevation: 1, + stateLayerOpacity: 0, + }), + ], + filled: [ + expectedVisual({ + containerRole: 'surfaceContainerHighest', + elevation: 0, + stateLayerOpacity: 0, + }), + expectedVisual({ + containerRole: 'surfaceContainerHighest', + elevation: 1, + stateLayerOpacity: 0.08, + }), + expectedVisual({ + containerRole: 'surfaceContainerHighest', + elevation: 0, + stateLayerOpacity: 0.1, + }), + expectedVisual({ + containerRole: 'surfaceContainerHighest', + elevation: 0, + stateLayerOpacity: 0.1, + }), + expectedVisual({ + containerRole: 'surfaceContainerHighest', + elevation: 3, + stateLayerOpacity: 0.16, + }), + expectedVisual({ + containerRole: 'surfaceVariant', + containerOpacity: 0.38, + elevation: 0, + stateLayerOpacity: 0, + }), + ], + outlined: [ + expectedOutlinedVisual({ elevation: 0, stateLayerOpacity: 0 }), + expectedOutlinedVisual({ elevation: 1, stateLayerOpacity: 0.08 }), + expectedOutlinedVisual({ + elevation: 0, + outlineRole: 'onSurface', + stateLayerOpacity: 0.1, + }), + expectedOutlinedVisual({ elevation: 0, stateLayerOpacity: 0.1 }), + expectedOutlinedVisual({ elevation: 3, stateLayerOpacity: 0.16 }), + expectedOutlinedVisual({ + elevation: 0, + outlineRole: 'outline', + outlineOpacity: 0.12, + stateLayerOpacity: 0, + }), + ], +}; + +describe('resolveCardVisuals', () => { + it.each(cardVariants)( + 'resolves every Material state for the %s variant', + (variant) => { + const theme = LightTheme; + + expect( + cardStates.map((state) => { + return resolveCardVisuals({ + theme, + variant, + ...stateFlags[state], + }); + }) + ).toEqual( + expectedVisuals[variant].map( + ( + { + containerRole, + containerOpacity, + outlineRole, + outlineOpacity, + outlineWidth, + elevation, + stateLayerOpacity, + }, + index + ) => ({ + state: cardStates[index], + containerColor: theme.colors[containerRole], + containerOpacity, + outlineColor: theme.colors[outlineRole], + outlineOpacity, + outlineWidth, + elevation, + shape: theme.shapes.corner.medium, + stateLayerColor: theme.colors.onSurface, + stateLayerOpacity, + }) + ) + ); + } + ); + + it('uses disabled, dragged, pressed, focused, hovered, then enabled precedence', () => { + const theme = LightTheme; + const common = { theme, variant: 'filled' as const }; + + expect([ + resolveCardVisuals({ + ...common, + disabled: true, + dragged: true, + pressed: true, + focused: true, + hovered: true, + }).state, + resolveCardVisuals({ + ...common, + dragged: true, + pressed: true, + focused: true, + hovered: true, + }).state, + resolveCardVisuals({ + ...common, + pressed: true, + focused: true, + hovered: true, + }).state, + resolveCardVisuals({ + ...common, + focused: true, + hovered: true, + }).state, + resolveCardVisuals({ ...common, hovered: true }).state, + resolveCardVisuals(common).state, + ]).toEqual(cardStates.toReversed()); + }); + + it('uses a custom resting elevation only for the enabled elevated state', () => { + const theme = LightTheme; + + expect( + resolveCardVisuals({ theme, variant: 'elevated', elevation: 5 }).elevation + ).toBe(5); + expect( + resolveCardVisuals({ + theme, + variant: 'elevated', + elevation: 5, + hovered: true, + }).elevation + ).toBe(2); + }); +}); From b4454df90e942e62c767cee4e86fd82e32143bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 4 Sep 2026 13:36:47 +0200 Subject: [PATCH 04/51] feat(card): modernize responsive cover media --- src/components/Card/CardCover.tsx | 77 +++++------ src/components/Card/utils.tsx | 31 ----- src/components/__tests__/Card/Card.test.tsx | 140 ++++++++++++++------ 3 files changed, 136 insertions(+), 112 deletions(-) delete mode 100644 src/components/Card/utils.tsx diff --git a/src/components/Card/CardCover.tsx b/src/components/Card/CardCover.tsx index 0a4acec9c9..3340d6024e 100644 --- a/src/components/Card/CardCover.tsx +++ b/src/components/Card/CardCover.tsx @@ -1,14 +1,16 @@ -import * as React from 'react'; -import { Image, StyleSheet, View } from 'react-native'; -import type { ImageProps, StyleProp, ViewStyle } from 'react-native'; +import { Image, StyleSheet } from 'react-native'; +import type { ImageProps, ImageStyle, StyleProp } from 'react-native'; -import { CardContext } from './CardContext'; -import { useInternalTheme } from '../../core/theming'; import { grey200 } from '../../theme/colors'; import type { ThemeProp } from '../../theme/types'; export type Props = Omit & { - style?: StyleProp; + /** + * Style for the cover image. The default size is full width by 195. Consumer + * styles are applied after these defaults. Supplying an `aspectRatio` + * removes the default height so the cover can resize responsively. + */ + style?: StyleProp; /** * @optional */ @@ -18,6 +20,12 @@ export type Props = Omit & { /** * A component to show a cover image inside a Card. * + * Card owns clipping when the cover is used in its `media` slot, so the image + * follows the Card's default or custom shape without adding another radius. + * Hide decorative covers from screen readers with `accessible={false}` and + * `aria-hidden`. For informative covers, provide `accessible`, + * `accessibilityRole="image"`, and a useful `accessibilityLabel`. + * * ## Usage * ```js * import * as React from 'react'; @@ -25,7 +33,15 @@ export type Props = Omit & { * * const MyComponent = () => ( * } + * media={ + * + * } * /> * ); * @@ -34,54 +50,31 @@ export type Props = Omit & { * * @extends Image props https://reactnative.dev/docs/image#props */ -const CardCover = ({ style, theme: themeOverrides, ...rest }: Props) => { - const theme = useInternalTheme(themeOverrides); - const cardContext = React.useContext(CardContext); - - const coverStyle = { borderRadius: theme.shapes.corner.medium }; - - const cardMarginStyle = cardContext - ? cardContext.direction === 'horizontal' - ? { - marginTop: -cardContext.padding, - marginLeft: -cardContext.padding, - marginBottom: -cardContext.padding, - } - : { - marginTop: -cardContext.padding, - marginLeft: -cardContext.padding, - marginRight: -cardContext.padding, - } - : null; +const CardCover = ({ style, theme: _theme, ...rest }: Props) => { + const usesAspectRatio = StyleSheet.flatten(style)?.aspectRatio !== undefined; // The container clips the image with `overflow: 'hidden'`, // so any border radius passed in `style` is applied to the image as well return ( - - - + ); }; CardCover.displayName = 'Card.Cover'; const styles = StyleSheet.create({ - container: { - height: 194, - backgroundColor: grey200, - overflow: 'hidden', - }, image: { - flex: 1, - height: 'auto', - width: 'auto', + width: '100%', + backgroundColor: grey200, justifyContent: 'flex-end', }, + defaultHeight: { + height: 195, + }, }); export default CardCover; diff --git a/src/components/Card/utils.tsx b/src/components/Card/utils.tsx deleted file mode 100644 index f7fff786a6..0000000000 --- a/src/components/Card/utils.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import type { ViewStyle } from 'react-native'; - -import type { InternalTheme } from '../../theme/types'; - -type BorderRadiusStyles = Pick< - ViewStyle, - Extract ->; - -export const getCardCoverStyle = ({ - theme, - index: _index, - total: _total, - borderRadiusStyles, -}: { - theme: InternalTheme; - borderRadiusStyles: BorderRadiusStyles; - index?: number; - total?: number; -}) => { - if (Object.keys(borderRadiusStyles).length > 0) { - return { - borderRadius: theme.shapes.corner.medium, - ...borderRadiusStyles, - }; - } - - return { - borderRadius: theme.shapes.corner.medium, - }; -}; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 3f6fa97c79..2de4a9f286 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -8,15 +8,8 @@ import { render, screen } from '../../../test-utils'; import { LightTheme } from '../../../theme/schemes'; import Button from '../../Button/Button'; import Card from '../../Card/Card'; -import { getCardCoverStyle } from '../../Card/utils'; const styles = StyleSheet.create({ - customCoverRadius: { - borderTopLeftRadius: 4, - borderTopRightRadius: 8, - borderBottomLeftRadius: 0, - borderBottomRightRadius: 2, - }, contentStyle: { flexDirection: 'column-reverse', }, @@ -329,6 +322,9 @@ describe('Card types', () => { {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} } leading={() => } /> + + {/* @ts-expect-error: Cover placement metadata is not public. */} + ); @@ -337,34 +333,117 @@ describe('Card types', () => { }); describe('CardCover', () => { - it('renders with the theme border radius by default', async () => { + it('uses the documented full-width default size', async () => { await render( - - - + ); - expect(screen.getByTestId('card-cover').parent).toHaveStyle({ - borderRadius: LightTheme.shapes.corner.medium, + expect(screen.getByTestId('card-cover')).toHaveStyle({ + width: '100%', + height: 195, }); }); - it('renders with custom border radius', async () => { + it('uses an aspect ratio instead of the default height', async () => { await render( + ); + + const cover = screen.getByTestId('responsive-cover'); + + expect(cover).toHaveStyle({ width: '100%', aspectRatio: 16 / 9 }); + expect(cover).not.toHaveStyle({ height: 195 }); + }); + + it('exposes supplied semantics for an informative image', async () => { + await render( + + ); + + expect(screen.getByRole('image')).toBe( + screen.getByLabelText('Snow-covered mountains') + ); + }); + + it('preserves explicit decorative image semantics', async () => { + await render( + + ); + + const cover = screen.getByTestId('decorative-cover', { + includeHiddenElements: true, + }); + + expect(cover).toHaveProp('accessible', false); + expect(cover).toHaveProp('aria-hidden', true); + expect(screen.queryByRole('image')).not.toBeOnTheScreen(); + }); + + it('applies consumer image styles after the defaults', async () => { + await render( + ); - // The border radius is applied to the container which clips the image - expect(screen.getByTestId('card-cover').parent).toHaveStyle( - styles.customCoverRadius + expect(screen.getByTestId('styled-cover')).toHaveStyle({ + width: 320, + height: 200, + opacity: 0.8, + borderRadius: 6, + }); + }); + + it('uses the Card clipping shape for edge media without double rounding', async () => { + await render( + + } + /> ); + + expect(screen.getByTestId('shaped-card-visual')).toHaveStyle({ + overflow: 'hidden', + borderTopLeftRadius: 4, + borderTopRightRadius: 8, + borderBottomRightRadius: 16, + borderBottomLeftRadius: 20, + }); + expect(screen.getByTestId('edge-cover')).not.toHaveStyle({ + borderRadius: getTheme().shapes.corner.medium, + }); }); }); @@ -496,20 +575,3 @@ describe('CardActions', () => { }); }); }); - -describe('getCardCoverStyle - border radius', () => { - it('should return custom border radius', () => { - expect( - getCardCoverStyle({ - theme: LightTheme, - borderRadiusStyles: styles.customCoverRadius, - }) - ).toMatchObject(styles.customCoverRadius); - }); - - expect(screen.getByTestId('card-content').parent).toHaveStyle({ - padding: 16, - gap: 16, - }); - }); -}); From d047afff4831d765778e1d98f9ad29c9ec25bf46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 4 Sep 2026 13:48:21 +0200 Subject: [PATCH 05/51] feat(card)!: expose one actionable target --- src/components/Card/Card.tsx | 190 +++++++++++- src/components/__tests__/Card/Card.test.tsx | 312 +++++++++++++++++++- 2 files changed, 483 insertions(+), 19 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 9785b4e2c4..3fcf462c6f 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { StyleSheet, Pressable, View } from 'react-native'; +import { StyleSheet, View } from 'react-native'; import type { GestureResponderEvent, StyleProp, @@ -18,6 +18,8 @@ import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; +import TouchableRipple from '../TouchableRipple/TouchableRipple'; +import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; type ConvenienceHeaderProps = { /** @@ -189,6 +191,14 @@ type CardBaseProps = Omit & * Function to execute as soon as the touch is released even before onPress. */ onPressOut?: (e: GestureResponderEvent) => void; + /** + * Function called when the pointer starts hovering over an actionable Card. + */ + onHoverIn?: TouchableRippleProps['onHoverIn']; + /** + * Function called when the pointer stops hovering over an actionable Card. + */ + onHoverOut?: TouchableRippleProps['onHoverOut']; /** * The number of milliseconds a user must touch the element before executing `onLongPress`. */ @@ -207,15 +217,21 @@ type CardBaseProps = Omit & */ theme?: ThemeProp; /** - * Pass down testID from card props to touchable + * Test ID for the interaction node when the Card is actionable, or the + * content node when it is neutral. The shell and clipped visual region use + * `${testID}-container` and `${testID}-visual` respectively. */ testID?: string; /** - * Pass down accessible from card props to touchable + * Whether the Card's semantic target is an accessibility element. */ accessible?: boolean; /** - * Reference to the card container. + * Reference to the actionable Card interaction node. + */ + touchableRef?: React.Ref; + /** + * Reference to the outer Card shell. */ ref?: React.Ref; }; @@ -229,6 +245,10 @@ export type Props = CardBaseProps & * Use the `filled` (default), `elevated`, or `outlined` variant to select its * Material 3 emphasis. * + * A Card with an interaction handler represents one action. It receives button + * semantics by default and must not contain independent controls in `actions`. + * Use a neutral Card when its actions provide their own interaction targets. + * * ## Usage * ```js * import * as React from 'react'; @@ -280,6 +300,50 @@ const Card = ({ testID = 'card', accessible, disabled, + accessibilityActions, + role, + accessibilityRole, + 'aria-label': ariaLabel, + accessibilityLabel, + accessibilityHint, + accessibilityState, + accessibilityValue, + 'aria-busy': ariaBusy, + 'aria-checked': ariaChecked, + 'aria-disabled': ariaDisabled, + 'aria-expanded': ariaExpanded, + 'aria-hidden': ariaHidden, + 'aria-labelledby': ariaLabelledBy, + 'aria-live': ariaLive, + 'aria-modal': ariaModal, + 'aria-selected': ariaSelected, + 'aria-valuemax': ariaValueMax, + 'aria-valuemin': ariaValueMin, + 'aria-valuenow': ariaValueNow, + 'aria-valuetext': ariaValueText, + accessibilityLabelledBy, + accessibilityLiveRegion, + accessibilityElementsHidden, + accessibilityViewIsModal, + accessibilityIgnoresInvertColors, + accessibilityLanguage, + accessibilityShowsLargeContentViewer, + accessibilityLargeContentTitle, + accessibilityRespondsToUserInteraction, + importantForAccessibility, + screenReaderFocusable, + onAccessibilityAction, + onAccessibilityEscape, + onAccessibilityTap, + onMagicTap, + focusable, + tabIndex, + hitSlop, + onFocus, + onBlur, + onHoverIn, + onHoverOut, + touchableRef, borderRadius, borderBottomEndRadius, borderBottomLeftRadius, @@ -299,11 +363,15 @@ const Card = ({ }: Props) => { const theme = useInternalTheme(themeOverrides); + const isDisabled = Boolean( + disabled || ariaDisabled || accessibilityState?.disabled + ); + const visuals = resolveCardVisuals({ theme, variant: cardVariant, elevation: customElevation, - disabled, + disabled: isDisabled, }); const hasPassedTouchHandler = hasTouchHandler({ @@ -312,6 +380,23 @@ const Card = ({ onPressIn, onPressOut, }); + const hasWarnedAboutActions = React.useRef(false); + const hasActions = + actions !== null && actions !== undefined && actions !== false; + + React.useEffect(() => { + if ( + process.env.NODE_ENV !== 'production' && + hasPassedTouchHandler && + hasActions && + !hasWarnedAboutActions.current + ) { + console.warn( + 'An actionable Card cannot contain actions. Remove the Card interaction handlers or move the independent actions outside the Card.' + ); + hasWarnedAboutActions.current = true; + } + }, [hasActions, hasPassedTouchHandler]); const shapeStyle = { borderRadius: borderRadius ?? visuals.shape, @@ -333,7 +418,10 @@ const Card = ({ title != null || subtitle != null || leading != null || trailing != null; const content = ( - + {media} {header ?? (hasConvenienceHeader ? ( @@ -349,6 +437,62 @@ const Card = ({ ); + const actionableRole = + role ?? (accessibilityRole === undefined ? 'button' : undefined); + const accessibilityProps = { + accessible, + accessibilityActions, + role, + accessibilityRole, + 'aria-label': ariaLabel, + accessibilityLabel, + accessibilityHint, + accessibilityState, + accessibilityValue, + 'aria-busy': ariaBusy, + 'aria-checked': ariaChecked, + 'aria-disabled': ariaDisabled, + 'aria-expanded': ariaExpanded, + 'aria-hidden': ariaHidden, + 'aria-labelledby': ariaLabelledBy, + 'aria-live': ariaLive, + 'aria-modal': ariaModal, + 'aria-selected': ariaSelected, + 'aria-valuemax': ariaValueMax, + 'aria-valuemin': ariaValueMin, + 'aria-valuenow': ariaValueNow, + 'aria-valuetext': ariaValueText, + accessibilityLabelledBy, + accessibilityLiveRegion, + accessibilityElementsHidden, + accessibilityViewIsModal, + accessibilityIgnoresInvertColors, + accessibilityLanguage, + accessibilityShowsLargeContentViewer, + accessibilityLargeContentTitle, + accessibilityRespondsToUserInteraction, + importantForAccessibility, + screenReaderFocusable, + onAccessibilityAction, + onAccessibilityEscape, + onAccessibilityTap, + onMagicTap, + }; + const actionableAccessibilityProps = { + ...accessibilityProps, + role: actionableRole, + 'aria-disabled': isDisabled, + accessibilityActions: isDisabled ? undefined : accessibilityActions, + onAccessibilityAction: isDisabled ? undefined : onAccessibilityAction, + onAccessibilityEscape: isDisabled ? undefined : onAccessibilityEscape, + onAccessibilityTap: isDisabled ? undefined : onAccessibilityTap, + onMagicTap: isDisabled ? undefined : onMagicTap, + }; + const neutralAccessibilityProps = { + ...accessibilityProps, + 'aria-disabled': isDisabled || ariaDisabled, + }; + return ( {hasPassedTouchHandler ? ( - {content} - + ) : ( content )} diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 2de4a9f286..2e8eccd00f 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -4,8 +4,8 @@ import type { StyleProp, ViewStyle } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; -import { render, screen } from '../../../test-utils'; -import { LightTheme } from '../../../theme/schemes'; +import { getTheme } from '../../../core/theming'; +import { fireEvent, render, screen, userEvent } from '../../../test-utils'; import Button from '../../Button/Button'; import Card from '../../Card/Card'; @@ -242,9 +242,238 @@ describe('Card', () => { expect(screen.getByTestId('card-visual')).toHaveStyle({ backgroundColor: getTheme().colors.surfaceContainerHighest, }); + expect(screen.getByTestId('card')).not.toHaveProp('focusable'); + expect(screen.getByTestId('card-container')).not.toHaveProp('focusable'); expect(screen.queryByRole('button')).not.toBeOnTheScreen(); }); + it('preserves explicit semantics on a neutral Card shell', async () => { + await render( + + ); + + const shell = screen.getByRole('summary', { name: 'Product summary' }); + + expect(shell).toBe(screen.getByTestId('product-card-container')); + expect(shell).toHaveProp( + 'accessibilityHint', + 'Contains product information' + ); + expect(shell).toHaveProp('focusable', false); + expect(screen.getByTestId('product-card')).not.toHaveProp('role'); + }); + + it('creates one target for whole-Card interaction callbacks', async () => { + const onPress = jest.fn(); + const onLongPress = jest.fn(); + const onPressIn = jest.fn(); + const onPressOut = jest.fn(); + const onFocus = jest.fn(); + const onBlur = jest.fn(); + const onHoverIn = jest.fn(); + const onHoverOut = jest.fn(); + const hitSlop = { top: 4, right: 8, bottom: 12, left: 16 }; + await render( + + ); + + const [target] = screen.getAllByRole('button'); + const events = { + press: { nativeEvent: { target: 'press' } }, + longPress: { nativeEvent: { target: 'long-press' } }, + pressIn: { nativeEvent: { target: 'press-in' } }, + pressOut: { nativeEvent: { target: 'press-out' } }, + focus: { nativeEvent: { target: 'focus' } }, + blur: { nativeEvent: { target: 'blur' } }, + hoverIn: { nativeEvent: { target: 'hover-in' } }, + hoverOut: { nativeEvent: { target: 'hover-out' } }, + }; + + expect(screen.getAllByRole('button')).toHaveLength(1); + expect(target).toBe(screen.getByTestId('card')); + expect(target).toHaveProp('hitSlop', hitSlop); + expect(target).toHaveProp('focusable', true); + + await fireEvent(target, 'press', events.press); + await fireEvent(target, 'longPress', events.longPress); + await fireEvent(target, 'pressIn', events.pressIn); + await fireEvent(target, 'pressOut', events.pressOut); + await fireEvent(target, 'focus', events.focus); + await fireEvent(target, 'blur', events.blur); + await fireEvent(target, 'hoverIn', events.hoverIn); + await fireEvent(target, 'hoverOut', events.hoverOut); + + expect(onPress).toHaveBeenCalledWith(events.press); + expect(onLongPress).toHaveBeenCalledWith(events.longPress); + expect(onPressIn).toHaveBeenCalledWith(events.pressIn); + expect(onPressOut).toHaveBeenCalledWith(events.pressOut); + expect(onFocus).toHaveBeenCalledWith(events.focus); + expect(onBlur).toHaveBeenCalledWith(events.blur); + expect(onHoverIn).toHaveBeenCalledWith(events.hoverIn); + expect(onHoverOut).toHaveBeenCalledWith(events.hoverOut); + }); + + it('routes whole-Card accessibility semantics and callbacks to its target', async () => { + const onAccessibilityAction = jest.fn(); + const onAccessibilityEscape = jest.fn(); + const onAccessibilityTap = jest.fn(); + const onMagicTap = jest.fn(); + const accessibilityActionEvent = { + nativeEvent: { actionName: 'activate' }, + }; + await render( + {}} + role="link" + accessibilityLabel="Open product" + accessibilityHint="Shows product details" + accessibilityState={{ selected: true }} + accessibilityValue={{ text: 'In stock' }} + accessibilityActions={[{ name: 'activate', label: 'Open product' }]} + onAccessibilityAction={onAccessibilityAction} + onAccessibilityEscape={onAccessibilityEscape} + onAccessibilityTap={onAccessibilityTap} + onMagicTap={onMagicTap} + /> + ); + + const target = screen.getByRole('link', { name: 'Open product' }); + const shell = screen.getByTestId('product-card-container'); + + expect(target).toBe(screen.getByTestId('product-card')); + expect(target).toHaveProp('accessibilityHint', 'Shows product details'); + expect(target).toHaveProp( + 'accessibilityState', + expect.objectContaining({ selected: true }) + ); + expect(target).toHaveAccessibilityValue({ text: 'In stock' }); + expect(target).toHaveProp('accessibilityActions', [ + { name: 'activate', label: 'Open product' }, + ]); + expect(shell).not.toHaveProp('accessibilityLabel'); + expect(shell).not.toHaveProp('accessibilityActions'); + + await fireEvent(target, 'accessibilityAction', accessibilityActionEvent); + await fireEvent(target, 'accessibilityEscape'); + await fireEvent(target, 'accessibilityTap'); + await fireEvent(target, 'magicTap'); + + expect(onAccessibilityAction).toHaveBeenCalledWith( + accessibilityActionEvent + ); + expect(onAccessibilityEscape).toHaveBeenCalledTimes(1); + expect(onAccessibilityTap).toHaveBeenCalledTimes(1); + expect(onMagicTap).toHaveBeenCalledTimes(1); + }); + + it('targets documented shell, visual, and shaped interaction nodes', async () => { + const shellRef = React.createRef>(); + const touchableRef = React.createRef>(); + const shape = { + borderTopLeftRadius: 4, + borderTopRightRadius: 8, + borderBottomRightRadius: 16, + borderBottomLeftRadius: 20, + }; + await render( + {}} + /> + ); + + const interaction = screen.getByTestId('product-card'); + const shell = screen.getByTestId('product-card-container'); + const visual = screen.getByTestId('product-card-visual'); + + expect(interaction).toHaveStyle(shape); + expect(visual).toHaveStyle({ overflow: 'hidden', ...shape }); + expect(shell).toBeOnTheScreen(); + expect(shellRef.current).not.toBeNull(); + expect(touchableRef.current).not.toBeNull(); + expect(touchableRef.current).not.toBe(shellRef.current); + }); + + it('warns once when whole-Card interaction is combined with populated actions', async () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + const { rerender } = await render( + {}} actions={null} /> + ); + + expect(warn).not.toHaveBeenCalled(); + + await rerender( + {}} + actions={ + + + + } + /> + ); + await rerender( + {}} + actions={ + + + + } + /> + ); + + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + 'An actionable Card cannot contain actions. Remove the Card interaction handlers or move the independent actions outside the Card.' + ); + }); + + it('does not warn about Card actions in production', async () => { + const environment = process.env.NODE_ENV; + process.env.NODE_ENV = 'production'; + const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + + try { + await render( + {}} + actions={ + + + + } + /> + ); + + expect(warn).not.toHaveBeenCalled(); + } finally { + process.env.NODE_ENV = environment; + } + }); + it('renders the convenience header inputs', async () => { await render( { expect(screen.getByText('Content').parent).toHaveStyle(styles.contentStyle); }); - it('does render a disabled accessibility state', async () => { - await render( {}} disabled />); + it('exposes disabled semantics and suppresses every activation callback', async () => { + const onAccessibilityAction = jest.fn(); + const callbacks = { + onPress: jest.fn(), + onLongPress: jest.fn(), + onPressIn: jest.fn(), + onPressOut: jest.fn(), + onFocus: jest.fn(), + onBlur: jest.fn(), + onHoverIn: jest.fn(), + onHoverOut: jest.fn(), + onAccessibilityEscape: jest.fn(), + onAccessibilityTap: jest.fn(), + onMagicTap: jest.fn(), + }; + await render( + + ); + + const target = screen.getByTestId('card'); + + expect(target).toBeDisabled(); + expect(target).toHaveProp( + 'accessibilityState', + expect.objectContaining({ disabled: true }) + ); + expect(target).not.toHaveProp('accessibilityActions'); + expect(target).toHaveProp('focusable', false); + expect(target).toHaveProp('tabIndex', -1); + + await userEvent.press(target); + await userEvent.longPress(target); + await fireEvent(target, 'focus'); + await fireEvent(target, 'blur'); + await fireEvent(target, 'hoverIn'); + await fireEvent(target, 'hoverOut'); + await fireEvent(target, 'accessibilityAction', { + nativeEvent: { actionName: 'activate' }, + }); + await fireEvent(target, 'accessibilityEscape'); + await fireEvent(target, 'accessibilityTap'); + await fireEvent(target, 'magicTap'); + + Object.values(callbacks).forEach((callback) => { + expect(callback).not.toHaveBeenCalled(); + }); + expect(onAccessibilityAction).not.toHaveBeenCalled(); + }); + + it('exposes disabled state on an explicitly semantic neutral Card', async () => { + await render(); + + expect(screen.getByRole('summary')).toBeDisabled(); + }); + + it.each([ + { name: 'aria-disabled', props: { 'aria-disabled': true } }, + { + name: 'accessibilityState.disabled', + props: { accessibilityState: { disabled: true } }, + }, + ] as const)('honors $name as a disabled Card state', async ({ props }) => { + const onPress = jest.fn(); + await render(); + + const target = screen.getByTestId('card'); - expect(screen.getByTestId('card')).toBeDisabled(); + expect(target).toBeDisabled(); + await userEvent.press(target); + expect(onPress).not.toHaveBeenCalled(); }); }); From 9939c319fb4c4dee70d1ed1e7daa68c1947152b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 4 Sep 2026 14:07:25 +0200 Subject: [PATCH 06/51] feat(card): add actionable state feedback --- src/components/Card/Card.tsx | 227 +++++++++++++++--- src/components/Surface.tsx | 85 ++++++- .../TouchableRipple.native.tsx | 2 + .../TouchableRipple/TouchableRipple.tsx | 11 +- src/components/__tests__/Card/Card.test.tsx | 199 ++++++++++++++- src/components/__tests__/Surface.test.tsx | 37 +++ 6 files changed, 522 insertions(+), 39 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 3fcf462c6f..8109b8967f 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { StyleSheet, View } from 'react-native'; +import { Platform, StyleSheet, View } from 'react-native'; import type { GestureResponderEvent, StyleProp, @@ -7,6 +7,12 @@ import type { ViewStyle, } from 'react-native'; +import Animated, { + useAnimatedStyle, + useDerivedValue, + useSharedValue, +} from 'react-native-reanimated'; + import CardActions from './CardActions'; import CardContent from './CardContent'; import CardCover from './CardCover'; @@ -14,8 +20,10 @@ import CardTitle from './CardTitle'; import type { Props as CardTitleProps } from './CardTitle'; import { resolveCardVisuals } from './tokens'; import { useInternalTheme } from '../../core/theming'; +import { tokens as systemTokens } from '../../theme/tokens'; import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; +import { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; @@ -374,12 +382,66 @@ const Card = ({ disabled: isDisabled, }); + const enabledVisuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + }); + const hoveredVisuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + hovered: true, + }); + const focusedVisuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + focused: true, + }); + const pressedVisuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + pressed: true, + }); + + const hovered = useSharedValue(false); + const focused = useSharedValue(false); + const pressed = useSharedValue(false); + const currentInteractiveVisuals = useDerivedValue(() => { + if (pressed.value) { + return pressedVisuals; + } + if (focused.value) { + return focusedVisuals; + } + if (hovered.value) { + return hoveredVisuals; + } + return enabledVisuals; + }); + const interactiveElevation = useDerivedValue(() => { + return currentInteractiveVisuals.value.elevation; + }); + const stateLayerAnimatedStyle = useAnimatedStyle(() => ({ + opacity: currentInteractiveVisuals.value.stateLayerOpacity, + })); + const outlineAnimatedStyle = useAnimatedStyle(() => ({ + borderColor: currentInteractiveVisuals.value.outlineColor, + opacity: currentInteractiveVisuals.value.outlineOpacity, + })); + const focusIndicatorAnimatedStyle = useAnimatedStyle(() => ({ + opacity: focused.value ? 1 : 0, + })); + const hasPassedTouchHandler = hasTouchHandler({ onPress, onLongPress, onPressIn, onPressOut, }); + const isInteractive = hasPassedTouchHandler && !isDisabled; const hasWarnedAboutActions = React.useRef(false); const hasActions = actions !== null && actions !== undefined && actions !== false; @@ -398,22 +460,35 @@ const Card = ({ } }, [hasActions, hasPassedTouchHandler]); - const shapeStyle = { - borderRadius: borderRadius ?? visuals.shape, - borderBottomEndRadius, - borderBottomLeftRadius, - borderBottomRightRadius, - borderBottomStartRadius, - borderEndEndRadius, - borderEndStartRadius, - borderStartEndRadius, - borderStartStartRadius, - borderTopEndRadius, - borderTopLeftRadius, - borderTopRightRadius, - borderTopStartRadius, - borderCurve, - }; + const shapeStyle = Object.fromEntries( + Object.entries({ + borderRadius: borderRadius ?? visuals.shape, + borderBottomEndRadius, + borderBottomLeftRadius, + borderBottomRightRadius, + borderBottomStartRadius, + borderEndEndRadius, + borderEndStartRadius, + borderStartEndRadius, + borderStartStartRadius, + borderTopEndRadius, + borderTopLeftRadius, + borderTopRightRadius, + borderTopStartRadius, + borderCurve, + }).filter(([, value]) => value !== undefined) + ); + const focusIndicatorInset = + systemTokens.md.sys.state.focusIndicator.outerOffset + + systemTokens.md.sys.state.focusIndicator.thickness; + const focusIndicatorShapeStyle = Object.fromEntries( + Object.entries(shapeStyle).map(([property, value]) => [ + property, + property !== 'borderCurve' && typeof value === 'number' + ? value + focusIndicatorInset + : value, + ]) + ); const hasConvenienceHeader = title != null || subtitle != null || leading != null || trailing != null; @@ -492,6 +567,53 @@ const Card = ({ ...accessibilityProps, 'aria-disabled': isDisabled || ariaDisabled, }; + const handlePressIn = React.useCallback( + (event: GestureResponderEvent) => { + pressed.value = true; + onPressIn?.(event); + }, + [onPressIn, pressed] + ); + const handlePressOut = React.useCallback( + (event: GestureResponderEvent) => { + pressed.value = false; + onPressOut?.(event); + }, + [onPressOut, pressed] + ); + const handleFocus: NonNullable = + React.useCallback( + (event) => { + focused.value = isKeyboardFocusEvent(event); + onFocus?.(event); + }, + [focused, onFocus] + ); + const handleBlur: NonNullable = + React.useCallback( + (event) => { + focused.value = false; + pressed.value = false; + onBlur?.(event); + }, + [focused, onBlur, pressed] + ); + const handleHoverIn: NonNullable = + React.useCallback( + (event) => { + hovered.value = true; + onHoverIn?.(event); + }, + [hovered, onHoverIn] + ); + const handleHoverOut: NonNullable = + React.useCallback( + (event) => { + hovered.value = false; + onHoverOut?.(event); + }, + [hovered, onHoverOut] + ); return ( - {hasPassedTouchHandler ? ( @@ -550,7 +674,11 @@ const Card = ({ ref={touchableRef} testID={testID} borderless={false} - style={shapeStyle} + hoverColor="transparent" + style={[ + shapeStyle, + Platform.OS === 'web' ? webNoOutline : undefined, + ]} theme={theme} focusable={isDisabled ? false : focusable} tabIndex={isDisabled ? -1 : tabIndex} @@ -560,12 +688,12 @@ const Card = ({ delayLongPress={delayLongPress} onLongPress={isDisabled ? undefined : onLongPress} onPress={isDisabled ? undefined : onPress} - onPressIn={isDisabled ? undefined : onPressIn} - onPressOut={isDisabled ? undefined : onPressOut} - onFocus={isDisabled ? undefined : onFocus} - onBlur={isDisabled ? undefined : onBlur} - onHoverIn={isDisabled ? undefined : onHoverIn} - onHoverOut={isDisabled ? undefined : onHoverOut} + onPressIn={isDisabled ? undefined : handlePressIn} + onPressOut={isDisabled ? undefined : handlePressOut} + onFocus={isDisabled ? undefined : handleFocus} + onBlur={isDisabled ? undefined : handleBlur} + onHoverIn={isDisabled ? undefined : handleHoverIn} + onHoverOut={isDisabled ? undefined : handleHoverOut} > {content} @@ -573,21 +701,42 @@ const Card = ({ content )} {visuals.outlineWidth > 0 ? ( - ) : null} + {hasPassedTouchHandler ? ( + + ) : null} ); }; @@ -612,6 +761,18 @@ const styles = StyleSheet.create({ flexShrink: 1, position: 'relative', }, + focusIndicator: { + position: 'absolute', + pointerEvents: 'none', + }, + hidden: { + opacity: 0, + }, }); +// React Native Web otherwise draws its browser-default outline in addition to +// the Material focus indicator. +// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion +const webNoOutline = { outline: 'none' } as unknown as ViewStyle; + export default Card; diff --git a/src/components/Surface.tsx b/src/components/Surface.tsx index d1a4e07e99..00b7735e94 100644 --- a/src/components/Surface.tsx +++ b/src/components/Surface.tsx @@ -5,6 +5,7 @@ import type { ColorValue, StyleProp, ViewProps, ViewStyle } from 'react-native'; import Animated, { cubicBezier, isSharedValue, + type SharedValue, type AnimatedStyle, type CSSTransitionTimingFunction, useAnimatedStyle, @@ -131,8 +132,9 @@ export type Props = Omit & * * Note: In version 2 the `elevation` prop was accepted via `style` prop i.e. `style={{ elevation: 4 }}`. * It's no longer supported with theme version 3 and you should use `elevation` property instead. + * A Reanimated shared value can drive elevation without a React render. */ - elevation?: Elevation; + elevation?: Elevation | SharedValue; /** * @supported Available in v5.x with theme version 3 * Mode of the Surface. @@ -155,6 +157,12 @@ export type Props = Omit & ref?: React.Ref>; }; +type StaticSurfaceProps = Omit & { + elevation?: Elevation; + animatedSurfaceStyle?: AnimatedStyle; + animatedAmbientStyle?: AnimatedStyle; +}; + /** * Surface is a basic container that can give depth to an element with elevation shadow. * @@ -186,7 +194,7 @@ export type Props = Omit & * }); * ``` */ -const Surface = ({ +const StaticSurface = ({ elevation = 1, children, theme: overriddenTheme, @@ -211,9 +219,11 @@ const Surface = ({ transitionDuration: customTransitionDuration, shapeTransitionDuration, shapeTransitionTimingFunction, + animatedSurfaceStyle, + animatedAmbientStyle, ref, ...rest -}: Props) => { +}: StaticSurfaceProps) => { const theme = useInternalTheme(overriddenTheme); const reduceMotion = useReduceMotion(); @@ -316,6 +326,7 @@ const Surface = ({ visualStyle, ...radiusStyles, isElevated ? elevationShadow : null, + ...(animatedSurfaceStyle ? [animatedSurfaceStyle] : []), ]} > {children} @@ -343,6 +354,7 @@ const Surface = ({ visualStyle, ...radiusStyles, isElevated && { elevation: elevationAndroid }, + ...(animatedSurfaceStyle ? [animatedSurfaceStyle] : []), ]} > {children} @@ -370,6 +382,7 @@ const Surface = ({ visualStyle, ...radiusStyles, isElevated && spotShadow, + ...(animatedSurfaceStyle ? [animatedSurfaceStyle] : []), ]} testID={testID} > @@ -384,6 +397,7 @@ const Surface = ({ shadowVisualStyle, ...radiusStyles, ambientShadow, + ...(animatedAmbientStyle ? [animatedAmbientStyle] : []), ]} /> ) : null} @@ -392,6 +406,71 @@ const Surface = ({ ); }; +const AnimatedElevationSurface = ({ + elevation, + theme: themeOverrides, + backgroundColor: customBackgroundColor, + mode = 'elevated', + ...rest +}: Props & { elevation: SharedValue }) => { + const theme = useInternalTheme(themeOverrides); + const elevationShadows = React.useMemo( + () => + ([0, 1, 2, 3, 4, 5] as const).map((level) => + shadow(level, theme.colors.shadow) + ), + [theme.colors.shadow] + ); + const animatedSurfaceStyle = useAnimatedStyle(() => { + const level = elevation.value; + const backgroundStyle = + customBackgroundColor == null + ? { backgroundColor: theme.colors.elevation?.[`level${level}`] } + : {}; + + if (mode === 'flat') { + return backgroundStyle; + } + if (Platform.OS === 'android') { + return { + ...backgroundStyle, + elevation: androidElevationLevels[level], + }; + } + + return { ...backgroundStyle, ...elevationShadows[level][0] }; + }, [customBackgroundColor, elevation, elevationShadows, mode, theme.colors]); + const animatedAmbientStyle = useAnimatedStyle(() => { + if (mode === 'flat') { + return {}; + } + + return elevationShadows[elevation.value][1] ?? {}; + }, [elevation, elevationShadows, mode]); + + return ( + + ); +}; + +const Surface = (props: Props) => { + const elevation = props.elevation ?? 1; + + return isSharedValue(elevation) ? ( + + ) : ( + + ); +}; + const useSurfaceVisualStyle = ({ borderRadius, borderBottomEndRadius, diff --git a/src/components/TouchableRipple/TouchableRipple.native.tsx b/src/components/TouchableRipple/TouchableRipple.native.tsx index 4325f13d37..9b0c7d1252 100644 --- a/src/components/TouchableRipple/TouchableRipple.native.tsx +++ b/src/components/TouchableRipple/TouchableRipple.native.tsx @@ -51,6 +51,7 @@ export type Props = PressableProps & { onPressOut?: (e: GestureResponderEvent) => void; rippleColor?: ColorValue; underlayColor?: string; + hoverColor?: ColorValue; ref?: React.Ref>; theme?: ThemeProp; }; @@ -62,6 +63,7 @@ const TouchableRipple = ({ disabled: disabledProp, rippleColor, underlayColor, + hoverColor: _hoverColor, children, theme: themeOverrides, focusRing = 'outward', diff --git a/src/components/TouchableRipple/TouchableRipple.tsx b/src/components/TouchableRipple/TouchableRipple.tsx index f1bb352835..5abfdfbd54 100644 --- a/src/components/TouchableRipple/TouchableRipple.tsx +++ b/src/components/TouchableRipple/TouchableRipple.tsx @@ -88,6 +88,11 @@ export type Props = PressableProps & { * Color of the underlay for the highlight effect (Android < 5.0 and iOS). */ underlayColor?: string; + /** + * Color of the hover feedback on web. Set this to `transparent` when the + * caller renders its own state layer. + */ + hoverColor?: ColorValue; /** * Content of the `TouchableRipple`: any React node, including several * children, fragments and `null`. Can be a function that receives the @@ -141,6 +146,7 @@ const TouchableRipple = ({ disabled: disabledProp, rippleColor, underlayColor: _underlayColor, + hoverColor: customHoverColor, children, theme: themeOverrides, hitSlop, @@ -156,9 +162,10 @@ const TouchableRipple = ({ // Web-only style. PlatformColor doesn't exist on web, so the calculated // ripple color is effectively always a string here. const hoverColor = - typeof calculatedRippleColor === 'string' + customHoverColor ?? + (typeof calculatedRippleColor === 'string' ? color(calculatedRippleColor).fade(0.5).rgb().string() - : calculatedRippleColor; + : calculatedRippleColor); const { rippleEffectEnabled } = React.useContext(SettingsContext); const { onPress, onLongPress, onPressIn, onPressOut } = rest; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 2e8eccd00f..12ccec5fd2 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -3,6 +3,8 @@ import { Platform, StyleSheet, Text, View } from 'react-native'; import type { StyleProp, ViewStyle } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; +import { act } from '@testing-library/react-native'; +import { getAnimatedStyle } from 'react-native-reanimated'; import { getTheme } from '../../../core/theming'; import { fireEvent, render, screen, userEvent } from '../../../test-utils'; @@ -18,6 +20,15 @@ const styles = StyleSheet.create({ }, }); +const expectAnimatedStyle = ( + testID: string, + expectedStyle: Record +) => { + expect(getAnimatedStyle(screen.getByTestId(testID))).toEqual( + expect.objectContaining(expectedStyle) + ); +}; + afterEach(() => { jest.restoreAllMocks(); }); @@ -385,7 +396,7 @@ describe('Card', () => { expect(onMagicTap).toHaveBeenCalledTimes(1); }); - it('targets documented shell, visual, and shaped interaction nodes', async () => { + it('keeps the ripple, visual layers, and focus indicator on the Card shape', async () => { const shellRef = React.createRef>(); const touchableRef = React.createRef>(); const shape = { @@ -410,12 +421,198 @@ describe('Card', () => { expect(interaction).toHaveStyle(shape); expect(visual).toHaveStyle({ overflow: 'hidden', ...shape }); + expect(interaction.parent).toBe(visual); + expect(screen.getByTestId('product-card-focus-indicator')).toHaveStyle({ + top: -5, + right: -5, + bottom: -5, + left: -5, + borderColor: getTheme().colors.secondary, + borderWidth: 3, + borderTopLeftRadius: 9, + borderTopRightRadius: 13, + borderBottomRightRadius: 21, + borderBottomLeftRadius: 25, + }); expect(shell).toBeOnTheScreen(); expect(shellRef.current).not.toBeNull(); expect(touchableRef.current).not.toBeNull(); expect(touchableRef.current).not.toBe(shellRef.current); }); + it.each([ + { variant: 'filled' as const, hoveredElevation: 1 }, + { variant: 'elevated' as const, hoveredElevation: 2 }, + { variant: 'outlined' as const, hoveredElevation: 1 }, + ])( + 'shows and clears the $variant hover feedback', + async ({ variant, hoveredElevation }) => { + expect.hasAssertions(); + jest.replaceProperty(Platform, 'OS', 'android'); + const card = + variant === 'elevated' ? ( + {}} /> + ) : variant === 'outlined' ? ( + {}} /> + ) : ( + {}} /> + ); + await render(card); + + const target = screen.getByTestId('card'); + + await fireEvent(target, 'hoverIn'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { opacity: 0.08 }); + expectAnimatedStyle('card-container', { + elevation: hoveredElevation === 1 ? 1 : 3, + }); + + await fireEvent(target, 'hoverOut'); + + expectAnimatedStyle('card-state-layer', { opacity: 0 }); + } + ); + + it.each([ + { variant: 'filled' as const, pressedElevation: 0 }, + { variant: 'elevated' as const, pressedElevation: 1 }, + { variant: 'outlined' as const, pressedElevation: 0 }, + ])( + 'shows and clears the $variant pressed feedback', + async ({ variant, pressedElevation }) => { + expect.hasAssertions(); + jest.replaceProperty(Platform, 'OS', 'android'); + const card = + variant === 'elevated' ? ( + {}} /> + ) : variant === 'outlined' ? ( + {}} /> + ) : ( + {}} /> + ); + await render(card); + + const target = screen.getByTestId('card'); + + await fireEvent(target, 'pressIn'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { opacity: 0.1 }); + expectAnimatedStyle('card-container', { elevation: pressedElevation }); + + await fireEvent(target, 'pressOut'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { opacity: 0 }); + } + ); + + it('shows focus feedback only for keyboard-visible focus and clears it on blur', async () => { + expect.hasAssertions(); + jest.replaceProperty(Platform, 'OS', 'web'); + const theme = getTheme(); + await render( {}} theme={theme} />); + const target = screen.getByTestId('card'); + const pointerTarget = { matches: () => false }; + const keyboardTarget = { matches: () => true }; + + await fireEvent(target, 'focus', { currentTarget: pointerTarget }); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); + expectAnimatedStyle('card-state-layer', { opacity: 0 }); + + await fireEvent(target, 'focus', { currentTarget: keyboardTarget }); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-focus-indicator', { opacity: 1 }); + expectAnimatedStyle('card-state-layer', { opacity: 0.1 }); + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.onSurface, + opacity: 1, + }); + + await fireEvent(target, 'blur'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); + expectAnimatedStyle('card-state-layer', { opacity: 0 }); + }); + + it('uses pressed, focused, then hovered precedence and settles at the latest state', async () => { + expect.hasAssertions(); + const theme = getTheme(); + await render( {}} theme={theme} />); + const target = screen.getByTestId('card'); + + await fireEvent(target, 'hoverIn'); + await fireEvent(target, 'focus'); + await fireEvent(target, 'pressIn'); + await fireEvent(target, 'pressOut'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.onSurface, + opacity: 1, + }); + + await fireEvent(target, 'blur'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { opacity: 0.08 }); + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.outlineVariant, + opacity: 1, + }); + + await fireEvent(target, 'hoverOut'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { opacity: 0 }); + }); + + it('does not rerender stable memoized slot content for transient feedback', async () => { + const renderCount = jest.fn(); + const StableContent = React.memo(() => { + renderCount(); + return Stable content; + }); + await render( {}} content={} />); + const target = screen.getByTestId('card'); + + await fireEvent(target, 'hoverIn'); + await fireEvent(target, 'focus'); + await fireEvent(target, 'pressIn'); + await fireEvent(target, 'pressOut'); + await fireEvent(target, 'blur'); + await fireEvent(target, 'hoverOut'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expect(renderCount).toHaveBeenCalledTimes(1); + }); + it('warns once when whole-Card interaction is combined with populated actions', async () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); const { rerender } = await render( diff --git a/src/components/__tests__/Surface.test.tsx b/src/components/__tests__/Surface.test.tsx index cb568ad767..8416d1d34e 100644 --- a/src/components/__tests__/Surface.test.tsx +++ b/src/components/__tests__/Surface.test.tsx @@ -23,6 +23,7 @@ import { import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; import { LightTheme } from '../../theme/schemes'; +import type { Elevation } from '../../theme/types'; import Surface from '../Surface'; const SPOT_SHADOW_OPACITY = 0.19; @@ -70,6 +71,24 @@ const AnimatedVisualSurface = () => { ); }; +const SharedElevationSurface = () => { + const elevation = useSharedValue(0); + + return ( + <> + { + elevation.value = 2; + }} + /> + + {null} + + + ); +}; + afterEach(() => { jest.restoreAllMocks(); }); @@ -229,6 +248,24 @@ describe('Surface', () => { }); }); + it('updates shared elevation without rerendering the Surface', async () => { + await render(); + const surface = screen.getByTestId('shared-elevation-surface'); + + expect(getAnimatedStyle(surface)).toMatchObject({ + backgroundColor: LightTheme.colors.elevation.level0, + elevation: 0, + }); + + await userEvent.press(screen.getByTestId('raise-surface')); + await jest.runAllTimersAsync(); + + expect(getAnimatedStyle(surface)).toMatchObject({ + backgroundColor: LightTheme.colors.elevation.level2, + elevation: 3, + }); + }); + it('does not transition a PlatformColor background', async () => { await render( Date: Fri, 4 Sep 2026 14:32:48 +0200 Subject: [PATCH 07/51] feat(card): complete state and motion behavior --- src/components/Card/Card.tsx | 127 +++++-- src/components/__tests__/Card/Card.test.tsx | 356 +++++++++++++++++++- 2 files changed, 447 insertions(+), 36 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 8109b8967f..7992ec31f8 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -8,6 +8,7 @@ import type { } from 'react-native'; import Animated, { + cubicBezier, useAnimatedStyle, useDerivedValue, useSharedValue, @@ -20,6 +21,7 @@ import CardTitle from './CardTitle'; import type { Props as CardTitleProps } from './CardTitle'; import { resolveCardVisuals } from './tokens'; import { useInternalTheme } from '../../core/theming'; +import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import { tokens as systemTokens } from '../../theme/tokens'; import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; @@ -215,6 +217,11 @@ type CardBaseProps = Omit & * If true, disable all interactions for this component. */ disabled?: boolean; + /** + * Whether to show the Card's controlled Material dragged presentation. + * Gesture recognition and drag lifecycle remain the consumer's responsibility. + */ + dragged?: boolean; /** * Style of card's inner content. */ @@ -308,6 +315,7 @@ const Card = ({ testID = 'card', accessible, disabled, + dragged = false, accessibilityActions, role, accessibilityRole, @@ -370,6 +378,7 @@ const Card = ({ ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); + const reduceMotion = useReduceMotion(); const isDisabled = Boolean( disabled || ariaDisabled || accessibilityState?.disabled @@ -380,6 +389,7 @@ const Card = ({ variant: cardVariant, elevation: customElevation, disabled: isDisabled, + dragged, }); const enabledVisuals = resolveCardVisuals({ @@ -405,11 +415,30 @@ const Card = ({ elevation: customElevation, pressed: true, }); - + const draggedVisuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + dragged: true, + }); + const disabledVisuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + disabled: true, + }); + const disabledState = useSharedValue(isDisabled); + const draggedState = useSharedValue(dragged); const hovered = useSharedValue(false); const focused = useSharedValue(false); const pressed = useSharedValue(false); const currentInteractiveVisuals = useDerivedValue(() => { + if (disabledState.value) { + return disabledVisuals; + } + if (draggedState.value) { + return draggedVisuals; + } if (pressed.value) { return pressedVisuals; } @@ -420,20 +449,74 @@ const Card = ({ return hoveredVisuals; } return enabledVisuals; - }); + }, [ + disabledState, + disabledVisuals, + draggedState, + draggedVisuals, + enabledVisuals, + focusedVisuals, + hoveredVisuals, + pressedVisuals, + ]); const interactiveElevation = useDerivedValue(() => { return currentInteractiveVisuals.value.elevation; }); - const stateLayerAnimatedStyle = useAnimatedStyle(() => ({ - opacity: currentInteractiveVisuals.value.stateLayerOpacity, - })); - const outlineAnimatedStyle = useAnimatedStyle(() => ({ - borderColor: currentInteractiveVisuals.value.outlineColor, - opacity: currentInteractiveVisuals.value.outlineOpacity, - })); - const focusIndicatorAnimatedStyle = useAnimatedStyle(() => ({ - opacity: focused.value ? 1 : 0, - })); + const transitionDuration = reduceMotion + ? 0 + : theme.motion.duration.short3 * theme.animation.scale; + const transitionTimingFunction = cubicBezier(...theme.motion.easing.standard); + const stateLayerAnimatedStyle = useAnimatedStyle( + () => ({ + opacity: currentInteractiveVisuals.value.stateLayerOpacity, + transitionDuration, + transitionProperty: ['opacity'], + transitionTimingFunction, + }), + [currentInteractiveVisuals, transitionDuration, transitionTimingFunction] + ); + const outlineAnimatedStyle = useAnimatedStyle(() => { + const outlineColor = currentInteractiveVisuals.value.outlineColor; + + return { + borderColor: outlineColor, + opacity: currentInteractiveVisuals.value.outlineOpacity, + transitionDuration, + transitionProperty: + typeof outlineColor === 'string' + ? ['borderColor', 'opacity'] + : ['opacity'], + transitionTimingFunction, + }; + }, [currentInteractiveVisuals, transitionDuration, transitionTimingFunction]); + const focusIndicatorAnimatedStyle = useAnimatedStyle( + () => ({ + opacity: disabledState.value ? 0 : focused.value ? 1 : 0, + transitionDuration, + transitionProperty: ['opacity'], + transitionTimingFunction, + }), + [disabledState, transitionDuration, transitionTimingFunction] + ); + + React.useEffect(() => { + disabledState.value = isDisabled; + draggedState.value = dragged; + + if (isDisabled) { + hovered.value = false; + focused.value = false; + pressed.value = false; + } + }, [ + disabledState, + dragged, + draggedState, + focused, + hovered, + isDisabled, + pressed, + ]); const hasPassedTouchHandler = hasTouchHandler({ onPress, @@ -441,7 +524,6 @@ const Card = ({ onPressIn, onPressOut, }); - const isInteractive = hasPassedTouchHandler && !isDisabled; const hasWarnedAboutActions = React.useRef(false); const hasActions = actions !== null && actions !== undefined && actions !== false; @@ -622,7 +704,8 @@ const Card = ({ backgroundColor="transparent" style={style} theme={theme} - elevation={isInteractive ? interactiveElevation : visuals.elevation} + elevation={interactiveElevation} + transitionDuration={transitionDuration} testID={`${testID}-container`} {...(!hasPassedTouchHandler && neutralAccessibilityProps)} onFocus={!hasPassedTouchHandler ? onFocus : undefined} @@ -663,9 +746,7 @@ const Card = ({ { backgroundColor: visuals.stateLayerColor, }, - isInteractive - ? stateLayerAnimatedStyle - : { opacity: visuals.stateLayerOpacity }, + stateLayerAnimatedStyle, ]} /> {hasPassedTouchHandler ? ( @@ -708,12 +789,7 @@ const Card = ({ StyleSheet.absoluteFill, shapeStyle, { borderWidth: visuals.outlineWidth }, - isInteractive - ? outlineAnimatedStyle - : { - borderColor: visuals.outlineColor, - opacity: visuals.outlineOpacity, - }, + outlineAnimatedStyle, ]} /> ) : null} @@ -733,7 +809,7 @@ const Card = ({ borderWidth: systemTokens.md.sys.state.focusIndicator.thickness, }, focusIndicatorShapeStyle, - isInteractive ? focusIndicatorAnimatedStyle : styles.hidden, + focusIndicatorAnimatedStyle, ]} /> ) : null} @@ -765,9 +841,6 @@ const styles = StyleSheet.create({ position: 'absolute', pointerEvents: 'none', }, - hidden: { - opacity: 0, - }, }); // React Native Web otherwise draws its browser-default outline in addition to diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 12ccec5fd2..8942b916dc 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -4,12 +4,16 @@ import type { StyleProp, ViewStyle } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; import { act } from '@testing-library/react-native'; +import * as Reanimated from 'react-native-reanimated'; import { getAnimatedStyle } from 'react-native-reanimated'; -import { getTheme } from '../../../core/theming'; import { fireEvent, render, screen, userEvent } from '../../../test-utils'; +import { ReduceMotionContext } from '../../../theme/accessibility/ReduceMotionContext'; +import { DarkTheme, LightTheme } from '../../../theme/schemes'; +import { tokens as systemTokens } from '../../../theme/tokens'; import Button from '../../Button/Button'; import Card from '../../Card/Card'; +import type { Props as CardProps } from '../../Card/Card'; const styles = StyleSheet.create({ contentStyle: { @@ -29,6 +33,28 @@ const expectAnimatedStyle = ( ); }; +const getVariantCard = ( + variant: 'filled' | 'elevated' | 'outlined', + props: Pick = {} +) => { + if (variant === 'elevated') { + return ; + } + if (variant === 'outlined') { + return ; + } + return ; +}; + +const expectOutlineStyle = (expectedStyle?: Record) => { + const outline = screen.queryByTestId('card-outline'); + + expect(Boolean(outline)).toBe(Boolean(expectedStyle)); + expect(outline ? getAnimatedStyle(outline) : {}).toEqual( + expect.objectContaining(expectedStyle ?? {}) + ); +}; + afterEach(() => { jest.restoreAllMocks(); }); @@ -48,7 +74,7 @@ describe('Card', () => { 'renders the enabled $variant appearance in light and dark themes', async ({ variant, colorRole }) => { for (const isDark of [false, true] as const) { - const theme = getTheme(isDark); + const theme = isDark ? DarkTheme : LightTheme; const card = variant === 'elevated' ? ( @@ -70,7 +96,7 @@ describe('Card', () => { it('renders the enabled outlined role in light and dark themes', async () => { for (const isDark of [false, true] as const) { - const theme = getTheme(isDark); + const theme = isDark ? DarkTheme : LightTheme; const { unmount } = await render( ); @@ -198,7 +224,7 @@ describe('Card', () => { ); const expectedShape = { - borderRadius: getTheme().shapes.corner.medium, + borderRadius: LightTheme.shapes.corner.medium, borderTopLeftRadius: 4, borderTopRightRadius: 8, borderBottomRightRadius: 16, @@ -251,7 +277,7 @@ describe('Card', () => { await render(); expect(screen.getByTestId('card-visual')).toHaveStyle({ - backgroundColor: getTheme().colors.surfaceContainerHighest, + backgroundColor: LightTheme.colors.surfaceContainerHighest, }); expect(screen.getByTestId('card')).not.toHaveProp('focusable'); expect(screen.getByTestId('card-container')).not.toHaveProp('focusable'); @@ -427,7 +453,7 @@ describe('Card', () => { right: -5, bottom: -5, left: -5, - borderColor: getTheme().colors.secondary, + borderColor: LightTheme.colors.secondary, borderWidth: 3, borderTopLeftRadius: 9, borderTopRightRadius: 13, @@ -515,10 +541,237 @@ describe('Card', () => { } ); + it.each([ + { + variant: 'filled' as const, + containerRole: 'surfaceContainerHighest' as const, + draggedElevation: 3, + outlineRole: undefined, + }, + { + variant: 'elevated' as const, + containerRole: 'surfaceContainerLow' as const, + draggedElevation: 4, + outlineRole: undefined, + }, + { + variant: 'outlined' as const, + containerRole: 'surface' as const, + draggedElevation: 3, + outlineRole: 'outlineVariant' as const, + }, + ])( + 'renders the consumer-controlled $variant dragged presentation', + async ({ variant, containerRole, draggedElevation, outlineRole }) => { + jest.replaceProperty(Platform, 'OS', 'android'); + const theme = LightTheme; + const card = getVariantCard(variant, { dragged: true, theme }); + + await render(card); + + expect(screen.getByTestId('card-background')).toHaveStyle({ + backgroundColor: theme.colors[containerRole], + opacity: 1, + }); + expect(screen.getByTestId('card-state-layer')).toHaveStyle({ + backgroundColor: theme.colors.onSurface, + opacity: systemTokens.md.sys.state.opacity.dragged, + }); + expect(screen.getByTestId('card-container')).toHaveStyle({ + elevation: draggedElevation === 3 ? 6 : 8, + }); + + const expectedOutlineStyle = outlineRole + ? { + borderColor: theme.colors[outlineRole], + borderWidth: 1, + opacity: 1, + } + : undefined; + expectOutlineStyle(expectedOutlineStyle); + } + ); + + it.each([ + { + variant: 'filled' as const, + containerRole: 'surfaceVariant' as const, + containerOpacity: systemTokens.md.sys.state.opacity.disabled, + elevation: 0, + outlineRole: undefined, + outlineOpacity: undefined, + }, + { + variant: 'elevated' as const, + containerRole: 'surface' as const, + containerOpacity: systemTokens.md.sys.state.opacity.disabled, + elevation: 1, + outlineRole: undefined, + outlineOpacity: undefined, + }, + { + variant: 'outlined' as const, + containerRole: 'surface' as const, + containerOpacity: 1, + elevation: 0, + outlineRole: 'outline' as const, + outlineOpacity: 0.12, + }, + ])( + 'renders the Material disabled treatment for $variant Cards', + async ({ + variant, + containerRole, + containerOpacity, + elevation, + outlineRole, + outlineOpacity, + }) => { + jest.replaceProperty(Platform, 'OS', 'android'); + const theme = LightTheme; + const card = getVariantCard(variant, { + disabled: true, + onPress: () => {}, + theme, + }); + + await render(card); + + expect(screen.getByTestId('card-background')).toHaveStyle({ + backgroundColor: theme.colors[containerRole], + opacity: containerOpacity, + }); + expect(screen.getByTestId('card-state-layer')).toHaveStyle({ + opacity: 0, + }); + expect(screen.getByTestId('card-container')).toHaveStyle({ elevation }); + expect(screen.getByTestId('card-focus-indicator')).toHaveStyle({ + opacity: 0, + }); + + const expectedOutlineStyle = outlineRole + ? { + borderColor: theme.colors[outlineRole], + borderWidth: 1, + opacity: outlineOpacity, + } + : undefined; + expectOutlineStyle(expectedOutlineStyle); + } + ); + + it('resolves disabled and dragged before pressed, focused, and hovered visuals', async () => { + expect.hasAssertions(); + jest.replaceProperty(Platform, 'OS', 'android'); + const theme = LightTheme; + const { rerender } = await render( + {}} theme={theme} /> + ); + const target = screen.getByTestId('card'); + + await fireEvent(target, 'hoverIn'); + await fireEvent(target, 'focus'); + await fireEvent(target, 'pressIn'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { + opacity: systemTokens.md.sys.state.opacity.dragged, + }); + expectAnimatedStyle('card-container', { elevation: 6 }); + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.outlineVariant, + opacity: 1, + }); + expectAnimatedStyle('card-focus-indicator', { opacity: 1 }); + + await rerender( + {}} + theme={theme} + /> + ); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { opacity: 0 }); + expectAnimatedStyle('card-container', { elevation: 0 }); + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.outline, + opacity: 0.12, + }); + expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); + }); + + it('updates the controlled dragged presentation in both directions', async () => { + expect.hasAssertions(); + jest.replaceProperty(Platform, 'OS', 'android'); + const theme = LightTheme; + const props = { + variant: 'outlined' as const, + onPress: () => {}, + theme, + }; + const { rerender } = await render(); + + await rerender(); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { + opacity: systemTokens.md.sys.state.opacity.dragged, + }); + expectAnimatedStyle('card-container', { elevation: 6 }); + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.outlineVariant, + opacity: 1, + }); + + await rerender(); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { opacity: 0 }); + expectAnimatedStyle('card-container', { elevation: 0 }); + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.outlineVariant, + opacity: 1, + }); + }); + + it.each(['filled', 'elevated', 'outlined'] as const)( + 'renders keyboard focus feedback for the %s variant', + async (variant) => { + expect.hasAssertions(); + jest.replaceProperty(Platform, 'OS', 'web'); + const card = getVariantCard(variant, { onPress: () => {} }); + await render(card); + + await fireEvent(screen.getByTestId('card'), 'focus', { + currentTarget: { matches: () => true }, + }); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { + opacity: systemTokens.md.sys.state.opacity.focused, + }); + expectAnimatedStyle('card-focus-indicator', { opacity: 1 }); + } + ); + it('shows focus feedback only for keyboard-visible focus and clears it on blur', async () => { expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'web'); - const theme = getTheme(); + const theme = LightTheme; await render( {}} theme={theme} />); const target = screen.getByTestId('card'); const pointerTarget = { matches: () => false }; @@ -555,7 +808,7 @@ describe('Card', () => { it('uses pressed, focused, then hovered precedence and settles at the latest state', async () => { expect.hasAssertions(); - const theme = getTheme(); + const theme = LightTheme; await render( {}} theme={theme} />); const target = screen.getByTestId('card'); @@ -591,6 +844,91 @@ describe('Card', () => { expectAnimatedStyle('card-state-layer', { opacity: 0 }); }); + it('uses scaled theme motion duration and easing for visual transitions', async () => { + expect.hasAssertions(); + const easing = [0.1, 0.2, 0.3, 0.4] as const; + const theme = { + animation: { scale: 0.5 }, + motion: { + duration: { short3: 320 }, + easing: { standard: easing }, + }, + }; + const { rerender } = await render( + {}} theme={theme} /> + ); + + expectAnimatedStyle('card-state-layer', { + transitionDuration: 160, + transitionProperty: ['opacity'], + transitionTimingFunction: Reanimated.cubicBezier(...easing), + }); + expectAnimatedStyle('card-container', { transitionDuration: 160 }); + + await rerender( {}} theme={theme} />); + + expectAnimatedStyle('card-state-layer', { transitionDuration: 160 }); + expectAnimatedStyle('card-container', { transitionDuration: 160 }); + }); + + it('settles transitions immediately when reduced motion is enabled', async () => { + expect.hasAssertions(); + await render( + + {}} /> + + ); + + await fireEvent(screen.getByTestId('card'), 'pressIn'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { + opacity: systemTokens.md.sys.state.opacity.pressed, + transitionDuration: 0, + }); + expectAnimatedStyle('card-container', { transitionDuration: 0 }); + expectAnimatedStyle('card-outline', { transitionDuration: 0 }); + expectAnimatedStyle('card-focus-indicator', { transitionDuration: 0 }); + }); + + it('settles rapid changes at the latest complete visual state', async () => { + expect.hasAssertions(); + jest.replaceProperty(Platform, 'OS', 'android'); + const theme = LightTheme; + const props = { + variant: 'outlined' as const, + onPress: () => {}, + theme, + }; + const { rerender } = await render(); + const target = screen.getByTestId('card'); + + await fireEvent(target, 'hoverIn'); + await fireEvent(target, 'focus'); + await fireEvent(target, 'pressIn'); + await rerender(); + await rerender(); + await fireEvent(target, 'pressOut'); + await fireEvent(target, 'blur'); + await fireEvent(target, 'hoverOut'); + await fireEvent(target, 'hoverIn'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + + expectAnimatedStyle('card-state-layer', { + opacity: systemTokens.md.sys.state.opacity.hovered, + }); + expectAnimatedStyle('card-container', { elevation: 1 }); + expectAnimatedStyle('card-outline', { + borderColor: theme.colors.outlineVariant, + opacity: 1, + }); + expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); + }); + it('does not rerender stable memoized slot content for transient feedback', async () => { const renderCount = jest.fn(); const StableContent = React.memo(() => { @@ -941,7 +1279,7 @@ describe('CardCover', () => { borderBottomLeftRadius: 20, }); expect(screen.getByTestId('edge-cover')).not.toHaveStyle({ - borderRadius: getTheme().shapes.corner.medium, + borderRadius: LightTheme.shapes.corner.medium, }); }); }); From 33f8cedc8ed187786f7ed0443120b8d80f526be4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 4 Sep 2026 14:58:59 +0200 Subject: [PATCH 08/51] fix(card): fix worklet related complaints --- src/components/Card/Card.tsx | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 7992ec31f8..2eaf7fb5f3 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -9,6 +9,7 @@ import type { import Animated, { cubicBezier, + type AnimatedStyle, useAnimatedStyle, useDerivedValue, useSharedValue, @@ -466,14 +467,24 @@ const Card = ({ ? 0 : theme.motion.duration.short3 * theme.animation.scale; const transitionTimingFunction = cubicBezier(...theme.motion.easing.standard); + // Parametrized timing functions are class instances and cannot cross the + // worklet boundary, so keep them in regular styles. + const stateLayerTransitionStyle: AnimatedStyle = { + transitionTimingFunction, + }; + const outlineTransitionStyle: AnimatedStyle = { + transitionTimingFunction, + }; + const focusIndicatorTransitionStyle: AnimatedStyle = { + transitionTimingFunction, + }; const stateLayerAnimatedStyle = useAnimatedStyle( () => ({ opacity: currentInteractiveVisuals.value.stateLayerOpacity, transitionDuration, transitionProperty: ['opacity'], - transitionTimingFunction, }), - [currentInteractiveVisuals, transitionDuration, transitionTimingFunction] + [currentInteractiveVisuals, transitionDuration] ); const outlineAnimatedStyle = useAnimatedStyle(() => { const outlineColor = currentInteractiveVisuals.value.outlineColor; @@ -486,17 +497,15 @@ const Card = ({ typeof outlineColor === 'string' ? ['borderColor', 'opacity'] : ['opacity'], - transitionTimingFunction, }; - }, [currentInteractiveVisuals, transitionDuration, transitionTimingFunction]); + }, [currentInteractiveVisuals, transitionDuration]); const focusIndicatorAnimatedStyle = useAnimatedStyle( () => ({ opacity: disabledState.value ? 0 : focused.value ? 1 : 0, transitionDuration, transitionProperty: ['opacity'], - transitionTimingFunction, }), - [disabledState, transitionDuration, transitionTimingFunction] + [disabledState, transitionDuration] ); React.useEffect(() => { @@ -746,6 +755,7 @@ const Card = ({ { backgroundColor: visuals.stateLayerColor, }, + stateLayerTransitionStyle, stateLayerAnimatedStyle, ]} /> @@ -789,6 +799,7 @@ const Card = ({ StyleSheet.absoluteFill, shapeStyle, { borderWidth: visuals.outlineWidth }, + outlineTransitionStyle, outlineAnimatedStyle, ]} /> @@ -809,6 +820,7 @@ const Card = ({ borderWidth: systemTokens.md.sys.state.focusIndicator.thickness, }, focusIndicatorShapeStyle, + focusIndicatorTransitionStyle, focusIndicatorAnimatedStyle, ]} /> From d1217baf6b9051d8ca5e31d77cd86b469e2e66c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 7 Sep 2026 08:31:15 +0200 Subject: [PATCH 09/51] feat(card): add expressive example gallery --- example/src/Examples/CardExample.tsx | 537 +++++++++++------- .../src/Examples/CardRenderCountExample.tsx | 114 ++++ .../__tests__/CardRenderCountExample.test.tsx | 76 +++ 3 files changed, 524 insertions(+), 203 deletions(-) create mode 100644 example/src/Examples/CardRenderCountExample.tsx create mode 100644 example/src/Examples/__tests__/CardRenderCountExample.test.tsx diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index ec48b4c4cc..9b4c279d23 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -1,212 +1,301 @@ -import * as React from 'react'; -import { Alert, Platform, ScrollView, StyleSheet } from 'react-native'; +import { Alert, Platform, StyleSheet, View } from 'react-native'; import { Avatar, Button, Card, + DarkTheme, IconButton, + LightTheme, Text, + ThemeProvider, useTheme, } from 'react-native-paper'; +import type { CardCoverProps, Theme } from 'react-native-paper'; -import { PreferencesContext } from '../PreferencesContext'; +import CardRenderCountExample from './CardRenderCountExample'; import ScreenWrapper from '../ScreenWrapper'; +const showMessage = (message: string) => { + if (Platform.OS === 'web') { + alert(message); + } else { + Alert.alert(message); + } +}; + +const CustomHeader = () => ( + + + + Custom header + Neutral container, independent actions + + +); + +const ResponsiveCover = ({ + aspectRatio = 16 / 9, + ...props +}: Omit & { aspectRatio?: number }) => ( + + + +); + +const ThemePreview = ({ name }: { name: string }) => { + const theme = useTheme(); + + return ( + + {name} + showMessage(`${name} filled Card pressed`)} + onLongPress={() => showMessage(`${name} filled Card long pressed`)} + title="Filled interaction" + subtitle="Tab, hover, press, or long press" + content={ + + + State layers and keyboard focus stay inside the shape. + + + } + /> + + Compare the raised surface. + + } + /> + + } + title="Outlined clipping" + /> + + ); +}; + +const ThemedPreview = ({ name, theme }: { name: string; theme: Theme }) => ( + + + +); + const CardExample = () => { - const { colors } = useTheme(); - const [isSelected, setIsSelected] = React.useState(false); - const preferences = React.useContext(PreferencesContext); + const theme = useTheme(); return ( - - + + Expressive Card gallery + + Filled is the default. Whole-Card actions are shown without nested + controls; neutral Cards own any independent actions. + + + + + Variants and composition + + showMessage('Default filled Card pressed')} + onLongPress={() => showMessage('Default filled Card long pressed')} + media={ + + } + title="Filled (default)" + subtitle="Actionable Card" + content={ + + + One coherent target with direct title and content slots. + + + } + /> + + } + content={ + + + Card.Actions preserves each control's own presentation. + + + } + actions={ + + showMessage('Saved')} + /> + + + } + /> + + + } + title="Outlined" + subtitle="Responsive informative media" + /> + + + + + States, shapes, and omitted slots + + showMessage('Disabled Card pressed')} + title="Disabled action" + content={ + + Not focusable or pressable. + + } + /> + + Controlled visual state. + + } + /> + + } + content={ + + Asymmetric shape, no header. + + } + /> + } + right={(props) => ( + showMessage('More options')} + /> + )} + /> + } + /> + + + + + Light and dark verification + + Compare surfaces, outlines, elevation, clipping, and interaction + feedback without changing the application theme. + + + + + + + + - - } - title="Abandoned Ship" - content={ - - - The Abandoned Ship is a wrecked ship located on Route 108 in - Hoenn, originally being a ship named the S.S. Cactus. The second - part of the ship can only be accessed by using Dive and contains - the Scanner. - - - } - /> - - } - header={ - - } - content={ - - - This is a card using title and subtitle with specified variants. - - - } - /> - - } - actions={ - - - - - } - /> - } - trailing={(props) => ( - {}} /> - )} - content={ - - - Dotted around the Hoenn region, you will find loamy soil, many - of which are housing berries. Once you have picked the berries, - then you have the ability to use that loamy soil to grow your - own berries. These can be any berry and will require attention - to get the best crop. - - - } - /> - - } - title="Custom Button styles" - actions={ - - - - - } - /> - - } - title="Custom border radius" - subtitle="... for card and cover" - /> - - } - title="Just Strawberries" - subtitle="... and only Strawberries" - trailing={(props) => ( - setIsSelected(!isSelected)} - /> - )} - /> - { - Platform.OS === 'web' - ? alert('The Chameleon is Pressed') - : Alert.alert('The Chameleon is Pressed'); - }} - media={ - - } - title="Pressable Chameleon" - content={ - - - This is a pressable chameleon. If you press me, I will alert. - - - } - /> - { - Platform.OS === 'web' - ? alert('The City is Long Pressed') - : Alert.alert('The City is Long Pressed'); - }} - media={ - - } - title="Long Pressable City" - leading={(props) => } - content={ - - - This is a long press only city. If you long press me, I will - alert. - - - } - /> - { - preferences?.toggleTheme(); - }} - title="Pressable Theme Change" - leading={(props) => } - content={ - - - This is pressable card. If you press me, I will switch the - theme. - - - } - /> - + Platform verification + + Android · iOS · web: compare layout, both themes, surface roles, + outlines, clipping, and elevation. + + + Web: use Tab and hover on actionable Cards to inspect focus and state + layers. + + + Native: touch actionable Cards to inspect bounded ripple, clipping, + and elevation. Current platform: {Platform.OS}. + + + + + + ); }; @@ -214,19 +303,61 @@ const CardExample = () => { CardExample.title = 'Card'; const styles = StyleSheet.create({ - container: { - flex: 1, + screen: { + gap: 28, + padding: 16, + }, + intro: { + gap: 8, + }, + section: { + gap: 12, + }, + gallery: { + alignItems: 'flex-start', + flexDirection: 'row', + flexWrap: 'wrap', + gap: 16, }, - content: { - padding: 4, + galleryCard: { + minWidth: 260, + flexBasis: 300, + flexGrow: 1, + }, + compactCard: { + minWidth: 220, + flexBasis: 250, + flexGrow: 1, + }, + mediaFrame: { + overflow: 'hidden', + width: '100%', + }, + mediaFill: { + height: '100%', + }, + customHeader: { + alignItems: 'center', + flexDirection: 'row', + gap: 12, + paddingHorizontal: 16, + paddingTop: 16, + }, + customHeaderText: { + flex: 1, }, - card: { - margin: 4, + themePreview: { + borderWidth: 1, + flexBasis: 300, + flexGrow: 1, + gap: 12, + minWidth: 260, + padding: 16, }, - customCoverRadius: { - borderTopLeftRadius: 0, - borderTopRightRadius: 0, - borderBottomRightRadius: 24, + verification: { + borderLeftWidth: 4, + gap: 6, + paddingLeft: 12, }, bottomCover: { marginTop: 0, diff --git a/example/src/Examples/CardRenderCountExample.tsx b/example/src/Examples/CardRenderCountExample.tsx new file mode 100644 index 0000000000..368883f0f1 --- /dev/null +++ b/example/src/Examples/CardRenderCountExample.tsx @@ -0,0 +1,114 @@ +import * as React from 'react'; +import { FlatList, StyleSheet, View } from 'react-native'; + +import { Button, Card, Text } from 'react-native-paper'; + +const benchmarkItems = Array.from({ length: 30 }, (_, index) => ({ + id: index + 1, + title: `List item ${String(index + 1).padStart(2, '0')}`, +})); + +type BenchmarkItem = (typeof benchmarkItems)[number]; + +const handleCardPress = () => {}; + +const StableCardContent = React.memo(({ item }: { item: BenchmarkItem }) => { + const renderCount = React.useRef(0); + renderCount.current += 1; + + return ( + + Referentially stable slot content + + {`Stable content renders: ${renderCount.current}`} + + + ); +}); + +StableCardContent.displayName = 'StableCardContent'; + +const BenchmarkCard = ({ item }: { item: BenchmarkItem }) => ( + } + /> +); + +const CardRenderCountExample = () => { + const [listRevision, setListRevision] = React.useState(0); + const parentRenderCount = React.useRef(0); + parentRenderCount.current += 1; + + const renderItem = React.useCallback( + ({ item }: { item: BenchmarkItem }) => , + [] + ); + + return ( + + Large-list render boundary + + Interact with a Card using touch, hover, or keyboard focus. Its stable + content counter should remain at 1. + + + {`Parent render passes: ${parentRenderCount.current}`} + + + String(item.id)} + renderItem={renderItem} + showsHorizontalScrollIndicator + contentContainerStyle={styles.list} + /> + + 30 actionable Cards · counters are recorded by memoized content + subtrees, not by the Card shell. + + + ); +}; + +const styles = StyleSheet.create({ + container: { + gap: 12, + }, + metrics: { + alignItems: 'center', + flexDirection: 'row', + flexWrap: 'wrap', + gap: 12, + justifyContent: 'space-between', + }, + list: { + gap: 12, + padding: 4, + }, + card: { + marginVertical: 4, + width: 240, + }, +}); + +export default CardRenderCountExample; diff --git a/example/src/Examples/__tests__/CardRenderCountExample.test.tsx b/example/src/Examples/__tests__/CardRenderCountExample.test.tsx new file mode 100644 index 0000000000..e34e33c32c --- /dev/null +++ b/example/src/Examples/__tests__/CardRenderCountExample.test.tsx @@ -0,0 +1,76 @@ +import { Platform } from 'react-native'; + +import { describe, expect, it, jest } from '@jest/globals'; +import { getAnimatedStyle } from 'react-native-reanimated'; + +import { + act, + fireEvent, + render, + screen, + userEvent, +} from '../../../../src/test-utils'; +import CardRenderCountExample from '../CardRenderCountExample'; + +jest.mock('react', () => jest.requireActual('../../../../node_modules/react')); +jest.mock('react-native-reanimated', () => + jest.requireActual('../../../../node_modules/react-native-reanimated') +); +jest.mock('react-native-paper', () => + jest.requireActual('../../../../src/index') +); + +describe('CardRenderCountExample', () => { + it('keeps stable content at one render through feedback and a parent rerender', async () => { + jest.replaceProperty(Platform, 'OS', 'web'); + const user = userEvent.setup(); + await render(); + + const firstCard = screen.getByTestId('card-benchmark-item-1'); + + await fireEvent(firstCard, 'hoverIn'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + expect( + getAnimatedStyle(screen.getByTestId('card-benchmark-item-1-state-layer')) + ).toEqual(expect.objectContaining({ opacity: 0.08 })); + + await fireEvent(firstCard, 'focus', { + currentTarget: { matches: () => true }, + }); + await act(() => { + jest.runOnlyPendingTimers(); + }); + expect( + getAnimatedStyle( + screen.getByTestId('card-benchmark-item-1-focus-indicator') + ) + ).toEqual(expect.objectContaining({ opacity: 1 })); + + await fireEvent(firstCard, 'pressIn'); + await act(() => { + jest.runOnlyPendingTimers(); + }); + expect( + getAnimatedStyle(screen.getByTestId('card-benchmark-item-1-state-layer')) + ).toEqual(expect.objectContaining({ opacity: 0.1 })); + + await fireEvent(firstCard, 'pressOut'); + await fireEvent(firstCard, 'blur'); + await fireEvent(firstCard, 'hoverOut'); + + expect( + screen.getByTestId('card-benchmark-render-count-1') + ).toHaveTextContent('Stable content renders: 1'); + + await user.press(screen.getByTestId('card-benchmark-rerender')); + + expect(screen.getByTestId('card-benchmark-parent-count')).toHaveTextContent( + 'Parent render passes: 2' + ); + expect( + screen.getByTestId('card-benchmark-render-count-1') + ).toHaveTextContent('Stable content renders: 1'); + }); +}); From 7e85772b97443e04fe3f43262f742788ab157d82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 7 Sep 2026 09:08:08 +0200 Subject: [PATCH 10/51] docs(card): publish v6 contract and migration --- docs/6.x/docs/guides/migration.md | 87 +++++++++++- .../guides/theming-with-react-navigation.md | 12 +- docs/component-docs.config.ts | 6 +- .../component-docs/__tests__/parser.test.ts | 25 ++++ docs/plugins/component-docs/parser.ts | 16 +-- docs/src/components/ThemeColorsTable.tsx | 15 +- docs/src/data/screenshots.ts | 2 +- docs/src/data/themeColors.ts | 8 +- src/components/Card/Card.tsx | 128 +++++++++++++----- src/components/Card/tokens.ts | 6 +- src/components/__tests__/Card/Card.test.tsx | 30 +++- 11 files changed, 262 insertions(+), 73 deletions(-) create mode 100644 docs/plugins/component-docs/__tests__/parser.test.ts diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index e577f6be37..74fdb658cc 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -38,7 +38,7 @@ const MyComponent = () => { opacity: opacity.value, })); - return Button; + return ; }; ``` @@ -75,7 +75,7 @@ To follow the same preference in your own components, use the `useReduceMotion() The `elevation` prop no longer accepts a React Native `Animated.Value` in the following components: - `Banner` -- `Card` +- `Card` (`variant="elevated"` only) - `Searchbar` - `Snackbar` - `Surface` @@ -494,6 +494,89 @@ e.g.: + ``` +### Card + +Paper 6 replaces the Card's `mode` and arbitrary-children interfaces with Material 3 variants and explicit slots. These interfaces were removed; they are not deprecated APIs. Migrate each Card directly to the new contract. + +#### Variants and default + +Replace `mode` with `variant`: + +| Paper 5 | Paper 6 | +| --- | --- | +| `mode="contained"` | `variant="filled"` | +| `mode="elevated"` | `variant="elevated"` | +| `mode="outlined"` | `variant="outlined"` | + +The default also changed. A Paper 5 Card without `mode` was elevated; a Paper 6 Card without `variant` is filled and has no resting shadow. Add `variant="elevated"` if you need to preserve the old default emphasis. The `elevation` prop is accepted only with `variant="elevated"`. + +#### Replace nested composition with slots + +Arbitrary Card children were removed. Paper 6 renders the explicit regions in the deterministic order `media`, header, `content`, and `actions`, regardless of the order in which props are written. Arrays, fragments, conditional values, and custom wrappers can be passed inside a slot without changing region placement. + +For the common header form, move `Card.Title` values to `title`, `subtitle`, `leading`, and `trailing`. Move the remaining regions to their corresponding slots: + +```tsx +// Before (v5) + + + + + View the itinerary. + + + +// After (v6) +} + title="Weekend trip" + subtitle="2 days" + content={ + + View the itinerary. + + } +/> +``` + +Use `header` when the complete header is custom. It is mutually exclusive with `title`, `subtitle`, `leading`, and `trailing`: + +```tsx +} + content={{trip.summary}} +/> +``` + +`Card.Content`, `Card.Cover`, `Card.Title`, and `Card.Actions` remain available as layout helpers inside the new slots. They are not arbitrary Card children. + +#### Choose one interaction model + +Give the Card an interaction handler when the whole Card represents one action. It becomes one accessibility target with button semantics by default, so do not place independent controls in its `actions` slot. + +When buttons or other controls perform independent actions, keep the Card itself neutral and put those controls in `actions`: + +```tsx +Review before saving.} + actions={ + + + + + } +/> +``` + +Paper 6 warns in development if whole-Card interaction handlers and a populated `actions` slot are combined. A neutral Card remains a grouping container unless you provide accessibility semantics explicitly. The `dragged` prop controls the Material dragged presentation only; drag gestures and lifecycle remain application responsibilities. + +Card refs and test IDs now target documented nodes: `ref` targets the outer shell, `touchableRef` targets the actionable interaction node, and `testID` targets the interaction node for actionable Cards or the slot-content node for neutral Cards. `${testID}-container` and `${testID}-visual` identify the outer shell and clipped visual region. + ### Surface - The `elevation` prop no longer accepts a React Native `Animated.Value`. Any `elevation` changes are animated automatically. diff --git a/docs/6.x/docs/guides/theming-with-react-navigation.md b/docs/6.x/docs/guides/theming-with-react-navigation.md index d16b4f8a62..31244be5cd 100644 --- a/docs/6.x/docs/guides/theming-with-react-navigation.md +++ b/docs/6.x/docs/guides/theming-with-react-navigation.md @@ -45,7 +45,6 @@ For React Native Paper theme to work, we need to use `PaperProvider` also at the ```js import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; -import { TouchableOpacity } from 'react-native'; import { Card, Text, List, PaperProvider } from 'react-native-paper'; const Stack = createNativeStackNavigator(); @@ -54,21 +53,22 @@ const title = 'Card title'; const content = 'Card content'; const HomeScreen = ({ navigation }) => ( - navigation?.push('Details', { title, content, }) } - > - + title={title} + content={ {title} {content} - - + } + /> ); const DetailsScreen = (props) => { diff --git a/docs/component-docs.config.ts b/docs/component-docs.config.ts index 73ebb3b3b2..0e457f64e2 100644 --- a/docs/component-docs.config.ts +++ b/docs/component-docs.config.ts @@ -130,7 +130,11 @@ const pages = { SegmentedButtons: 'SegmentedButtons/SegmentedButtons', }, Snackbar: 'Snackbar', - Surface: 'Surface', + Surface: { + source: 'Surface', + component: 'StaticSurface', + title: 'Surface', + }, Switch: { Switch: 'Switch/Switch', }, diff --git a/docs/plugins/component-docs/__tests__/parser.test.ts b/docs/plugins/component-docs/__tests__/parser.test.ts new file mode 100644 index 0000000000..6b3ff8c68b --- /dev/null +++ b/docs/plugins/component-docs/__tests__/parser.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from '@jest/globals'; +import path from 'node:path'; + +import { createComponentParser } from '../parser'; + +describe('component docs parser', () => { + it('documents every branch of the Card public prop unions', () => { + const repositoryRoot = process.cwd(); + const parse = createComponentParser( + path.join(repositoryRoot, 'tsconfig.source.json') + ); + const { props: documentedProps } = parse( + path.join(repositoryRoot, 'src', 'components'), + { source: 'Card/Card' } + ); + const props = new Map(documentedProps.map((prop) => [prop.name, prop])); + + expect(props.get('variant')?.type).toContain('"filled"'); + expect(props.get('variant')?.type).toContain('"elevated"'); + expect(props.get('variant')?.type).toContain('"outlined"'); + expect(props.get('elevation')?.type).toContain('Elevation'); + expect(props.get('header')?.type).toBe('React.ReactNode'); + expect(props.get('title')?.type).toBe('React.ReactNode'); + }); +}); diff --git a/docs/plugins/component-docs/parser.ts b/docs/plugins/component-docs/parser.ts index 800bd8f2f3..ed03c20bb8 100644 --- a/docs/plugins/component-docs/parser.ts +++ b/docs/plugins/component-docs/parser.ts @@ -206,22 +206,8 @@ const getProps = ( ? [item.type.getText(item.getSourceFile())] : [] ); - const hasUnionDeclarations = declarations.some((item) => { - let parent: ts.Node | undefined = item.parent; - - while (parent && !ts.isTypeAliasDeclaration(parent)) { - if (ts.isUnionTypeNode(parent)) { - return true; - } - - parent = parent.parent; - } - - return false; - }); const type = - (hasUnionDeclarations && new Set(declarationTypes).size > 1) || - !declarations.includes(property) + new Set(declarationTypes).size > 1 || !declarations.includes(property) ? checker.typeToString( checker.getTypeOfSymbolAtLocation(symbol, property), property, diff --git a/docs/src/components/ThemeColorsTable.tsx b/docs/src/components/ThemeColorsTable.tsx index d9c5cec724..ba6f5cfc2e 100644 --- a/docs/src/components/ThemeColorsTable.tsx +++ b/docs/src/components/ThemeColorsTable.tsx @@ -24,9 +24,11 @@ const isDataObject = (value: DataObject[string]): value is DataObject => typeof value === 'object'; const FlatTable = ({ + firstColumnLabel, themeColorsData, uniqueKeys, }: { + firstColumnLabel: string; themeColorsData: DataObject; uniqueKeys: string[]; }): ReactNode => { @@ -50,7 +52,7 @@ const FlatTable = ({ - + {getTableHeader(uniqueKeys)} @@ -61,9 +63,11 @@ const FlatTable = ({ }; const TabbedTable = ({ + firstColumnLabel, themeColorsData, uniqueKeys, }: { + firstColumnLabel: string; themeColorsData: DataObject; uniqueKeys: string[]; }): ReactNode => { @@ -88,7 +92,7 @@ const TabbedTable = ({
mode{firstColumnLabel}
- + {getTableHeader(uniqueKeys)} @@ -120,12 +124,17 @@ const ThemeColorsTable = ({ const uniqueKeys = getUniqueNestedKeys(themeColorsData); const nestingLevel = getMaxNestedLevel(themeColorsData); const isFlatTable = nestingLevel === 1; + const firstColumnLabel = componentName === 'Card' ? 'variant' : 'mode'; const Table = isFlatTable ? FlatTable : TabbedTable; return ( <> -
mode{firstColumnLabel}
+

If a dedicated prop for a specific color is not available or the{' '} diff --git a/docs/src/data/screenshots.ts b/docs/src/data/screenshots.ts index 90f9f0273c..ce90fa97d3 100644 --- a/docs/src/data/screenshots.ts +++ b/docs/src/data/screenshots.ts @@ -29,9 +29,9 @@ export const screenshots = { text: 'screenshots/button-1.png', }, Card: { + filled: 'screenshots/card-3.png', elevated: 'screenshots/card-1.png', outlined: 'screenshots/card-2.png', - contained: 'screenshots/card-3.png', }, 'Card.Actions': 'screenshots/card-actions.png', 'Card.Content': 'screenshots/card-content-example.png', diff --git a/docs/src/data/themeColors.ts b/docs/src/data/themeColors.ts index c283c119e0..bc58b78595 100644 --- a/docs/src/data/themeColors.ts +++ b/docs/src/data/themeColors.ts @@ -126,15 +126,15 @@ export const themeColors = { }, }, Card: { - contained: { - backgroundColor: 'theme.colors.surfaceVariant', + filled: { + backgroundColor: 'theme.colors.surfaceContainerHighest', }, elevated: { - backgroundColor: 'theme.colors.elevation.level1', + backgroundColor: 'theme.colors.surfaceContainerLow', }, outlined: { backgroundColor: 'theme.colors.surface', - borderColor: 'theme.colors.outline', + borderColor: 'theme.colors.outlineVariant', }, }, Dialog: { diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 2eaf7fb5f3..05578e5ff1 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -34,30 +34,32 @@ import type { Props as TouchableRippleProps } from '../TouchableRipple/Touchable type ConvenienceHeaderProps = { /** - * Header title. + * Title rendered in the Card's header region. */ title?: React.ReactNode; /** - * Header subtitle. + * Subtitle rendered below `title` in the Card's header region. */ subtitle?: React.ReactNode; /** - * Render slot displayed before the title and subtitle. + * Render slot displayed before `title` and `subtitle`. */ leading?: CardTitleProps['left']; /** - * Render slot displayed after the title and subtitle. + * Render slot displayed after `title` and `subtitle`. */ trailing?: CardTitleProps['right']; /** - * A fully custom header cannot be combined with convenience header props. + * Fully custom header region. This cannot be combined with `title`, + * `subtitle`, `leading`, or `trailing`. */ header?: never; }; type CustomHeaderProps = { /** - * Fully custom header content. + * Fully custom header region. This cannot be combined with `title`, + * `subtitle`, `leading`, or `trailing`. */ header: React.ReactNode; /** @@ -139,11 +141,12 @@ type CardShapeProps = { type FilledCardProps = { /** - * Filled Card variant (default). + * Material Card variant. `filled` is the default, `elevated` adds hierarchy + * with a shadow, and `outlined` adds a visible boundary. */ variant?: 'filled'; /** - * Filled Cards do not support custom elevation. + * Resting elevation. Available only when `variant="elevated"`. */ elevation?: never; }; @@ -172,18 +175,22 @@ type OutlinedCardProps = { type CardVariantProps = FilledCardProps | ElevatedCardProps | OutlinedCardProps; -type CardBaseProps = Omit & +export type Props = Omit & CardShapeProps & { /** - * Media rendered at the start of the Card. + * Media rendered as the first Card region. Use `Card.Cover` for responsive + * edge-to-edge image media, or pass any React node, array, or fragment. */ media?: React.ReactNode; /** - * Main Card content. + * Main content rendered after the header. Use `Card.Content` when the + * standard Card padding is desired. */ content?: React.ReactNode; /** - * Actions rendered at the end of the Card. + * Actions rendered as the final Card region. Independent controls belong + * here only when the Card itself is neutral, without interaction handlers. + * `Card.Actions` provides the standard action-row layout. */ actions?: React.ReactNode; /** @@ -220,13 +227,18 @@ type CardBaseProps = Omit & disabled?: boolean; /** * Whether to show the Card's controlled Material dragged presentation. - * Gesture recognition and drag lifecycle remain the consumer's responsibility. + * This controls visuals only; gesture recognition, drag lifecycle, list + * reordering, and drop behavior remain the consumer's responsibility. */ dragged?: boolean; /** - * Style of card's inner content. + * Style of the inner region that contains all Card slots. */ contentStyle?: StyleProp; + /** + * Layout style for the outer Card shell. Use the dedicated shape props and + * `variant` or `elevation` for Card visuals. + */ style?: StyleProp; /** * @optional @@ -239,7 +251,9 @@ type CardBaseProps = Omit & */ testID?: string; /** - * Whether the Card's semantic target is an accessibility element. + * Whether the Card's semantic target is an accessibility element. For an + * actionable Card this applies to its single interaction target; otherwise + * it applies to the neutral outer shell. */ accessible?: boolean; /** @@ -250,47 +264,87 @@ type CardBaseProps = Omit & * Reference to the outer Card shell. */ ref?: React.Ref; - }; - -export type Props = CardBaseProps & - (ConvenienceHeaderProps | CustomHeaderProps) & + } & (ConvenienceHeaderProps | CustomHeaderProps) & CardVariantProps; /** - * A Card groups related media, header content, body content, and actions. - * Use the `filled` (default), `elevated`, or `outlined` variant to select its - * Material 3 emphasis. + * A Card groups related media, header content, body content, and actions. It + * renders populated regions in the fixed order `media`, header, `content`, and + * `actions`, regardless of prop order. Slots accept React nodes, including + * arrays and fragments, and Card does not clone or rewrite them. + * + * The header region can be created directly with `title`, `subtitle`, `leading`, + * and `trailing`, or replaced completely with `header`; the two forms are + * mutually exclusive. `Card.Title`, `Card.Content`, `Card.Cover`, and + * `Card.Actions` remain optional layout helpers for their corresponding slots. * - * A Card with an interaction handler represents one action. It receives button - * semantics by default and must not contain independent controls in `actions`. - * Use a neutral Card when its actions provide their own interaction targets. + * Use `filled` (the default), `elevated`, or `outlined` for Material 3 emphasis. + * Only an elevated Card accepts `elevation`. Every variant uses the theme's + * medium shape by default; the dedicated corner props consistently shape the + * shadow shell, clipped visual region, outline, state layer, ripple, focus + * indicator, and edge media. + * + * Supplying `onPress`, `onLongPress`, `onPressIn`, or `onPressOut` makes the + * whole Card one actionable target. It receives button semantics by default, + * routes accessibility props and `touchableRef` to that target, and must not + * contain independent controls in `actions`. Keep the Card neutral when the + * controls in `actions` are the interaction targets. A neutral Card remains a + * grouping container unless accessibility semantics are supplied explicitly. + * Disabled Cards expose disabled semantics and suppress interaction callbacks. + * + * `ref` targets the outer shadow shell. On an actionable Card, `testID` targets + * the interaction node; on a neutral Card it targets the slot-content node. + * `${testID}-container` and `${testID}-visual` target the outer shell and the + * clipped visual region. `dragged` controls Material dragged visuals only; the + * consumer remains responsible for gesture recognition and drag lifecycle. * * ## Usage - * ```js + * + * An actionable filled Card represents one action and contains no independent + * controls: + * + * ```tsx * import * as React from 'react'; * import { Avatar, Button, Card, Text } from 'react-native-paper'; + * import { View } from 'react-native'; * - * const Leading = props => + * const CardExamples = () => ( + * + * console.log('Open trip details')} + * media={} + * title="Weekend trip" + * subtitle="Actionable filled Card" + * leading={(props) => } + * content={ + * View the itinerary. + * } + * /> * - * const MyComponent = () => ( * } - * title="Card Title" - * subtitle="Card Subtitle" - * leading={Leading} + * title="Draft itinerary" * content={ - * Card title - * Card content + * Review before saving. * } * actions={ - * - * + * + * * } * /> + * + * } + * content={ + * Supply any React node as the header. + * } + * /> + * * ); * - * export default MyComponent; + * export default CardExamples; * ``` */ diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index aaa00a2f11..70dc3322e5 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -41,14 +41,14 @@ const { opacity } = systemTokens.md.sys.state; /** * Material 3 Card variant-by-state tokens. * - * Rechecked 2026-09-04 against the Material 3 Card specification and the + * Rechecked 2026-09-07 against the Material 3 Card specification and the * current AndroidX generated Card tokens at commit - * 160825094a81825468a95b115bfb1b541e549856: + * 8c85cbb3ccccbaf5ca40c45527e2028ced01e472: * https://m3.material.io/components/cards/specs * - FilledCardTokens v0_210 * - ElevatedCardTokens v0_210 * - OutlinedCardTokens v0_192 - * https://github.com/androidx/androidx/tree/160825094a81825468a95b115bfb1b541e549856/compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens + * https://android.googlesource.com/platform/frameworks/support/+/8c85cbb3ccccbaf5ca40c45527e2028ced01e472/compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens * * State opacities were rechecked against Material Components Android generated * token set 34.0.0 at commit 4d3710682140722f48a5965b68109b240e1fe79e. diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 8942b916dc..ac2df12c1d 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1114,10 +1114,38 @@ describe('Card', () => { }); describe('Card types', () => { - it('rejects the removed API and mixed header forms', () => { + it('accepts documented examples and rejects removed or mixed forms', () => { const typeCases = ( <> + {}} + media={} + title="Weekend trip" + subtitle="Actionable filled Card" + content={View the itinerary.} + /> + Review before saving.} + actions={ + + + + + } + /> + } + content={ + Supply any React node as the header. + } + /> Date: Mon, 7 Sep 2026 09:10:56 +0200 Subject: [PATCH 11/51] fix(docs): correct card migration examples --- docs/6.x/docs/guides/migration.md | 15 ++++++++++++--- docs/src/components/ThemeColorsTable.tsx | 18 ++++++++---------- src/components/__tests__/Card/Card.test.tsx | 16 +++++++++++++--- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 74fdb658cc..2f044746f5 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -31,6 +31,7 @@ So you can use Reanimated's `useSharedValue` and `useAnimatedStyle` to animate t ```tsx import { useAnimatedStyle, useSharedValue } from 'react-native-reanimated'; +import { Card, Text } from 'react-native-paper'; const MyComponent = () => { const opacity = useSharedValue(1); @@ -38,7 +39,7 @@ const MyComponent = () => { opacity: opacity.value, })); - return ; + return Animated Card} style={animatedStyle} />; }; ``` @@ -547,7 +548,11 @@ Use `header` when the complete header is custom. It is mutually exclusive with ` } - content={{trip.summary}} + content={ + + {trip.summary} + + } /> ``` @@ -563,7 +568,11 @@ When buttons or other controls perform independent actions, keep the Card itself Review before saving.} + content={ + + Review before saving. + + } actions={ diff --git a/docs/src/components/ThemeColorsTable.tsx b/docs/src/components/ThemeColorsTable.tsx index ba6f5cfc2e..c26155b3e6 100644 --- a/docs/src/components/ThemeColorsTable.tsx +++ b/docs/src/components/ThemeColorsTable.tsx @@ -23,15 +23,17 @@ const getTableCell = (keys: string[], modes: DataObject): ReactNode[] => { const isDataObject = (value: DataObject[string]): value is DataObject => typeof value === 'object'; +type TableProps = { + firstColumnLabel: string; + themeColorsData: DataObject; + uniqueKeys: string[]; +}; + const FlatTable = ({ firstColumnLabel, themeColorsData, uniqueKeys, -}: { - firstColumnLabel: string; - themeColorsData: DataObject; - uniqueKeys: string[]; -}): ReactNode => { +}: TableProps): ReactNode => { const rows = Object.keys(themeColorsData).map((mode) => { const value = themeColorsData[mode]; @@ -66,11 +68,7 @@ const TabbedTable = ({ firstColumnLabel, themeColorsData, uniqueKeys, -}: { - firstColumnLabel: string; - themeColorsData: DataObject; - uniqueKeys: string[]; -}): ReactNode => { +}: TableProps): ReactNode => { const tabTableContent = Object.entries(themeColorsData).map( ([key, modes]) => { if (!isDataObject(modes)) { diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index ac2df12c1d..7b0002ae16 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1124,12 +1124,20 @@ describe('Card types', () => { media={} title="Weekend trip" subtitle="Actionable filled Card" - content={View the itinerary.} + content={ + + View the itinerary. + + } /> Review before saving.} + content={ + + Review before saving. + + } actions={ @@ -1143,7 +1151,9 @@ describe('Card types', () => { variant="outlined" header={} content={ - Supply any React node as the header. + + Supply any React node as the header. + } /> Date: Wed, 23 Sep 2026 12:02:00 +0200 Subject: [PATCH 12/51] refactor(card): drop derived testID's + fix tests --- eslint.config.mjs | 5 +- .../__tests__/CardRenderCountExample.test.tsx | 15 +- src/components/Card/Card.tsx | 14 +- src/components/__tests__/Card/Card.test.tsx | 440 +- .../Card/__snapshots__/Card.test.tsx.snap | 11612 ++++++++++++++++ 5 files changed, 11706 insertions(+), 380 deletions(-) create mode 100644 src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap diff --git a/eslint.config.mjs b/eslint.config.mjs index 04a315a5c5..fdea443ae4 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -219,7 +219,10 @@ export default defineConfig( }, ], - 'jest/expect-expect': 'error', + 'jest/expect-expect': [ + 'error', + { assertFunctionNames: ['expect', 'expectVisualSnapshot'] }, + ], 'jest/no-commented-out-tests': 'error', 'jest/no-disabled-tests': 'error', 'jest/prefer-importing-jest-globals': 'error', diff --git a/example/src/Examples/__tests__/CardRenderCountExample.test.tsx b/example/src/Examples/__tests__/CardRenderCountExample.test.tsx index e34e33c32c..57357b4d44 100644 --- a/example/src/Examples/__tests__/CardRenderCountExample.test.tsx +++ b/example/src/Examples/__tests__/CardRenderCountExample.test.tsx @@ -1,7 +1,6 @@ import { Platform } from 'react-native'; import { describe, expect, it, jest } from '@jest/globals'; -import { getAnimatedStyle } from 'react-native-reanimated'; import { act, @@ -28,13 +27,13 @@ describe('CardRenderCountExample', () => { const firstCard = screen.getByTestId('card-benchmark-item-1'); + // Hover, focus, and pressed feedback opacities are covered by + // Card.test.tsx; this benchmark only needs to exercise the feedback + // paths to prove the memoized content does not rerender because of them. await fireEvent(firstCard, 'hoverIn'); await act(() => { jest.runOnlyPendingTimers(); }); - expect( - getAnimatedStyle(screen.getByTestId('card-benchmark-item-1-state-layer')) - ).toEqual(expect.objectContaining({ opacity: 0.08 })); await fireEvent(firstCard, 'focus', { currentTarget: { matches: () => true }, @@ -42,19 +41,11 @@ describe('CardRenderCountExample', () => { await act(() => { jest.runOnlyPendingTimers(); }); - expect( - getAnimatedStyle( - screen.getByTestId('card-benchmark-item-1-focus-indicator') - ) - ).toEqual(expect.objectContaining({ opacity: 1 })); await fireEvent(firstCard, 'pressIn'); await act(() => { jest.runOnlyPendingTimers(); }); - expect( - getAnimatedStyle(screen.getByTestId('card-benchmark-item-1-state-layer')) - ).toEqual(expect.objectContaining({ opacity: 0.1 })); await fireEvent(firstCard, 'pressOut'); await fireEvent(firstCard, 'blur'); diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 05578e5ff1..f8b98ff494 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -246,8 +246,7 @@ export type Props = Omit & theme?: ThemeProp; /** * Test ID for the interaction node when the Card is actionable, or the - * content node when it is neutral. The shell and clipped visual region use - * `${testID}-container` and `${testID}-visual` respectively. + * content node when it is neutral. */ testID?: string; /** @@ -294,9 +293,8 @@ export type Props = Omit & * * `ref` targets the outer shadow shell. On an actionable Card, `testID` targets * the interaction node; on a neutral Card it targets the slot-content node. - * `${testID}-container` and `${testID}-visual` target the outer shell and the - * clipped visual region. `dragged` controls Material dragged visuals only; the - * consumer remains responsible for gesture recognition and drag lifecycle. + * `dragged` controls Material dragged visuals only; the consumer remains + * responsible for gesture recognition and drag lifecycle. * * ## Usage * @@ -769,7 +767,6 @@ const Card = ({ theme={theme} elevation={interactiveElevation} transitionDuration={transitionDuration} - testID={`${testID}-container`} {...(!hasPassedTouchHandler && neutralAccessibilityProps)} onFocus={!hasPassedTouchHandler ? onFocus : undefined} onBlur={!hasPassedTouchHandler ? onBlur : undefined} @@ -779,7 +776,6 @@ const Card = ({ {...rest} > 0 ? ( -) => { - expect(getAnimatedStyle(screen.getByTestId(testID))).toEqual( - expect.objectContaining(expectedStyle) - ); -}; - const getVariantCard = ( variant: 'filled' | 'elevated' | 'outlined', props: Pick = {} @@ -46,13 +34,11 @@ const getVariantCard = ( return ; }; -const expectOutlineStyle = (expectedStyle?: Record) => { - const outline = screen.queryByTestId('card-outline'); - - expect(Boolean(outline)).toBe(Boolean(expectedStyle)); - expect(outline ? getAnimatedStyle(outline) : {}).toEqual( - expect.objectContaining(expectedStyle ?? {}) - ); +// The Card shell, clipped visual region, background, state layer, outline, +// and focus indicator are internal nodes with no public testID. Their +// styles are guarded with a snapshot of the rendered tree instead. +const expectVisualSnapshot = () => { + expect(screen.toJSON()).toMatchSnapshot(); }; afterEach(() => { @@ -60,34 +46,15 @@ afterEach(() => { }); describe('Card', () => { - it.each([ - { - variant: 'filled' as const, - colorRole: 'surfaceContainerHighest' as const, - }, - { - variant: 'elevated' as const, - colorRole: 'surfaceContainerLow' as const, - }, - { variant: 'outlined' as const, colorRole: 'surface' as const }, - ])( - 'renders the enabled $variant appearance in light and dark themes', - async ({ variant, colorRole }) => { + it.each(['filled', 'elevated', 'outlined'] as const)( + 'renders the enabled %s appearance in light and dark themes', + async (variant) => { for (const isDark of [false, true] as const) { const theme = isDark ? DarkTheme : LightTheme; - const card = - variant === 'elevated' ? ( - - ) : variant === 'outlined' ? ( - - ) : ( - - ); + const card = getVariantCard(variant, { theme }); const { unmount } = await render(card); - expect(screen.getByTestId('card-visual')).toHaveStyle({ - backgroundColor: theme.colors[colorRole], - }); + expectVisualSnapshot(); await unmount(); } @@ -101,11 +68,7 @@ describe('Card', () => { ); - expect(screen.getByTestId('card-outline')).toHaveStyle({ - borderColor: theme.colors.outlineVariant, - borderWidth: 1, - opacity: 1, - }); + expectVisualSnapshot(); await unmount(); } @@ -114,16 +77,11 @@ describe('Card', () => { it.each(['filled', 'elevated'] as const)( 'does not render an outline for the %s variant', async (variant) => { - const card = - variant === 'elevated' ? ( - - ) : ( - - ); + const card = getVariantCard(variant); await render(card); - expect(screen.queryByTestId('card-outline')).not.toBeOnTheScreen(); + expectVisualSnapshot(); } ); @@ -139,13 +97,7 @@ describe('Card', () => { /> ); - expect(screen.getByTestId('card-visual')).toHaveStyle({ - backgroundColor: '#111111', - }); - expect(screen.getByTestId('card-state-layer')).toHaveStyle({ - backgroundColor: '#222222', - opacity: 0, - }); + expectVisualSnapshot(); }); it('uses custom theme roles for elevated and outlined variants', async () => { @@ -156,9 +108,7 @@ describe('Card', () => { /> ); - expect(screen.getByTestId('card-visual')).toHaveStyle({ - backgroundColor: '#123456', - }); + expectVisualSnapshot(); await unmount(); await render( @@ -170,12 +120,7 @@ describe('Card', () => { /> ); - expect(screen.getByTestId('card-visual')).toHaveStyle({ - backgroundColor: '#abcdef', - }); - expect(screen.getByTestId('card-outline')).toHaveStyle({ - borderColor: '#654321', - }); + expectVisualSnapshot(); }); it('lets only elevated Cards customize their resting elevation', async () => { @@ -183,32 +128,18 @@ describe('Card', () => { await render(); - expect(screen.getByTestId('card-container')).toHaveStyle({ elevation: 12 }); + expectVisualSnapshot(); }); - it.each([ - { variant: 'filled' as const, elevation: 0 }, - { variant: 'elevated' as const, elevation: 1 }, - { variant: 'outlined' as const, elevation: 0 }, - ])( - 'renders the enabled $variant elevation', - async ({ variant, elevation }) => { + it.each(['filled', 'elevated', 'outlined'] as const)( + 'renders the enabled %s elevation', + async (variant) => { jest.replaceProperty(Platform, 'OS', 'android'); - const card = - variant === 'elevated' ? ( - - ) : variant === 'outlined' ? ( - - ) : ( - - ); + const card = getVariantCard(variant); await render(card); - expect(screen.getByTestId('card-container')).toHaveStyle({ elevation }); - expect(screen.getByTestId('card-container')).toHaveStyle({ - backgroundColor: 'transparent', - }); + expectVisualSnapshot(); } ); @@ -223,20 +154,7 @@ describe('Card', () => { /> ); - const expectedShape = { - borderRadius: LightTheme.shapes.corner.medium, - borderTopLeftRadius: 4, - borderTopRightRadius: 8, - borderBottomRightRadius: 16, - borderBottomLeftRadius: 20, - borderCurve: 'continuous', - }; - - expect(screen.getByTestId('card-container')).toHaveStyle(expectedShape); - expect(screen.getByTestId('card-visual')).toHaveStyle(expectedShape); - expect(screen.getByTestId('card-background')).toHaveStyle(expectedShape); - expect(screen.getByTestId('card-state-layer')).toHaveStyle(expectedShape); - expect(screen.getByTestId('card-outline')).toHaveStyle(expectedShape); + expectVisualSnapshot(); }); it('renders populated slots in deterministic order without rewriting nodes', async () => { @@ -276,11 +194,8 @@ describe('Card', () => { it('renders omitted slots as a neutral filled grouping container', async () => { await render(); - expect(screen.getByTestId('card-visual')).toHaveStyle({ - backgroundColor: LightTheme.colors.surfaceContainerHighest, - }); + expectVisualSnapshot(); expect(screen.getByTestId('card')).not.toHaveProp('focusable'); - expect(screen.getByTestId('card-container')).not.toHaveProp('focusable'); expect(screen.queryByRole('button')).not.toBeOnTheScreen(); }); @@ -298,7 +213,6 @@ describe('Card', () => { const shell = screen.getByRole('summary', { name: 'Product summary' }); - expect(shell).toBe(screen.getByTestId('product-card-container')); expect(shell).toHaveProp( 'accessibilityHint', 'Contains product information' @@ -394,7 +308,6 @@ describe('Card', () => { ); const target = screen.getByRole('link', { name: 'Open product' }); - const shell = screen.getByTestId('product-card-container'); expect(target).toBe(screen.getByTestId('product-card')); expect(target).toHaveProp('accessibilityHint', 'Shows product details'); @@ -406,8 +319,9 @@ describe('Card', () => { expect(target).toHaveProp('accessibilityActions', [ { name: 'activate', label: 'Open product' }, ]); - expect(shell).not.toHaveProp('accessibilityLabel'); - expect(shell).not.toHaveProp('accessibilityActions'); + // The shell only forwards accessibility semantics to the interaction + // target, so the shell itself should carry none of them. + expectVisualSnapshot(); await fireEvent(target, 'accessibilityAction', accessibilityActionEvent); await fireEvent(target, 'accessibilityEscape'); @@ -423,66 +337,50 @@ describe('Card', () => { }); it('keeps the ripple, visual layers, and focus indicator on the Card shape', async () => { - const shellRef = React.createRef>(); - const touchableRef = React.createRef>(); const shape = { borderTopLeftRadius: 4, borderTopRightRadius: 8, borderBottomRightRadius: 16, borderBottomLeftRadius: 20, }; + const { unmount } = await render( + {}} /> + ); + + const interaction = screen.getByTestId('product-card'); + + expect(interaction).toHaveStyle(shape); + // The clipped visual region and focus indicator are internal nodes with + // no public testID; the snapshot captures their shape, position, and the + // interaction node's place within the visual region. + expectVisualSnapshot(); + await unmount(); + + // `ref` forwards to a Reanimated Animated.View, which the test renderer + // cannot serialize once populated, so its behavior is verified in a + // separate, unsnapshotted render. + const shellRef = React.createRef>(); + const touchableRef = React.createRef>(); await render( {}} /> ); - const interaction = screen.getByTestId('product-card'); - const shell = screen.getByTestId('product-card-container'); - const visual = screen.getByTestId('product-card-visual'); - - expect(interaction).toHaveStyle(shape); - expect(visual).toHaveStyle({ overflow: 'hidden', ...shape }); - expect(interaction.parent).toBe(visual); - expect(screen.getByTestId('product-card-focus-indicator')).toHaveStyle({ - top: -5, - right: -5, - bottom: -5, - left: -5, - borderColor: LightTheme.colors.secondary, - borderWidth: 3, - borderTopLeftRadius: 9, - borderTopRightRadius: 13, - borderBottomRightRadius: 21, - borderBottomLeftRadius: 25, - }); - expect(shell).toBeOnTheScreen(); expect(shellRef.current).not.toBeNull(); expect(touchableRef.current).not.toBeNull(); expect(touchableRef.current).not.toBe(shellRef.current); }); - it.each([ - { variant: 'filled' as const, hoveredElevation: 1 }, - { variant: 'elevated' as const, hoveredElevation: 2 }, - { variant: 'outlined' as const, hoveredElevation: 1 }, - ])( - 'shows and clears the $variant hover feedback', - async ({ variant, hoveredElevation }) => { + it.each(['filled', 'elevated', 'outlined'] as const)( + 'shows and clears the %s hover feedback', + async (variant) => { expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'android'); - const card = - variant === 'elevated' ? ( - {}} /> - ) : variant === 'outlined' ? ( - {}} /> - ) : ( - {}} /> - ); + const card = getVariantCard(variant, { onPress: () => {} }); await render(card); const target = screen.getByTestId('card'); @@ -492,34 +390,20 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { opacity: 0.08 }); - expectAnimatedStyle('card-container', { - elevation: hoveredElevation === 1 ? 1 : 3, - }); + expectVisualSnapshot(); await fireEvent(target, 'hoverOut'); - expectAnimatedStyle('card-state-layer', { opacity: 0 }); + expectVisualSnapshot(); } ); - it.each([ - { variant: 'filled' as const, pressedElevation: 0 }, - { variant: 'elevated' as const, pressedElevation: 1 }, - { variant: 'outlined' as const, pressedElevation: 0 }, - ])( - 'shows and clears the $variant pressed feedback', - async ({ variant, pressedElevation }) => { + it.each(['filled', 'elevated', 'outlined'] as const)( + 'shows and clears the %s pressed feedback', + async (variant) => { expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'android'); - const card = - variant === 'elevated' ? ( - {}} /> - ) : variant === 'outlined' ? ( - {}} /> - ) : ( - {}} /> - ); + const card = getVariantCard(variant, { onPress: () => {} }); await render(card); const target = screen.getByTestId('card'); @@ -529,104 +413,33 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { opacity: 0.1 }); - expectAnimatedStyle('card-container', { elevation: pressedElevation }); + expectVisualSnapshot(); await fireEvent(target, 'pressOut'); await act(() => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { opacity: 0 }); + expectVisualSnapshot(); } ); - it.each([ - { - variant: 'filled' as const, - containerRole: 'surfaceContainerHighest' as const, - draggedElevation: 3, - outlineRole: undefined, - }, - { - variant: 'elevated' as const, - containerRole: 'surfaceContainerLow' as const, - draggedElevation: 4, - outlineRole: undefined, - }, - { - variant: 'outlined' as const, - containerRole: 'surface' as const, - draggedElevation: 3, - outlineRole: 'outlineVariant' as const, - }, - ])( - 'renders the consumer-controlled $variant dragged presentation', - async ({ variant, containerRole, draggedElevation, outlineRole }) => { + it.each(['filled', 'elevated', 'outlined'] as const)( + 'renders the consumer-controlled %s dragged presentation', + async (variant) => { jest.replaceProperty(Platform, 'OS', 'android'); const theme = LightTheme; const card = getVariantCard(variant, { dragged: true, theme }); await render(card); - expect(screen.getByTestId('card-background')).toHaveStyle({ - backgroundColor: theme.colors[containerRole], - opacity: 1, - }); - expect(screen.getByTestId('card-state-layer')).toHaveStyle({ - backgroundColor: theme.colors.onSurface, - opacity: systemTokens.md.sys.state.opacity.dragged, - }); - expect(screen.getByTestId('card-container')).toHaveStyle({ - elevation: draggedElevation === 3 ? 6 : 8, - }); - - const expectedOutlineStyle = outlineRole - ? { - borderColor: theme.colors[outlineRole], - borderWidth: 1, - opacity: 1, - } - : undefined; - expectOutlineStyle(expectedOutlineStyle); + expectVisualSnapshot(); } ); - it.each([ - { - variant: 'filled' as const, - containerRole: 'surfaceVariant' as const, - containerOpacity: systemTokens.md.sys.state.opacity.disabled, - elevation: 0, - outlineRole: undefined, - outlineOpacity: undefined, - }, - { - variant: 'elevated' as const, - containerRole: 'surface' as const, - containerOpacity: systemTokens.md.sys.state.opacity.disabled, - elevation: 1, - outlineRole: undefined, - outlineOpacity: undefined, - }, - { - variant: 'outlined' as const, - containerRole: 'surface' as const, - containerOpacity: 1, - elevation: 0, - outlineRole: 'outline' as const, - outlineOpacity: 0.12, - }, - ])( - 'renders the Material disabled treatment for $variant Cards', - async ({ - variant, - containerRole, - containerOpacity, - elevation, - outlineRole, - outlineOpacity, - }) => { + it.each(['filled', 'elevated', 'outlined'] as const)( + 'renders the Material disabled treatment for %s Cards', + async (variant) => { jest.replaceProperty(Platform, 'OS', 'android'); const theme = LightTheme; const card = getVariantCard(variant, { @@ -637,26 +450,7 @@ describe('Card', () => { await render(card); - expect(screen.getByTestId('card-background')).toHaveStyle({ - backgroundColor: theme.colors[containerRole], - opacity: containerOpacity, - }); - expect(screen.getByTestId('card-state-layer')).toHaveStyle({ - opacity: 0, - }); - expect(screen.getByTestId('card-container')).toHaveStyle({ elevation }); - expect(screen.getByTestId('card-focus-indicator')).toHaveStyle({ - opacity: 0, - }); - - const expectedOutlineStyle = outlineRole - ? { - borderColor: theme.colors[outlineRole], - borderWidth: 1, - opacity: outlineOpacity, - } - : undefined; - expectOutlineStyle(expectedOutlineStyle); + expectVisualSnapshot(); } ); @@ -676,15 +470,7 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { - opacity: systemTokens.md.sys.state.opacity.dragged, - }); - expectAnimatedStyle('card-container', { elevation: 6 }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.outlineVariant, - opacity: 1, - }); - expectAnimatedStyle('card-focus-indicator', { opacity: 1 }); + expectVisualSnapshot(); await rerender( { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { opacity: 0 }); - expectAnimatedStyle('card-container', { elevation: 0 }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.outline, - opacity: 0.12, - }); - expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); + expectVisualSnapshot(); }); it('updates the controlled dragged presentation in both directions', async () => { @@ -724,26 +504,14 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { - opacity: systemTokens.md.sys.state.opacity.dragged, - }); - expectAnimatedStyle('card-container', { elevation: 6 }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.outlineVariant, - opacity: 1, - }); + expectVisualSnapshot(); await rerender(); await act(() => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { opacity: 0 }); - expectAnimatedStyle('card-container', { elevation: 0 }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.outlineVariant, - opacity: 1, - }); + expectVisualSnapshot(); }); it.each(['filled', 'elevated', 'outlined'] as const)( @@ -761,10 +529,7 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { - opacity: systemTokens.md.sys.state.opacity.focused, - }); - expectAnimatedStyle('card-focus-indicator', { opacity: 1 }); + expectVisualSnapshot(); } ); @@ -782,28 +547,21 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); - expectAnimatedStyle('card-state-layer', { opacity: 0 }); + expectVisualSnapshot(); await fireEvent(target, 'focus', { currentTarget: keyboardTarget }); await act(() => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-focus-indicator', { opacity: 1 }); - expectAnimatedStyle('card-state-layer', { opacity: 0.1 }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.onSurface, - opacity: 1, - }); + expectVisualSnapshot(); await fireEvent(target, 'blur'); await act(() => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); - expectAnimatedStyle('card-state-layer', { opacity: 0 }); + expectVisualSnapshot(); }); it('uses pressed, focused, then hovered precedence and settles at the latest state', async () => { @@ -820,28 +578,21 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.onSurface, - opacity: 1, - }); + expectVisualSnapshot(); await fireEvent(target, 'blur'); await act(() => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { opacity: 0.08 }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.outlineVariant, - opacity: 1, - }); + expectVisualSnapshot(); await fireEvent(target, 'hoverOut'); await act(() => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { opacity: 0 }); + expectVisualSnapshot(); }); it('uses scaled theme motion duration and easing for visual transitions', async () => { @@ -858,17 +609,13 @@ describe('Card', () => { {}} theme={theme} /> ); - expectAnimatedStyle('card-state-layer', { - transitionDuration: 160, - transitionProperty: ['opacity'], - transitionTimingFunction: Reanimated.cubicBezier(...easing), - }); - expectAnimatedStyle('card-container', { transitionDuration: 160 }); + // The scaled duration and easing are set on the state layer and shell, + // both internal nodes with no public testID. + expectVisualSnapshot(); await rerender( {}} theme={theme} />); - expectAnimatedStyle('card-state-layer', { transitionDuration: 160 }); - expectAnimatedStyle('card-container', { transitionDuration: 160 }); + expectVisualSnapshot(); }); it('settles transitions immediately when reduced motion is enabled', async () => { @@ -884,13 +631,7 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { - opacity: systemTokens.md.sys.state.opacity.pressed, - transitionDuration: 0, - }); - expectAnimatedStyle('card-container', { transitionDuration: 0 }); - expectAnimatedStyle('card-outline', { transitionDuration: 0 }); - expectAnimatedStyle('card-focus-indicator', { transitionDuration: 0 }); + expectVisualSnapshot(); }); it('settles rapid changes at the latest complete visual state', async () => { @@ -918,15 +659,7 @@ describe('Card', () => { jest.runOnlyPendingTimers(); }); - expectAnimatedStyle('card-state-layer', { - opacity: systemTokens.md.sys.state.opacity.hovered, - }); - expectAnimatedStyle('card-container', { elevation: 1 }); - expectAnimatedStyle('card-outline', { - borderColor: theme.colors.outlineVariant, - opacity: 1, - }); - expectAnimatedStyle('card-focus-indicator', { opacity: 0 }); + expectVisualSnapshot(); }); it('does not rerender stable memoized slot content for transient feedback', async () => { @@ -1309,13 +1042,8 @@ describe('CardCover', () => { /> ); - expect(screen.getByTestId('shaped-card-visual')).toHaveStyle({ - overflow: 'hidden', - borderTopLeftRadius: 4, - borderTopRightRadius: 8, - borderBottomRightRadius: 16, - borderBottomLeftRadius: 20, - }); + // The clipped visual region is an internal node with no public testID. + expectVisualSnapshot(); expect(screen.getByTestId('edge-cover')).not.toHaveStyle({ borderRadius: LightTheme.shapes.corner.medium, }); diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap new file mode 100644 index 0000000000..a2a589ac43 --- /dev/null +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -0,0 +1,11612 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Card applies the medium shape and asymmetric overrides across the shell 1`] = ` + + + + + + + + + +`; + +exports[`Card does not render an outline for the elevated variant 1`] = ` + + + + + + + + +`; + +exports[`Card does not render an outline for the filled variant 1`] = ` + + + + + + + + +`; + +exports[`Card keeps the ripple, visual layers, and focus indicator on the Card shape 1`] = ` + + + + + + + + + + + +`; + +exports[`Card lets only elevated Cards customize their resting elevation 1`] = ` + + + + + + + +`; + +exports[`Card renders keyboard focus feedback for the elevated variant 1`] = ` + + + + + + + + + + +`; + +exports[`Card renders keyboard focus feedback for the filled variant 1`] = ` + + + + + + + + + + +`; + +exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` + + + + + + + + + + + +`; + +exports[`Card renders omitted slots as a neutral filled grouping container 1`] = ` + + + + + + + + +`; + +exports[`Card renders the Material disabled treatment for elevated Cards 1`] = ` + + + + + + + + + + +`; + +exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` + + + + + + + + + + +`; + +exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` + + + + + + + + + + + +`; + +exports[`Card renders the consumer-controlled elevated dragged presentation 1`] = ` + + + + + + + +`; + +exports[`Card renders the consumer-controlled filled dragged presentation 1`] = ` + + + + + + + +`; + +exports[`Card renders the consumer-controlled outlined dragged presentation 1`] = ` + + + + + + + + +`; + +exports[`Card renders the enabled elevated appearance in light and dark themes 1`] = ` + + + + + + + + +`; + +exports[`Card renders the enabled elevated appearance in light and dark themes 2`] = ` + + + + + + + + +`; + +exports[`Card renders the enabled elevated elevation 1`] = ` + + + + + + + +`; + +exports[`Card renders the enabled filled appearance in light and dark themes 1`] = ` + + + + + + + + +`; + +exports[`Card renders the enabled filled appearance in light and dark themes 2`] = ` + + + + + + + + +`; + +exports[`Card renders the enabled filled elevation 1`] = ` + + + + + + + +`; + +exports[`Card renders the enabled outlined appearance in light and dark themes 1`] = ` + + + + + + + + + +`; + +exports[`Card renders the enabled outlined appearance in light and dark themes 2`] = ` + + + + + + + + + +`; + +exports[`Card renders the enabled outlined elevation 1`] = ` + + + + + + + + +`; + +exports[`Card renders the enabled outlined role in light and dark themes 1`] = ` + + + + + + + + + +`; + +exports[`Card renders the enabled outlined role in light and dark themes 2`] = ` + + + + + + + + + +`; + +exports[`Card resolves disabled and dragged before pressed, focused, and hovered visuals 1`] = ` + + + + + + + + + + + +`; + +exports[`Card resolves disabled and dragged before pressed, focused, and hovered visuals 2`] = ` + + + + + + + + + + + +`; + +exports[`Card routes whole-Card accessibility semantics and callbacks to its target 1`] = ` + + + + + + + + + + + +`; + +exports[`Card settles rapid changes at the latest complete visual state 1`] = ` + + + + + + + + + + + +`; + +exports[`Card settles transitions immediately when reduced motion is enabled 1`] = ` + + + + + + + + + + + + +`; + +exports[`Card shows and clears the elevated hover feedback 1`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the elevated hover feedback 2`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the elevated pressed feedback 1`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the elevated pressed feedback 2`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the filled hover feedback 1`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the filled hover feedback 2`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the filled pressed feedback 1`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the filled pressed feedback 2`] = ` + + + + + + + + + + +`; + +exports[`Card shows and clears the outlined hover feedback 1`] = ` + + + + + + + + + + + +`; + +exports[`Card shows and clears the outlined hover feedback 2`] = ` + + + + + + + + + + + +`; + +exports[`Card shows and clears the outlined pressed feedback 1`] = ` + + + + + + + + + + + +`; + +exports[`Card shows and clears the outlined pressed feedback 2`] = ` + + + + + + + + + + + +`; + +exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 1`] = ` + + + + + + + + + + + +`; + +exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 2`] = ` + + + + + + + + + + + +`; + +exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 3`] = ` + + + + + + + + + + + +`; + +exports[`Card updates the controlled dragged presentation in both directions 1`] = ` + + + + + + + + + + + +`; + +exports[`Card updates the controlled dragged presentation in both directions 2`] = ` + + + + + + + + + + + +`; + +exports[`Card uses custom theme roles for elevated and outlined variants 1`] = ` + + + + + + + + +`; + +exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` + + + + + + + + + +`; + +exports[`Card uses filled as the default and resolves deeply merged custom colors 1`] = ` + + + + + + + + +`; + +exports[`Card uses pressed, focused, then hovered precedence and settles at the latest state 1`] = ` + + + + + + + + + + + + +`; + +exports[`Card uses pressed, focused, then hovered precedence and settles at the latest state 2`] = ` + + + + + + + + + + + + +`; + +exports[`Card uses pressed, focused, then hovered precedence and settles at the latest state 3`] = ` + + + + + + + + + + + + +`; + +exports[`Card uses scaled theme motion duration and easing for visual transitions 1`] = ` + + + + + + + + + + + +`; + +exports[`Card uses scaled theme motion duration and easing for visual transitions 2`] = ` + + + + + + + + + + + +`; + +exports[`CardCover uses the Card clipping shape for edge media without double rounding 1`] = ` + + + + + + + + + + +`; From d70d03496bd3d8a4a22cdb4a2035ffe2dfe5ae3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Wed, 23 Sep 2026 13:07:08 +0200 Subject: [PATCH 13/51] fix(card): disabled card color --- src/components/Card/tokens.ts | 12 ++++--- .../__tests__/Card/Card.tokens.test.ts | 31 ++++++++++++++++--- .../Card/__snapshots__/Card.test.tsx.snap | 4 +-- 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index 70dc3322e5..a1212c3ae1 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -19,8 +19,8 @@ export type CardState = (typeof cardStates)[number]; type ContainerColorRole = | 'surfaceContainerLow' | 'surfaceContainerHighest' - | 'surfaceVariant' - | 'surface'; + | 'surface' + | 'onSurface'; type OutlineColorRole = 'outlineVariant' | 'onSurface' | 'outline'; @@ -41,7 +41,7 @@ const { opacity } = systemTokens.md.sys.state; /** * Material 3 Card variant-by-state tokens. * - * Rechecked 2026-09-07 against the Material 3 Card specification and the + * Rechecked 2026-09-23 against the Material 3 Card specification and the * current AndroidX generated Card tokens at commit * 8c85cbb3ccccbaf5ca40c45527e2028ced01e472: * https://m3.material.io/components/cards/specs @@ -50,6 +50,10 @@ const { opacity } = systemTokens.md.sys.state; * - OutlinedCardTokens v0_192 * https://android.googlesource.com/platform/frameworks/support/+/8c85cbb3ccccbaf5ca40c45527e2028ced01e472/compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens * + * `filled.disabled.containerColor` follows the live `md.comp.filled-card.disabled.container.color` + * token on m3.material.io (onSurface), which has diverged from the AndroidX + * v0_210 source above (still SurfaceVariant there) — the live spec wins. + * * State opacities were rechecked against Material Components Android generated * token set 34.0.0 at commit 4d3710682140722f48a5965b68109b240e1fe79e. * https://github.com/material-components/material-components-android/tree/4d3710682140722f48a5965b68109b240e1fe79e/lib/java/com/google/android/material @@ -102,7 +106,7 @@ const cardTokenMatrix = { stateLayerOpacity: opacity.dragged, }, disabled: { - containerColor: 'surfaceVariant', + containerColor: 'onSurface', containerOpacity: opacity.disabled, outlineColor: 'outlineVariant', outlineOpacity: 0, diff --git a/src/components/__tests__/Card/Card.tokens.test.ts b/src/components/__tests__/Card/Card.tokens.test.ts index c89a1d93a5..c830d9c27a 100644 --- a/src/components/__tests__/Card/Card.tokens.test.ts +++ b/src/components/__tests__/Card/Card.tokens.test.ts @@ -6,7 +6,7 @@ import { cardVariants, resolveCardVisuals, } from '../../Card/tokens'; -import type { CardState } from '../../Card/tokens'; +import type { CardState, CardVariant } from '../../Card/tokens'; const stateFlags: Record< CardState, @@ -26,8 +26,8 @@ type ExpectedVisualTokens = { containerRole: | 'surfaceContainerLow' | 'surfaceContainerHighest' - | 'surfaceVariant' - | 'surface'; + | 'surface' + | 'onSurface'; containerOpacity: number; outlineRole: 'outlineVariant' | 'onSurface' | 'outline'; outlineOpacity: number; @@ -125,7 +125,7 @@ const expectedVisuals: Record< stateLayerOpacity: 0.16, }), expectedVisual({ - containerRole: 'surfaceVariant', + containerRole: 'onSurface', containerOpacity: 0.38, elevation: 0, stateLayerOpacity: 0, @@ -230,6 +230,29 @@ describe('resolveCardVisuals', () => { ]).toEqual(cardStates.toReversed()); }); + const disabledContainerCases: [ + CardVariant, + 'surface' | 'onSurface', + number, + ][] = [ + ['filled', 'onSurface', 0.38], + ['elevated', 'surface', 0.38], + ['outlined', 'surface', 1], + ]; + + it.each(disabledContainerCases)( + 'resolves the MD3 disabled container color role for the %s variant', + (variant, containerRole, containerOpacity) => { + const theme = LightTheme; + + const { containerColor, containerOpacity: resolvedOpacity } = + resolveCardVisuals({ theme, variant, disabled: true }); + + expect(containerColor).toBe(theme.colors[containerRole]); + expect(resolvedOpacity).toBe(containerOpacity); + } + ); + it('uses a custom resting elevation only for the enabled elevated state', () => { const theme = LightTheme; diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index a2a589ac43..200dfff00b 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -2052,7 +2052,7 @@ exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` "borderRadius": 12, }, { - "backgroundColor": "rgba(231, 224, 236, 1)", + "backgroundColor": "rgba(29, 27, 32, 1)", "opacity": 0.38, }, ] @@ -11269,7 +11269,7 @@ exports[`Card uses scaled theme motion duration and easing for visual transition "borderRadius": 12, }, { - "backgroundColor": "rgba(231, 224, 236, 1)", + "backgroundColor": "rgba(29, 27, 32, 1)", "opacity": 0.38, }, ] From f0d5a10666aad532717eec945cb5f40c2cca1368 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Wed, 23 Sep 2026 13:35:15 +0200 Subject: [PATCH 14/51] docs(card): add card.actions migration info --- docs/6.x/docs/guides/migration.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 2f044746f5..6607cbb70a 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -558,6 +558,24 @@ Use `header` when the complete header is custom. It is mutually exclusive with ` `Card.Content`, `Card.Cover`, `Card.Title`, and `Card.Actions` remain available as layout helpers inside the new slots. They are not arbitrary Card children. +#### `Card.Actions` no longer styles its buttons + +`Card.Actions` no longer assigns `mode="outlined"` to its first button, `mode="contained"` to the rest, or `compact` to any of them. It only lays its children out in a row; set each `Button`'s `mode` and `compact` explicitly to keep the old look: + +```tsx +// Before (v5) — Card.Actions styled the buttons automatically + + + + + +// After (v6) — set mode and compact explicitly + + + + +``` + #### Choose one interaction model Give the Card an interaction handler when the whole Card represents one action. It becomes one accessibility target with button semantics by default, so do not place independent controls in its `actions` slot. From b9086c3c24699330be3281839e91822628106364 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Tue, 17 Nov 2026 13:56:22 +0100 Subject: [PATCH 15/51] refactor(card): adapt to main and use the shared focus ring - Type `ref` and `touchableRef` as `React.ComponentRef` for RN 0.88. - Drop the default `testID`, as #5099 did for every component. - Draw the keyboard focus ring with `useFocusRing` (outward, `within`) on the Card's Surface instead of a Card-specific indicator view. The interaction node is now the Surface's direct child, so the web `:has(> :focus-visible)` rule lights the ring. - Restore `Card.Title`'s own padding and min height. #5076 moved them to the Card container, which the slot-based Card doesn't pad. - Remove the unused `CardContext`, a stale `Card.Cover` comment and a leftover example style. - Move examples and focus ring tests that still used `children` to slots, and use the renamed Button modes. --- example/src/Examples/CardExample.tsx | 9 +- example/src/Examples/TeamDetails.tsx | 16 +- src/components/Card/Card.tsx | 237 +- src/components/Card/CardContext.tsx | 16 - src/components/Card/CardCover.tsx | 2 - src/components/Card/CardTitle.tsx | 25 +- src/components/__tests__/Card/Card.test.tsx | 128 +- .../Card/__snapshots__/Card.test.tsx.snap | 4976 ++++++----------- .../__tests__/focusRingWiring.test.tsx | 31 +- .../__tests__/focusRingWithinWeb.test.tsx | 31 +- 10 files changed, 2088 insertions(+), 3383 deletions(-) delete mode 100644 src/components/Card/CardContext.tsx diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index 9b4c279d23..68ead2b65e 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -165,10 +165,7 @@ const CardExample = () => { icon="bookmark-outline" onPress={() => showMessage('Saved')} /> - @@ -359,10 +356,6 @@ const styles = StyleSheet.create({ gap: 6, paddingLeft: 12, }, - bottomCover: { - marginTop: 0, - marginBottom: -16, - }, }); export default CardExample; diff --git a/example/src/Examples/TeamDetails.tsx b/example/src/Examples/TeamDetails.tsx index d8bbc5c888..fa9a415c81 100644 --- a/example/src/Examples/TeamDetails.tsx +++ b/example/src/Examples/TeamDetails.tsx @@ -101,8 +101,12 @@ const News = () => { } actions={ - - + + } /> @@ -129,8 +133,12 @@ const News = () => { } actions={ - - + + } /> diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index f8b98ff494..753872c598 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Platform, StyleSheet, View } from 'react-native'; +import { StyleSheet, View } from 'react-native'; import type { GestureResponderEvent, StyleProp, @@ -23,10 +23,10 @@ import type { Props as CardTitleProps } from './CardTitle'; import { resolveCardVisuals } from './tokens'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; -import { tokens as systemTokens } from '../../theme/tokens'; import type { Elevation, ThemeProp } from '../../theme/types'; import hasTouchHandler from '../../utils/hasTouchHandler'; import { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent'; +import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; import Surface from '../Surface'; import type { SurfaceStyle } from '../Surface'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; @@ -258,11 +258,11 @@ export type Props = Omit & /** * Reference to the actionable Card interaction node. */ - touchableRef?: React.Ref; + touchableRef?: React.Ref>; /** * Reference to the outer Card shell. */ - ref?: React.Ref; + ref?: React.Ref>; } & (ConvenienceHeaderProps | CustomHeaderProps) & CardVariantProps; @@ -365,7 +365,7 @@ const Card = ({ style, contentStyle, theme: themeOverrides, - testID = 'card', + testID, accessible, disabled, dragged = false, @@ -527,9 +527,6 @@ const Card = ({ const outlineTransitionStyle: AnimatedStyle = { transitionTimingFunction, }; - const focusIndicatorTransitionStyle: AnimatedStyle = { - transitionTimingFunction, - }; const stateLayerAnimatedStyle = useAnimatedStyle( () => ({ opacity: currentInteractiveVisuals.value.stateLayerOpacity, @@ -551,14 +548,6 @@ const Card = ({ : ['opacity'], }; }, [currentInteractiveVisuals, transitionDuration]); - const focusIndicatorAnimatedStyle = useAnimatedStyle( - () => ({ - opacity: disabledState.value ? 0 : focused.value ? 1 : 0, - transitionDuration, - transitionProperty: ['opacity'], - }), - [disabledState, transitionDuration] - ); React.useEffect(() => { disabledState.value = isDisabled; @@ -585,6 +574,20 @@ const Card = ({ onPressIn, onPressOut, }); + // The ring goes on the Surface, the Card's visible box (`scope: 'within'`), + // not on the interaction node: the caller's `style` sizes and pads the + // Surface, so a ring on the interaction node would stop short of a taller + // Card's edge or sit inside its padding. On web the ring lights only for a + // focused direct child, so the interaction node is the Surface's only child. + // + // Off without a touch handler too: the interaction node unmounts then, and a + // focused one sends no blur, so the ring would come back with the handler. + const { target: focusTarget, ring: focusRing } = useFocusRing( + isDisabled || !hasPassedTouchHandler, + theme.colors.secondary, + 'outward', + 'within' + ); const hasWarnedAboutActions = React.useRef(false); const hasActions = actions !== null && actions !== undefined && actions !== false; @@ -621,17 +624,6 @@ const Card = ({ borderCurve, }).filter(([, value]) => value !== undefined) ); - const focusIndicatorInset = - systemTokens.md.sys.state.focusIndicator.outerOffset + - systemTokens.md.sys.state.focusIndicator.thickness; - const focusIndicatorShapeStyle = Object.fromEntries( - Object.entries(shapeStyle).map(([property, value]) => [ - property, - property !== 'borderCurve' && typeof value === 'number' - ? value + focusIndicatorInset - : value, - ]) - ); const hasConvenienceHeader = title != null || subtitle != null || leading != null || trailing != null; @@ -727,19 +719,21 @@ const Card = ({ const handleFocus: NonNullable = React.useCallback( (event) => { + focusTarget.onFocus?.(event); focused.value = isKeyboardFocusEvent(event); onFocus?.(event); }, - [focused, onFocus] + [focusTarget, focused, onFocus] ); const handleBlur: NonNullable = React.useCallback( (event) => { + focusTarget.onBlur?.(); focused.value = false; pressed.value = false; onBlur?.(event); }, - [focused, onBlur, pressed] + [focusTarget, focused, onBlur, pressed] ); const handleHoverIn: NonNullable = React.useCallback( @@ -758,12 +752,60 @@ const Card = ({ [hovered, onHoverOut] ); + const layers = ( + <> + + + {content} + {visuals.outlineWidth > 0 ? ( + + ) : null} + + ); + const visualStyle = [ + styles.visual, + shapeStyle, + visuals.containerOpacity === 1 && { + backgroundColor: visuals.containerColor, + }, + ]; + return ( - - - - {hasPassedTouchHandler ? ( - - {content} - - ) : ( - content - )} - {visuals.outlineWidth > 0 ? ( - - ) : null} - {hasPassedTouchHandler ? ( - - ) : null} + + {layers} + + ) : ( + {layers} + )} ); }; @@ -895,15 +873,6 @@ const styles = StyleSheet.create({ flexShrink: 1, position: 'relative', }, - focusIndicator: { - position: 'absolute', - pointerEvents: 'none', - }, }); -// React Native Web otherwise draws its browser-default outline in addition to -// the Material focus indicator. -// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -const webNoOutline = { outline: 'none' } as unknown as ViewStyle; - export default Card; diff --git a/src/components/Card/CardContext.tsx b/src/components/Card/CardContext.tsx deleted file mode 100644 index 1cf9bf0173..0000000000 --- a/src/components/Card/CardContext.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as React from 'react'; - -type CardContextType = { - /** - * Padding applied to the Card content. - */ - padding: number; - /** - * Direction of the Card layout. - */ - direction: 'vertical' | 'horizontal'; -}; - -export const CardContext = React.createContext(null); - -CardContext.displayName = 'CardContext'; diff --git a/src/components/Card/CardCover.tsx b/src/components/Card/CardCover.tsx index 3340d6024e..c720f5e9d6 100644 --- a/src/components/Card/CardCover.tsx +++ b/src/components/Card/CardCover.tsx @@ -53,8 +53,6 @@ export type Props = Omit & { const CardCover = ({ style, theme: _theme, ...rest }: Props) => { const usesAspectRatio = StyleSheet.flatten(style)?.aspectRatio !== undefined; - // The container clips the image with `overflow: 'hidden'`, - // so any border radius passed in `style` is applied to the image as well return ( { useInternalTheme(themeOverrides); + const minHeight = subtitle || left || right ? 72 : 50; + const marginBottom = subtitle ? 0 : 2; + return ( - + {left ? ( {left({ @@ -156,7 +159,7 @@ const CardTitle = ({ {title && ( = {} ) => { if (variant === 'elevated') { - return ; + return ; } if (variant === 'outlined') { - return ; + return ; } - return ; + return ; }; // The Card shell, clipped visual region, background, state layer, outline, @@ -65,7 +65,7 @@ describe('Card', () => { for (const isDark of [false, true] as const) { const theme = isDark ? DarkTheme : LightTheme; const { unmount } = await render( - + ); expectVisualSnapshot(); @@ -88,6 +88,7 @@ describe('Card', () => { it('uses filled as the default and resolves deeply merged custom colors', async () => { await render( { it('uses custom theme roles for elevated and outlined variants', async () => { const { unmount } = await render( @@ -113,6 +115,7 @@ describe('Card', () => { await render( { it('lets only elevated Cards customize their resting elevation', async () => { jest.replaceProperty(Platform, 'OS', 'android'); - await render(); + await render(); expectVisualSnapshot(); }); @@ -146,6 +149,7 @@ describe('Card', () => { it('applies the medium shape and asymmetric overrides across the shell', async () => { await render( { }); it('renders omitted slots as a neutral filled grouping container', async () => { - await render(); + await render(); expectVisualSnapshot(); expect(screen.getByTestId('card')).not.toHaveProp('focusable'); @@ -233,6 +237,7 @@ describe('Card', () => { const hitSlop = { top: 4, right: 8, bottom: 12, left: 16 }; await render( { const touchableRef = React.createRef>(); await render( { jest.replaceProperty(Platform, 'OS', 'android'); const theme = LightTheme; const { rerender } = await render( - {}} theme={theme} /> + {}} + theme={theme} + /> ); const target = screen.getByTestId('card'); @@ -474,6 +486,7 @@ describe('Card', () => { await rerender( { onPress: () => {}, theme, }; - const { rerender } = await render(); + const { rerender } = await render(); - await rerender(); + await rerender(); await act(() => { jest.runOnlyPendingTimers(); }); expectVisualSnapshot(); - await rerender(); + await rerender(); await act(() => { jest.runOnlyPendingTimers(); }); @@ -537,7 +550,9 @@ describe('Card', () => { expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'web'); const theme = LightTheme; - await render( {}} theme={theme} />); + await render( + {}} theme={theme} /> + ); const target = screen.getByTestId('card'); const pointerTarget = { matches: () => false }; const keyboardTarget = { matches: () => true }; @@ -567,7 +582,9 @@ describe('Card', () => { it('uses pressed, focused, then hovered precedence and settles at the latest state', async () => { expect.hasAssertions(); const theme = LightTheme; - await render( {}} theme={theme} />); + await render( + {}} theme={theme} /> + ); const target = screen.getByTestId('card'); await fireEvent(target, 'hoverIn'); @@ -606,14 +623,16 @@ describe('Card', () => { }, }; const { rerender } = await render( - {}} theme={theme} /> + {}} theme={theme} /> ); // The scaled duration and easing are set on the state layer and shell, // both internal nodes with no public testID. expectVisualSnapshot(); - await rerender( {}} theme={theme} />); + await rerender( + {}} theme={theme} /> + ); expectVisualSnapshot(); }); @@ -622,7 +641,7 @@ describe('Card', () => { expect.hasAssertions(); await render( - {}} /> + {}} /> ); @@ -643,14 +662,14 @@ describe('Card', () => { onPress: () => {}, theme, }; - const { rerender } = await render(); + const { rerender } = await render(); const target = screen.getByTestId('card'); await fireEvent(target, 'hoverIn'); await fireEvent(target, 'focus'); await fireEvent(target, 'pressIn'); - await rerender(); - await rerender(); + await rerender(); + await rerender(); await fireEvent(target, 'pressOut'); await fireEvent(target, 'blur'); await fireEvent(target, 'hoverOut'); @@ -668,7 +687,9 @@ describe('Card', () => { renderCount(); return Stable content; }); - await render( {}} content={} />); + await render( + {}} content={} /> + ); const target = screen.getByTestId('card'); await fireEvent(target, 'hoverIn'); @@ -687,13 +708,14 @@ describe('Card', () => { it('warns once when whole-Card interaction is combined with populated actions', async () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); const { rerender } = await render( - {}} actions={null} /> + {}} actions={null} /> ); expect(warn).not.toHaveBeenCalled(); await rerender( {}} actions={ @@ -704,6 +726,7 @@ describe('Card', () => { ); await rerender( {}} actions={ @@ -727,6 +750,7 @@ describe('Card', () => { try { await render( {}} actions={ @@ -745,6 +769,7 @@ describe('Card', () => { it('renders the convenience header inputs', async () => { await render( Leading {size}} @@ -760,7 +785,11 @@ describe('Card', () => { it('renders with a content style', async () => { await render( - Content} contentStyle={styles.contentStyle} /> + Content} + contentStyle={styles.contentStyle} + /> ); expect(screen.getByText('Content').parent).toHaveStyle(styles.contentStyle); @@ -783,6 +812,7 @@ describe('Card', () => { }; await render( { }); it('exposes disabled state on an explicitly semantic neutral Card', async () => { - await render(); + await render(); expect(screen.getByRole('summary')).toBeDisabled(); }); @@ -836,7 +866,7 @@ describe('Card', () => { }, ] as const)('honors $name as a disabled Card state', async ({ props }) => { const onPress = jest.fn(); - await render(); + await render(); const target = screen.getByTestId('card'); @@ -850,8 +880,9 @@ describe('Card types', () => { it('accepts documented examples and rejects removed or mixed forms', () => { const typeCases = ( <> - + {}} media={} @@ -864,6 +895,7 @@ describe('Card types', () => { } /> { actions={ - } /> } content={ @@ -890,46 +923,48 @@ describe('Card types', () => { } /> } trailing={({ size }) => } /> - } /> + } /> Content} actions={[]} /> - - - - + + + + {/* @ts-expect-error: Arbitrary children composition was removed. */} - + {/* @ts-expect-error: The old mode prop was removed. */} - + {/* @ts-expect-error: Contained is not a Card variant. */} - + {/* @ts-expect-error: The default filled Card cannot be elevated. */} - + {/* @ts-expect-error: Filled Cards cannot be elevated. */} - + {/* @ts-expect-error: Outlined Cards cannot be elevated. */} - + {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} - } title="Title" /> + } title="Title" /> {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} - } leading={() => } /> + } leading={() => } /> {/* @ts-expect-error: Cover placement metadata is not public. */} @@ -1050,6 +1085,23 @@ describe('CardCover', () => { }); }); +describe('CardTitle', () => { + // Card adds no padding around its slots, so the header pads itself like + // `Card.Content` does. + it('pads its own start edge and the end of its text', async () => { + await render( + + ); + + expect(screen.getByTestId('card-title')).toHaveStyle({ + paddingLeft: 16, + minHeight: 72, + }); + expect(screen.getByText('Title')).toHaveStyle({ paddingRight: 16 }); + expect(screen.getByText('Subtitle')).toHaveStyle({ paddingRight: 16 }); + }); +}); + describe('CardContent', () => { it('uses fixed padding when rendered standalone', async () => { await render( diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index 200dfff00b..fb568c081d 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -703,25 +703,59 @@ exports[`Card keeps the ripple, visual layers, and focus indicator on the Card s } /> - - + /> - `; @@ -996,6 +948,11 @@ exports[`Card lets only elevated Cards customize their resting elevation 1`] = ` exports[`Card renders keyboard focus feedback for the elevated variant 1`] = ` - - + /> - `; exports[`Card renders keyboard focus feedback for the filled variant 1`] = ` - - + /> - `; exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` - - + /> - `; @@ -1833,19 +1683,54 @@ exports[`Card renders the Material disabled treatment for elevated Cards 1`] = ` } > - - + /> - `; @@ -2022,19 +1832,54 @@ exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` } > - - + /> - `; @@ -2211,21 +1981,56 @@ exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` } > - - + /> - `; @@ -4743,6 +4473,12 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered [ {}, undefined, + { + "outlineColor": "rgba(98, 91, 113, 1)", + "outlineOffset": 2, + "outlineStyle": "solid", + "outlineWidth": 3, + }, {}, { "backgroundColor": "transparent", @@ -4773,21 +4509,55 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered } > - - + /> - `; @@ -4990,21 +4686,56 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered } > - - + /> - `; @@ -5276,21 +4932,69 @@ exports[`Card routes whole-Card accessibility semantics and callbacks to its tar } /> - - + /> - `; @@ -5480,21 +5096,55 @@ exports[`Card settles rapid changes at the latest complete visual state 1`] = ` } > - - + /> - `; @@ -5765,21 +5341,55 @@ exports[`Card settles transitions immediately when reduced motion is enabled 1`] } /> - - + /> - `; @@ -5982,21 +5518,55 @@ exports[`Card shows and clears the elevated hover feedback 1`] = ` } > - - + /> - `; @@ -6172,21 +5668,55 @@ exports[`Card shows and clears the elevated hover feedback 2`] = ` } > - - + /> - `; @@ -6362,21 +5818,55 @@ exports[`Card shows and clears the elevated pressed feedback 1`] = ` } > - - + /> - `; @@ -6552,21 +5968,55 @@ exports[`Card shows and clears the elevated pressed feedback 2`] = ` } > - - + /> - `; @@ -6742,21 +6118,55 @@ exports[`Card shows and clears the filled hover feedback 1`] = ` } > - - + /> - `; @@ -6932,21 +6268,55 @@ exports[`Card shows and clears the filled hover feedback 2`] = ` } > - - - - + { + "flexShrink": 1, + "position": "relative", + }, + undefined, + ] + } + /> + `; @@ -7122,21 +6418,55 @@ exports[`Card shows and clears the filled pressed feedback 1`] = ` } > - - + /> - `; @@ -7312,21 +6568,55 @@ exports[`Card shows and clears the filled pressed feedback 2`] = ` } > - - + /> - `; @@ -7502,21 +6718,55 @@ exports[`Card shows and clears the outlined hover feedback 1`] = ` } > - - + /> - `; @@ -7719,21 +6895,55 @@ exports[`Card shows and clears the outlined hover feedback 2`] = ` } > - - + /> - `; @@ -7936,21 +7072,55 @@ exports[`Card shows and clears the outlined pressed feedback 1`] = ` } > - - + /> - `; @@ -8153,21 +7249,55 @@ exports[`Card shows and clears the outlined pressed feedback 2`] = ` } > - - + /> - `; exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 1`] = ` - - + /> - `; exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 2`] = ` - - + /> - `; exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 3`] = ` - - + /> - `; @@ -9042,21 +7996,55 @@ exports[`Card updates the controlled dragged presentation in both directions 1`] } > - - - + /> - `; @@ -9259,21 +8173,55 @@ exports[`Card updates the controlled dragged presentation in both directions 2`] } > - - + /> - `; @@ -10028,6 +8902,12 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the [ {}, undefined, + { + "outlineColor": "rgba(98, 91, 113, 1)", + "outlineOffset": 2, + "outlineStyle": "solid", + "outlineWidth": 3, + }, {}, { "backgroundColor": "transparent", @@ -10126,21 +9006,55 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the } /> - - + /> - `; @@ -10411,21 +9251,55 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the } /> - - + [ + { + "flexShrink": 1, + "position": "relative", + }, + undefined, + ] + } + /> - `; @@ -10696,21 +9496,55 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the } /> - - + /> - `; @@ -10981,21 +9741,55 @@ exports[`Card uses scaled theme motion duration and easing for visual transition } /> - - + /> - `; @@ -11239,19 +9959,54 @@ exports[`Card uses scaled theme motion duration and easing for visual transition } /> - - + /> - `; diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 80817b0281..fde7fd8ba1 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -491,11 +491,7 @@ describe('focus ring wiring', () => { }); it('Card rings outward', async () => { - await render( - {}}> - card - - ); + await render( {}} content={card} />); await focusFirstFocusable(); @@ -507,9 +503,11 @@ describe('focus ring wiring', () => { // Pressable would stop at the content's height and sit inside the padding. it('Card rings its own box, whatever its size and padding', async () => { await render( - {}} style={{ height: 200, padding: 12 }}> - card - + {}} + style={{ height: 200, padding: 12 }} + content={card} + /> ); await focusFirstFocusable(); @@ -772,12 +770,8 @@ describe('focus ring after the handler goes away and comes back', () => { it('Card shows no ring until it is focused again', async () => { await dropAndRestore( - {}}> - card - , - - card - + {}} content={card} />, + card} /> ); expect(ringOffset()).toBeUndefined(); @@ -935,9 +929,12 @@ describe('focus ring wiring (web)', () => { it("Card marks its own box as the ring and leaves the Pressable's outline to the stylesheet", async () => { await render( - {}} style={{ height: 200 }}> - card - + {}} + style={{ height: 200 }} + content={card} + /> ); const pressable = screen.getByTestId('card'); diff --git a/src/components/__tests__/focusRingWithinWeb.test.tsx b/src/components/__tests__/focusRingWithinWeb.test.tsx index 6323d3de56..9f69e0b771 100644 --- a/src/components/__tests__/focusRingWithinWeb.test.tsx +++ b/src/components/__tests__/focusRingWithinWeb.test.tsx @@ -70,9 +70,12 @@ describe('focus ring `within` structure (web)', () => { ], [ 'Card', - {}}> - card - , + {}} + content={card} + />, ], [ 'Chip', @@ -123,20 +126,24 @@ describe('focus ring `within` structure (web)', () => { // must not light the Card's ring as well. it("does not hold a Card's nested controls directly inside the Card's ring", async () => { await render( - {}}> - - - - - + {}} + content={ + <> + + + + } + /> ); const [cardRing] = withinRings(); expect(cardRing.children).toContain(screen.getByTestId('card')); expect(cardRing.children).not.toContain(screen.getByTestId('input')); - expect(cardRing.children).not.toContain( - screen.getByRole('button', { name: 'OK' }) - ); + expect(cardRing.children).not.toContain(screen.getByTestId('ok')); }); // The chip's box draws the ring, so a ring on the ripple inside it would From d5ade580cb208bea6f785a211f92c7d7731b5798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 08:56:25 +0100 Subject: [PATCH 16/51] fix(card): add aspectRatio prop to Card.Cover StyleSheet.flatten is restricted in the codebase (#5114). Card.Cover now takes aspectRatio as a prop and drops its default height when it is set. --- .../src/Examples/CardRenderCountExample.tsx | 114 ------------------ .../__tests__/CardRenderCountExample.test.tsx | 67 ---------- src/components/Card/CardCover.tsx | 20 +-- src/components/__tests__/Card/Card.test.tsx | 2 +- 4 files changed, 14 insertions(+), 189 deletions(-) delete mode 100644 example/src/Examples/CardRenderCountExample.tsx delete mode 100644 example/src/Examples/__tests__/CardRenderCountExample.test.tsx diff --git a/example/src/Examples/CardRenderCountExample.tsx b/example/src/Examples/CardRenderCountExample.tsx deleted file mode 100644 index 368883f0f1..0000000000 --- a/example/src/Examples/CardRenderCountExample.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import * as React from 'react'; -import { FlatList, StyleSheet, View } from 'react-native'; - -import { Button, Card, Text } from 'react-native-paper'; - -const benchmarkItems = Array.from({ length: 30 }, (_, index) => ({ - id: index + 1, - title: `List item ${String(index + 1).padStart(2, '0')}`, -})); - -type BenchmarkItem = (typeof benchmarkItems)[number]; - -const handleCardPress = () => {}; - -const StableCardContent = React.memo(({ item }: { item: BenchmarkItem }) => { - const renderCount = React.useRef(0); - renderCount.current += 1; - - return ( - - Referentially stable slot content - - {`Stable content renders: ${renderCount.current}`} - - - ); -}); - -StableCardContent.displayName = 'StableCardContent'; - -const BenchmarkCard = ({ item }: { item: BenchmarkItem }) => ( - } - /> -); - -const CardRenderCountExample = () => { - const [listRevision, setListRevision] = React.useState(0); - const parentRenderCount = React.useRef(0); - parentRenderCount.current += 1; - - const renderItem = React.useCallback( - ({ item }: { item: BenchmarkItem }) => , - [] - ); - - return ( - - Large-list render boundary - - Interact with a Card using touch, hover, or keyboard focus. Its stable - content counter should remain at 1. - - - {`Parent render passes: ${parentRenderCount.current}`} - - - String(item.id)} - renderItem={renderItem} - showsHorizontalScrollIndicator - contentContainerStyle={styles.list} - /> - - 30 actionable Cards · counters are recorded by memoized content - subtrees, not by the Card shell. - - - ); -}; - -const styles = StyleSheet.create({ - container: { - gap: 12, - }, - metrics: { - alignItems: 'center', - flexDirection: 'row', - flexWrap: 'wrap', - gap: 12, - justifyContent: 'space-between', - }, - list: { - gap: 12, - padding: 4, - }, - card: { - marginVertical: 4, - width: 240, - }, -}); - -export default CardRenderCountExample; diff --git a/example/src/Examples/__tests__/CardRenderCountExample.test.tsx b/example/src/Examples/__tests__/CardRenderCountExample.test.tsx deleted file mode 100644 index 57357b4d44..0000000000 --- a/example/src/Examples/__tests__/CardRenderCountExample.test.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { Platform } from 'react-native'; - -import { describe, expect, it, jest } from '@jest/globals'; - -import { - act, - fireEvent, - render, - screen, - userEvent, -} from '../../../../src/test-utils'; -import CardRenderCountExample from '../CardRenderCountExample'; - -jest.mock('react', () => jest.requireActual('../../../../node_modules/react')); -jest.mock('react-native-reanimated', () => - jest.requireActual('../../../../node_modules/react-native-reanimated') -); -jest.mock('react-native-paper', () => - jest.requireActual('../../../../src/index') -); - -describe('CardRenderCountExample', () => { - it('keeps stable content at one render through feedback and a parent rerender', async () => { - jest.replaceProperty(Platform, 'OS', 'web'); - const user = userEvent.setup(); - await render(); - - const firstCard = screen.getByTestId('card-benchmark-item-1'); - - // Hover, focus, and pressed feedback opacities are covered by - // Card.test.tsx; this benchmark only needs to exercise the feedback - // paths to prove the memoized content does not rerender because of them. - await fireEvent(firstCard, 'hoverIn'); - await act(() => { - jest.runOnlyPendingTimers(); - }); - - await fireEvent(firstCard, 'focus', { - currentTarget: { matches: () => true }, - }); - await act(() => { - jest.runOnlyPendingTimers(); - }); - - await fireEvent(firstCard, 'pressIn'); - await act(() => { - jest.runOnlyPendingTimers(); - }); - - await fireEvent(firstCard, 'pressOut'); - await fireEvent(firstCard, 'blur'); - await fireEvent(firstCard, 'hoverOut'); - - expect( - screen.getByTestId('card-benchmark-render-count-1') - ).toHaveTextContent('Stable content renders: 1'); - - await user.press(screen.getByTestId('card-benchmark-rerender')); - - expect(screen.getByTestId('card-benchmark-parent-count')).toHaveTextContent( - 'Parent render passes: 2' - ); - expect( - screen.getByTestId('card-benchmark-render-count-1') - ).toHaveTextContent('Stable content renders: 1'); - }); -}); diff --git a/src/components/Card/CardCover.tsx b/src/components/Card/CardCover.tsx index c720f5e9d6..207c99695c 100644 --- a/src/components/Card/CardCover.tsx +++ b/src/components/Card/CardCover.tsx @@ -5,10 +5,14 @@ import { grey200 } from '../../theme/colors'; import type { ThemeProp } from '../../theme/types'; export type Props = Omit & { + /** + * Width-to-height ratio of the cover, for example `16 / 9`. When set, the + * cover drops its default height of 195 and resizes with the Card's width. + */ + aspectRatio?: number; /** * Style for the cover image. The default size is full width by 195. Consumer - * styles are applied after these defaults. Supplying an `aspectRatio` - * removes the default height so the cover can resize responsively. + * styles are applied after these defaults. */ style?: StyleProp; /** @@ -36,7 +40,7 @@ export type Props = Omit & { * media={ * & { * * @extends Image props https://reactnative.dev/docs/image#props */ -const CardCover = ({ style, theme: _theme, ...rest }: Props) => { - const usesAspectRatio = StyleSheet.flatten(style)?.aspectRatio !== undefined; - +const CardCover = ({ aspectRatio, style, theme: _theme, ...rest }: Props) => { return ( ); diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index a0ee1316dc..f59c94d905 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -995,7 +995,7 @@ describe('CardCover', () => { ); From 07ebcd697da6a7af143bb4cb1ee7372b2bbc52de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 08:56:35 +0100 Subject: [PATCH 17/51] chore(example): remove the Card render count example The QA-only render count section is not a usage example. Also simplify ResponsiveCover now that Card.Cover accepts aspectRatio. --- example/src/Examples/CardExample.tsx | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index 68ead2b65e..b4699d4ffd 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -13,7 +13,6 @@ import { } from 'react-native-paper'; import type { CardCoverProps, Theme } from 'react-native-paper'; -import CardRenderCountExample from './CardRenderCountExample'; import ScreenWrapper from '../ScreenWrapper'; const showMessage = (message: string) => { @@ -37,11 +36,7 @@ const CustomHeader = () => ( const ResponsiveCover = ({ aspectRatio = 16 / 9, ...props -}: Omit & { aspectRatio?: number }) => ( - - - -); +}: CardCoverProps) => ; const ThemePreview = ({ name }: { name: string }) => { const theme = useTheme(); @@ -289,10 +284,6 @@ const CardExample = () => { and elevation. Current platform: {Platform.OS}. - - - - ); }; @@ -326,13 +317,6 @@ const styles = StyleSheet.create({ flexBasis: 250, flexGrow: 1, }, - mediaFrame: { - overflow: 'hidden', - width: '100%', - }, - mediaFill: { - height: '100%', - }, customHeader: { alignItems: 'center', flexDirection: 'row', From e5f51cca3333cfbd880190f8f1f2d70177165a68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:21:26 +0100 Subject: [PATCH 18/51] fix(card): drive state feedback with React state Reanimated CSS transitions start when React commits a new style, so the transition props returned from useAnimatedStyle worklets never animated: the state layer, outline and elevation jumped in one frame. Hover, focus and press now live in useState and Card passes plain styles, so the short3 fade, the standard easing, the animation scale and reduced motion apply. disabled and dragged are read during render instead of being copied into shared values in an effect, so they no longer lag a frame behind. Surface goes back to main's version: Card passes a plain elevation, which Surface already transitions. --- src/components/Card/Card.tsx | 179 +--- src/components/Surface.tsx | 85 +- .../Card/__snapshots__/Card.test.tsx.snap | 935 +++--------------- src/components/__tests__/Surface.test.tsx | 37 - 4 files changed, 168 insertions(+), 1068 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 753872c598..dcb3aa9c29 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -10,9 +10,6 @@ import type { import Animated, { cubicBezier, type AnimatedStyle, - useAnimatedStyle, - useDerivedValue, - useSharedValue, } from 'react-native-reanimated'; import CardActions from './CardActions'; @@ -437,136 +434,49 @@ const Card = ({ disabled || ariaDisabled || accessibilityState?.disabled ); + // Hover, focus and press are changes between fixed states, so they live in + // React state: Reanimated CSS transitions start when React commits the new + // style, which a value written from a worklet would never do. + const [hovered, setHovered] = React.useState(false); + const [focused, setFocused] = React.useState(false); + const [pressed, setPressed] = React.useState(false); + + React.useEffect(() => { + if (isDisabled) { + setHovered(false); + setFocused(false); + setPressed(false); + } + }, [isDisabled]); + const visuals = resolveCardVisuals({ theme, variant: cardVariant, elevation: customElevation, disabled: isDisabled, dragged, - }); - - const enabledVisuals = resolveCardVisuals({ - theme, - variant: cardVariant, - elevation: customElevation, - }); - const hoveredVisuals = resolveCardVisuals({ - theme, - variant: cardVariant, - elevation: customElevation, - hovered: true, - }); - const focusedVisuals = resolveCardVisuals({ - theme, - variant: cardVariant, - elevation: customElevation, - focused: true, - }); - const pressedVisuals = resolveCardVisuals({ - theme, - variant: cardVariant, - elevation: customElevation, - pressed: true, - }); - const draggedVisuals = resolveCardVisuals({ - theme, - variant: cardVariant, - elevation: customElevation, - dragged: true, - }); - const disabledVisuals = resolveCardVisuals({ - theme, - variant: cardVariant, - elevation: customElevation, - disabled: true, - }); - const disabledState = useSharedValue(isDisabled); - const draggedState = useSharedValue(dragged); - const hovered = useSharedValue(false); - const focused = useSharedValue(false); - const pressed = useSharedValue(false); - const currentInteractiveVisuals = useDerivedValue(() => { - if (disabledState.value) { - return disabledVisuals; - } - if (draggedState.value) { - return draggedVisuals; - } - if (pressed.value) { - return pressedVisuals; - } - if (focused.value) { - return focusedVisuals; - } - if (hovered.value) { - return hoveredVisuals; - } - return enabledVisuals; - }, [ - disabledState, - disabledVisuals, - draggedState, - draggedVisuals, - enabledVisuals, - focusedVisuals, - hoveredVisuals, - pressedVisuals, - ]); - const interactiveElevation = useDerivedValue(() => { - return currentInteractiveVisuals.value.elevation; + pressed, + focused, + hovered, }); const transitionDuration = reduceMotion ? 0 : theme.motion.duration.short3 * theme.animation.scale; const transitionTimingFunction = cubicBezier(...theme.motion.easing.standard); - // Parametrized timing functions are class instances and cannot cross the - // worklet boundary, so keep them in regular styles. const stateLayerTransitionStyle: AnimatedStyle = { + transitionProperty: 'opacity', + transitionDuration, transitionTimingFunction, }; const outlineTransitionStyle: AnimatedStyle = { + // A PlatformColor outline cannot be interpolated. + transitionProperty: + typeof visuals.outlineColor === 'string' + ? ['borderColor', 'opacity'] + : 'opacity', + transitionDuration, transitionTimingFunction, }; - const stateLayerAnimatedStyle = useAnimatedStyle( - () => ({ - opacity: currentInteractiveVisuals.value.stateLayerOpacity, - transitionDuration, - transitionProperty: ['opacity'], - }), - [currentInteractiveVisuals, transitionDuration] - ); - const outlineAnimatedStyle = useAnimatedStyle(() => { - const outlineColor = currentInteractiveVisuals.value.outlineColor; - - return { - borderColor: outlineColor, - opacity: currentInteractiveVisuals.value.outlineOpacity, - transitionDuration, - transitionProperty: - typeof outlineColor === 'string' - ? ['borderColor', 'opacity'] - : ['opacity'], - }; - }, [currentInteractiveVisuals, transitionDuration]); - - React.useEffect(() => { - disabledState.value = isDisabled; - draggedState.value = dragged; - - if (isDisabled) { - hovered.value = false; - focused.value = false; - pressed.value = false; - } - }, [ - disabledState, - dragged, - draggedState, - focused, - hovered, - isDisabled, - pressed, - ]); const hasPassedTouchHandler = hasTouchHandler({ onPress, @@ -704,52 +614,52 @@ const Card = ({ }; const handlePressIn = React.useCallback( (event: GestureResponderEvent) => { - pressed.value = true; + setPressed(true); onPressIn?.(event); }, - [onPressIn, pressed] + [onPressIn] ); const handlePressOut = React.useCallback( (event: GestureResponderEvent) => { - pressed.value = false; + setPressed(false); onPressOut?.(event); }, - [onPressOut, pressed] + [onPressOut] ); const handleFocus: NonNullable = React.useCallback( (event) => { focusTarget.onFocus?.(event); - focused.value = isKeyboardFocusEvent(event); + setFocused(isKeyboardFocusEvent(event)); onFocus?.(event); }, - [focusTarget, focused, onFocus] + [focusTarget, onFocus] ); const handleBlur: NonNullable = React.useCallback( (event) => { focusTarget.onBlur?.(); - focused.value = false; - pressed.value = false; + setFocused(false); + setPressed(false); onBlur?.(event); }, - [focusTarget, focused, onBlur, pressed] + [focusTarget, onBlur] ); const handleHoverIn: NonNullable = React.useCallback( (event) => { - hovered.value = true; + setHovered(true); onHoverIn?.(event); }, - [hovered, onHoverIn] + [onHoverIn] ); const handleHoverOut: NonNullable = React.useCallback( (event) => { - hovered.value = false; + setHovered(false); onHoverOut?.(event); }, - [hovered, onHoverOut] + [onHoverOut] ); const layers = ( @@ -772,9 +682,9 @@ const Card = ({ shapeStyle, { backgroundColor: visuals.stateLayerColor, + opacity: visuals.stateLayerOpacity, }, stateLayerTransitionStyle, - stateLayerAnimatedStyle, ]} /> {content} @@ -784,9 +694,12 @@ const Card = ({ style={[ StyleSheet.absoluteFill, shapeStyle, - { borderWidth: visuals.outlineWidth }, + { + borderWidth: visuals.outlineWidth, + borderColor: visuals.outlineColor, + opacity: visuals.outlineOpacity, + }, outlineTransitionStyle, - outlineAnimatedStyle, ]} /> ) : null} @@ -807,7 +720,7 @@ const Card = ({ backgroundColor="transparent" style={[style, ...focusRing.style]} theme={theme} - elevation={interactiveElevation} + elevation={visuals.elevation} transitionDuration={transitionDuration} {...(!hasPassedTouchHandler && neutralAccessibilityProps)} onFocus={!hasPassedTouchHandler ? onFocus : undefined} diff --git a/src/components/Surface.tsx b/src/components/Surface.tsx index 00b7735e94..d1a4e07e99 100644 --- a/src/components/Surface.tsx +++ b/src/components/Surface.tsx @@ -5,7 +5,6 @@ import type { ColorValue, StyleProp, ViewProps, ViewStyle } from 'react-native'; import Animated, { cubicBezier, isSharedValue, - type SharedValue, type AnimatedStyle, type CSSTransitionTimingFunction, useAnimatedStyle, @@ -132,9 +131,8 @@ export type Props = Omit & * * Note: In version 2 the `elevation` prop was accepted via `style` prop i.e. `style={{ elevation: 4 }}`. * It's no longer supported with theme version 3 and you should use `elevation` property instead. - * A Reanimated shared value can drive elevation without a React render. */ - elevation?: Elevation | SharedValue; + elevation?: Elevation; /** * @supported Available in v5.x with theme version 3 * Mode of the Surface. @@ -157,12 +155,6 @@ export type Props = Omit & ref?: React.Ref>; }; -type StaticSurfaceProps = Omit & { - elevation?: Elevation; - animatedSurfaceStyle?: AnimatedStyle; - animatedAmbientStyle?: AnimatedStyle; -}; - /** * Surface is a basic container that can give depth to an element with elevation shadow. * @@ -194,7 +186,7 @@ type StaticSurfaceProps = Omit & { * }); * ``` */ -const StaticSurface = ({ +const Surface = ({ elevation = 1, children, theme: overriddenTheme, @@ -219,11 +211,9 @@ const StaticSurface = ({ transitionDuration: customTransitionDuration, shapeTransitionDuration, shapeTransitionTimingFunction, - animatedSurfaceStyle, - animatedAmbientStyle, ref, ...rest -}: StaticSurfaceProps) => { +}: Props) => { const theme = useInternalTheme(overriddenTheme); const reduceMotion = useReduceMotion(); @@ -326,7 +316,6 @@ const StaticSurface = ({ visualStyle, ...radiusStyles, isElevated ? elevationShadow : null, - ...(animatedSurfaceStyle ? [animatedSurfaceStyle] : []), ]} > {children} @@ -354,7 +343,6 @@ const StaticSurface = ({ visualStyle, ...radiusStyles, isElevated && { elevation: elevationAndroid }, - ...(animatedSurfaceStyle ? [animatedSurfaceStyle] : []), ]} > {children} @@ -382,7 +370,6 @@ const StaticSurface = ({ visualStyle, ...radiusStyles, isElevated && spotShadow, - ...(animatedSurfaceStyle ? [animatedSurfaceStyle] : []), ]} testID={testID} > @@ -397,7 +384,6 @@ const StaticSurface = ({ shadowVisualStyle, ...radiusStyles, ambientShadow, - ...(animatedAmbientStyle ? [animatedAmbientStyle] : []), ]} /> ) : null} @@ -406,71 +392,6 @@ const StaticSurface = ({ ); }; -const AnimatedElevationSurface = ({ - elevation, - theme: themeOverrides, - backgroundColor: customBackgroundColor, - mode = 'elevated', - ...rest -}: Props & { elevation: SharedValue }) => { - const theme = useInternalTheme(themeOverrides); - const elevationShadows = React.useMemo( - () => - ([0, 1, 2, 3, 4, 5] as const).map((level) => - shadow(level, theme.colors.shadow) - ), - [theme.colors.shadow] - ); - const animatedSurfaceStyle = useAnimatedStyle(() => { - const level = elevation.value; - const backgroundStyle = - customBackgroundColor == null - ? { backgroundColor: theme.colors.elevation?.[`level${level}`] } - : {}; - - if (mode === 'flat') { - return backgroundStyle; - } - if (Platform.OS === 'android') { - return { - ...backgroundStyle, - elevation: androidElevationLevels[level], - }; - } - - return { ...backgroundStyle, ...elevationShadows[level][0] }; - }, [customBackgroundColor, elevation, elevationShadows, mode, theme.colors]); - const animatedAmbientStyle = useAnimatedStyle(() => { - if (mode === 'flat') { - return {}; - } - - return elevationShadows[elevation.value][1] ?? {}; - }, [elevation, elevationShadows, mode]); - - return ( - - ); -}; - -const Surface = (props: Props) => { - const elevation = props.elevation ?? 1; - - return isSharedValue(elevation) ? ( - - ) : ( - - ); -}; - const useSurfaceVisualStyle = ({ borderRadius, borderBottomEndRadius, diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index fb568c081d..5ff21e42d4 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -36,15 +36,6 @@ exports[`Card applies the medium shape and asymmetric overrides across the shell "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -92,15 +83,6 @@ exports[`Card applies the medium shape and asymmetric overrides across the shell "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -173,11 +155,9 @@ exports[`Card applies the medium shape and asymmetric overrides across the shell }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -213,14 +193,12 @@ exports[`Card applies the medium shape and asymmetric overrides across the shell "borderTopLeftRadius": 4, "borderTopRightRadius": 8, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -255,15 +233,6 @@ exports[`Card does not render an outline for the elevated variant 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -311,15 +280,6 @@ exports[`Card does not render an outline for the elevated variant 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -389,11 +349,9 @@ exports[`Card does not render an outline for the elevated variant 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -449,15 +407,6 @@ exports[`Card does not render an outline for the filled variant 1`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -505,15 +454,6 @@ exports[`Card does not render an outline for the filled variant 1`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -574,11 +514,9 @@ exports[`Card does not render an outline for the filled variant 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -634,15 +572,6 @@ exports[`Card keeps the ripple, visual layers, and focus indicator on the Card s "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -690,15 +619,6 @@ exports[`Card keeps the ripple, visual layers, and focus indicator on the Card s "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -805,11 +725,9 @@ exports[`Card keeps the ripple, visual layers, and focus indicator on the Card s }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -855,9 +773,6 @@ exports[`Card lets only elevated Cards customize their resting elevation 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 12, }, @@ -921,11 +836,9 @@ exports[`Card lets only elevated Cards customize their resting elevation 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -983,9 +896,6 @@ exports[`Card renders keyboard focus feedback for the elevated variant 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", - }, { "boxShadow": "0px 0.55px 1.57px rgba(0, 0, 0, 0.19), 0px 0px 0.5px rgba(0, 0, 0, 0.039)", }, @@ -1085,11 +995,9 @@ exports[`Card renders keyboard focus feedback for the elevated variant 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -1149,9 +1057,6 @@ exports[`Card renders keyboard focus feedback for the filled variant 1`] = ` { "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", }, - { - "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", - }, ] } > @@ -1248,11 +1153,9 @@ exports[`Card renders keyboard focus feedback for the filled variant 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -1312,9 +1215,6 @@ exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` { "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", }, - { - "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", - }, ] } > @@ -1411,11 +1311,9 @@ exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -1447,13 +1345,11 @@ exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` "borderRadius": 12, }, { + "borderColor": "rgba(29, 27, 32, 1)", "borderWidth": 1, - }, - {}, - { - "borderColor": "rgba(202, 196, 208, 1)", "opacity": 1, }, + {}, ] } /> @@ -1497,15 +1393,6 @@ exports[`Card renders omitted slots as a neutral filled grouping container 1`] = "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -1553,15 +1440,6 @@ exports[`Card renders omitted slots as a neutral filled grouping container 1`] = "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -1622,11 +1500,9 @@ exports[`Card renders omitted slots as a neutral filled grouping container 1`] = }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -1673,9 +1549,6 @@ exports[`Card renders the Material disabled treatment for elevated Cards 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 1, }, @@ -1772,11 +1645,9 @@ exports[`Card renders the Material disabled treatment for elevated Cards 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -1825,9 +1696,6 @@ exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -1921,11 +1789,9 @@ exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -1974,9 +1840,6 @@ exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -2072,11 +1935,9 @@ exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -2107,14 +1968,12 @@ exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(121, 116, 126, 1)", + "borderWidth": 1, "opacity": 0.12, }, + {}, ] } /> @@ -2149,9 +2008,6 @@ exports[`Card renders the consumer-controlled elevated dragged presentation 1`] "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 8, }, @@ -2215,11 +2071,9 @@ exports[`Card renders the consumer-controlled elevated dragged presentation 1`] }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0.16, }, + {}, ] } /> @@ -2266,9 +2120,6 @@ exports[`Card renders the consumer-controlled filled dragged presentation 1`] = "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 6, }, @@ -2332,11 +2183,9 @@ exports[`Card renders the consumer-controlled filled dragged presentation 1`] = }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0.16, }, + {}, ] } /> @@ -2383,9 +2232,6 @@ exports[`Card renders the consumer-controlled outlined dragged presentation 1`] "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 6, }, @@ -2449,11 +2295,9 @@ exports[`Card renders the consumer-controlled outlined dragged presentation 1`] }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0.16, }, + {}, ] } /> @@ -2485,14 +2329,12 @@ exports[`Card renders the consumer-controlled outlined dragged presentation 1`] "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -2527,15 +2369,6 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 1 "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -2583,15 +2416,6 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 1 "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -2661,11 +2485,9 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 1 }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -2712,15 +2534,6 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 2 "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -2768,15 +2581,6 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 2 "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -2846,11 +2650,9 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 2 }, { "backgroundColor": "rgba(230, 224, 233, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -2897,9 +2699,6 @@ exports[`Card renders the enabled elevated elevation 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 1, }, @@ -2963,11 +2762,9 @@ exports[`Card renders the enabled elevated elevation 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -3023,15 +2820,6 @@ exports[`Card renders the enabled filled appearance in light and dark themes 1`] "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -3079,15 +2867,6 @@ exports[`Card renders the enabled filled appearance in light and dark themes 1`] "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -3148,11 +2927,9 @@ exports[`Card renders the enabled filled appearance in light and dark themes 1`] }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -3208,15 +2985,6 @@ exports[`Card renders the enabled filled appearance in light and dark themes 2`] "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -3264,15 +3032,6 @@ exports[`Card renders the enabled filled appearance in light and dark themes 2`] "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -3333,11 +3092,9 @@ exports[`Card renders the enabled filled appearance in light and dark themes 2`] }, { "backgroundColor": "rgba(230, 224, 233, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -3387,9 +3144,6 @@ exports[`Card renders the enabled filled elevation 1`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -3450,11 +3204,9 @@ exports[`Card renders the enabled filled elevation 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -3510,15 +3262,6 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 1 "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -3566,15 +3309,6 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 1 "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -3635,11 +3369,9 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 1 }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -3671,14 +3403,12 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 1 "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -3722,15 +3452,6 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 2 "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -3778,15 +3499,6 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 2 "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -3847,11 +3559,9 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 2 }, { "backgroundColor": "rgba(230, 224, 233, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -3883,14 +3593,12 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 2 "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(73, 69, 79, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -3928,9 +3636,6 @@ exports[`Card renders the enabled outlined elevation 1`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -3991,11 +3696,9 @@ exports[`Card renders the enabled outlined elevation 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -4027,14 +3730,12 @@ exports[`Card renders the enabled outlined elevation 1`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -4078,15 +3779,6 @@ exports[`Card renders the enabled outlined role in light and dark themes 1`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -4134,15 +3826,6 @@ exports[`Card renders the enabled outlined role in light and dark themes 1`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -4203,11 +3886,9 @@ exports[`Card renders the enabled outlined role in light and dark themes 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -4239,14 +3920,12 @@ exports[`Card renders the enabled outlined role in light and dark themes 1`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -4290,15 +3969,6 @@ exports[`Card renders the enabled outlined role in light and dark themes 2`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -4346,15 +4016,6 @@ exports[`Card renders the enabled outlined role in light and dark themes 2`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -4415,11 +4076,9 @@ exports[`Card renders the enabled outlined role in light and dark themes 2`] = ` }, { "backgroundColor": "rgba(230, 224, 233, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -4451,14 +4110,12 @@ exports[`Card renders the enabled outlined role in light and dark themes 2`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(73, 69, 79, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -4499,9 +4156,6 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 6, }, @@ -4599,11 +4253,9 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0.16, }, + {}, ] } /> @@ -4634,14 +4286,12 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -4679,9 +4329,6 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered { "elevation": 0, }, - { - "elevation": 6, - }, ] } > @@ -4777,11 +4424,9 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0, }, {}, - { - "opacity": 0.16, - }, ] } /> @@ -4813,13 +4458,11 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered "borderRadius": 12, }, { + "borderColor": "rgba(121, 116, 126, 1)", "borderWidth": 1, + "opacity": 0.12, }, {}, - { - "borderColor": "rgba(202, 196, 208, 1)", - "opacity": 1, - }, ] } /> @@ -4863,15 +4506,6 @@ exports[`Card routes whole-Card accessibility semantics and callbacks to its tar "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -4919,15 +4553,6 @@ exports[`Card routes whole-Card accessibility semantics and callbacks to its tar "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -5036,11 +4661,9 @@ exports[`Card routes whole-Card accessibility semantics and callbacks to its tar }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -5087,10 +4710,7 @@ exports[`Card settles rapid changes at the latest complete visual state 1`] = ` "borderTopStartRadius": undefined, }, { - "elevation": 0, - }, - { - "elevation": 0, + "elevation": 1, }, ] } @@ -5186,11 +4806,9 @@ exports[`Card settles rapid changes at the latest complete visual state 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.08, }, {}, - { - "opacity": 0, - }, ] } /> @@ -5221,14 +4839,12 @@ exports[`Card settles rapid changes at the latest complete visual state 1`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -5272,15 +4888,6 @@ exports[`Card settles transitions immediately when reduced motion is enabled 1`] "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -5328,15 +4935,6 @@ exports[`Card settles transitions immediately when reduced motion is enabled 1`] "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -5431,11 +5029,9 @@ exports[`Card settles transitions immediately when reduced motion is enabled 1`] }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -5467,13 +5063,11 @@ exports[`Card settles transitions immediately when reduced motion is enabled 1`] "borderRadius": 12, }, { + "borderColor": "rgba(202, 196, 208, 1)", "borderWidth": 1, + "opacity": 1, }, {}, - { - "borderColor": "rgba(202, 196, 208, 1)", - "opacity": 1, - }, ] } /> @@ -5509,10 +5103,7 @@ exports[`Card shows and clears the elevated hover feedback 1`] = ` "borderTopStartRadius": undefined, }, { - "elevation": 0, - }, - { - "elevation": 1, + "elevation": 3, }, ] } @@ -5608,11 +5199,9 @@ exports[`Card shows and clears the elevated hover feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.08, }, {}, - { - "opacity": 0, - }, ] } /> @@ -5658,9 +5247,6 @@ exports[`Card shows and clears the elevated hover feedback 2`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 1, }, @@ -5758,11 +5344,9 @@ exports[`Card shows and clears the elevated hover feedback 2`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -5808,9 +5392,6 @@ exports[`Card shows and clears the elevated pressed feedback 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 1, }, @@ -5908,11 +5489,9 @@ exports[`Card shows and clears the elevated pressed feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -5958,9 +5537,6 @@ exports[`Card shows and clears the elevated pressed feedback 2`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "elevation": 0, - }, { "elevation": 1, }, @@ -6058,11 +5634,9 @@ exports[`Card shows and clears the elevated pressed feedback 2`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -6109,10 +5683,7 @@ exports[`Card shows and clears the filled hover feedback 1`] = ` "borderTopStartRadius": undefined, }, { - "elevation": 0, - }, - { - "elevation": 0, + "elevation": 1, }, ] } @@ -6208,11 +5779,9 @@ exports[`Card shows and clears the filled hover feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.08, }, {}, - { - "opacity": 0, - }, ] } /> @@ -6261,9 +5830,6 @@ exports[`Card shows and clears the filled hover feedback 2`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -6358,11 +5924,9 @@ exports[`Card shows and clears the filled hover feedback 2`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -6411,9 +5975,6 @@ exports[`Card shows and clears the filled pressed feedback 1`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -6508,11 +6069,9 @@ exports[`Card shows and clears the filled pressed feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -6561,9 +6120,6 @@ exports[`Card shows and clears the filled pressed feedback 2`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -6658,11 +6214,9 @@ exports[`Card shows and clears the filled pressed feedback 2`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -6709,10 +6263,7 @@ exports[`Card shows and clears the outlined hover feedback 1`] = ` "borderTopStartRadius": undefined, }, { - "elevation": 0, - }, - { - "elevation": 0, + "elevation": 1, }, ] } @@ -6808,11 +6359,9 @@ exports[`Card shows and clears the outlined hover feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.08, }, {}, - { - "opacity": 0, - }, ] } /> @@ -6843,14 +6392,12 @@ exports[`Card shows and clears the outlined hover feedback 1`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -6888,9 +6435,6 @@ exports[`Card shows and clears the outlined hover feedback 2`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -6985,11 +6529,9 @@ exports[`Card shows and clears the outlined hover feedback 2`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -7020,14 +6562,12 @@ exports[`Card shows and clears the outlined hover feedback 2`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -7065,9 +6605,6 @@ exports[`Card shows and clears the outlined pressed feedback 1`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -7162,11 +6699,9 @@ exports[`Card shows and clears the outlined pressed feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -7197,14 +6732,12 @@ exports[`Card shows and clears the outlined pressed feedback 1`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -7242,9 +6775,6 @@ exports[`Card shows and clears the outlined pressed feedback 2`] = ` { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -7339,11 +6869,9 @@ exports[`Card shows and clears the outlined pressed feedback 2`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -7374,14 +6902,12 @@ exports[`Card shows and clears the outlined pressed feedback 2`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -7430,9 +6956,6 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it { "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", }, - { - "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", - }, ] } > @@ -7529,11 +7052,9 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -7564,14 +7085,12 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -7620,9 +7139,6 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it { "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", }, - { - "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", - }, ] } > @@ -7719,11 +7235,9 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -7755,13 +7269,11 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it "borderRadius": 12, }, { + "borderColor": "rgba(29, 27, 32, 1)", "borderWidth": 1, - }, - {}, - { - "borderColor": "rgba(202, 196, 208, 1)", "opacity": 1, }, + {}, ] } /> @@ -7810,9 +7322,6 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it { "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", }, - { - "boxShadow": "0px 0px 0px rgba(0, 0, 0, 0.19), 0px 0px 0px rgba(0, 0, 0, 0.039)", - }, ] } > @@ -7909,11 +7418,9 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -7944,14 +7451,12 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -7987,10 +7492,7 @@ exports[`Card updates the controlled dragged presentation in both directions 1`] "borderTopStartRadius": undefined, }, { - "elevation": 0, - }, - { - "elevation": 0, + "elevation": 6, }, ] } @@ -8086,11 +7588,9 @@ exports[`Card updates the controlled dragged presentation in both directions 1`] }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.16, }, {}, - { - "opacity": 0, - }, ] } /> @@ -8121,14 +7621,12 @@ exports[`Card updates the controlled dragged presentation in both directions 1`] "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -8166,9 +7664,6 @@ exports[`Card updates the controlled dragged presentation in both directions 2`] { "elevation": 0, }, - { - "elevation": 0, - }, ] } > @@ -8263,11 +7758,9 @@ exports[`Card updates the controlled dragged presentation in both directions 2`] }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -8298,14 +7791,12 @@ exports[`Card updates the controlled dragged presentation in both directions 2`] "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -8340,15 +7831,6 @@ exports[`Card uses custom theme roles for elevated and outlined variants 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -8396,15 +7878,6 @@ exports[`Card uses custom theme roles for elevated and outlined variants 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { @@ -8474,11 +7947,9 @@ exports[`Card uses custom theme roles for elevated and outlined variants 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -8534,15 +8005,6 @@ exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -8590,15 +8052,6 @@ exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -8659,11 +8112,9 @@ exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -8695,14 +8146,12 @@ exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "#654321", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -8746,15 +8195,6 @@ exports[`Card uses filled as the default and resolves deeply merged custom color "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -8802,15 +8242,6 @@ exports[`Card uses filled as the default and resolves deeply merged custom color "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -8871,11 +8302,9 @@ exports[`Card uses filled as the default and resolves deeply merged custom color }, { "backgroundColor": "#222222", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -8937,15 +8366,6 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -8993,15 +8413,6 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -9096,11 +8507,9 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.1, }, {}, - { - "opacity": 0, - }, ] } /> @@ -9132,13 +8541,11 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "borderRadius": 12, }, { + "borderColor": "rgba(29, 27, 32, 1)", "borderWidth": 1, - }, - {}, - { - "borderColor": "rgba(202, 196, 208, 1)", "opacity": 1, }, + {}, ] } /> @@ -9176,20 +8583,11 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the { "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, + "height": 0.55, "width": 0, }, - "shadowOpacity": 0, - "shadowRadius": 0, + "shadowOpacity": 0.19, + "shadowRadius": 0.79, }, ] } @@ -9235,17 +8633,8 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "height": 0, "width": 0, }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, + "shadowOpacity": 0.039, + "shadowRadius": 0.25, }, ] } @@ -9341,11 +8730,9 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the }, { "backgroundColor": "rgba(29, 27, 32, 1)", + "opacity": 0.08, }, {}, - { - "opacity": 0, - }, ] } /> @@ -9376,14 +8763,12 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -9427,15 +8812,6 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -9483,15 +8859,6 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -9586,11 +8953,9 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -9621,14 +8986,12 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "borderCurve": "continuous", "borderRadius": 12, }, - { - "borderWidth": 1, - }, - {}, { "borderColor": "rgba(202, 196, 208, 1)", + "borderWidth": 1, "opacity": 1, }, + {}, ] } /> @@ -9672,15 +9035,6 @@ exports[`Card uses scaled theme motion duration and easing for visual transition "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -9728,15 +9082,6 @@ exports[`Card uses scaled theme motion duration and easing for visual transition "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -9831,11 +9176,9 @@ exports[`Card uses scaled theme motion duration and easing for visual transition }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -9890,15 +9233,6 @@ exports[`Card uses scaled theme motion duration and easing for visual transition "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -9946,15 +9280,6 @@ exports[`Card uses scaled theme motion duration and easing for visual transition "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -10048,11 +9373,9 @@ exports[`Card uses scaled theme motion duration and easing for visual transition }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> @@ -10107,15 +9430,6 @@ exports[`CardCover uses the Card clipping shape for edge media without double ro "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } > @@ -10163,15 +9477,6 @@ exports[`CardCover uses the Card clipping shape for edge media without double ro "shadowOpacity": 0, "shadowRadius": 0, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, ] } /> @@ -10244,11 +9549,9 @@ exports[`CardCover uses the Card clipping shape for edge media without double ro }, { "backgroundColor": "rgba(29, 27, 32, 1)", - }, - {}, - { "opacity": 0, }, + {}, ] } /> diff --git a/src/components/__tests__/Surface.test.tsx b/src/components/__tests__/Surface.test.tsx index 8416d1d34e..cb568ad767 100644 --- a/src/components/__tests__/Surface.test.tsx +++ b/src/components/__tests__/Surface.test.tsx @@ -23,7 +23,6 @@ import { import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; import { LightTheme } from '../../theme/schemes'; -import type { Elevation } from '../../theme/types'; import Surface from '../Surface'; const SPOT_SHADOW_OPACITY = 0.19; @@ -71,24 +70,6 @@ const AnimatedVisualSurface = () => { ); }; -const SharedElevationSurface = () => { - const elevation = useSharedValue(0); - - return ( - <> - { - elevation.value = 2; - }} - /> - - {null} - - - ); -}; - afterEach(() => { jest.restoreAllMocks(); }); @@ -248,24 +229,6 @@ describe('Surface', () => { }); }); - it('updates shared elevation without rerendering the Surface', async () => { - await render(); - const surface = screen.getByTestId('shared-elevation-surface'); - - expect(getAnimatedStyle(surface)).toMatchObject({ - backgroundColor: LightTheme.colors.elevation.level0, - elevation: 0, - }); - - await userEvent.press(screen.getByTestId('raise-surface')); - await jest.runAllTimersAsync(); - - expect(getAnimatedStyle(surface)).toMatchObject({ - backgroundColor: LightTheme.colors.elevation.level2, - elevation: 3, - }); - }); - it('does not transition a PlatformColor background', async () => { await render( Date: Wed, 18 Nov 2026 09:22:01 +0100 Subject: [PATCH 19/51] fix(card): draw the pressed state layer once TouchableRipple already draws a 10% onSurface pressed layer (the ripple on Android, the underlay elsewhere), and the Card state layer added a second one. Card now skips its own pressed layer and keeps the pressed elevation and outline tokens. The token matrix still lists the spec value. --- src/components/Card/Card.tsx | 6 +++++- .../__tests__/Card/__snapshots__/Card.test.tsx.snap | 8 ++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index dcb3aa9c29..9116f4a04a 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -463,6 +463,10 @@ const Card = ({ ? 0 : theme.motion.duration.short3 * theme.animation.scale; const transitionTimingFunction = cubicBezier(...theme.motion.easing.standard); + // TouchableRipple already draws the pressed state layer (the ripple on + // Android, the underlay elsewhere), so a second one would double it. + const stateLayerOpacity = + visuals.state === 'pressed' ? 0 : visuals.stateLayerOpacity; const stateLayerTransitionStyle: AnimatedStyle = { transitionProperty: 'opacity', transitionDuration, @@ -682,7 +686,7 @@ const Card = ({ shapeStyle, { backgroundColor: visuals.stateLayerColor, - opacity: visuals.stateLayerOpacity, + opacity: stateLayerOpacity, }, stateLayerTransitionStyle, ]} diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index 5ff21e42d4..59aeb16d97 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -5029,7 +5029,7 @@ exports[`Card settles transitions immediately when reduced motion is enabled 1`] }, { "backgroundColor": "rgba(29, 27, 32, 1)", - "opacity": 0.1, + "opacity": 0, }, {}, ] @@ -5489,7 +5489,7 @@ exports[`Card shows and clears the elevated pressed feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - "opacity": 0.1, + "opacity": 0, }, {}, ] @@ -6069,7 +6069,7 @@ exports[`Card shows and clears the filled pressed feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - "opacity": 0.1, + "opacity": 0, }, {}, ] @@ -6699,7 +6699,7 @@ exports[`Card shows and clears the outlined pressed feedback 1`] = ` }, { "backgroundColor": "rgba(29, 27, 32, 1)", - "opacity": 0.1, + "opacity": 0, }, {}, ] From 59ae8fa9e567ea5c40441a550adb3c2d244ee745 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:22:33 +0100 Subject: [PATCH 20/51] fix(card): draw the state layer over the slot content The state layer rendered before the slots, so media painted over it and hover, focus and dragged feedback skipped the image. It now renders after the content, as Material draws state layers over the whole component. It already ignores pointer events. --- src/components/Card/Card.tsx | 3 +- .../Card/__snapshots__/Card.test.tsx.snap | 1350 ++++++++--------- 2 files changed, 677 insertions(+), 676 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 9116f4a04a..030e55cc4b 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -679,6 +679,8 @@ const Card = ({ }, ]} /> + {content} + {/* Material draws state layers over the whole Card, media included. */} - {content} {visuals.outlineWidth > 0 ? ( + - + - `; @@ -496,6 +496,18 @@ exports[`Card does not render an outline for the filled variant 1`] = ` ] } /> + - `; @@ -703,6 +703,17 @@ exports[`Card keeps the ripple, visual layers, and focus indicator on the Card s ] } /> + - `; @@ -818,6 +818,18 @@ exports[`Card lets only elevated Cards customize their resting elevation 1`] = ` ] } /> + - `; @@ -977,6 +977,17 @@ exports[`Card renders keyboard focus feedback for the elevated variant 1`] = ` ] } /> + - `; @@ -1135,6 +1135,17 @@ exports[`Card renders keyboard focus feedback for the filled variant 1`] = ` ] } /> + - `; @@ -1293,6 +1293,17 @@ exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` ] } /> + - + - `; @@ -1627,6 +1627,17 @@ exports[`Card renders the Material disabled treatment for elevated Cards 1`] = ` ] } /> + - `; @@ -1771,6 +1771,17 @@ exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` ] } /> + - `; @@ -1918,13 +1918,24 @@ exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` } /> + - + - `; @@ -2165,6 +2165,18 @@ exports[`Card renders the consumer-controlled filled dragged presentation 1`] = ] } /> + - `; @@ -2277,6 +2277,18 @@ exports[`Card renders the consumer-controlled outlined dragged presentation 1`] ] } /> + - + - `; @@ -2632,6 +2632,18 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 2 ] } /> + - `; @@ -2744,6 +2744,18 @@ exports[`Card renders the enabled elevated elevation 1`] = ` ] } /> + - `; @@ -2909,6 +2909,18 @@ exports[`Card renders the enabled filled appearance in light and dark themes 1`] ] } /> + - `; @@ -3074,6 +3074,18 @@ exports[`Card renders the enabled filled appearance in light and dark themes 2`] ] } /> + - `; @@ -3186,6 +3186,18 @@ exports[`Card renders the enabled filled elevation 1`] = ` ] } /> + - `; @@ -3351,6 +3351,18 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 1 ] } /> + - + - + - + - + - + - + - + - `; @@ -4788,6 +4788,17 @@ exports[`Card settles rapid changes at the latest complete visual state 1`] = ` ] } /> + - + - + - `; @@ -5326,6 +5326,17 @@ exports[`Card shows and clears the elevated hover feedback 2`] = ` ] } /> + - `; @@ -5471,6 +5471,17 @@ exports[`Card shows and clears the elevated pressed feedback 1`] = ` ] } /> + - `; @@ -5616,6 +5616,17 @@ exports[`Card shows and clears the elevated pressed feedback 2`] = ` ] } /> + - `; @@ -5761,6 +5761,17 @@ exports[`Card shows and clears the filled hover feedback 1`] = ` ] } /> + - @@ -5906,6 +5906,17 @@ exports[`Card shows and clears the filled hover feedback 2`] = ` ] } /> + - `; @@ -6051,6 +6051,17 @@ exports[`Card shows and clears the filled pressed feedback 1`] = ` ] } /> + - `; @@ -6196,6 +6196,17 @@ exports[`Card shows and clears the filled pressed feedback 2`] = ` ] } /> + - `; @@ -6341,6 +6341,17 @@ exports[`Card shows and clears the outlined hover feedback 1`] = ` ] } /> + - + - + - + - + - + - + - + - + @@ -7764,17 +7775,6 @@ exports[`Card updates the controlled dragged presentation in both directions 2`] ] } /> - + - `; @@ -8094,6 +8094,18 @@ exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` ] } /> + - + - `; @@ -8489,6 +8489,17 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the ] } /> + - + - + - + - `; @@ -9355,6 +9355,17 @@ exports[`Card uses scaled theme motion duration and easing for visual transition ] } /> + - `; @@ -9527,34 +9527,6 @@ exports[`CardCover uses the Card clipping shape for edge media without double ro ] } /> - + `; From 6eeacd3dd086fb3593bc69d8fd2ad2b80029182f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:23:23 +0100 Subject: [PATCH 21/51] fix(card): dim the content of a disabled Card A disabled Card dimmed only its container or outline, so a disabled outlined Card looked like an enabled one with a fainter border. resolveCardVisuals now returns contentOpacity, the disabled state opacity (0.38) for a disabled Card, like Compose's disabledContentColor, and Card applies it to the slot content. --- src/components/Card/Card.tsx | 6 +- src/components/Card/tokens.ts | 2 + src/components/__tests__/Card/Card.test.tsx | 12 ++ .../__tests__/Card/Card.tokens.test.ts | 1 + .../Card/__snapshots__/Card.test.tsx.snap | 171 ++++++++++++++++++ 5 files changed, 191 insertions(+), 1 deletion(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 030e55cc4b..1227502a19 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -543,7 +543,11 @@ const Card = ({ const content = ( {media} diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index a1212c3ae1..5bc3072278 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -280,5 +280,7 @@ export const resolveCardVisuals = ({ shape: theme.shapes.corner.medium, stateLayerColor: theme.colors.onSurface, stateLayerOpacity: stateTokens.stateLayerOpacity, + // Compose dims disabled Card content to the content color at 38%. + contentOpacity: state === 'disabled' ? opacity.disabled : 1, }; }; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index f59c94d905..fa4ab5ecaa 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -852,6 +852,18 @@ describe('Card', () => { expect(onAccessibilityAction).not.toHaveBeenCalled(); }); + it('dims the slot content of a disabled Card', async () => { + const { rerender } = await render( + Body} /> + ); + + expect(screen.getByTestId('card')).toHaveStyle({ opacity: 0.38 }); + + await rerender(Body} />); + + expect(screen.getByTestId('card')).toHaveStyle({ opacity: 1 }); + }); + it('exposes disabled state on an explicitly semantic neutral Card', async () => { await render(); diff --git a/src/components/__tests__/Card/Card.tokens.test.ts b/src/components/__tests__/Card/Card.tokens.test.ts index c830d9c27a..d13930e054 100644 --- a/src/components/__tests__/Card/Card.tokens.test.ts +++ b/src/components/__tests__/Card/Card.tokens.test.ts @@ -188,6 +188,7 @@ describe('resolveCardVisuals', () => { shape: theme.shapes.corner.medium, stateLayerColor: theme.colors.onSurface, stateLayerOpacity, + contentOpacity: cardStates[index] === 'disabled' ? 0.38 : 1, }) ) ); diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index 3d036a3067..5cb4da2006 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -140,6 +140,9 @@ exports[`Card applies the medium shape and asymmetric overrides across the shell "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -338,6 +341,9 @@ exports[`Card does not render an outline for the elevated variant 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -503,6 +509,9 @@ exports[`Card does not render an outline for the filled variant 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -710,6 +719,9 @@ exports[`Card keeps the ripple, visual layers, and focus indicator on the Card s "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -825,6 +837,9 @@ exports[`Card lets only elevated Cards customize their resting elevation 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -984,6 +999,9 @@ exports[`Card renders keyboard focus feedback for the elevated variant 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -1142,6 +1160,9 @@ exports[`Card renders keyboard focus feedback for the filled variant 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -1300,6 +1321,9 @@ exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -1489,6 +1513,9 @@ exports[`Card renders omitted slots as a neutral filled grouping container 1`] = "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -1634,6 +1661,9 @@ exports[`Card renders the Material disabled treatment for elevated Cards 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 0.38, + }, undefined, ] } @@ -1778,6 +1808,9 @@ exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 0.38, + }, undefined, ] } @@ -1924,6 +1957,9 @@ exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 0.38, + }, undefined, ] } @@ -2060,6 +2096,9 @@ exports[`Card renders the consumer-controlled elevated dragged presentation 1`] "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -2172,6 +2211,9 @@ exports[`Card renders the consumer-controlled filled dragged presentation 1`] = "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -2284,6 +2326,9 @@ exports[`Card renders the consumer-controlled outlined dragged presentation 1`] "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -2474,6 +2519,9 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 1 "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -2639,6 +2687,9 @@ exports[`Card renders the enabled elevated appearance in light and dark themes 2 "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -2751,6 +2802,9 @@ exports[`Card renders the enabled elevated elevation 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -2916,6 +2970,9 @@ exports[`Card renders the enabled filled appearance in light and dark themes 1`] "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -3081,6 +3138,9 @@ exports[`Card renders the enabled filled appearance in light and dark themes 2`] "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -3193,6 +3253,9 @@ exports[`Card renders the enabled filled elevation 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -3358,6 +3421,9 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 1 "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -3548,6 +3614,9 @@ exports[`Card renders the enabled outlined appearance in light and dark themes 2 "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -3685,6 +3754,9 @@ exports[`Card renders the enabled outlined elevation 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -3875,6 +3947,9 @@ exports[`Card renders the enabled outlined role in light and dark themes 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -4065,6 +4140,9 @@ exports[`Card renders the enabled outlined role in light and dark themes 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -4242,6 +4320,9 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -4413,6 +4494,9 @@ exports[`Card resolves disabled and dragged before pressed, focused, and hovered "flexShrink": 1, "position": "relative", }, + { + "opacity": 0.38, + }, undefined, ] } @@ -4650,6 +4734,9 @@ exports[`Card routes whole-Card accessibility semantics and callbacks to its tar "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -4795,6 +4882,9 @@ exports[`Card settles rapid changes at the latest complete visual state 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -5018,6 +5108,9 @@ exports[`Card settles transitions immediately when reduced motion is enabled 1`] "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -5188,6 +5281,9 @@ exports[`Card shows and clears the elevated hover feedback 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -5333,6 +5429,9 @@ exports[`Card shows and clears the elevated hover feedback 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -5478,6 +5577,9 @@ exports[`Card shows and clears the elevated pressed feedback 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -5623,6 +5725,9 @@ exports[`Card shows and clears the elevated pressed feedback 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -5768,6 +5873,9 @@ exports[`Card shows and clears the filled hover feedback 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -5913,6 +6021,9 @@ exports[`Card shows and clears the filled hover feedback 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -6058,6 +6169,9 @@ exports[`Card shows and clears the filled pressed feedback 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -6203,6 +6317,9 @@ exports[`Card shows and clears the filled pressed feedback 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -6348,6 +6465,9 @@ exports[`Card shows and clears the outlined hover feedback 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -6518,6 +6638,9 @@ exports[`Card shows and clears the outlined hover feedback 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -6688,6 +6811,9 @@ exports[`Card shows and clears the outlined pressed feedback 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -6858,6 +6984,9 @@ exports[`Card shows and clears the outlined pressed feedback 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -7041,6 +7170,9 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -7224,6 +7356,9 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -7407,6 +7542,9 @@ exports[`Card shows focus feedback only for keyboard-visible focus and clears it "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -7577,6 +7715,9 @@ exports[`Card updates the controlled dragged presentation in both directions 1`] "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -7747,6 +7888,9 @@ exports[`Card updates the controlled dragged presentation in both directions 2`] "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -7936,6 +8080,9 @@ exports[`Card uses custom theme roles for elevated and outlined variants 1`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -8101,6 +8248,9 @@ exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -8291,6 +8441,9 @@ exports[`Card uses filled as the default and resolves deeply merged custom color "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -8496,6 +8649,9 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -8719,6 +8875,9 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -8942,6 +9101,9 @@ exports[`Card uses pressed, focused, then hovered precedence and settles at the "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -9165,6 +9327,9 @@ exports[`Card uses scaled theme motion duration and easing for visual transition "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } @@ -9362,6 +9527,9 @@ exports[`Card uses scaled theme motion duration and easing for visual transition "flexShrink": 1, "position": "relative", }, + { + "opacity": 0.38, + }, undefined, ] } @@ -9534,6 +9702,9 @@ exports[`CardCover uses the Card clipping shape for edge media without double ro "flexShrink": 1, "position": "relative", }, + { + "opacity": 1, + }, undefined, ] } From 95038c66d06f6e1f7aa68951de02ef468e9ebf70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:24:45 +0100 Subject: [PATCH 22/51] feat(card): restore the borderColor prop for outlined Cards main added borderColor in #5114 to replace the style-derived outline color, and the slot rewrite dropped it. Outlined Cards accept it again; it replaces the theme outline color in every state while the state opacities still apply. The other variants reject it at the type level, like elevation. --- src/components/Card/Card.tsx | 22 +++++++++++++++++---- src/components/__tests__/Card/Card.test.tsx | 21 ++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 1227502a19..66983a6191 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -1,6 +1,7 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { + ColorValue, GestureResponderEvent, StyleProp, ViewProps, @@ -146,6 +147,10 @@ type FilledCardProps = { * Resting elevation. Available only when `variant="elevated"`. */ elevation?: never; + /** + * Outline color. Available only when `variant="outlined"`. + */ + borderColor?: never; }; type ElevatedCardProps = { @@ -157,6 +162,10 @@ type ElevatedCardProps = { * Resting shadow elevation for an elevated Card. */ elevation?: Elevation; + /** + * Outline color. Available only when `variant="outlined"`. + */ + borderColor?: never; }; type OutlinedCardProps = { @@ -168,6 +177,11 @@ type OutlinedCardProps = { * Outlined Cards do not support custom elevation. */ elevation?: never; + /** + * Color of the outline. It replaces the theme color in every state; the + * state opacities still apply, so a disabled outline stays at 12%. + */ + borderColor?: ColorValue; }; type CardVariantProps = FilledCardProps | ElevatedCardProps | OutlinedCardProps; @@ -346,6 +360,7 @@ export type Props = Omit & const Card = ({ variant: cardVariant = 'filled', elevation: customElevation, + borderColor: customBorderColor, delayLongPress, onPress, onLongPress, @@ -467,6 +482,7 @@ const Card = ({ // Android, the underlay elsewhere), so a second one would double it. const stateLayerOpacity = visuals.state === 'pressed' ? 0 : visuals.stateLayerOpacity; + const outlineColor = customBorderColor ?? visuals.outlineColor; const stateLayerTransitionStyle: AnimatedStyle = { transitionProperty: 'opacity', transitionDuration, @@ -475,9 +491,7 @@ const Card = ({ const outlineTransitionStyle: AnimatedStyle = { // A PlatformColor outline cannot be interpolated. transitionProperty: - typeof visuals.outlineColor === 'string' - ? ['borderColor', 'opacity'] - : 'opacity', + typeof outlineColor === 'string' ? ['borderColor', 'opacity'] : 'opacity', transitionDuration, transitionTimingFunction, }; @@ -705,7 +719,7 @@ const Card = ({ shapeStyle, { borderWidth: visuals.outlineWidth, - borderColor: visuals.outlineColor, + borderColor: outlineColor, opacity: visuals.outlineOpacity, }, outlineTransitionStyle, diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index fa4ab5ecaa..6f1420bfb1 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -852,6 +852,20 @@ describe('Card', () => { expect(onAccessibilityAction).not.toHaveBeenCalled(); }); + it('uses a custom outline color in every state', async () => { + const { rerender } = await render( + + ); + + expect(JSON.stringify(screen.toJSON())).toContain('"borderColor":"red"'); + + await rerender( + + ); + + expect(JSON.stringify(screen.toJSON())).toContain('"borderColor":"red"'); + }); + it('dims the slot content of a disabled Card', async () => { const { rerender } = await render( Body} /> @@ -951,6 +965,7 @@ describe('Card types', () => { + {/* @ts-expect-error: Arbitrary children composition was removed. */} @@ -972,6 +987,12 @@ describe('Card types', () => { {/* @ts-expect-error: Outlined Cards cannot be elevated. */} + {/* @ts-expect-error: Only outlined Cards have an outline color. */} + + + {/* @ts-expect-error: Only outlined Cards have an outline color. */} + + {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} } title="Title" /> From 5659f002f0685fca5eb6e35a8c38da95f5f13bbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:25:59 +0100 Subject: [PATCH 23/51] docs(card): merge the Card migration notes into one section Remove main's second Card section, which described the children layout with Card padding, gap and negative margins that the slot Card no longer has. Its outline color and Card.Cover notes move into the slot section, rewritten for variant and aspectRatio. Also document the Card.Content padding change, horizontal layouts through contentStyle in place of direction, and the Button mode rename in the examples. Drop the derived test IDs that Card no longer renders. --- docs/6.x/docs/guides/migration.md | 195 ++++++++++-------------------- 1 file changed, 67 insertions(+), 128 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 6607cbb70a..763d34e197 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -503,11 +503,11 @@ Paper 6 replaces the Card's `mode` and arbitrary-children interfaces with Materi Replace `mode` with `variant`: -| Paper 5 | Paper 6 | -| --- | --- | -| `mode="contained"` | `variant="filled"` | -| `mode="elevated"` | `variant="elevated"` | -| `mode="outlined"` | `variant="outlined"` | +| Paper 5 | Paper 6 | +| ------------------ | -------------------- | +| `mode="contained"` | `variant="filled"` | +| `mode="elevated"` | `variant="elevated"` | +| `mode="outlined"` | `variant="outlined"` | The default also changed. A Paper 5 Card without `mode` was elevated; a Paper 6 Card without `variant` is filled and has no resting shadow. Add `variant="elevated"` if you need to preserve the old default emphasis. The `elevation` prop is accepted only with `variant="elevated"`. @@ -558,9 +558,65 @@ Use `header` when the complete header is custom. It is mutually exclusive with ` `Card.Content`, `Card.Cover`, `Card.Title`, and `Card.Actions` remain available as layout helpers inside the new slots. They are not arbitrary Card children. +#### `Card.Content` padding + +`Card.Content` no longer changes its padding based on its neighbors. In Paper 5 it added top padding only when it came first and bottom padding only when it came last. It now always uses `16dp` on every side. A `Card.Content` followed by `Card.Actions` gets `24dp` between the text and the buttons (`16dp` from `Card.Content` and `8dp` from `Card.Actions`). Override the padding with the `style` prop of `Card.Content` to keep a tighter layout: + +```tsx + + View the itinerary. + + } + actions={ + + + + } +/> +``` + +#### Horizontal layout + +To place the regions in a row, set `flexDirection` in `contentStyle`, which styles the wrapper around the slots: + +```tsx +} + title="Card title" +/> +``` + +#### Outline color + +The `borderColor` in `style` no longer changes the outline color of an outlined Card. Use the `borderColor` prop instead. It is accepted only with `variant="outlined"`: + +```diff + +``` + +#### `Card.Cover` + +Use the `aspectRatio` prop to size a cover responsively. It replaces the default height of `195`: + +```tsx +} /> +``` + +The Card clips media to its shape, so a `Card.Cover` in the `media` slot follows the Card's corners without its own border radius. + #### `Card.Actions` no longer styles its buttons -`Card.Actions` no longer assigns `mode="outlined"` to its first button, `mode="contained"` to the rest, or `compact` to any of them. It only lays its children out in a row; set each `Button`'s `mode` and `compact` explicitly to keep the old look: +`Card.Actions` no longer assigns `mode="outlined"` to its first button, `mode="contained"` (now `mode="filled"`) to the rest, or `compact` to any of them. It only lays its children out in a row; set each `Button`'s `mode` and `compact` explicitly to keep the old look: ```tsx // Before (v5) — Card.Actions styled the buttons automatically @@ -572,7 +628,7 @@ Use `header` when the complete header is custom. It is mutually exclusive with ` // After (v6) — set mode and compact explicitly - + ``` @@ -594,7 +650,9 @@ When buttons or other controls perform independent actions, keep the Card itself actions={ - + } /> @@ -602,7 +660,7 @@ When buttons or other controls perform independent actions, keep the Card itself Paper 6 warns in development if whole-Card interaction handlers and a populated `actions` slot are combined. A neutral Card remains a grouping container unless you provide accessibility semantics explicitly. The `dragged` prop controls the Material dragged presentation only; drag gestures and lifecycle remain application responsibilities. -Card refs and test IDs now target documented nodes: `ref` targets the outer shell, `touchableRef` targets the actionable interaction node, and `testID` targets the interaction node for actionable Cards or the slot-content node for neutral Cards. `${testID}-container` and `${testID}-visual` identify the outer shell and clipped visual region. +Card refs and test IDs now target documented nodes: `ref` targets the outer shell, `touchableRef` targets the actionable interaction node, and `testID` targets the interaction node for actionable Cards or the slot-content node for neutral Cards. ### Surface @@ -1201,125 +1259,6 @@ These need no code change, but the rendering differs: `elevated` and `outlined`, and **12dp** for `text` (**16dp** with an icon). Existing buttons change width. -### Card - -#### `Card` layout - -`Card` and its related components have been reworked. Instead of injecting padding to its children, the `Card` component now adds a padding (`16dp`) around its content as well as a gap (`16dp`) between its children. - -For the related components: - -- `Card.Cover` and `Card.Actions` now apply negative margins to extend into the Card's edges: - - `Card.Cover` applies top, left and right margins for vertical cards and left, top, and bottom margins for horizontal cards. - - `Card.Actions` applies bottom, left, and right margins for vertical cards and left, bottom, and right margins for horizontal cards. -- `Card.Title` and `Card.Content` no longer apply padding around them. - -This means, in a typical card layout, the Card will automatically apply the necessary spacing between these sections: - -```tsx - - - - - Card content - - - - - - -``` - -So your existing layouts with the following structure will continue to work as before: - -- `Card` without `Card.Cover` or `Card.Actions`. -- `Card` with `Card.Cover` at the top and/or `Card.Actions` at the bottom. - -If you have `Card.Cover` or `Card.Actions` in positions other than the top and bottom respectively, you will need to adjust their margins. For example, for a `Card.Cover` in the middle of the Card, you would need to set its top and bottom margins to zero: - -```tsx - - - - - Card content - - -``` - -We have also added a `direction` prop to the `Card` component, which lets you arrange its items horizontally instead of the default vertical layout. So if you have custom `flexDirection` styles on the Card, you should replace them with the `direction` prop. - -```tsx -// Before (v5) - - - - - Card content - - - - - - - -// After (v6) - - - - - Card content - - - - - - -``` - -#### Outline color - -The `borderColor` in `style` no longer changes the outline color in `outlined` mode. Use the `borderColor` prop instead: - -```diff - - ... - -``` - -#### `Card.Cover` - -The `style` prop of `Card.Cover` is now typed as a `View` style. Image style properties such as `resizeMode` or `tintColor` were never applied, so pass them as `Image` props instead: - -```diff -- -+ -``` - -`Card.Cover` no longer applies the border radius from `style` to the image directly. The image is clipped by the container, so any border radius passed in `style` still applies. - -#### `Card.Actions` - -`Card.Actions` no longer injects `mode` on the buttons. To keep the previous behavior, you need to set `mode="outlined"` on the first button and `mode="filled"` (formerly `contained`) on the rest: - -```tsx -// Before (v5) - - - - - -// After (v6) - - - - -``` - ### List #### `List.Accordion` From a9f2d4513c7f0b7aadd166f7b1cb845f7ec6252a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:25:59 +0100 Subject: [PATCH 24/51] docs(card): render the title once in the navigation theming example The Card already receives title, so the Text inside Card.Content rendered it a second time. --- docs/6.x/docs/guides/theming-with-react-navigation.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/6.x/docs/guides/theming-with-react-navigation.md b/docs/6.x/docs/guides/theming-with-react-navigation.md index 31244be5cd..b932b05483 100644 --- a/docs/6.x/docs/guides/theming-with-react-navigation.md +++ b/docs/6.x/docs/guides/theming-with-react-navigation.md @@ -64,7 +64,6 @@ const HomeScreen = ({ navigation }) => ( title={title} content={ - {title} {content} } From 5586f16369db73a05bb29a450016140b2928457a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:33:44 +0100 Subject: [PATCH 25/51] test(card): assert Card visuals directly instead of whole-tree snapshots Most visual tests snapshotted the whole rendered tree, a 9.8k-line file nobody could review that asserted exact internal style values. They now check the layers they are about against resolveCardVisuals through a small helper that reaches the layers from the Card's testID node. One small snapshot per variant remains. The jest/expect-expect override for the snapshot helper is reverted. --- eslint.config.mjs | 5 +- src/components/__tests__/Card/Card.test.tsx | 546 +- .../Card/__snapshots__/Card.test.tsx.snap | 9294 +---------------- 3 files changed, 369 insertions(+), 9476 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index fdea443ae4..04a315a5c5 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -219,10 +219,7 @@ export default defineConfig( }, ], - 'jest/expect-expect': [ - 'error', - { assertFunctionNames: ['expect', 'expectVisualSnapshot'] }, - ], + 'jest/expect-expect': 'error', 'jest/no-commented-out-tests': 'error', 'jest/no-disabled-tests': 'error', 'jest/prefer-importing-jest-globals': 'error', diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 6f1420bfb1..48cc750fd4 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -4,13 +4,17 @@ import type { StyleProp, ViewStyle } from 'react-native'; import { afterEach, describe, expect, it, jest } from '@jest/globals'; import { act } from '@testing-library/react-native'; +import { cubicBezier, getAnimatedStyle } from 'react-native-reanimated'; import { fireEvent, render, screen, userEvent } from '../../../test-utils'; import { ReduceMotionContext } from '../../../theme/accessibility/ReduceMotionContext'; import { DarkTheme, LightTheme } from '../../../theme/schemes'; +import { androidElevationLevels } from '../../../theme/tokens/sys/elevation'; import Button from '../../Button/Button'; import Card from '../../Card/Card'; import type { Props as CardProps } from '../../Card/Card'; +import { resolveCardVisuals } from '../../Card/tokens'; +import type { CardVariant, CardStateFlags } from '../../Card/tokens'; const styles = StyleSheet.create({ contentStyle: { @@ -34,11 +38,81 @@ const getVariantCard = ( return ; }; -// The Card shell, clipped visual region, background, state layer, outline, -// and focus indicator are internal nodes with no public testID. Their -// styles are guarded with a snapshot of the rendered tree instead. -const expectVisualSnapshot = () => { - expect(screen.toJSON()).toMatchSnapshot(); +type Layer = NonNullable['parent']>; + +// The Card's visual layers are internal nodes with no public testID, so they +// are reached from the node that has one. For an actionable Card that is the +// interaction node; for a neutral Card it is the slot content. Either way the +// layers are the children of the clipped visual node, in paint order: +// container, slot content, state layer, then the outline of an outlined Card. +// The Surface that carries the elevation and the focus ring is its parent. +const getCardLayers = ({ neutral = false } = {}) => { + const target = screen.getByTestId('card'); + const visual = neutral ? target.parent : target; + + if (!visual?.parent) { + throw new Error('Card visual node not found'); + } + + const [container, content, stateLayer, outline] = visual.children.filter( + (child): child is Layer => typeof child !== 'string' + ); + + return { + surface: visual.parent, + visual, + container, + content, + stateLayer, + outline, + }; +}; + +// Asserts that every layer shows the Material visuals of one state. The +// values come from the token matrix, which `Card.tokens.test.ts` checks +// against the specification. +const expectCardState = ( + variant: CardVariant, + flags: CardStateFlags = {}, + { theme = LightTheme, neutral = false } = {} +) => { + const visuals = resolveCardVisuals({ theme, variant, ...flags }); + const { surface, container, content, stateLayer, outline } = getCardLayers({ + neutral, + }); + + expect(container).toHaveStyle({ + backgroundColor: visuals.containerColor, + opacity: visuals.containerOpacity, + }); + expect(content).toHaveStyle({ opacity: visuals.contentOpacity }); + // TouchableRipple draws the pressed layer, so Card skips its own. + expect(stateLayer).toHaveStyle({ + backgroundColor: visuals.stateLayerColor, + opacity: visuals.state === 'pressed' ? 0 : visuals.stateLayerOpacity, + }); + + if (variant === 'outlined') { + expect(outline).toHaveStyle({ + borderWidth: 1, + borderColor: visuals.outlineColor, + opacity: visuals.outlineOpacity, + }); + } else { + expect(outline).toBeUndefined(); + } + + if (Platform.OS === 'android') { + expect(surface).toHaveStyle({ + elevation: androidElevationLevels[visuals.elevation], + }); + } +}; + +const settle = async () => { + await act(() => { + jest.runOnlyPendingTimers(); + }); }; afterEach(() => { @@ -47,45 +121,49 @@ afterEach(() => { describe('Card', () => { it.each(['filled', 'elevated', 'outlined'] as const)( - 'renders the enabled %s appearance in light and dark themes', + 'renders the enabled %s appearance', async (variant) => { - for (const isDark of [false, true] as const) { - const theme = isDark ? DarkTheme : LightTheme; - const card = getVariantCard(variant, { theme }); - const { unmount } = await render(card); - - expectVisualSnapshot(); + await render(getVariantCard(variant)); - await unmount(); - } + expect(screen.toJSON()).toMatchSnapshot(); } ); - it('renders the enabled outlined role in light and dark themes', async () => { - for (const isDark of [false, true] as const) { - const theme = isDark ? DarkTheme : LightTheme; - const { unmount } = await render( - - ); + it.each< + [CardVariant, 'surfaceContainerHighest' | 'surfaceContainerLow' | 'surface'] + >([ + ['filled', 'surfaceContainerHighest'], + ['elevated', 'surfaceContainerLow'], + ['outlined', 'surface'], + ])( + 'uses the %s theme roles in light and dark themes', + async (variant, containerRole) => { + jest.replaceProperty(Platform, 'OS', 'android'); + + for (const theme of [LightTheme, DarkTheme]) { + const { unmount } = await render(getVariantCard(variant, { theme })); - expectVisualSnapshot(); + expect(getCardLayers({ neutral: true }).container).toHaveStyle({ + backgroundColor: theme.colors[containerRole], + }); + expectCardState(variant, {}, { theme, neutral: true }); - await unmount(); + await unmount(); + } } - }); + ); it.each(['filled', 'elevated'] as const)( 'does not render an outline for the %s variant', async (variant) => { - const card = getVariantCard(variant); + await render(getVariantCard(variant)); - await render(card); - - expectVisualSnapshot(); + expect(getCardLayers({ neutral: true }).outline).toBeUndefined(); } ); it('uses filled as the default and resolves deeply merged custom colors', async () => { + jest.replaceProperty(Platform, 'OS', 'android'); await render( { /> ); - expectVisualSnapshot(); + const { surface, container, stateLayer, outline } = getCardLayers({ + neutral: true, + }); + + expect(container).toHaveStyle({ backgroundColor: '#111111' }); + expect(stateLayer).toHaveStyle({ backgroundColor: '#222222' }); + expect(outline).toBeUndefined(); + expect(surface).toHaveStyle({ elevation: 0 }); }); it('uses custom theme roles for elevated and outlined variants', async () => { @@ -110,7 +195,9 @@ describe('Card', () => { /> ); - expectVisualSnapshot(); + expect(getCardLayers({ neutral: true }).container).toHaveStyle({ + backgroundColor: '#123456', + }); await unmount(); await render( @@ -123,7 +210,10 @@ describe('Card', () => { /> ); - expectVisualSnapshot(); + const { container, outline } = getCardLayers({ neutral: true }); + + expect(container).toHaveStyle({ backgroundColor: '#abcdef' }); + expect(outline).toHaveStyle({ borderColor: '#654321' }); }); it('lets only elevated Cards customize their resting elevation', async () => { @@ -131,34 +221,58 @@ describe('Card', () => { await render(); - expectVisualSnapshot(); + expect(getCardLayers({ neutral: true }).surface).toHaveStyle({ + elevation: androidElevationLevels[5], + }); }); - it.each(['filled', 'elevated', 'outlined'] as const)( - 'renders the enabled %s elevation', - async (variant) => { - jest.replaceProperty(Platform, 'OS', 'android'); - const card = getVariantCard(variant); + it.each<[CardVariant, number]>([ + ['filled', 0], + ['elevated', 1], + ['outlined', 0], + ])('renders the enabled %s elevation at level %d', async (variant, level) => { + jest.replaceProperty(Platform, 'OS', 'android'); - await render(card); + await render(getVariantCard(variant)); - expectVisualSnapshot(); - } - ); + expect(getCardLayers({ neutral: true }).surface).toHaveStyle({ + elevation: androidElevationLevels[level], + }); + }); it('applies the medium shape and asymmetric overrides across the shell', async () => { - await render( - - ); + const shape = { + borderTopLeftRadius: 4, + borderTopRightRadius: 8, + borderBottomRightRadius: 16, + borderBottomLeftRadius: 20, + }; + const { unmount } = await render(); + + const medium = getCardLayers({ neutral: true }); + + for (const layer of [ + medium.surface, + medium.visual, + medium.container, + medium.stateLayer, + medium.outline, + ]) { + expect(layer).toHaveStyle({ + borderRadius: LightTheme.shapes.corner.medium, + }); + } + await unmount(); + + await render(); - expectVisualSnapshot(); + const { surface, visual, container, stateLayer, outline } = getCardLayers({ + neutral: true, + }); + + for (const layer of [surface, visual, container, stateLayer, outline]) { + expect(layer).toHaveStyle(shape); + } }); it('renders populated slots in deterministic order without rewriting nodes', async () => { @@ -198,7 +312,7 @@ describe('Card', () => { it('renders omitted slots as a neutral filled grouping container', async () => { await render(); - expectVisualSnapshot(); + expectCardState('filled', {}, { neutral: true }); expect(screen.getByTestId('card')).not.toHaveProp('focusable'); expect(screen.queryByRole('button')).not.toBeOnTheScreen(); }); @@ -326,7 +440,13 @@ describe('Card', () => { ]); // The shell only forwards accessibility semantics to the interaction // target, so the shell itself should carry none of them. - expectVisualSnapshot(); + const shell = target.parent?.parent; + + expect(shell).not.toHaveProp('role'); + expect(shell).not.toHaveProp('accessibilityHint'); + expect(shell).not.toHaveProp('accessibilityState'); + expect(shell).not.toHaveProp('accessibilityValue'); + expect(shell).not.toHaveProp('accessibilityActions'); await fireEvent(target, 'accessibilityAction', accessibilityActionEvent); await fireEvent(target, 'accessibilityEscape'); @@ -353,12 +473,16 @@ describe('Card', () => { ); const interaction = screen.getByTestId('product-card'); + const [container, , stateLayer] = interaction.children.filter( + (child): child is Layer => typeof child !== 'string' + ); - expect(interaction).toHaveStyle(shape); - // The clipped visual region and focus indicator are internal nodes with - // no public testID; the snapshot captures their shape, position, and the - // interaction node's place within the visual region. - expectVisualSnapshot(); + // The interaction node is the clipped visual region, so the ripple + // stays inside the Card shape. The Surface around it draws the ring. + expect(interaction).toHaveStyle({ ...shape, overflow: 'hidden' }); + expect(container).toHaveStyle(shape); + expect(stateLayer).toHaveStyle(shape); + expect(interaction.parent).toHaveStyle(shape); await unmount(); // `ref` forwards to a Reanimated Animated.View, which the test renderer @@ -384,236 +508,222 @@ describe('Card', () => { it.each(['filled', 'elevated', 'outlined'] as const)( 'shows and clears the %s hover feedback', async (variant) => { - expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'android'); - const card = getVariantCard(variant, { onPress: () => {} }); - await render(card); - + await render(getVariantCard(variant, { onPress: () => {} })); const target = screen.getByTestId('card'); await fireEvent(target, 'hoverIn'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.08 }); + expectCardState(variant, { hovered: true }); await fireEvent(target, 'hoverOut'); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState(variant); } ); it.each(['filled', 'elevated', 'outlined'] as const)( 'shows and clears the %s pressed feedback', async (variant) => { - expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'android'); - const card = getVariantCard(variant, { onPress: () => {} }); - await render(card); - + await render(getVariantCard(variant, { onPress: () => {} })); const target = screen.getByTestId('card'); await fireEvent(target, 'pressIn'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState(variant, { pressed: true }); await fireEvent(target, 'pressOut'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expectCardState(variant); } ); - it.each(['filled', 'elevated', 'outlined'] as const)( - 'renders the consumer-controlled %s dragged presentation', - async (variant) => { + it.each<[CardVariant, number]>([ + ['filled', 3], + ['elevated', 4], + ['outlined', 3], + ])( + 'renders the consumer-controlled %s dragged presentation at level %d', + async (variant, level) => { jest.replaceProperty(Platform, 'OS', 'android'); - const theme = LightTheme; - const card = getVariantCard(variant, { dragged: true, theme }); - await render(card); + await render(getVariantCard(variant, { dragged: true })); - expectVisualSnapshot(); + const { surface, stateLayer } = getCardLayers({ neutral: true }); + + expect(surface).toHaveStyle({ elevation: androidElevationLevels[level] }); + expect(stateLayer).toHaveStyle({ opacity: 0.16 }); + expectCardState(variant, { dragged: true }, { neutral: true }); } ); - it.each(['filled', 'elevated', 'outlined'] as const)( + it.each(['filled', 'elevated'] as const)( 'renders the Material disabled treatment for %s Cards', async (variant) => { jest.replaceProperty(Platform, 'OS', 'android'); - const theme = LightTheme; - const card = getVariantCard(variant, { - disabled: true, - onPress: () => {}, - theme, - }); + await render( + getVariantCard(variant, { disabled: true, onPress: () => {} }) + ); - await render(card); + const { container, content } = getCardLayers(); - expectVisualSnapshot(); + expect(container).toHaveStyle({ opacity: 0.38 }); + expect(content).toHaveStyle({ opacity: 0.38 }); + expectCardState(variant, { disabled: true }); } ); - it('resolves disabled and dragged before pressed, focused, and hovered visuals', async () => { - expect.hasAssertions(); + it('renders the Material disabled treatment for outlined Cards', async () => { jest.replaceProperty(Platform, 'OS', 'android'); - const theme = LightTheme; - const { rerender } = await render( - {}} - theme={theme} - /> + await render( + getVariantCard('outlined', { disabled: true, onPress: () => {} }) ); + + const { container, content, outline } = getCardLayers(); + + expect(container).toHaveStyle({ opacity: 1 }); + expect(outline).toHaveStyle({ opacity: 0.12 }); + expect(content).toHaveStyle({ opacity: 0.38 }); + expectCardState('outlined', { disabled: true }); + }); + + it('resolves disabled and dragged before pressed, focused, and hovered visuals', async () => { + jest.replaceProperty(Platform, 'OS', 'android'); + const props = { + variant: 'outlined' as const, + dragged: true, + onPress: () => {}, + }; + const { rerender } = await render(); const target = screen.getByTestId('card'); await fireEvent(target, 'hoverIn'); await fireEvent(target, 'focus'); await fireEvent(target, 'pressIn'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.16 }); + expectCardState('outlined', { dragged: true }); - await rerender( - {}} - theme={theme} - /> - ); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await rerender(); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().outline).toHaveStyle({ opacity: 0.12 }); + expectCardState('outlined', { disabled: true }); }); it('updates the controlled dragged presentation in both directions', async () => { - expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'android'); - const theme = LightTheme; - const props = { - variant: 'outlined' as const, - onPress: () => {}, - theme, - }; + const props = { variant: 'outlined' as const, onPress: () => {} }; const { rerender } = await render(); await rerender(); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.16 }); + expectCardState('outlined', { dragged: true }); await rerender(); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined'); }); it.each(['filled', 'elevated', 'outlined'] as const)( 'renders keyboard focus feedback for the %s variant', async (variant) => { - expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'web'); - const card = getVariantCard(variant, { onPress: () => {} }); - await render(card); + await render(getVariantCard(variant, { onPress: () => {} })); await fireEvent(screen.getByTestId('card'), 'focus', { currentTarget: { matches: () => true }, }); - await act(() => { - jest.runOnlyPendingTimers(); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.1 }); + expectCardState(variant, { focused: true }); + // The ring itself is drawn by CSS on web when a direct child of the + // Surface has `:focus-visible`. + expect(getCardLayers().surface).toHaveProp('dataSet', { + focusRingWithin: 'outward', }); - - expectVisualSnapshot(); + expect(getCardLayers().surface).toHaveStyle( + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + { + ['--rnp-focus-ring-color']: LightTheme.colors.secondary, + } as unknown as ViewStyle + ); } ); it('shows focus feedback only for keyboard-visible focus and clears it on blur', async () => { - expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'web'); - const theme = LightTheme; - await render( - {}} theme={theme} /> - ); + await render( {}} />); const target = screen.getByTestId('card'); - const pointerTarget = { matches: () => false }; - const keyboardTarget = { matches: () => true }; - await fireEvent(target, 'focus', { currentTarget: pointerTarget }); - await act(() => { - jest.runOnlyPendingTimers(); + await fireEvent(target, 'focus', { + currentTarget: { matches: () => false }, }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined'); - await fireEvent(target, 'focus', { currentTarget: keyboardTarget }); - await act(() => { - jest.runOnlyPendingTimers(); + await fireEvent(target, 'focus', { + currentTarget: { matches: () => true }, }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.1 }); + expectCardState('outlined', { focused: true }); await fireEvent(target, 'blur'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined'); }); it('uses pressed, focused, then hovered precedence and settles at the latest state', async () => { - expect.hasAssertions(); - const theme = LightTheme; - await render( - {}} theme={theme} /> - ); + await render( {}} />); const target = screen.getByTestId('card'); await fireEvent(target, 'hoverIn'); await fireEvent(target, 'focus'); await fireEvent(target, 'pressIn'); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined', { pressed: true }); + await fireEvent(target, 'pressOut'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.1 }); + expectCardState('outlined', { focused: true }); await fireEvent(target, 'blur'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.08 }); + expectCardState('outlined', { hovered: true }); await fireEvent(target, 'hoverOut'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined'); }); it('uses scaled theme motion duration and easing for visual transitions', async () => { - expect.hasAssertions(); const easing = [0.1, 0.2, 0.3, 0.4] as const; const theme = { animation: { scale: 0.5 }, @@ -622,23 +732,43 @@ describe('Card', () => { easing: { standard: easing }, }, }; + const transition = { + transitionDuration: 160, + transitionTimingFunction: cubicBezier(...easing), + }; const { rerender } = await render( - {}} theme={theme} /> + {}} theme={theme} /> ); - // The scaled duration and easing are set on the state layer and shell, - // both internal nodes with no public testID. - expectVisualSnapshot(); + const expectTransitions = () => { + const { stateLayer, outline } = getCardLayers(); + + expect(getAnimatedStyle(stateLayer)).toMatchObject({ + ...transition, + transitionProperty: 'opacity', + }); + expect(getAnimatedStyle(outline)).toMatchObject({ + ...transition, + transitionProperty: ['borderColor', 'opacity'], + }); + }; + + expectTransitions(); await rerender( - {}} theme={theme} /> + {}} + theme={theme} + /> ); - expectVisualSnapshot(); + expectTransitions(); }); it('settles transitions immediately when reduced motion is enabled', async () => { - expect.hasAssertions(); await render( {}} /> @@ -646,22 +776,18 @@ describe('Card', () => { ); await fireEvent(screen.getByTestId('card'), 'pressIn'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + const { stateLayer, outline } = getCardLayers(); + + for (const layer of [stateLayer, outline]) { + expect(getAnimatedStyle(layer)).toMatchObject({ transitionDuration: 0 }); + } }); it('settles rapid changes at the latest complete visual state', async () => { - expect.hasAssertions(); jest.replaceProperty(Platform, 'OS', 'android'); - const theme = LightTheme; - const props = { - variant: 'outlined' as const, - onPress: () => {}, - theme, - }; + const props = { variant: 'outlined' as const, onPress: () => {} }; const { rerender } = await render(); const target = screen.getByTestId('card'); @@ -674,11 +800,10 @@ describe('Card', () => { await fireEvent(target, 'blur'); await fireEvent(target, 'hoverOut'); await fireEvent(target, 'hoverIn'); - await act(() => { - jest.runOnlyPendingTimers(); - }); + await settle(); - expectVisualSnapshot(); + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.08 }); + expectCardState('outlined', { hovered: true }); }); it('does not rerender stable memoized slot content for transient feedback', async () => { @@ -1110,8 +1235,15 @@ describe('CardCover', () => { /> ); - // The clipped visual region is an internal node with no public testID. - expectVisualSnapshot(); + // The Card clips its media: the visual node around the slots carries + // the shape and hides the overflow, so the cover needs no radius. + expect(screen.getByTestId('edge-cover').parent?.parent).toHaveStyle({ + overflow: 'hidden', + borderTopLeftRadius: 4, + borderTopRightRadius: 8, + borderBottomRightRadius: 16, + borderBottomLeftRadius: 20, + }); expect(screen.getByTestId('edge-cover')).not.toHaveStyle({ borderRadius: LightTheme.shapes.corner.medium, }); diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index 5cb4da2006..56d14cf7be 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`Card applies the medium shape and asymmetric overrides across the shell 1`] = ` +exports[`Card renders the enabled elevated appearance 1`] = ` - `; -exports[`Card does not render an outline for the elevated variant 1`] = ` +exports[`Card renders the enabled filled appearance 1`] = ` `; -exports[`Card does not render an outline for the filled variant 1`] = ` +exports[`Card renders the enabled outlined appearance 1`] = ` - - -`; - -exports[`Card keeps the ripple, visual layers, and focus indicator on the Card shape 1`] = ` - - - - - - - -`; - -exports[`Card lets only elevated Cards customize their resting elevation 1`] = ` - - - - - - - -`; - -exports[`Card renders keyboard focus feedback for the elevated variant 1`] = ` - - - - - - - -`; - -exports[`Card renders keyboard focus feedback for the filled variant 1`] = ` - - - - - - - -`; - -exports[`Card renders keyboard focus feedback for the outlined variant 1`] = ` - - - - - - - - -`; - -exports[`Card renders omitted slots as a neutral filled grouping container 1`] = ` - - - - - - - - -`; - -exports[`Card renders the Material disabled treatment for elevated Cards 1`] = ` - - - - - - - -`; - -exports[`Card renders the Material disabled treatment for filled Cards 1`] = ` - - - - - - - -`; - -exports[`Card renders the Material disabled treatment for outlined Cards 1`] = ` - - - - - - - - -`; - -exports[`Card renders the consumer-controlled elevated dragged presentation 1`] = ` - - - - - - - -`; - -exports[`Card renders the consumer-controlled filled dragged presentation 1`] = ` - - - - - - - -`; - -exports[`Card renders the consumer-controlled outlined dragged presentation 1`] = ` - - - - - - - - -`; - -exports[`Card renders the enabled elevated appearance in light and dark themes 1`] = ` - - - - - - - - -`; - -exports[`Card renders the enabled elevated appearance in light and dark themes 2`] = ` - - - - - - - - -`; - -exports[`Card renders the enabled elevated elevation 1`] = ` - - - - - - - -`; - -exports[`Card renders the enabled filled appearance in light and dark themes 1`] = ` - - - - - - - - -`; - -exports[`Card renders the enabled filled appearance in light and dark themes 2`] = ` - - - - - - - - -`; - -exports[`Card renders the enabled filled elevation 1`] = ` - - - - - - - -`; - -exports[`Card renders the enabled outlined appearance in light and dark themes 1`] = ` - - - - - - - - - -`; - -exports[`Card renders the enabled outlined appearance in light and dark themes 2`] = ` - - - - - - - - - -`; - -exports[`Card renders the enabled outlined elevation 1`] = ` - - - - - - - - -`; - -exports[`Card renders the enabled outlined role in light and dark themes 1`] = ` - - - - - - - - - -`; - -exports[`Card renders the enabled outlined role in light and dark themes 2`] = ` - - - - - - - - - -`; - -exports[`Card resolves disabled and dragged before pressed, focused, and hovered visuals 1`] = ` - - - - - - - - -`; - -exports[`Card resolves disabled and dragged before pressed, focused, and hovered visuals 2`] = ` - - - - - - - - -`; - -exports[`Card routes whole-Card accessibility semantics and callbacks to its target 1`] = ` - - - - - - - - -`; - -exports[`Card settles rapid changes at the latest complete visual state 1`] = ` - - - - - - - - -`; - -exports[`Card settles transitions immediately when reduced motion is enabled 1`] = ` - - - - - - - - - -`; - -exports[`Card shows and clears the elevated hover feedback 1`] = ` - - - - - - - -`; - -exports[`Card shows and clears the elevated hover feedback 2`] = ` - - - - - - - -`; - -exports[`Card shows and clears the elevated pressed feedback 1`] = ` - - - - - - - -`; - -exports[`Card shows and clears the elevated pressed feedback 2`] = ` - - - - - - - -`; - -exports[`Card shows and clears the filled hover feedback 1`] = ` - - - - - - - -`; - -exports[`Card shows and clears the filled hover feedback 2`] = ` - - - - - - - -`; - -exports[`Card shows and clears the filled pressed feedback 1`] = ` - - - - - - - -`; - -exports[`Card shows and clears the filled pressed feedback 2`] = ` - - - - - - - -`; - -exports[`Card shows and clears the outlined hover feedback 1`] = ` - - - - - - - - -`; - -exports[`Card shows and clears the outlined hover feedback 2`] = ` - - - - - - - - -`; - -exports[`Card shows and clears the outlined pressed feedback 1`] = ` - - - - - - - - -`; - -exports[`Card shows and clears the outlined pressed feedback 2`] = ` - - - - - - - - -`; - -exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 1`] = ` - - - - - - - - -`; - -exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 2`] = ` - - - - - - - - -`; - -exports[`Card shows focus feedback only for keyboard-visible focus and clears it on blur 3`] = ` - - - - - - - - -`; - -exports[`Card updates the controlled dragged presentation in both directions 1`] = ` - - - - - - - - -`; - -exports[`Card updates the controlled dragged presentation in both directions 2`] = ` - - - - - - - - -`; - -exports[`Card uses custom theme roles for elevated and outlined variants 1`] = ` - - - - - - - - -`; - -exports[`Card uses custom theme roles for elevated and outlined variants 2`] = ` - - - - - - - - - -`; - -exports[`Card uses filled as the default and resolves deeply merged custom colors 1`] = ` - - - - - - - - -`; - -exports[`Card uses pressed, focused, then hovered precedence and settles at the latest state 1`] = ` - - - - - - - - - -`; - -exports[`Card uses pressed, focused, then hovered precedence and settles at the latest state 2`] = ` - - - - - - - - - -`; - -exports[`Card uses pressed, focused, then hovered precedence and settles at the latest state 3`] = ` - - - - - - - - - -`; - -exports[`Card uses scaled theme motion duration and easing for visual transitions 1`] = ` - - - - - - - - -`; - -exports[`Card uses scaled theme motion duration and easing for visual transitions 2`] = ` - - - - - - - - -`; - -exports[`CardCover uses the Card clipping shape for edge media without double rounding 1`] = ` - - - - - - - - Date: Wed, 18 Nov 2026 09:34:00 +0100 Subject: [PATCH 26/51] fix(card): let aspectRatio size a Card.Cover from a static source React Native gives an image from a static require() source its intrinsic height, which won over aspectRatio: a 16:9 cover 484 wide rendered 510 tall on web instead of 272. Card.Cover now sets height to auto with aspectRatio so the ratio decides. --- src/components/Card/CardCover.tsx | 9 ++++++++- src/components/__tests__/Card/Card.test.tsx | 9 +++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/components/Card/CardCover.tsx b/src/components/Card/CardCover.tsx index 207c99695c..dc9ce080b6 100644 --- a/src/components/Card/CardCover.tsx +++ b/src/components/Card/CardCover.tsx @@ -60,7 +60,11 @@ const CardCover = ({ aspectRatio, style, theme: _theme, ...rest }: Props) => { {...rest} style={[ styles.image, - aspectRatio === undefined ? styles.defaultHeight : { aspectRatio }, + // `height: 'auto'` lets the ratio win over the intrinsic height that + // React Native gives an image from a static `require()` source. + aspectRatio === undefined + ? styles.defaultHeight + : [styles.autoHeight, { aspectRatio }], style, ]} accessibilityIgnoresInvertColors @@ -79,6 +83,9 @@ const styles = StyleSheet.create({ defaultHeight: { height: 195, }, + autoHeight: { + height: 'auto', + }, }); export default CardCover; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 48cc750fd4..30dd1fd6e7 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1159,8 +1159,13 @@ describe('CardCover', () => { const cover = screen.getByTestId('responsive-cover'); - expect(cover).toHaveStyle({ width: '100%', aspectRatio: 16 / 9 }); - expect(cover).not.toHaveStyle({ height: 195 }); + // `height: 'auto'` overrides the intrinsic height React Native gives a + // static `require()` source, which would otherwise win over the ratio. + expect(cover).toHaveStyle({ + width: '100%', + height: 'auto', + aspectRatio: 16 / 9, + }); }); it('exposes supplied semantics for an informative image', async () => { From d0a0a3263e0344d26b689b9f108fc0cfc944020a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:34:22 +0100 Subject: [PATCH 27/51] docs(example): rebuild the Card example around a variant switcher The example app ships to the app stores, so the platform verification notes and the light and dark comparison panels, which were QA tools, are removed. The variant switcher and the layouts from main's example come back on the slot API: a cover with only actions, custom button styles, a custom corner radius, long press and theme switching. A states section shows disabled, dragged, a custom outline color, an asymmetric shape and a custom header. --- example/src/Examples/CardExample.tsx | 542 ++++++++++++++------------- 1 file changed, 283 insertions(+), 259 deletions(-) diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index b4699d4ffd..98b4943dd2 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -1,20 +1,23 @@ +import * as React from 'react'; import { Alert, Platform, StyleSheet, View } from 'react-native'; import { Avatar, Button, Card, - DarkTheme, + Chip, IconButton, - LightTheme, Text, - ThemeProvider, useTheme, } from 'react-native-paper'; -import type { CardCoverProps, Theme } from 'react-native-paper'; +import { PreferencesContext } from '../PreferencesContext'; import ScreenWrapper from '../ScreenWrapper'; +type Variant = 'filled' | 'elevated' | 'outlined'; + +const variants: Variant[] = ['filled', 'elevated', 'outlined']; + const showMessage = (message: string) => { if (Platform.OS === 'web') { alert(message); @@ -28,262 +31,309 @@ const CustomHeader = () => ( Custom header - Neutral container, independent actions + Any React node in the header slot ); -const ResponsiveCover = ({ - aspectRatio = 16 / 9, - ...props -}: CardCoverProps) => ; - -const ThemePreview = ({ name }: { name: string }) => { - const theme = useTheme(); +const CardExample = () => { + const { colors } = useTheme(); + const [variant, setVariant] = React.useState('filled'); + const [isFavorite, setIsFavorite] = React.useState(false); + const preferences = React.useContext(PreferencesContext); return ( - - {name} + + + {variants.map((item) => ( + setVariant(item)} + > + {item} + + ))} + + showMessage(`${name} filled Card pressed`)} - onLongPress={() => showMessage(`${name} filled Card long pressed`)} - title="Filled interaction" - subtitle="Tab, hover, press, or long press" + variant={variant} + media={ + + } + title="Abandoned Ship" content={ - - State layers and keyboard focus stay inside the shape. + + The Abandoned Ship is a wrecked ship located on Route 108 in + Hoenn, originally being a ship named the S.S. Cactus. The second + part of the ship can only be accessed by using Dive and contains + the Scanner. } /> + + } + header={ + + } content={ - Compare the raised surface. + + A responsive 16:9 cover with a title and subtitle in custom + variants. + } /> + } + trailing={(props) => ( + showMessage('More options')} /> + )} + content={ + + + Dotted around the Hoenn region, you will find loamy soil, many of + which are housing berries. Once you have picked the berries, then + you have the ability to use that loamy soil to grow your own + berries. + + } - title="Outlined clipping" /> - - ); -}; -const ThemedPreview = ({ name, theme }: { name: string; theme: Theme }) => ( - - - -); - -const CardExample = () => { - const theme = useTheme(); + + } + title="Custom Button styles" + actions={ + + + + + } + /> - return ( - - - Expressive Card gallery - - Filled is the default. Whole-Card actions are shown without nested - controls; neutral Cards own any independent actions. - - + + } + title="Custom border radius" + subtitle="The cover follows the Card's shape" + /> - - Variants and composition - - showMessage('Default filled Card pressed')} - onLongPress={() => showMessage('Default filled Card long pressed')} - media={ - - } - title="Filled (default)" - subtitle="Actionable Card" - content={ - - - One coherent target with direct title and content slots. - - - } + - - } - content={ - - - Card.Actions preserves each control's own presentation. - - - } - actions={ - - showMessage('Saved')} - /> - - + } + title="Just Strawberries" + subtitle="... and only Strawberries" + trailing={(props) => ( + setIsFavorite(!isFavorite)} /> + )} + /> - - } - title="Outlined" - subtitle="Responsive informative media" - /> - - + showMessage('The Chameleon is Pressed')} + media={ + + } + title="Pressable Chameleon" + content={ + + + The whole Card is one target. If you press me, I will alert. + + + } + /> - - States, shapes, and omitted slots - - showMessage('Disabled Card pressed')} - title="Disabled action" - content={ - - Not focusable or pressable. - - } - /> - - Controlled visual state. - - } - /> - - } - content={ - - Asymmetric shape, no header. - - } - /> - } - right={(props) => ( - showMessage('More options')} - /> - )} - /> - } - /> - - + showMessage('The City is Long Pressed')} + media={} + title="Long Pressable City" + leading={(props) => } + content={ + + + This is a long press only city. If you long press me, I will + alert. + + + } + /> - - Light and dark verification - - Compare surfaces, outlines, elevation, clipping, and interaction - feedback without changing the application theme. - - - - - - + preferences?.toggleTheme()} + title="Pressable Theme Change" + leading={(props) => } + content={ + + + This is a pressable Card. If you press me, I will switch the + theme. + + + } + /> - - Platform verification - - Android · iOS · web: compare layout, both themes, surface roles, - outlines, clipping, and elevation. - - - Web: use Tab and hover on actionable Cards to inspect focus and state - layers. - - - Native: touch actionable Cards to inspect bounded ripple, clipping, - and elevation. Current platform: {Platform.OS}. - - + + States and customization + + + + } + actions={ + + + + + } + /> + + showMessage('Disabled Card pressed')} + title="Disabled" + content={ + + Not focusable or pressable. + + } + /> + + + + The dragged look is controlled by the app. + + + } + /> + + + Set with the borderColor prop. + + } + /> + + + } + title="Asymmetric shape" + /> + + } + content={ + + + A neutral Card with independent actions. + + + } + actions={ + + showMessage('Saved')} + /> + + + } + /> ); }; @@ -292,30 +342,17 @@ CardExample.title = 'Card'; const styles = StyleSheet.create({ screen: { - gap: 28, - padding: 16, - }, - intro: { gap: 8, + padding: 8, }, - section: { - gap: 12, - }, - gallery: { - alignItems: 'flex-start', + variants: { flexDirection: 'row', flexWrap: 'wrap', - gap: 16, - }, - galleryCard: { - minWidth: 260, - flexBasis: 300, - flexGrow: 1, + gap: 8, + paddingVertical: 4, }, - compactCard: { - minWidth: 220, - flexBasis: 250, - flexGrow: 1, + sectionTitle: { + marginTop: 16, }, customHeader: { alignItems: 'center', @@ -327,19 +364,6 @@ const styles = StyleSheet.create({ customHeaderText: { flex: 1, }, - themePreview: { - borderWidth: 1, - flexBasis: 300, - flexGrow: 1, - gap: 12, - minWidth: 260, - padding: 16, - }, - verification: { - borderLeftWidth: 4, - gap: 6, - paddingLeft: 12, - }, }); export default CardExample; From 4b6878d059b6fc12c10da966924b226725666f23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:37:26 +0100 Subject: [PATCH 28/51] docs: document Surface from its own component again The Surface page pointed at StaticSurface, which only existed while Surface took shared-value elevation. Surface is main's single component again, so the docs build failed to find StaticSurface. --- docs/component-docs.config.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/component-docs.config.ts b/docs/component-docs.config.ts index 0e457f64e2..73ebb3b3b2 100644 --- a/docs/component-docs.config.ts +++ b/docs/component-docs.config.ts @@ -130,11 +130,7 @@ const pages = { SegmentedButtons: 'SegmentedButtons/SegmentedButtons', }, Snackbar: 'Snackbar', - Surface: { - source: 'Surface', - component: 'StaticSurface', - title: 'Surface', - }, + Surface: 'Surface', Switch: { Switch: 'Switch/Switch', }, From a05ec87603f12da976a52505c156d3eb2293ead8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 09:37:55 +0100 Subject: [PATCH 29/51] fix(docs): merge prop types only across union branches The parser change for Card's prop unions merged the declared types of every prop declared more than once, so pressable props such as IconButton.onPress and List.Item.style showed long intersection types on 11 other pages. Types are merged again only when every declaration is a union branch, now also counting type aliases that a file uses as union members. A branch typed never is skipped, so elevation and borderColor read Elevation and ColorValue. Only the Card page differs from main. --- .../component-docs/__tests__/parser.test.ts | 23 +++++ docs/plugins/component-docs/parser.ts | 84 +++++++++++++++++-- 2 files changed, 99 insertions(+), 8 deletions(-) diff --git a/docs/plugins/component-docs/__tests__/parser.test.ts b/docs/plugins/component-docs/__tests__/parser.test.ts index 6b3ff8c68b..be4acc6879 100644 --- a/docs/plugins/component-docs/__tests__/parser.test.ts +++ b/docs/plugins/component-docs/__tests__/parser.test.ts @@ -21,5 +21,28 @@ describe('component docs parser', () => { expect(props.get('elevation')?.type).toContain('Elevation'); expect(props.get('header')?.type).toBe('React.ReactNode'); expect(props.get('title')?.type).toBe('React.ReactNode'); + expect(props.get('borderColor')?.type).toBe('ColorValue'); + }); + + it('keeps the written type of props that are not union branches', () => { + const repositoryRoot = process.cwd(); + const parse = createComponentParser( + path.join(repositoryRoot, 'tsconfig.source.json') + ); + const getType = (source: string, name: string) => { + const { props: documentedProps } = parse( + path.join(repositoryRoot, 'src', 'components'), + { source } + ); + + return documentedProps.find((prop) => prop.name === name)?.type; + }; + + // Declared again by the pressable props it extends. + expect(getType('IconButton/IconButton', 'onPress')).toBe( + '(e: GestureResponderEvent) => void' + ); + // Written out in the main props object for the docs, next to the union. + expect(getType('Appbar/AppbarContent', 'title')).toBe('React.ReactNode'); }); }); diff --git a/docs/plugins/component-docs/parser.ts b/docs/plugins/component-docs/parser.ts index ed03c20bb8..f6e3e768f6 100644 --- a/docs/plugins/component-docs/parser.ts +++ b/docs/plugins/component-docs/parser.ts @@ -164,6 +164,61 @@ const isPathInside = (parentPath: string, childPath: string) => { return !relativePath.startsWith('..') && !path.isAbsolute(relativePath); }; +const unionMemberAliasesCache = new WeakMap>(); + +// Names of the type aliases that a file uses as union members, such as the +// branches of `type Props = Base & (WithTitle | WithHeader)`. +const getUnionMemberAliases = (sourceFile: ts.SourceFile) => { + const cached = unionMemberAliasesCache.get(sourceFile); + + if (cached) { + return cached; + } + + const names = new Set(); + const visit = (node: ts.Node) => { + if (ts.isUnionTypeNode(node)) { + for (const member of node.types) { + if ( + ts.isTypeReferenceNode(member) && + ts.isIdentifier(member.typeName) + ) { + names.add(member.typeName.text); + } + } + } + + ts.forEachChild(node, visit); + }; + + visit(sourceFile); + unionMemberAliasesCache.set(sourceFile, names); + + return names; +}; + +// A prop belongs to a union branch when a union encloses its declaration +// directly, or when the type alias that declares it is a union member. +const isUnionBranchDeclaration = (declaration: ts.Declaration) => { + let parent: ts.Node | undefined = declaration.parent; + + while (parent) { + if (ts.isUnionTypeNode(parent)) { + return true; + } + + if (ts.isTypeAliasDeclaration(parent)) { + return getUnionMemberAliases(parent.getSourceFile()).has( + parent.name.text + ); + } + + parent = parent.parent; + } + + return false; +}; + const getProps = ( checker: ts.TypeChecker, sourceRootDir: string, @@ -206,15 +261,28 @@ const getProps = ( ? [item.type.getText(item.getSourceFile())] : [] ); + // A `never` branch only marks a prop as unavailable in that branch, so + // a prop typed `never` everywhere but one branch keeps that branch's text. + const availableTypes = new Set( + declarationTypes.filter((item) => item !== 'never') + ); + // A declaration outside the union branches is the documented type, as + // in `Appbar.Content`, so only merge the types when every one is a branch. + const hasOnlyUnionDeclarations = declarations.every( + isUnionBranchDeclaration + ); const type = - new Set(declarationTypes).size > 1 || !declarations.includes(property) - ? checker.typeToString( - checker.getTypeOfSymbolAtLocation(symbol, property), - property, - ts.TypeFormatFlags.NoTruncation | - ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope - ) - : property.type.getText(propertySourceFile); + hasOnlyUnionDeclarations && availableTypes.size === 1 + ? [...availableTypes][0] + : (hasOnlyUnionDeclarations && new Set(declarationTypes).size > 1) || + !declarations.includes(property) + ? checker.typeToString( + checker.getTypeOfSymbolAtLocation(symbol, property), + property, + ts.TypeFormatFlags.NoTruncation | + ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope + ) + : property.type.getText(propertySourceFile); return [ { From 67887615b21e3d8df25c48792a7f7592bb390270 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 10:17:32 +0100 Subject: [PATCH 30/51] fix(card): annotate the resolveCardVisuals return type Building the package failed with TS2742: the inferred return type of resolveCardVisuals referred to React Native's internal StyleSheetTypes path, which declaration emit cannot name portably. It now returns the exported CardVisuals type. --- src/components/Card/tokens.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index 5bc3072278..fd8ddcdedc 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -1,3 +1,5 @@ +import type { ColorValue } from 'react-native'; + import { tokens as systemTokens } from '../../theme/tokens'; import type { Elevation, InternalTheme } from '../../theme/types'; @@ -243,6 +245,20 @@ export type ResolveCardVisualsOptions = CardStateFlags & { elevation?: Elevation; }; +export type CardVisuals = { + state: CardState; + containerColor: ColorValue; + containerOpacity: number; + outlineColor: ColorValue; + outlineOpacity: number; + outlineWidth: 0 | 1; + elevation: Elevation; + shape: number; + stateLayerColor: ColorValue; + stateLayerOpacity: number; + contentOpacity: number; +}; + export const resolveCardVisuals = ({ theme, variant, @@ -252,7 +268,7 @@ export const resolveCardVisuals = ({ pressed = false, focused = false, hovered = false, -}: ResolveCardVisualsOptions) => { +}: ResolveCardVisualsOptions): CardVisuals => { const state: CardState = disabled ? 'disabled' : dragged From 3f4f5c3fc638236363a91fbedd28793cea788c56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 12:47:12 +0100 Subject: [PATCH 31/51] docs(card): drop removed Button props from the Card examples --- docs/6.x/docs/guides/migration.md | 8 ++++---- src/components/Card/Card.tsx | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 763d34e197..7c8006a6c1 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -616,7 +616,7 @@ The Card clips media to its shape, so a `Card.Cover` in the `media` slot follows #### `Card.Actions` no longer styles its buttons -`Card.Actions` no longer assigns `mode="outlined"` to its first button, `mode="contained"` (now `mode="filled"`) to the rest, or `compact` to any of them. It only lays its children out in a row; set each `Button`'s `mode` and `compact` explicitly to keep the old look: +`Card.Actions` no longer assigns `mode="outlined"` to its first button, `mode="contained"` (now `mode="filled"`) to the rest, or `compact` to any of them. It only lays its children out in a row; set each `Button`'s `mode` explicitly to keep the old look. `compact` was removed from `Button`; see [`Button`](#button) for its `size` replacement: ```tsx // Before (v5) — Card.Actions styled the buttons automatically @@ -625,10 +625,10 @@ The Card clips media to its shape, so a `Card.Cover` in the `media` slot follows -// After (v6) — set mode and compact explicitly +// After (v6) — set mode explicitly - - + + ``` diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 66983a6191..389acced3e 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -339,7 +339,7 @@ export type Props = Omit & * } * actions={ * - * + * * } * /> * From 90ec7f01cd450875ff7dc873516ef5b4bcd56275 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 12:47:39 +0100 Subject: [PATCH 32/51] fix(card): skip the actions warning when the actions slot is empty --- src/components/Card/Card.tsx | 3 +-- src/components/__tests__/Card/Card.test.tsx | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 389acced3e..7818cba539 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -517,8 +517,7 @@ const Card = ({ 'within' ); const hasWarnedAboutActions = React.useRef(false); - const hasActions = - actions !== null && actions !== undefined && actions !== false; + const hasActions = React.Children.toArray(actions).length > 0; React.useEffect(() => { if ( diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 30dd1fd6e7..a083967a95 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -867,6 +867,22 @@ describe('Card', () => { ); }); + it.each([ + ['an empty array', []], + ['an array of empty values', [null, false, undefined]], + ['nested empty arrays', [[], []]], + ['true', true], + ])( + 'does not warn when whole-Card interaction is combined with %s in actions', + async (_, actions) => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + + await render( {}} actions={actions} />); + + expect(warn).not.toHaveBeenCalled(); + } + ); + it('does not warn about Card actions in production', async () => { const environment = process.env.NODE_ENV; process.env.NODE_ENV = 'production'; From 0ae62d9959333715f1a895f99efc9784210c92e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 14:23:33 +0100 Subject: [PATCH 33/51] docs(example): show every Card state in each variant --- example/src/Examples/CardExample.tsx | 37 ++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index 98b4943dd2..e91a1d3fc2 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -261,7 +261,7 @@ const CardExample = () => { /> showMessage('Disabled Card pressed')} title="Disabled" @@ -273,7 +273,7 @@ const CardExample = () => { /> { } /> + + + Set with the elevation prop. Only elevated Cards accept it. + + + } + /> + { title="Asymmetric shape" /> + + } + title="Horizontal layout" + subtitle="Set flexDirection in contentStyle" + /> + } @@ -354,6 +380,13 @@ const styles = StyleSheet.create({ sectionTitle: { marginTop: 16, }, + horizontal: { + flexDirection: 'row', + }, + horizontalCover: { + height: 80, + width: 80, + }, customHeader: { alignItems: 'center', flexDirection: 'row', From fe9953fe27f8f6d980ece877cc7ea1a5f277fd33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 15:14:06 +0100 Subject: [PATCH 34/51] fix(card): pad Card.Actions 16dp at the sides --- docs/6.x/docs/guides/migration.md | 2 ++ src/components/Card/CardActions.tsx | 4 +++- src/components/__tests__/Card/Card.test.tsx | 13 ++++++++++--- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 7c8006a6c1..2c2735ed65 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -632,6 +632,8 @@ The Card clips media to its shape, so a `Card.Cover` in the `media` slot follows ``` +`Card.Actions` also has **16dp** of padding at the start and end, the Material Design 3 Card padding, instead of 8dp, and 8dp above and below. To keep the 5.x spacing, pass `style={{ paddingHorizontal: 8, paddingTop: 0 }}`. + #### Choose one interaction model Give the Card an interaction handler when the whole Card represents one action. It becomes one accessibility target with button semantics by default, so do not place independent controls in its `actions` slot. diff --git a/src/components/Card/CardActions.tsx b/src/components/Card/CardActions.tsx index 1d26a6f70d..5c03d0a801 100644 --- a/src/components/Card/CardActions.tsx +++ b/src/components/Card/CardActions.tsx @@ -46,7 +46,9 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', - padding: 8, + // Material Card specs: 16dp left/right padding. + paddingHorizontal: 16, + paddingVertical: 8, gap: 8, }, }); diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index a083967a95..afd08adac1 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1354,7 +1354,8 @@ describe('CardActions', () => { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', - padding: 8, + paddingHorizontal: 16, + paddingVertical: 8, gap: 8, }); expect(screen.getByTestId('custom-action')).toBeOnTheScreen(); @@ -1365,7 +1366,12 @@ describe('CardActions', () => { await render( Action @@ -1373,7 +1379,8 @@ describe('CardActions', () => { expect(screen.getByTestId('card-actions')).toHaveStyle({ justifyContent: 'flex-start', - padding: 4, + paddingHorizontal: 4, + paddingVertical: 4, gap: 12, }); }); From 190734101737b3a3930cb54cb1f46b25ff8cee26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 15:14:27 +0100 Subject: [PATCH 35/51] docs(card): note the single-pointer alternative to dragging --- src/components/Card/Card.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 7818cba539..3b05eb6d61 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -240,6 +240,9 @@ export type Props = Omit & * Whether to show the Card's controlled Material dragged presentation. * This controls visuals only; gesture recognition, drag lifecycle, list * reordering, and drop behavior remain the consumer's responsibility. + * Material requires a single-pointer alternative to dragging, such as a + * menu with move and delete actions opened by tapping or long-pressing + * the Card. */ dragged?: boolean; /** From e823c0fc86550aeb444ea36875b4cfbb2435becd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 15:25:01 +0100 Subject: [PATCH 36/51] fix(card): keep Card.Title visible in a row-laid-out Card --- src/components/Card/CardTitle.tsx | 5 ++++- src/components/__tests__/Card/Card.test.tsx | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/components/Card/CardTitle.tsx b/src/components/Card/CardTitle.tsx index 2855c6428c..e2a6bfdbd4 100644 --- a/src/components/Card/CardTitle.tsx +++ b/src/components/Card/CardTitle.tsx @@ -201,7 +201,10 @@ const styles = StyleSheet.create({ }, titles: { - flex: 1, + // Not `flex: 1`: its zero basis gives the titles no width when a Card + // lays its regions out in a row, as with `contentStyle={{ flexDirection: 'row' }}`. + flexGrow: 1, + flexShrink: 1, flexDirection: 'column', justifyContent: 'center', }, diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index afd08adac1..4730b78181 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1286,6 +1286,23 @@ describe('CardTitle', () => { expect(screen.getByText('Title')).toHaveStyle({ paddingRight: 16 }); expect(screen.getByText('Subtitle')).toHaveStyle({ paddingRight: 16 }); }); + + // A zero flex basis would collapse the titles in a row-laid-out Card on + // iOS and Android, so they size from their text and grow into free space. + it('sizes the titles from their text in a row-laid-out Card', async () => { + await render( + } + title="Title" + /> + ); + + const titles = screen.getByText('Title').parent; + + expect(titles).toHaveStyle({ flexGrow: 1, flexShrink: 1 }); + expect(titles).not.toHaveStyle({ flex: 1 }); + }); }); describe('CardContent', () => { From 64d3ef81f198d64f25d7504ea0b333f7d150a819 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Wed, 18 Nov 2026 15:44:37 +0100 Subject: [PATCH 37/51] fix(card): accept a union variant on a Card without a header --- example/src/Examples/CardExample.tsx | 2 +- src/components/Card/Card.tsx | 5 ++++- src/components/__tests__/Card/Card.test.tsx | 9 +++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index e91a1d3fc2..a25d9a4dd4 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -244,7 +244,7 @@ const CardExample = () => { } diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 3b05eb6d61..1a1009a97f 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -59,7 +59,10 @@ type CustomHeaderProps = { * Fully custom header region. This cannot be combined with `title`, * `subtitle`, `leading`, or `trailing`. */ - header: React.ReactNode; + // Optional, so a Card with no header region matches this branch too: with a + // required `header`, TypeScript rejects a header-less Card whose `variant` + // is a union, e.g. `variant={variant}`. + header?: React.ReactNode; /** * Unavailable when a custom header is supplied. */ diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 4730b78181..2bfb10d96c 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1045,9 +1045,18 @@ describe('Card', () => { describe('Card types', () => { it('accepts documented examples and rejects removed or mixed forms', () => { + const variant = 'filled' as 'filled' | 'elevated' | 'outlined'; const typeCases = ( <> + } + actions={} + /> + + } /> Date: Wed, 18 Nov 2026 16:32:45 +0100 Subject: [PATCH 38/51] fix(card): drop theme.animation.scale, removed on main --- src/components/Card/Card.tsx | 4 +--- src/components/__tests__/Card/Card.test.tsx | 5 ++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 1a1009a97f..b4710808ce 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -480,9 +480,7 @@ const Card = ({ focused, hovered, }); - const transitionDuration = reduceMotion - ? 0 - : theme.motion.duration.short3 * theme.animation.scale; + const transitionDuration = reduceMotion ? 0 : theme.motion.duration.short3; const transitionTimingFunction = cubicBezier(...theme.motion.easing.standard); // TouchableRipple already draws the pressed state layer (the ripple on // Android, the underlay elsewhere), so a second one would double it. diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 2bfb10d96c..98973c286d 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -723,17 +723,16 @@ describe('Card', () => { expectCardState('outlined'); }); - it('uses scaled theme motion duration and easing for visual transitions', async () => { + it('uses the theme motion duration and easing for visual transitions', async () => { const easing = [0.1, 0.2, 0.3, 0.4] as const; const theme = { - animation: { scale: 0.5 }, motion: { duration: { short3: 320 }, easing: { standard: easing }, }, }; const transition = { - transitionDuration: 160, + transitionDuration: 320, transitionTimingFunction: cubicBezier(...easing), }; const { rerender } = await render( From 7d5d2141f0bcfd2a14707b0441a0a756ddd8c891 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Thu, 19 Nov 2026 09:03:18 +0100 Subject: [PATCH 39/51] fix(card): clear state feedback when a Card stops being actionable Without a touch handler the interaction node unmounts and sends no hover out or blur, so a Card that became actionable again showed the hover state layer with the pointer long gone. --- src/components/Card/Card.tsx | 20 ++++++----- src/components/__tests__/Card/Card.test.tsx | 40 ++++++++++++++++----- 2 files changed, 43 insertions(+), 17 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index b4710808ce..33ce9433e9 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -462,14 +462,6 @@ const Card = ({ const [focused, setFocused] = React.useState(false); const [pressed, setPressed] = React.useState(false); - React.useEffect(() => { - if (isDisabled) { - setHovered(false); - setFocused(false); - setPressed(false); - } - }, [isDisabled]); - const visuals = resolveCardVisuals({ theme, variant: cardVariant, @@ -506,6 +498,18 @@ const Card = ({ onPressIn, onPressOut, }); + + // A disabled Card gets no hover, focus or press events, and without a touch + // handler the interaction node unmounts and sends no hover out or blur, so + // the flags are cleared here rather than left for a later state to show. + React.useEffect(() => { + if (isDisabled || !hasPassedTouchHandler) { + setHovered(false); + setFocused(false); + setPressed(false); + } + }, [isDisabled, hasPassedTouchHandler]); + // The ring goes on the Surface, the Card's visible box (`scope: 'within'`), // not on the interaction node: the caller's `style` sizes and pads the // Surface, so a ring on the interaction node would stop short of a taller diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 98973c286d..f60aee0ed0 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -68,6 +68,13 @@ const getCardLayers = ({ neutral = false } = {}) => { }; }; +// A focus event the Card's own interaction node receives. On web, +// `focusVisible` is what `:focus-visible` matches. +const selfFocus = (focusVisible: boolean) => { + const node = { matches: () => focusVisible }; + return { target: node, currentTarget: node }; +}; + // Asserts that every layer shows the Material visuals of one state. The // values come from the token matrix, which `Card.tokens.test.ts` checks // against the specification. @@ -644,9 +651,7 @@ describe('Card', () => { jest.replaceProperty(Platform, 'OS', 'web'); await render(getVariantCard(variant, { onPress: () => {} })); - await fireEvent(screen.getByTestId('card'), 'focus', { - currentTarget: { matches: () => true }, - }); + await fireEvent(screen.getByTestId('card'), 'focus', selfFocus(true)); await settle(); expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.1 }); @@ -670,17 +675,13 @@ describe('Card', () => { await render( {}} />); const target = screen.getByTestId('card'); - await fireEvent(target, 'focus', { - currentTarget: { matches: () => false }, - }); + await fireEvent(target, 'focus', selfFocus(false)); await settle(); expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); expectCardState('outlined'); - await fireEvent(target, 'focus', { - currentTarget: { matches: () => true }, - }); + await fireEvent(target, 'focus', selfFocus(true)); await settle(); expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.1 }); @@ -693,6 +694,27 @@ describe('Card', () => { expectCardState('outlined'); }); + it('clears hover feedback when the Card stops being actionable', async () => { + jest.replaceProperty(Platform, 'OS', 'android'); + const { rerender } = await render( + {}} /> + ); + + await fireEvent(screen.getByTestId('card'), 'hoverIn'); + await settle(); + expectCardState('outlined', { hovered: true }); + + // The interaction node unmounts without a handler, so it sends no hover out. + await rerender(); + await rerender( + {}} /> + ); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined'); + }); + it('uses pressed, focused, then hovered precedence and settles at the latest state', async () => { await render( {}} />); const target = screen.getByTestId('card'); From 48772be0745e6b4b922998ab0911929fdcfacc70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Thu, 19 Nov 2026 09:03:29 +0100 Subject: [PATCH 40/51] fix(card): ignore focus that bubbles up from a descendant Native focus events bubble, so focusing a TextInput inside an actionable Card lit the Card's focused state layer. Only the interaction node's own focus counts now, as in useFocusRing. --- src/components/Card/Card.tsx | 9 ++++++++- src/components/__tests__/Card/Card.test.tsx | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 33ce9433e9..be7db94b48 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -659,7 +659,14 @@ const Card = ({ React.useCallback( (event) => { focusTarget.onFocus?.(event); - setFocused(isKeyboardFocusEvent(event)); + // Possibly missing, as `useFocusRing` allows: an app test can fire + // focus with no event at all. + const focusEvent: typeof event | undefined = event; + // Native focus events bubble: a focused descendant, such as a + // TextInput in the content, reaches this handler too. + if (!focusEvent || focusEvent.target === focusEvent.currentTarget) { + setFocused(!focusEvent || isKeyboardFocusEvent(focusEvent)); + } onFocus?.(event); }, [focusTarget, onFocus] diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index f60aee0ed0..3c86ac1568 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -694,6 +694,20 @@ describe('Card', () => { expectCardState('outlined'); }); + it('ignores focus that bubbles up from a focused descendant', async () => { + jest.replaceProperty(Platform, 'OS', 'web'); + await render( {}} />); + + await fireEvent(screen.getByTestId('card'), 'focus', { + target: {}, + currentTarget: { matches: () => true }, + }); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined'); + }); + it('clears hover feedback when the Card stops being actionable', async () => { jest.replaceProperty(Platform, 'OS', 'android'); const { rerender } = await render( From 8d987e8aa30480c613571268851d50362fe4941d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:13:00 +0100 Subject: [PATCH 41/51] fix(card): restore main's 194dp default cover height The Card.Cover rewrite brought back the 195 that main had replaced with 194 in #5076, a leftover of the rebase rather than a decision. 194 is the 16:9 media height of a 344dp Material card (344 x 9/16, rounded), and the Material 3 spec sets no cover height, so main's value stays. --- docs/6.x/docs/guides/migration.md | 2 +- src/components/Card/CardCover.tsx | 6 +++--- src/components/__tests__/Card/Card.test.tsx | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 2c2735ed65..88123c3128 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -606,7 +606,7 @@ The `borderColor` in `style` no longer changes the outline color of an outlined #### `Card.Cover` -Use the `aspectRatio` prop to size a cover responsively. It replaces the default height of `195`: +Use the `aspectRatio` prop to size a cover responsively. It replaces the default height of `194`: ```tsx } /> diff --git a/src/components/Card/CardCover.tsx b/src/components/Card/CardCover.tsx index dc9ce080b6..d2d77b14f8 100644 --- a/src/components/Card/CardCover.tsx +++ b/src/components/Card/CardCover.tsx @@ -7,11 +7,11 @@ import type { ThemeProp } from '../../theme/types'; export type Props = Omit & { /** * Width-to-height ratio of the cover, for example `16 / 9`. When set, the - * cover drops its default height of 195 and resizes with the Card's width. + * cover drops its default height of 194 and resizes with the Card's width. */ aspectRatio?: number; /** - * Style for the cover image. The default size is full width by 195. Consumer + * Style for the cover image. The default size is full width by 194. Consumer * styles are applied after these defaults. */ style?: StyleProp; @@ -81,7 +81,7 @@ const styles = StyleSheet.create({ justifyContent: 'flex-end', }, defaultHeight: { - height: 195, + height: 194, }, autoHeight: { height: 'auto', diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 3c86ac1568..41aba1ea42 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1204,7 +1204,7 @@ describe('CardCover', () => { expect(screen.getByTestId('card-cover')).toHaveStyle({ width: '100%', - height: 195, + height: 194, }); }); From 6056a2f63acdfe24240fee2e3ebf909d92fdc8aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:13:17 +0100 Subject: [PATCH 42/51] fix(card): show the focused outline color over a custom borderColor A custom borderColor replaced the outline color in every state, so an outlined Card with one showed no outline change on keyboard focus. Material 3 turns the outline onSurface on focus, the only state where its color changes, so the custom color now gives way there. --- src/components/Card/Card.tsx | 13 ++++++--- src/components/__tests__/Card/Card.test.tsx | 29 ++++++++++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index be7db94b48..fddaaaac79 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -181,8 +181,10 @@ type OutlinedCardProps = { */ elevation?: never; /** - * Color of the outline. It replaces the theme color in every state; the - * state opacities still apply, so a disabled outline stays at 12%. + * Color of the outline. It replaces the theme color in every state except + * keyboard focus, where the outline turns `onSurface` as Material 3 + * specifies. The state opacities still apply, so a disabled outline stays + * at 12%. */ borderColor?: ColorValue; }; @@ -478,7 +480,12 @@ const Card = ({ // Android, the underlay elsewhere), so a second one would double it. const stateLayerOpacity = visuals.state === 'pressed' ? 0 : visuals.stateLayerOpacity; - const outlineColor = customBorderColor ?? visuals.outlineColor; + // Focus is the one state where Material changes the outline color, so a + // custom color gives way to it there. + const outlineColor = + visuals.state === 'focused' + ? visuals.outlineColor + : (customBorderColor ?? visuals.outlineColor); const stateLayerTransitionStyle: AnimatedStyle = { transitionProperty: 'opacity', transitionDuration, diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 41aba1ea42..af4184e715 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1028,7 +1028,7 @@ describe('Card', () => { expect(onAccessibilityAction).not.toHaveBeenCalled(); }); - it('uses a custom outline color in every state', async () => { + it('uses a custom outline color at rest and when disabled', async () => { const { rerender } = await render( ); @@ -1042,6 +1042,33 @@ describe('Card', () => { expect(JSON.stringify(screen.toJSON())).toContain('"borderColor":"red"'); }); + it('gives way to the focused outline color on keyboard focus', async () => { + jest.replaceProperty(Platform, 'OS', 'web'); + await render( + {}} + /> + ); + const target = screen.getByTestId('card'); + + expect(getCardLayers().outline).toHaveStyle({ borderColor: 'red' }); + + await fireEvent(target, 'focus', selfFocus(true)); + await settle(); + + expect(getCardLayers().outline).toHaveStyle({ + borderColor: LightTheme.colors.onSurface, + }); + + await fireEvent(target, 'blur'); + await settle(); + + expect(getCardLayers().outline).toHaveStyle({ borderColor: 'red' }); + }); + it('dims the slot content of a disabled Card', async () => { const { rerender } = await render( Body} /> From 3a436e739f20d6440e97aa84945a45f6f9da0d24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:13:37 +0100 Subject: [PATCH 43/51] docs(card): note that Card.Cover style now applies to the image Card.Cover no longer wraps its image in a View, so its style is typed as ImageStyle and lands on the Image. The migration guide shows how to style the area around a cover instead. --- docs/6.x/docs/guides/migration.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 88123c3128..7d2654be09 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -614,6 +614,15 @@ Use the `aspectRatio` prop to size a cover responsively. It replaces the default The Card clips media to its shape, so a `Card.Cover` in the `media` slot follows the Card's corners without its own border radius. +`Card.Cover` no longer wraps its image in a `View`. Its `style` is now typed as `ImageStyle` and applies to the `Image` itself instead of a wrapper `View`. To style the area around the cover, wrap the cover in your own `View`: + +```diff +- ++ ++ ++ +``` + #### `Card.Actions` no longer styles its buttons `Card.Actions` no longer assigns `mode="outlined"` to its first button, `mode="contained"` (now `mode="filled"`) to the rest, or `compact` to any of them. It only lays its children out in a row; set each `Button`'s `mode` explicitly to keep the old look. `compact` was removed from `Button`; see [`Button`](#button) for its `size` replacement: From 1b705060e8f657c1596c056136a13b0964047f7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:13:37 +0100 Subject: [PATCH 44/51] test(card): query the nested Button by role in the focus ring test The test looked the Button up by testID because the actionable Card is also a button and took its name from the Button's text. Giving the Card its own label keeps the accessibility query unambiguous. --- src/components/__tests__/focusRingWithinWeb.test.tsx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/components/__tests__/focusRingWithinWeb.test.tsx b/src/components/__tests__/focusRingWithinWeb.test.tsx index 9f69e0b771..0647ce1821 100644 --- a/src/components/__tests__/focusRingWithinWeb.test.tsx +++ b/src/components/__tests__/focusRingWithinWeb.test.tsx @@ -128,13 +128,14 @@ describe('focus ring `within` structure (web)', () => { await render( {}} content={ <> - + } /> @@ -143,7 +144,9 @@ describe('focus ring `within` structure (web)', () => { const [cardRing] = withinRings(); expect(cardRing.children).toContain(screen.getByTestId('card')); expect(cardRing.children).not.toContain(screen.getByTestId('input')); - expect(cardRing.children).not.toContain(screen.getByTestId('ok')); + expect(cardRing.children).not.toContain( + screen.getByRole('button', { name: 'OK' }) + ); }); // The chip's box draws the ring, so a ring on the ripple inside it would From f35fddabae302d0e3ef49f0f3896ceaaa27c743e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:13:47 +0100 Subject: [PATCH 45/51] docs(card): explain the aria-disabled pass-through and the actions check `isDisabled || ariaDisabled` reads as redundant but keeps an enabled neutral Card from rendering aria-disabled={false}, and React.Children in the actions check only keeps an empty slot from triggering the warning. --- src/components/Card/Card.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index fddaaaac79..4905923d36 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -532,6 +532,8 @@ const Card = ({ 'within' ); const hasWarnedAboutActions = React.useRef(false); + // `React.Children` is used only so an empty slot (`[]`, `null`, `false`) + // does not trigger the warning below; layout never depends on it. const hasActions = React.Children.toArray(actions).length > 0; React.useEffect(() => { @@ -646,6 +648,8 @@ const Card = ({ }; const neutralAccessibilityProps = { ...accessibilityProps, + // When enabled, pass the user's value through unchanged, so a neutral + // Card without `aria-disabled` does not render `aria-disabled={false}`. 'aria-disabled': isDisabled || ariaDisabled, }; const handlePressIn = React.useCallback( From 7fa309062c69310c552ce8d596a7816adc8c4490 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:31:16 +0100 Subject: [PATCH 46/51] refactor(card): move resolveCardVisuals to utils.ts tokens.ts now holds only the Material token data, as in Switch, Checkbox and FAB, and the resolver that turns it into visuals for a theme and state lives in utils.ts. The token table is exported as CardTokens, after SwitchTokens and CheckboxTokens. --- src/components/Card/Card.tsx | 2 +- src/components/Card/tokens.ts | 76 +----------------- src/components/Card/utils.ts | 78 +++++++++++++++++++ src/components/__tests__/Card/Card.test.tsx | 5 +- .../__tests__/Card/Card.tokens.test.ts | 7 +- 5 files changed, 86 insertions(+), 82 deletions(-) create mode 100644 src/components/Card/utils.ts diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 4905923d36..f70c53d6d7 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -18,7 +18,7 @@ import CardContent from './CardContent'; import CardCover from './CardCover'; import CardTitle from './CardTitle'; import type { Props as CardTitleProps } from './CardTitle'; -import { resolveCardVisuals } from './tokens'; +import { resolveCardVisuals } from './utils'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; import type { Elevation, ThemeProp } from '../../theme/types'; diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index fd8ddcdedc..6a32b550ca 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -1,7 +1,5 @@ -import type { ColorValue } from 'react-native'; - import { tokens as systemTokens } from '../../theme/tokens'; -import type { Elevation, InternalTheme } from '../../theme/types'; +import type { Elevation } from '../../theme/types'; export const cardVariants = ['filled', 'elevated', 'outlined'] as const; @@ -60,7 +58,7 @@ const { opacity } = systemTokens.md.sys.state; * token set 34.0.0 at commit 4d3710682140722f48a5965b68109b240e1fe79e. * https://github.com/material-components/material-components-android/tree/4d3710682140722f48a5965b68109b240e1fe79e/lib/java/com/google/android/material */ -const cardTokenMatrix = { +export const CardTokens = { filled: { enabled: { containerColor: 'surfaceContainerHighest', @@ -230,73 +228,3 @@ const cardTokenMatrix = { }, }, } as const satisfies CardTokenMatrix; - -export type CardStateFlags = { - disabled?: boolean; - dragged?: boolean; - pressed?: boolean; - focused?: boolean; - hovered?: boolean; -}; - -export type ResolveCardVisualsOptions = CardStateFlags & { - theme: InternalTheme; - variant: CardVariant; - elevation?: Elevation; -}; - -export type CardVisuals = { - state: CardState; - containerColor: ColorValue; - containerOpacity: number; - outlineColor: ColorValue; - outlineOpacity: number; - outlineWidth: 0 | 1; - elevation: Elevation; - shape: number; - stateLayerColor: ColorValue; - stateLayerOpacity: number; - contentOpacity: number; -}; - -export const resolveCardVisuals = ({ - theme, - variant, - elevation: customElevation, - disabled = false, - dragged = false, - pressed = false, - focused = false, - hovered = false, -}: ResolveCardVisualsOptions): CardVisuals => { - const state: CardState = disabled - ? 'disabled' - : dragged - ? 'dragged' - : pressed - ? 'pressed' - : focused - ? 'focused' - : hovered - ? 'hovered' - : 'enabled'; - const stateTokens = cardTokenMatrix[variant][state]; - - return { - state, - containerColor: theme.colors[stateTokens.containerColor], - containerOpacity: stateTokens.containerOpacity, - outlineColor: theme.colors[stateTokens.outlineColor], - outlineOpacity: stateTokens.outlineOpacity, - outlineWidth: stateTokens.outlineWidth, - elevation: - variant === 'elevated' && state === 'enabled' && customElevation != null - ? customElevation - : stateTokens.elevation, - shape: theme.shapes.corner.medium, - stateLayerColor: theme.colors.onSurface, - stateLayerOpacity: stateTokens.stateLayerOpacity, - // Compose dims disabled Card content to the content color at 38%. - contentOpacity: state === 'disabled' ? opacity.disabled : 1, - }; -}; diff --git a/src/components/Card/utils.ts b/src/components/Card/utils.ts new file mode 100644 index 0000000000..b28c9c744f --- /dev/null +++ b/src/components/Card/utils.ts @@ -0,0 +1,78 @@ +import type { ColorValue } from 'react-native'; + +import { CardTokens } from './tokens'; +import type { CardState, CardVariant } from './tokens'; +import { tokens as systemTokens } from '../../theme/tokens'; +import type { Elevation, InternalTheme } from '../../theme/types'; + +const { opacity } = systemTokens.md.sys.state; + +export type CardStateFlags = { + disabled?: boolean; + dragged?: boolean; + pressed?: boolean; + focused?: boolean; + hovered?: boolean; +}; + +export type ResolveCardVisualsOptions = CardStateFlags & { + theme: InternalTheme; + variant: CardVariant; + elevation?: Elevation; +}; + +export type CardVisuals = { + state: CardState; + containerColor: ColorValue; + containerOpacity: number; + outlineColor: ColorValue; + outlineOpacity: number; + outlineWidth: 0 | 1; + elevation: Elevation; + shape: number; + stateLayerColor: ColorValue; + stateLayerOpacity: number; + contentOpacity: number; +}; + +export const resolveCardVisuals = ({ + theme, + variant, + elevation: customElevation, + disabled = false, + dragged = false, + pressed = false, + focused = false, + hovered = false, +}: ResolveCardVisualsOptions): CardVisuals => { + const state: CardState = disabled + ? 'disabled' + : dragged + ? 'dragged' + : pressed + ? 'pressed' + : focused + ? 'focused' + : hovered + ? 'hovered' + : 'enabled'; + const stateTokens = CardTokens[variant][state]; + + return { + state, + containerColor: theme.colors[stateTokens.containerColor], + containerOpacity: stateTokens.containerOpacity, + outlineColor: theme.colors[stateTokens.outlineColor], + outlineOpacity: stateTokens.outlineOpacity, + outlineWidth: stateTokens.outlineWidth, + elevation: + variant === 'elevated' && state === 'enabled' && customElevation != null + ? customElevation + : stateTokens.elevation, + shape: theme.shapes.corner.medium, + stateLayerColor: theme.colors.onSurface, + stateLayerOpacity: stateTokens.stateLayerOpacity, + // Compose dims disabled Card content to the content color at 38%. + contentOpacity: state === 'disabled' ? opacity.disabled : 1, + }; +}; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index af4184e715..ee5fa7476c 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -13,8 +13,9 @@ import { androidElevationLevels } from '../../../theme/tokens/sys/elevation'; import Button from '../../Button/Button'; import Card from '../../Card/Card'; import type { Props as CardProps } from '../../Card/Card'; -import { resolveCardVisuals } from '../../Card/tokens'; -import type { CardVariant, CardStateFlags } from '../../Card/tokens'; +import type { CardVariant } from '../../Card/tokens'; +import { resolveCardVisuals } from '../../Card/utils'; +import type { CardStateFlags } from '../../Card/utils'; const styles = StyleSheet.create({ contentStyle: { diff --git a/src/components/__tests__/Card/Card.tokens.test.ts b/src/components/__tests__/Card/Card.tokens.test.ts index d13930e054..c6adae37dd 100644 --- a/src/components/__tests__/Card/Card.tokens.test.ts +++ b/src/components/__tests__/Card/Card.tokens.test.ts @@ -1,12 +1,9 @@ import { describe, expect, it } from '@jest/globals'; import { LightTheme } from '../../../theme/schemes'; -import { - cardStates, - cardVariants, - resolveCardVisuals, -} from '../../Card/tokens'; +import { cardStates, cardVariants } from '../../Card/tokens'; import type { CardState, CardVariant } from '../../Card/tokens'; +import { resolveCardVisuals } from '../../Card/utils'; const stateFlags: Record< CardState, From ea6f530c5bc400717c499791ba131d8615b5a3f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:32:05 +0100 Subject: [PATCH 47/51] refactor(card): name the layout helpers' spacing in tokens Card.Title, Card.Content and Card.Actions used bare numbers. They now read one CardSpacing group in tokens.ts, which says where each value comes from: the 16dp left/right padding is the Material 3 spec, and the Card.Title heights are kept from Paper 5, since the spec sets none. No value changes. --- src/components/Card/CardActions.tsx | 8 ++++---- src/components/Card/CardContent.tsx | 6 ++++-- src/components/Card/CardTitle.tsx | 20 ++++++++++++-------- src/components/Card/tokens.ts | 25 +++++++++++++++++++++++++ 4 files changed, 45 insertions(+), 14 deletions(-) diff --git a/src/components/Card/CardActions.tsx b/src/components/Card/CardActions.tsx index 5c03d0a801..1562758dde 100644 --- a/src/components/Card/CardActions.tsx +++ b/src/components/Card/CardActions.tsx @@ -2,6 +2,7 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { StyleProp, ViewProps, ViewStyle } from 'react-native'; +import { CardSpacing } from './tokens'; import type { ThemeProp } from '../../theme/types'; export type Props = ViewProps & { @@ -46,10 +47,9 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', - // Material Card specs: 16dp left/right padding. - paddingHorizontal: 16, - paddingVertical: 8, - gap: 8, + paddingHorizontal: CardSpacing.horizontalPadding, + paddingVertical: CardSpacing.actionsVerticalPadding, + gap: CardSpacing.actionsGap, }, }); diff --git a/src/components/Card/CardContent.tsx b/src/components/Card/CardContent.tsx index 9281390f87..d198ae00eb 100644 --- a/src/components/Card/CardContent.tsx +++ b/src/components/Card/CardContent.tsx @@ -2,6 +2,8 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { StyleProp, ViewProps, ViewStyle } from 'react-native'; +import { CardSpacing } from './tokens'; + export type Props = ViewProps & { /** * Items inside the `Card.Content`. @@ -38,8 +40,8 @@ CardContent.displayName = 'Card.Content'; const styles = StyleSheet.create({ container: { - paddingHorizontal: 16, - paddingVertical: 16, + paddingHorizontal: CardSpacing.horizontalPadding, + paddingVertical: CardSpacing.contentVerticalPadding, }, }); diff --git a/src/components/Card/CardTitle.tsx b/src/components/Card/CardTitle.tsx index e2a6bfdbd4..332688ebaf 100644 --- a/src/components/Card/CardTitle.tsx +++ b/src/components/Card/CardTitle.tsx @@ -2,6 +2,7 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { StyleProp, TextStyle, ViewProps, ViewStyle } from 'react-native'; +import { CardSpacing } from './tokens'; import { useInternalTheme } from '../../core/theming'; import type { TypescaleKey, ThemeProp } from '../../theme/types'; import Text from '../Typography/Text'; @@ -143,8 +144,11 @@ const CardTitle = ({ }: Props) => { useInternalTheme(themeOverrides); - const minHeight = subtitle || left || right ? 72 : 50; - const marginBottom = subtitle ? 0 : 2; + const minHeight = + subtitle || left || right + ? CardSpacing.titleWithSupportingMinHeight + : CardSpacing.titleMinHeight; + const marginBottom = subtitle ? 0 : CardSpacing.titleBottomMargin; return ( @@ -190,12 +194,12 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', - paddingLeft: 16, + paddingLeft: CardSpacing.horizontalPadding, }, left: { justifyContent: 'center', - marginRight: 16, + marginRight: CardSpacing.titleLeadingGap, height: LEFT_SIZE, width: LEFT_SIZE, }, @@ -210,14 +214,14 @@ const styles = StyleSheet.create({ }, title: { - minHeight: 30, - paddingRight: 16, + minHeight: CardSpacing.titleTextMinHeight, + paddingRight: CardSpacing.horizontalPadding, }, subtitle: { - minHeight: 20, + minHeight: CardSpacing.subtitleTextMinHeight, marginVertical: 0, - paddingRight: 16, + paddingRight: CardSpacing.horizontalPadding, }, }); diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index 6a32b550ca..1f9f962f9a 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -228,3 +228,28 @@ export const CardTokens = { }, }, } as const satisfies CardTokenMatrix; + +/** + * Spacing of the Card layout helpers. + * + * Material 3 specifies only the 16dp left/right padding + * (https://m3.material.io/components/cards/specs). It sets no header height, + * so the `Card.Title` heights below are kept from Paper 5 and headers keep + * their size. + */ +export const CardSpacing = { + horizontalPadding: 16, + contentVerticalPadding: 16, + actionsVerticalPadding: 8, + actionsGap: 8, + /** Between `Card.Title`'s leading element and its text. */ + titleLeadingGap: 16, + /** `Card.Title` with only a title. */ + titleMinHeight: 50, + /** `Card.Title` with a subtitle, a leading or a trailing element. */ + titleWithSupportingMinHeight: 72, + titleTextMinHeight: 30, + /** Below the title when there is no subtitle. */ + titleBottomMargin: 2, + subtitleTextMinHeight: 20, +} as const; From d6acca87af612fea0f2a91df11285c65463e6699 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 13:33:11 +0100 Subject: [PATCH 48/51] docs(card): record the November recheck of the Card tokens Every Card token was compared with the live md.comp.*-card values on m3.material.io on 2026-11-20 and all of them still match. The earlier AndroidX references stay, with their own date. --- src/components/Card/tokens.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index 1f9f962f9a..b8936241aa 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -41,7 +41,12 @@ const { opacity } = systemTokens.md.sys.state; /** * Material 3 Card variant-by-state tokens. * - * Rechecked 2026-09-23 against the Material 3 Card specification and the + * Rechecked 2026-11-20 against the live `md.comp.*-card` tokens on + * https://m3.material.io/components/cards/specs: every container color, + * outline color and opacity, elevation and state layer opacity below + * matches, as do the 1dp outline width and the `corner.medium` shape. + * + * Checked 2026-09-23 against the Material 3 Card specification and the * current AndroidX generated Card tokens at commit * 8c85cbb3ccccbaf5ca40c45527e2028ced01e472: * https://m3.material.io/components/cards/specs From b1117bce26d22d03ec356519fb4c567ff7b20922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 14:24:11 +0100 Subject: [PATCH 49/51] perf(card): drop the Card layers that draw nothing Two of the Card's full-size layers were invisible in most states: - The container layer painted the same opaque color as the visual node behind it. Only a disabled filled or elevated Card needs it, to fade the container but not the content, so it is drawn only then. - A neutral Card has no hover, focus or press, so its state layer stayed at 0% unless the app set `dragged`. It is drawn only for an actionable or dragged Card, so a neutral Card's dragged tint now appears and clears without a fade. Views per Card: neutral 6 to 4 (outlined 7 to 5), actionable 6 to 5 (outlined 7 to 6); disabled unchanged. The rendering matches the previous one apart from anti-aliasing on the rounded corners, in screenshots of every variant: - web: at rest, hovered, pressed and keyboard-focused; - iOS simulator: at rest, and pressed through `testOnly_pressed`; - Android emulator: at rest, and during a real held touch, where the foreground ripple still covers the whole Card, media included. --- src/components/Card/Card.tsx | 56 +++--- src/components/__tests__/Card/Card.test.tsx | 164 +++++++++++++----- .../Card/__snapshots__/Card.test.tsx.snap | 138 --------------- 3 files changed, 152 insertions(+), 206 deletions(-) diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index f70c53d6d7..69e1145104 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -711,31 +711,39 @@ const Card = ({ const layers = ( <> - + {/* The visual node paints an opaque container itself. Only a disabled + Card needs its own layer, to fade the container but not the content. */} + {visuals.containerOpacity !== 1 ? ( + + ) : null} {content} - {/* Material draws state layers over the whole Card, media included. */} - + {/* Material draws state layers over the whole Card, media included. A + neutral Card has no hover, focus or press, so it needs one only for + the dragged state, which then appears and clears without a fade. */} + {hasPassedTouchHandler || dragged ? ( + + ) : null} {visuals.outlineWidth > 0 ? ( ['parent']>; // The Card's visual layers are internal nodes with no public testID, so they // are reached from the node that has one. For an actionable Card that is the // interaction node; for a neutral Card it is the slot content. Either way the -// layers are the children of the clipped visual node, in paint order: -// container, slot content, state layer, then the outline of an outlined Card. -// The Surface that carries the elevation and the focus ring is its parent. +// layers are the children of the clipped visual node, in paint order: the +// container layer of a disabled Card, the slot content, the state layer of an +// actionable or dragged Card, then the outline of an outlined Card. The +// Surface that carries the elevation and the focus ring is the visual node's +// parent. The layers have no role, text or testID, so only their props tell +// them apart: a layer ignores touches, and only the outline has a border. +const isLayer = (child: Layer) => + // eslint-disable-next-line no-restricted-syntax -- see the comment above. + child.props.pointerEvents === 'none'; +const hasBorder = (child: Layer) => + // eslint-disable-next-line no-restricted-syntax -- see the comment above. + (StyleSheet.flatten(child.props.style)?.borderWidth ?? 0) > 0; + const getCardLayers = ({ neutral = false } = {}) => { const target = screen.getByTestId('card'); const visual = neutral ? target.parent : target; @@ -55,20 +65,40 @@ const getCardLayers = ({ neutral = false } = {}) => { throw new Error('Card visual node not found'); } - const [container, content, stateLayer, outline] = visual.children.filter( + const children = visual.children.filter( (child): child is Layer => typeof child !== 'string' ); + const contentIndex = children.findIndex((child) => !isLayer(child)); + + if (contentIndex === -1) { + throw new Error('Card content region not found'); + } + const [containerLayer] = children.slice(0, contentIndex); + const overlays = children.slice(contentIndex + 1); + const outline = overlays.find(hasBorder); + const stateLayer = overlays.find((child) => child !== outline); return { surface: visual.parent, visual, - container, - content, + // The node that paints the container color: the visual node itself, or + // the container layer of a disabled Card, which fades it on its own. + container: containerLayer ?? visual, + containerLayer, + content: children[contentIndex], stateLayer, outline, }; }; +// For a layer the Card under test is known to draw. +const present = (layer: Layer | undefined) => { + if (!layer) { + throw new Error('Card layer not found'); + } + return layer; +}; + // A focus event the Card's own interaction node receives. On web, // `focusVisible` is what `:focus-visible` matches. const selfFocus = (focusVisible: boolean) => { @@ -85,20 +115,29 @@ const expectCardState = ( { theme = LightTheme, neutral = false } = {} ) => { const visuals = resolveCardVisuals({ theme, variant, ...flags }); - const { surface, container, content, stateLayer, outline } = getCardLayers({ - neutral, - }); + const { surface, visual, containerLayer, content, stateLayer, outline } = + getCardLayers({ neutral }); - expect(container).toHaveStyle({ - backgroundColor: visuals.containerColor, - opacity: visuals.containerOpacity, - }); + if (visuals.containerOpacity === 1) { + expect(containerLayer).toBeUndefined(); + expect(visual).toHaveStyle({ backgroundColor: visuals.containerColor }); + } else { + expect(containerLayer).toHaveStyle({ + backgroundColor: visuals.containerColor, + opacity: visuals.containerOpacity, + }); + } expect(content).toHaveStyle({ opacity: visuals.contentOpacity }); - // TouchableRipple draws the pressed layer, so Card skips its own. - expect(stateLayer).toHaveStyle({ - backgroundColor: visuals.stateLayerColor, - opacity: visuals.state === 'pressed' ? 0 : visuals.stateLayerOpacity, - }); + if (neutral && !flags.dragged) { + // A neutral Card has no hover, focus or press to show. + expect(stateLayer).toBeUndefined(); + } else { + // TouchableRipple draws the pressed layer, so Card skips its own. + expect(stateLayer).toHaveStyle({ + backgroundColor: visuals.stateLayerColor, + opacity: visuals.state === 'pressed' ? 0 : visuals.stateLayerOpacity, + }); + } if (variant === 'outlined') { expect(outline).toHaveStyle({ @@ -175,6 +214,7 @@ describe('Card', () => { await render( {}} theme={{ colors: { surfaceContainerHighest: '#111111', @@ -184,9 +224,7 @@ describe('Card', () => { /> ); - const { surface, container, stateLayer, outline } = getCardLayers({ - neutral: true, - }); + const { surface, container, stateLayer, outline } = getCardLayers(); expect(container).toHaveStyle({ backgroundColor: '#111111' }); expect(stateLayer).toHaveStyle({ backgroundColor: '#222222' }); @@ -259,28 +297,31 @@ describe('Card', () => { const medium = getCardLayers({ neutral: true }); - for (const layer of [ - medium.surface, - medium.visual, - medium.container, - medium.stateLayer, - medium.outline, - ]) { + for (const layer of [medium.surface, medium.visual, medium.outline]) { expect(layer).toHaveStyle({ borderRadius: LightTheme.shapes.corner.medium, }); } await unmount(); - await render(); + const { unmount: unmountOutlined } = await render( + + ); - const { surface, visual, container, stateLayer, outline } = getCardLayers({ - neutral: true, - }); + const { surface, visual, outline } = getCardLayers({ neutral: true }); - for (const layer of [surface, visual, container, stateLayer, outline]) { + for (const layer of [surface, visual, outline]) { expect(layer).toHaveStyle(shape); } + await unmountOutlined(); + + // A disabled, dragged Card also draws its own container and state layers. + await render(); + + const { containerLayer, stateLayer } = getCardLayers({ neutral: true }); + + expect(containerLayer).toHaveStyle(shape); + expect(stateLayer).toHaveStyle(shape); }); it('renders populated slots in deterministic order without rewriting nodes', async () => { @@ -481,14 +522,14 @@ describe('Card', () => { ); const interaction = screen.getByTestId('product-card'); - const [container, , stateLayer] = interaction.children.filter( - (child): child is Layer => typeof child !== 'string' - ); + const stateLayer = interaction.children + .filter((child): child is Layer => typeof child !== 'string') + .find(isLayer); - // The interaction node is the clipped visual region, so the ripple - // stays inside the Card shape. The Surface around it draws the ring. + // The interaction node is the clipped visual region and paints the + // container, so the ripple stays inside the Card shape. The Surface + // around it draws the ring. expect(interaction).toHaveStyle({ ...shape, overflow: 'hidden' }); - expect(container).toHaveStyle(shape); expect(stateLayer).toHaveStyle(shape); expect(interaction.parent).toHaveStyle(shape); await unmount(); @@ -595,9 +636,10 @@ describe('Card', () => { getVariantCard('outlined', { disabled: true, onPress: () => {} }) ); - const { container, content, outline } = getCardLayers(); + const { containerLayer, content, outline } = getCardLayers(); - expect(container).toHaveStyle({ opacity: 1 }); + // The outlined container stays opaque, so it needs no layer to fade it. + expect(containerLayer).toBeUndefined(); expect(outline).toHaveStyle({ opacity: 0.12 }); expect(content).toHaveStyle({ opacity: 0.38 }); expectCardState('outlined', { disabled: true }); @@ -779,11 +821,11 @@ describe('Card', () => { const expectTransitions = () => { const { stateLayer, outline } = getCardLayers(); - expect(getAnimatedStyle(stateLayer)).toMatchObject({ + expect(getAnimatedStyle(present(stateLayer))).toMatchObject({ ...transition, transitionProperty: 'opacity', }); - expect(getAnimatedStyle(outline)).toMatchObject({ + expect(getAnimatedStyle(present(outline))).toMatchObject({ ...transition, transitionProperty: ['borderColor', 'opacity'], }); @@ -817,7 +859,9 @@ describe('Card', () => { const { stateLayer, outline } = getCardLayers(); for (const layer of [stateLayer, outline]) { - expect(getAnimatedStyle(layer)).toMatchObject({ transitionDuration: 0 }); + expect(getAnimatedStyle(present(layer))).toMatchObject({ + transitionDuration: 0, + }); } }); @@ -1070,6 +1114,38 @@ describe('Card', () => { expect(getCardLayers().outline).toHaveStyle({ borderColor: 'red' }); }); + it('draws a separate container layer only for a disabled Card', async () => { + const { rerender } = await render( + {}} /> + ); + + expect(getCardLayers().containerLayer).toBeUndefined(); + expect(getCardLayers().visual).toHaveStyle({ + backgroundColor: LightTheme.colors.surfaceContainerHighest, + }); + + await rerender( {}} disabled />); + + expect(getCardLayers().containerLayer).toHaveStyle({ + backgroundColor: LightTheme.colors.onSurface, + opacity: 0.38, + }); + }); + + it('draws a state layer on a neutral Card only while it is dragged', async () => { + const { rerender } = await render( + Body} /> + ); + + expect(getCardLayers({ neutral: true }).stateLayer).toBeUndefined(); + + await rerender(Body} />); + + expect(getCardLayers({ neutral: true }).stateLayer).toHaveStyle({ + opacity: 0.16, + }); + }); + it('dims the slot content of a disabled Card', async () => { const { rerender } = await render( Body} /> diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index 56d14cf7be..ee91f81f2f 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -103,28 +103,6 @@ exports[`Card renders the enabled elevated appearance 1`] = ` ] } > - - `; @@ -271,28 +225,6 @@ exports[`Card renders the enabled filled appearance 1`] = ` ] } > - - `; @@ -439,28 +347,6 @@ exports[`Card renders the enabled outlined appearance 1`] = ` ] } > - - Date: Fri, 20 Nov 2026 16:00:07 +0100 Subject: [PATCH 50/51] fix(card): space Card regions as on main The rebase brought back Paper 5's Card.Title heights (72 and 50 minimum, 30 and 20 per line), which main removed in #5076, and Card.Content's bottom padding stacked with Card.Actions' top padding. A full Card was 20px taller than on main, with no reason in the Material 3 spec, which sets only the 16dp left/right padding. Each region now pads its own top and sides with 16dp, and the Card adds 16dp below a last header or content region, chosen from the populated slots alone. An action row ends 8dp below its buttons. Card.Title sizes from its content and spaces its parts with a 16dp gap, so a trailing element also sits 16dp from the edge. All eight cases of the comparison screen now match main to the pixel in height and text position. A row layout removes the closing space with `contentStyle={{ paddingBottom: 0 }}`, as the example and the migration guide now show. BREAKING CHANGE: Card.Content used outside a Card no longer has bottom padding, and Card.Title has no minimum height. --- docs/6.x/docs/guides/migration.md | 24 ++--- example/src/Examples/CardExample.tsx | 2 + src/components/Card/Card.tsx | 44 ++++++--- src/components/Card/CardActions.tsx | 3 +- src/components/Card/CardContent.tsx | 2 +- src/components/Card/CardTitle.tsx | 30 ++----- src/components/Card/tokens.ts | 29 +++--- src/components/__tests__/Card/Card.test.tsx | 89 +++++++++++++++++-- .../Card/__snapshots__/Card.test.tsx.snap | 3 + 9 files changed, 147 insertions(+), 79 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 7d2654be09..251e962874 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -560,31 +560,23 @@ Use `header` when the complete header is custom. It is mutually exclusive with ` #### `Card.Content` padding -`Card.Content` no longer changes its padding based on its neighbors. In Paper 5 it added top padding only when it came first and bottom padding only when it came last. It now always uses `16dp` on every side. A `Card.Content` followed by `Card.Actions` gets `24dp` between the text and the buttons (`16dp` from `Card.Content` and `8dp` from `Card.Actions`). Override the padding with the `style` prop of `Card.Content` to keep a tighter layout: +`Card.Content` no longer changes its padding based on its neighbors. In Paper 5 it added top padding only when it came first and bottom padding only when it came last. Now each region pads its own top and sides with `16dp`, and the Card adds `16dp` below its last region. An action row instead ends `8dp` below its buttons. `Card.Title` no longer has a minimum height: it sizes from its content. + +Used outside a Card, `Card.Content` has no bottom padding. Add it with the `style` prop: ```tsx - - View the itinerary. - - } - actions={ - - - - } -/> + + Shown outside a Card + ``` #### Horizontal layout -To place the regions in a row, set `flexDirection` in `contentStyle`, which styles the wrapper around the slots: +To place the regions in a row, set `flexDirection` in `contentStyle`, which styles the wrapper around the slots. Also set `paddingBottom: 0`, so the media in the row reaches the Card's bottom edge instead of sitting above the `16dp` the Card adds below its last region: ```tsx } title="Card title" /> diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index a25d9a4dd4..5b3ea54ee5 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -382,6 +382,8 @@ const styles = StyleSheet.create({ }, horizontal: { flexDirection: 'row', + // The cover reaches the bottom edge, so the row needs no closing space. + paddingBottom: 0, }, horizontalCover: { height: 80, diff --git a/src/components/Card/Card.tsx b/src/components/Card/Card.tsx index 69e1145104..155007c772 100644 --- a/src/components/Card/Card.tsx +++ b/src/components/Card/Card.tsx @@ -18,6 +18,7 @@ import CardContent from './CardContent'; import CardCover from './CardCover'; import CardTitle from './CardTitle'; import type { Props as CardTitleProps } from './CardTitle'; +import { CardSpacing } from './tokens'; import { resolveCardVisuals } from './utils'; import { useInternalTheme } from '../../core/theming'; import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; @@ -251,7 +252,10 @@ export type Props = Omit & */ dragged?: boolean; /** - * Style of the inner region that contains all Card slots. + * Style of the inner region that contains all Card slots. It applies + * after the Card's own spacing, so `paddingBottom` can replace the `16dp` + * the Card adds below a last header or content region, for example in a + * row layout. */ contentStyle?: StyleProp; /** @@ -285,6 +289,9 @@ export type Props = Omit & } & (ConvenienceHeaderProps | CustomHeaderProps) & CardVariantProps; +const isPopulated = (slot: React.ReactNode) => + React.Children.toArray(slot).length > 0; + /** * A Card groups related media, header content, body content, and actions. It * renders populated regions in the fixed order `media`, header, `content`, and @@ -532,9 +539,9 @@ const Card = ({ 'within' ); const hasWarnedAboutActions = React.useRef(false); - // `React.Children` is used only so an empty slot (`[]`, `null`, `false`) - // does not trigger the warning below; layout never depends on it. - const hasActions = React.Children.toArray(actions).length > 0; + // `React.Children` only tells an empty slot (`[]`, `null`, `false`) from a + // populated one; it never looks inside the slot. + const hasActions = isPopulated(actions); React.useEffect(() => { if ( @@ -570,26 +577,34 @@ const Card = ({ ); const hasConvenienceHeader = title != null || subtitle != null || leading != null || trailing != null; + const headerRegion = + header ?? + (hasConvenienceHeader ? ( + + ) : null); + // Each region pads its own top, so the Card closes the bottom when the + // last region is the header or the content. An action row pads its own + // bottom, and media stays flush with the Card's edge. + const closesBottom = + !hasActions && (isPopulated(cardContent) || headerRegion != null); const content = ( {media} - {header ?? - (hasConvenienceHeader ? ( - - ) : null)} + {headerRegion} {cardContent} {actions} @@ -842,6 +857,9 @@ const styles = StyleSheet.create({ flexShrink: 1, position: 'relative', }, + closedContent: { + paddingBottom: CardSpacing.regionGap, + }, }); export default Card; diff --git a/src/components/Card/CardActions.tsx b/src/components/Card/CardActions.tsx index 1562758dde..e6067b3d10 100644 --- a/src/components/Card/CardActions.tsx +++ b/src/components/Card/CardActions.tsx @@ -48,7 +48,8 @@ const styles = StyleSheet.create({ alignItems: 'center', justifyContent: 'flex-end', paddingHorizontal: CardSpacing.horizontalPadding, - paddingVertical: CardSpacing.actionsVerticalPadding, + paddingTop: CardSpacing.regionGap, + paddingBottom: CardSpacing.actionsBottomPadding, gap: CardSpacing.actionsGap, }, }); diff --git a/src/components/Card/CardContent.tsx b/src/components/Card/CardContent.tsx index d198ae00eb..30148129a6 100644 --- a/src/components/Card/CardContent.tsx +++ b/src/components/Card/CardContent.tsx @@ -41,7 +41,7 @@ CardContent.displayName = 'Card.Content'; const styles = StyleSheet.create({ container: { paddingHorizontal: CardSpacing.horizontalPadding, - paddingVertical: CardSpacing.contentVerticalPadding, + paddingTop: CardSpacing.regionGap, }, }); diff --git a/src/components/Card/CardTitle.tsx b/src/components/Card/CardTitle.tsx index 332688ebaf..05483a8669 100644 --- a/src/components/Card/CardTitle.tsx +++ b/src/components/Card/CardTitle.tsx @@ -144,14 +144,8 @@ const CardTitle = ({ }: Props) => { useInternalTheme(themeOverrides); - const minHeight = - subtitle || left || right - ? CardSpacing.titleWithSupportingMinHeight - : CardSpacing.titleMinHeight; - const marginBottom = subtitle ? 0 : CardSpacing.titleBottomMargin; - return ( - + {left ? ( {left({ @@ -163,7 +157,7 @@ const CardTitle = ({ {title && ( )} - {right ? right({ size: 24 }) : null} + {right ? {right({ size: 24 })} : null} ); }; @@ -194,12 +188,13 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', - paddingLeft: CardSpacing.horizontalPadding, + gap: CardSpacing.titleGap, + paddingHorizontal: CardSpacing.horizontalPadding, + paddingTop: CardSpacing.regionGap, }, left: { justifyContent: 'center', - marginRight: CardSpacing.titleLeadingGap, height: LEFT_SIZE, width: LEFT_SIZE, }, @@ -212,17 +207,6 @@ const styles = StyleSheet.create({ flexDirection: 'column', justifyContent: 'center', }, - - title: { - minHeight: CardSpacing.titleTextMinHeight, - paddingRight: CardSpacing.horizontalPadding, - }, - - subtitle: { - minHeight: CardSpacing.subtitleTextMinHeight, - marginVertical: 0, - paddingRight: CardSpacing.horizontalPadding, - }, }); export default CardTitle; diff --git a/src/components/Card/tokens.ts b/src/components/Card/tokens.ts index b8936241aa..de8317f96b 100644 --- a/src/components/Card/tokens.ts +++ b/src/components/Card/tokens.ts @@ -235,26 +235,21 @@ export const CardTokens = { } as const satisfies CardTokenMatrix; /** - * Spacing of the Card layout helpers. + * Spacing of the Card and its layout helpers. * - * Material 3 specifies only the 16dp left/right padding - * (https://m3.material.io/components/cards/specs). It sets no header height, - * so the `Card.Title` heights below are kept from Paper 5 and headers keep - * their size. + * Material 3 specifies the 16dp left/right padding + * (https://m3.material.io/components/cards/specs) and no vertical spacing, + * so the vertical rhythm follows the Paper 6 Card from #5076: 16dp above + * each region and below the last one, 8dp below an action row. */ export const CardSpacing = { horizontalPadding: 16, - contentVerticalPadding: 16, - actionsVerticalPadding: 8, + /** Above each region, and below the last one when it is not an action row. */ + regionGap: 16, + /** Below an action row. */ + actionsBottomPadding: 8, + /** Between the controls of an action row. */ actionsGap: 8, - /** Between `Card.Title`'s leading element and its text. */ - titleLeadingGap: 16, - /** `Card.Title` with only a title. */ - titleMinHeight: 50, - /** `Card.Title` with a subtitle, a leading or a trailing element. */ - titleWithSupportingMinHeight: 72, - titleTextMinHeight: 30, - /** Below the title when there is no subtitle. */ - titleBottomMargin: 2, - subtitleTextMinHeight: 20, + /** Between `Card.Title`'s leading element, its text and its trailing element. */ + titleGap: 16, } as const; diff --git a/src/components/__tests__/Card/Card.test.tsx b/src/components/__tests__/Card/Card.test.tsx index 6654b395cf..77cfd58c8b 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1146,6 +1146,71 @@ describe('Card', () => { }); }); + const body = ( + + Body + + ); + const actionRow = ( + + Action + + ); + + it.each<[string, React.ReactElement]>([ + ['a header', ], + ['content', ], + [ + 'a header and content', + , + ], + ])('closes the bottom with 16dp when %s comes last', async (_, card) => { + await render(card); + + // A neutral Card puts its testID on the region that holds the slots. + expect(screen.getByTestId('card')).toHaveStyle({ paddingBottom: 16 }); + }); + + it.each<[string, React.ReactElement]>([ + [ + 'an action row', + , + ], + ['only media', } />], + ['no slot', ], + ])( + 'leaves the bottom to the last region when %s comes last', + async (_, card) => { + await render(card); + + expect(screen.getByTestId('card')).not.toHaveStyle({ + paddingBottom: 16, + }); + } + ); + + it('lets contentStyle remove the closing space of a row layout', async () => { + await render( + } + title="Title" + /> + ); + + expect(screen.getByTestId('card')).toHaveStyle({ + flexDirection: 'row', + paddingBottom: 0, + }); + }); + it('dims the slot content of a disabled Card', async () => { const { rerender } = await render( Body} /> @@ -1422,17 +1487,20 @@ describe('CardCover', () => { describe('CardTitle', () => { // Card adds no padding around its slots, so the header pads itself like // `Card.Content` does. - it('pads its own start edge and the end of its text', async () => { + it('pads its top and sides and spaces its parts by 16dp', async () => { await render( ); expect(screen.getByTestId('card-title')).toHaveStyle({ - paddingLeft: 16, + paddingHorizontal: 16, + paddingTop: 16, + gap: 16, + }); + // The header sizes from its content, with no minimum height. + expect(screen.getByTestId('card-title')).not.toHaveStyle({ minHeight: 72, }); - expect(screen.getByText('Title')).toHaveStyle({ paddingRight: 16 }); - expect(screen.getByText('Subtitle')).toHaveStyle({ paddingRight: 16 }); }); // A zero flex basis would collapse the titles in a row-laid-out Card on @@ -1454,7 +1522,7 @@ describe('CardTitle', () => { }); describe('CardContent', () => { - it('uses fixed padding when rendered standalone', async () => { + it('pads its top and sides when rendered standalone', async () => { await render( Content @@ -1463,7 +1531,11 @@ describe('CardContent', () => { expect(screen.getByTestId('card-content')).toHaveStyle({ paddingHorizontal: 16, - paddingVertical: 16, + paddingTop: 16, + }); + // The Card, not Card.Content, closes the bottom. + expect(screen.getByTestId('card-content')).not.toHaveStyle({ + paddingBottom: 16, }); }); @@ -1484,7 +1556,7 @@ describe('CardContent', () => { expect(screen.getByTestId('card-content')).toHaveStyle({ paddingHorizontal: 16, - paddingVertical: 16, + paddingTop: 16, }); }); @@ -1520,7 +1592,8 @@ describe('CardActions', () => { alignItems: 'center', justifyContent: 'flex-end', paddingHorizontal: 16, - paddingVertical: 8, + paddingTop: 16, + paddingBottom: 8, gap: 8, }); expect(screen.getByTestId('custom-action')).toBeOnTheScreen(); diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index ee91f81f2f..7768733c84 100644 --- a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap +++ b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap @@ -110,6 +110,7 @@ exports[`Card renders the enabled elevated appearance 1`] = ` "flexShrink": 1, "position": "relative", }, + false, { "opacity": 1, }, @@ -232,6 +233,7 @@ exports[`Card renders the enabled filled appearance 1`] = ` "flexShrink": 1, "position": "relative", }, + false, { "opacity": 1, }, @@ -354,6 +356,7 @@ exports[`Card renders the enabled outlined appearance 1`] = ` "flexShrink": 1, "position": "relative", }, + false, { "opacity": 1, }, From 37e974aa99a80cd42d33cde64ec652e2582ec2f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Norbert=20Kamie=C5=84ski?= Date: Fri, 20 Nov 2026 16:11:54 +0100 Subject: [PATCH 51/51] fix(card): round all four corners of Card.Cover again The Card.Cover rewrite dropped the cover's own corner radius and relied on the Card's clipping alone, so a cover met the rest of the Card with square corners. The Material 3 card examples round the image on every side, the inner corners included, and Paper 5 and main round it with `corner.medium`. Card.Cover again rounds all four corners with the theme's `corner.medium`, which also puts its `theme` prop back to use. The Card still clips its media to its own shape, and `style.borderRadius` still replaces the rounding. --- docs/6.x/docs/guides/migration.md | 2 +- example/src/Examples/CardExample.tsx | 2 +- src/components/Card/CardCover.tsx | 22 ++++++++++++++++----- src/components/__tests__/Card/Card.test.tsx | 22 ++++++++++++++++++--- 4 files changed, 38 insertions(+), 10 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 251e962874..fd3847ff6b 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -604,7 +604,7 @@ Use the `aspectRatio` prop to size a cover responsively. It replaces the default } /> ``` -The Card clips media to its shape, so a `Card.Cover` in the `media` slot follows the Card's corners without its own border radius. +`Card.Cover` rounds all four corners with the theme's `corner.medium`, as in Paper 5, and the Card also clips its media to the Card's shape. Pass `borderRadius` in the cover's `style` to change the rounding. `Card.Cover` no longer wraps its image in a `View`. Its `style` is now typed as `ImageStyle` and applies to the `Image` itself instead of a wrapper `View`. To style the area around the cover, wrap the cover in your own `View`: diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index 5b3ea54ee5..83d12b5d21 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -165,7 +165,7 @@ const CardExample = () => { } title="Custom border radius" - subtitle="The cover follows the Card's shape" + subtitle="The Card clips the cover to its shape" /> & { */ aspectRatio?: number; /** - * Style for the cover image. The default size is full width by 194. Consumer - * styles are applied after these defaults. + * Style for the cover image. The default size is full width by 194, with + * `corner.medium` rounding on every corner. Consumer styles are applied + * after these defaults, so `borderRadius` replaces the rounding. */ style?: StyleProp; /** @@ -24,8 +26,10 @@ export type Props = Omit & { /** * A component to show a cover image inside a Card. * - * Card owns clipping when the cover is used in its `media` slot, so the image - * follows the Card's default or custom shape without adding another radius. + * The cover rounds all four corners with the theme's `corner.medium`, as the + * Material 3 card examples show, including the inner corners where it meets + * the rest of the Card. In the `media` slot the Card also clips it to the + * Card's own shape. * Hide decorative covers from screen readers with `accessible={false}` and * `aria-hidden`. For informative covers, provide `accessible`, * `accessibilityRole="image"`, and a useful `accessibilityLabel`. @@ -54,12 +58,20 @@ export type Props = Omit & { * * @extends Image props https://reactnative.dev/docs/image#props */ -const CardCover = ({ aspectRatio, style, theme: _theme, ...rest }: Props) => { +const CardCover = ({ + aspectRatio, + style, + theme: themeOverrides, + ...rest +}: Props) => { + const theme = useInternalTheme(themeOverrides); + return ( { }); }); - it('uses the Card clipping shape for edge media without double rounding', async () => { + it('rounds its own corners inside the Card clipping shape', async () => { await render( { ); // The Card clips its media: the visual node around the slots carries - // the shape and hides the overflow, so the cover needs no radius. + // the shape and hides the overflow. expect(screen.getByTestId('edge-cover').parent?.parent).toHaveStyle({ overflow: 'hidden', borderTopLeftRadius: 4, @@ -1478,10 +1478,26 @@ describe('CardCover', () => { borderBottomRightRadius: 16, borderBottomLeftRadius: 20, }); - expect(screen.getByTestId('edge-cover')).not.toHaveStyle({ + // The cover still rounds its own corners, the inner ones included, as + // the Material 3 card examples show. + expect(screen.getByTestId('edge-cover')).toHaveStyle({ borderRadius: LightTheme.shapes.corner.medium, }); }); + + it('takes its corner rounding from the theme', async () => { + await render( + + ); + + expect(screen.getByTestId('themed-cover')).toHaveStyle({ + borderRadius: 20, + }); + }); }); describe('CardTitle', () => {