diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index e577f6be37..fd3847ff6b 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 Button; + return Animated Card} style={animatedStyle} />; }; ``` @@ -75,7 +76,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 +495,176 @@ 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. + +#### `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. 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 + + Shown outside a Card + +``` + +#### Horizontal layout + +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" +/> +``` + +#### 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 `194`: + +```tsx +} /> +``` + +`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 +- ++ ++ ++ +``` + +#### `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: + +```tsx +// Before (v5) — Card.Actions styled the buttons automatically + + + + + +// After (v6) — set mode explicitly + + + + +``` + +`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. + +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. + ### Surface - The `elevation` prop no longer accepts a React Native `Animated.Value`. Any `elevation` changes are animated automatically. @@ -1091,125 +1262,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` 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..b932b05483 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,21 @@ 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/plugins/component-docs/__tests__/parser.test.ts b/docs/plugins/component-docs/__tests__/parser.test.ts new file mode 100644 index 0000000000..be4acc6879 --- /dev/null +++ b/docs/plugins/component-docs/__tests__/parser.test.ts @@ -0,0 +1,48 @@ +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'); + 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 800bd8f2f3..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,29 +261,28 @@ 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; - }); + // 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 = - (hasUnionDeclarations && 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 [ { diff --git a/docs/src/components/ThemeColorsTable.tsx b/docs/src/components/ThemeColorsTable.tsx index d9c5cec724..c26155b3e6 100644 --- a/docs/src/components/ThemeColorsTable.tsx +++ b/docs/src/components/ThemeColorsTable.tsx @@ -23,13 +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, -}: { - themeColorsData: DataObject; - uniqueKeys: string[]; -}): ReactNode => { +}: TableProps): ReactNode => { const rows = Object.keys(themeColorsData).map((mode) => { const value = themeColorsData[mode]; @@ -50,7 +54,7 @@ const FlatTable = ({ - + {getTableHeader(uniqueKeys)} @@ -61,12 +65,10 @@ const FlatTable = ({ }; const TabbedTable = ({ + firstColumnLabel, themeColorsData, uniqueKeys, -}: { - themeColorsData: DataObject; - uniqueKeys: string[]; -}): ReactNode => { +}: TableProps): ReactNode => { const tabTableContent = Object.entries(themeColorsData).map( ([key, modes]) => { if (!isDataObject(modes)) { @@ -88,7 +90,7 @@ const TabbedTable = ({
mode{firstColumnLabel}
- + {getTableHeader(uniqueKeys)} @@ -120,12 +122,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/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index 09b732d9d0..83d12b5d21 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Alert, Platform, ScrollView, StyleSheet, View } from 'react-native'; +import { Alert, Platform, StyleSheet, View } from 'react-native'; import { Avatar, @@ -14,40 +14,58 @@ import { import { PreferencesContext } from '../PreferencesContext'; import ScreenWrapper from '../ScreenWrapper'; -type Mode = 'elevated' | 'outlined' | 'contained'; +type Variant = 'filled' | 'elevated' | 'outlined'; + +const variants: Variant[] = ['filled', 'elevated', 'outlined']; + +const showMessage = (message: string) => { + if (Platform.OS === 'web') { + alert(message); + } else { + Alert.alert(message); + } +}; + +const CustomHeader = () => ( + + + + Custom header + Any React node in the header slot + + +); const CardExample = () => { const { colors } = useTheme(); - const [selectedMode, setSelectedMode] = React.useState('elevated'); - const [isSelected, setIsSelected] = React.useState(false); + const [variant, setVariant] = React.useState('filled'); + const [isFavorite, setIsFavorite] = React.useState(false); const preferences = React.useContext(PreferencesContext); - const modes: Mode[] = ['elevated', 'outlined', 'contained']; - return ( - - - {modes.map((mode) => ( + + + {variants.map((item) => ( setSelectedMode(mode)} - style={styles.chip} + onPress={() => setVariant(item)} > - {mode} + {item} ))} - - + + - + } + title="Abandoned Ship" + content={ The Abandoned Ship is a wrecked ship located on Route 108 in @@ -56,62 +74,75 @@ const CardExample = () => { the Scanner. - - - + } + /> + + + } + header={ + } + content={ - This is a card using title and subtitle with specified variants. + A responsive 16:9 cover with a title and subtitle in custom + variants. - - - - - - - - - - } - right={(props: any) => ( - {}} /> - )} + } + /> + + } + 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. These can be any berry and will require attention to get - the best crop. + berries. - - + } + /> + + - + } + title="Custom Button styles" + actions={ @@ -119,98 +150,216 @@ const CardExample = () => { mode="filled" shape="square" theme={{ shapes: { corner: { medium: 12 } } }} - onPress={() => {}} + onPress={() => showMessage('Explored')} > Explore - - - - - - + } + /> + + + } + title="Custom border radius" + subtitle="The Card clips the cover to its shape" + /> + + - ( - setIsSelected(!isSelected)} - /> - )} + } + title="Just Strawberries" + subtitle="... and only Strawberries" + trailing={(props) => ( + setIsFavorite(!isFavorite)} /> - - { - Platform.OS === 'web' - ? alert('The Chameleon is Pressed') - : Alert.alert('The Chameleon is Pressed'); - }} - mode={selectedMode} - > + )} + /> + + showMessage('The Chameleon is Pressed')} + media={ - + } + title="Pressable Chameleon" + content={ - This is a pressable chameleon. If you press me, I will alert. + The whole Card is one target. If you press me, I will alert. - - { - Platform.OS === 'web' - ? alert('The City is Long Pressed') - : Alert.alert('The City is Long Pressed'); - }} - mode={selectedMode} - > - - } - /> + } + /> + + 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. - - { - preferences?.toggleTheme(); - }} - mode={selectedMode} - > - } + } + /> + + preferences?.toggleTheme()} + title="Pressable Theme Change" + leading={(props) => } + content={ + + + This is a pressable Card. If you press me, I will switch the + theme. + + + } + /> + + + 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 elevation prop. Only elevated Cards accept it. + + + } + /> + + + Set with the borderColor prop. + + } + /> + + + } + title="Asymmetric shape" + /> + + + } + title="Horizontal layout" + subtitle="Set flexDirection in contentStyle" + /> + + } + content={ - This is pressable card. If you press me, I will switch the theme. + A neutral Card with independent actions. - - + } + actions={ + + showMessage('Saved')} + /> + + + } + /> ); }; @@ -218,32 +367,37 @@ const CardExample = () => { CardExample.title = 'Card'; const styles = StyleSheet.create({ - container: { - flex: 1, + screen: { + gap: 8, + padding: 8, }, - content: { - padding: 4, + variants: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: 8, + paddingVertical: 4, }, - card: { - margin: 4, + sectionTitle: { + marginTop: 16, }, - chip: { - margin: 4, + horizontal: { + flexDirection: 'row', + // The cover reaches the bottom edge, so the row needs no closing space. + paddingBottom: 0, + }, + horizontalCover: { + height: 80, + width: 80, }, - preference: { + customHeader: { alignItems: 'center', flexDirection: 'row', - paddingVertical: 12, - paddingHorizontal: 8, + gap: 12, + paddingHorizontal: 16, + paddingTop: 16, }, - customCoverRadius: { - borderTopLeftRadius: 0, - borderTopRightRadius: 0, - borderBottomRightRadius: 24, - }, - bottomCover: { - marginTop: 0, - marginBottom: -16, + customHeaderText: { + flex: 1, }, }); 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..fa9a415c81 100644 --- a/example/src/Examples/TeamDetails.tsx +++ b/example/src/Examples/TeamDetails.tsx @@ -79,49 +79,69 @@ 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 876ba099c0..155007c772 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 { ColorValue, GestureResponderEvent, @@ -8,171 +8,504 @@ import type { ViewStyle, } from 'react-native'; -import useLatestCallback from 'use-latest-callback'; +import Animated, { + cubicBezier, + type AnimatedStyle, +} from 'react-native-reanimated'; 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 { CardSpacing } from './tokens'; +import { resolveCardVisuals } from './utils'; import { useInternalTheme } from '../../core/theming'; +import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; 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'; +import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; -type OutlinedCardProps = { - mode: 'outlined'; - elevation?: never; -}; - -type ElevatedCardProps = { - mode?: 'elevated'; - elevation?: Elevation; +type ConvenienceHeaderProps = { + /** + * Title rendered in the Card's header region. + */ + title?: React.ReactNode; + /** + * Subtitle rendered below `title` in the Card's header region. + */ + subtitle?: React.ReactNode; + /** + * Render slot displayed before `title` and `subtitle`. + */ + leading?: CardTitleProps['left']; + /** + * Render slot displayed after `title` and `subtitle`. + */ + trailing?: CardTitleProps['right']; + /** + * Fully custom header region. This cannot be combined with `title`, + * `subtitle`, `leading`, or `trailing`. + */ + header?: never; }; -type ContainedCardProps = { - mode?: 'contained'; - elevation?: never; +type CustomHeaderProps = { + /** + * Fully custom header region. This cannot be combined with `title`, + * `subtitle`, `leading`, or `trailing`. + */ + // 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. + */ + 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 CardShapeProps = { /** - * 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. + * Radius of every Card corner. */ - mode?: Mode; + borderRadius?: ViewStyle['borderRadius']; /** - * Direction of the Card's content. - * - `vertical` - * - `horizontal` + * Radius of the Card's bottom-end corner. */ - direction?: Direction; + borderBottomEndRadius?: ViewStyle['borderBottomEndRadius']; /** - * Content of the `Card`. + * Radius of the Card's bottom-left corner. */ - children: 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']; /** - * Changes Card shadow and background on iOS and Android. + * Radius of the Card's top-end corner. */ - elevation?: Elevation; + borderTopEndRadius?: ViewStyle['borderTopEndRadius']; /** - * Color of the outline in `outlined` mode. + * Radius of the Card's top-left corner. */ - borderColor?: ColorValue; + borderTopLeftRadius?: ViewStyle['borderTopLeftRadius']; + /** + * Radius of the Card's top-right corner. + */ + borderTopRightRadius?: ViewStyle['borderTopRightRadius']; /** - * Style of card's content. + * Radius of the Card's top-start corner. */ - contentStyle?: StyleProp; - style?: StyleProp; + borderTopStartRadius?: ViewStyle['borderTopStartRadius']; /** - * @optional + * Corner curve used by the Card on iOS. */ - theme?: ThemeProp; + borderCurve?: ViewStyle['borderCurve']; +}; + +type FilledCardProps = { /** - * Pass down testID from card props to touchable + * Material Card variant. `filled` is the default, `elevated` adds hierarchy + * with a shadow, and `outlined` adds a visible boundary. */ - testID?: string; + variant?: 'filled'; /** - * Pass down accessible from card props to touchable + * Resting elevation. Available only when `variant="elevated"`. */ - accessible?: boolean; + elevation?: never; /** - * Reference to the card container. + * Outline color. Available only when `variant="outlined"`. */ - ref?: React.Ref>; + borderColor?: never; }; -const DEFAULT_CARD_GAP = 16; -const DEFAULT_CARD_PADDING = 16; +type ElevatedCardProps = { + /** + * Elevated Card variant. + */ + variant: 'elevated'; + /** + * Resting shadow elevation for an elevated Card. + */ + elevation?: Elevation; + /** + * Outline color. Available only when `variant="outlined"`. + */ + borderColor?: never; +}; + +type OutlinedCardProps = { + /** + * Outlined Card variant. + */ + variant: 'outlined'; + /** + * Outlined Cards do not support custom elevation. + */ + elevation?: never; + /** + * 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; +}; + +type CardVariantProps = FilledCardProps | ElevatedCardProps | OutlinedCardProps; + +export type Props = Omit & + CardShapeProps & { + /** + * 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 content rendered after the header. Use `Card.Content` when the + * standard Card padding is desired. + */ + content?: React.ReactNode; + /** + * 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; + /** + * 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; + /** + * 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`. + */ + delayLongPress?: number; + /** + * If true, disable all interactions for this component. + */ + disabled?: boolean; + /** + * 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; + /** + * 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; + /** + * Layout style for the outer Card shell. Use the dedicated shape props and + * `variant` or `elevation` for Card visuals. + */ + style?: StyleProp; + /** + * @optional + */ + theme?: ThemeProp; + /** + * Test ID for the interaction node when the Card is actionable, or the + * content node when it is neutral. + */ + testID?: string; + /** + * 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; + /** + * Reference to the actionable Card interaction node. + */ + touchableRef?: React.Ref>; + /** + * Reference to the outer Card shell. + */ + ref?: React.Ref>; + } & (ConvenienceHeaderProps | CustomHeaderProps) & + CardVariantProps; + +const isPopulated = (slot: React.ReactNode) => + React.Children.toArray(slot).length > 0; /** - * A card is a sheet of material that serves as an entry point to more detailed information. + * 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. + * + * 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. + * `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 CardExamples = () => ( + * + * console.log('Open trip details')} + * media={} + * title="Weekend trip" + * subtitle="Actionable filled Card" + * leading={(props) => } + * content={ + * View the itinerary. + * } + * /> * - * const LeftContent = props => + * + * Review before saving. + * } + * actions={ + * + * + * } + * /> * - * const MyComponent = () => ( - * - * - * - * - * Card title - * Card content - * - * - * - * - * - * + * } + * content={ + * Supply any React node as the header. + * } + * /> + * * ); * - * export default MyComponent; + * export default CardExamples; * ``` */ + const Card = ({ - elevation: cardElevation = 1, + variant: cardVariant = 'filled', + elevation: customElevation, + borderColor: customBorderColor, 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, accessible, disabled, + dragged = false, + 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, + borderBottomRightRadius, + borderBottomStartRadius, + borderEndEndRadius, + borderEndStartRadius, + borderStartEndRadius, + borderStartStartRadius, + borderTopEndRadius, + borderTopLeftRadius, + borderTopRightRadius, + borderTopStartRadius, + borderCurve = 'continuous', ref, ...rest -}: (OutlinedCardProps | ElevatedCardProps | ContainedCardProps) & Props) => { +}: Props) => { const theme = useInternalTheme(themeOverrides); - const isMode = React.useCallback( - (modeToCompare: Mode) => { - return cardMode === modeToCompare; - }, - [cardMode] + const reduceMotion = useReduceMotion(); + + const isDisabled = Boolean( + 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); + + const visuals = resolveCardVisuals({ + theme, + variant: cardVariant, + elevation: customElevation, + disabled: isDisabled, + dragged, + pressed, + focused, + hovered, + }); + 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. + const stateLayerOpacity = + visuals.state === 'pressed' ? 0 : visuals.stateLayerOpacity; + // 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, + transitionTimingFunction, + }; + const outlineTransitionStyle: AnimatedStyle = { + // A PlatformColor outline cannot be interpolated. + transitionProperty: + typeof outlineColor === 'string' ? ['borderColor', 'opacity'] : 'opacity', + transitionDuration, + transitionTimingFunction, + }; + const hasPassedTouchHandler = hasTouchHandler({ onPress, onLongPress, @@ -180,119 +513,325 @@ 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. + // 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 + // 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 `Pressable` unmounts then, and a + // 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( - disabled || !hasPassedTouchHandler, + isDisabled || !hasPassedTouchHandler, theme.colors.secondary, 'outward', 'within' ); + const hasWarnedAboutActions = React.useRef(false); + // `React.Children` only tells an empty slot (`[]`, `null`, `false`) from a + // populated one; it never looks inside the slot. + const hasActions = isPopulated(actions); - 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); + 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 handlePressOut = useLatestCallback((e: GestureResponderEvent) => { - onPressOut?.(e); - - if (isMode('elevated')) { - setPressed(false); - } - }); - - const { backgroundColor, borderColor: themedBorderColor } = getCardColors({ - theme, - mode: cardMode, - }); - - const borderColor = customBorderColor ?? themedBorderColor; + 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 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 borderRadius = theme.shapes.corner.medium; + const content = ( + + {media} + {headerRegion} + {cardContent} + {actions} + + ); - const cardContext = React.useMemo( - () => ({ padding: DEFAULT_CARD_PADDING, direction: cardDirection }), - [cardDirection] + 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, + // 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( + (event: GestureResponderEvent) => { + setPressed(true); + onPressIn?.(event); + }, + [onPressIn] + ); + const handlePressOut = React.useCallback( + (event: GestureResponderEvent) => { + setPressed(false); + onPressOut?.(event); + }, + [onPressOut] ); + const handleFocus: NonNullable = + React.useCallback( + (event) => { + focusTarget.onFocus?.(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] + ); + const handleBlur: NonNullable = + React.useCallback( + (event) => { + focusTarget.onBlur?.(); + setFocused(false); + setPressed(false); + onBlur?.(event); + }, + [focusTarget, onBlur] + ); + const handleHoverIn: NonNullable = + React.useCallback( + (event) => { + setHovered(true); + onHoverIn?.(event); + }, + [onHoverIn] + ); + const handleHoverOut: NonNullable = + React.useCallback( + (event) => { + setHovered(false); + onHoverOut?.(event); + }, + [onHoverOut] + ); - const content = ( - - - {children} - - + 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. 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 ? ( + + ) : null} + ); + const visualStyle = [ + styles.visual, + shapeStyle, + visuals.containerOpacity === 1 && { + backgroundColor: visuals.containerColor, + }, + ]; return ( - {isMode('outlined') && ( - - )} - {hasPassedTouchHandler ? ( - - {content} - + {layers} + ) : ( - content + {layers} )} ); @@ -310,22 +849,16 @@ Card.Cover = CardCover; Card.Title = CardTitle; const styles = StyleSheet.create({ - content: { + visual: { flexShrink: 1, overflow: 'hidden', }, - horizontal: { - flexDirection: 'row', - }, - vertical: { - flexDirection: 'column', + content: { + flexShrink: 1, + position: 'relative', }, - outline: { - borderWidth: 1, - position: 'absolute', - width: '100%', - height: '100%', - zIndex: 2, + closedContent: { + paddingBottom: CardSpacing.regionGap, }, }); diff --git a/src/components/Card/CardActions.tsx b/src/components/Card/CardActions.tsx index a126824025..e6067b3d10 100644 --- a/src/components/Card/CardActions.tsx +++ b/src/components/Card/CardActions.tsx @@ -2,8 +2,7 @@ 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 { CardSpacing } from './tokens'; import type { ThemeProp } from '../../theme/types'; export type Props = ViewProps & { @@ -24,48 +23,22 @@ export type Props = ViewProps & { * import { Card, Button } from 'react-native-paper'; * * const MyComponent = () => ( - * - * - * - * - * - * + * + * + * + * } + * /> * ); * * 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 +46,11 @@ const styles = StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center', - columnGap: 8, - paddingHorizontal: 8, - paddingBottom: 8, + justifyContent: 'flex-end', + paddingHorizontal: CardSpacing.horizontalPadding, + paddingTop: CardSpacing.regionGap, + paddingBottom: CardSpacing.actionsBottomPadding, + gap: CardSpacing.actionsGap, }, }); diff --git a/src/components/Card/CardContent.tsx b/src/components/Card/CardContent.tsx index fea1e519da..30148129a6 100644 --- a/src/components/Card/CardContent.tsx +++ b/src/components/Card/CardContent.tsx @@ -1,7 +1,9 @@ import * as React from 'react'; -import { View } from 'react-native'; +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`. @@ -19,21 +21,28 @@ export type Props = ViewProps & { * import { Card, Text } from 'react-native-paper'; * * const MyComponent = () => ( - * - * + * * Card title * Card content - * - * + * } + * /> * ); * * export default MyComponent; * ``` */ const CardContent = ({ style, ...rest }: Props) => ( - + ); CardContent.displayName = 'Card.Content'; +const styles = StyleSheet.create({ + container: { + paddingHorizontal: CardSpacing.horizontalPadding, + paddingTop: CardSpacing.regionGap, + }, +}); + export default CardContent; 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 173cd316c2..956303bbf9 100644 --- a/src/components/Card/CardCover.tsx +++ b/src/components/Card/CardCover.tsx @@ -1,14 +1,22 @@ -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; + /** + * Width-to-height ratio of the cover, for example `16 / 9`. When set, the + * 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 194, with + * `corner.medium` rounding on every corner. Consumer styles are applied + * after these defaults, so `borderRadius` replaces the rounding. + */ + style?: StyleProp; /** * @optional */ @@ -18,15 +26,31 @@ export type Props = Omit & { /** * A component to show a cover image inside a Card. * + * 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`. + * * ## Usage * ```js * import * as React from 'react'; * import { Card } from 'react-native-paper'; * * const MyComponent = () => ( - * - * - * + * + * } + * /> * ); * * export default MyComponent; @@ -34,53 +58,45 @@ export type Props = Omit & { * * @extends Image props https://reactnative.dev/docs/image#props */ -const CardCover = ({ style, theme: themeOverrides, ...rest }: Props) => { +const CardCover = ({ + aspectRatio, + 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; - // 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, + image: { + width: '100%', backgroundColor: grey200, - overflow: 'hidden', + justifyContent: 'flex-end', }, - image: { - flex: 1, + defaultHeight: { + height: 194, + }, + autoHeight: { height: 'auto', - width: 'auto', - justifyContent: 'flex-end', }, }); diff --git a/src/components/Card/CardTitle.tsx b/src/components/Card/CardTitle.tsx index ed8289cde5..05483a8669 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'; @@ -175,7 +176,7 @@ const CardTitle = ({ )} - {right ? right({ size: 24 }) : null} + {right ? {right({ size: 24 })} : null} ); }; @@ -187,15 +188,22 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', - gap: 16, + gap: CardSpacing.titleGap, + paddingHorizontal: CardSpacing.horizontalPadding, + paddingTop: CardSpacing.regionGap, }, + left: { justifyContent: 'center', height: LEFT_SIZE, width: LEFT_SIZE, }, + 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/Card/tokens.ts b/src/components/Card/tokens.ts new file mode 100644 index 0000000000..de8317f96b --- /dev/null +++ b/src/components/Card/tokens.ts @@ -0,0 +1,255 @@ +import { tokens as systemTokens } from '../../theme/tokens'; +import type { Elevation } 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' + | 'surface' + | 'onSurface'; + +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-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 + * - FilledCardTokens v0_210 + * - ElevatedCardTokens v0_210 + * - 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 + */ +export const CardTokens = { + 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: 'onSurface', + 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; + +/** + * Spacing of the Card and its layout helpers. + * + * 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, + /** 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, its text and its trailing element. */ + titleGap: 16, +} as const; 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/Card/utils.tsx b/src/components/Card/utils.tsx deleted file mode 100644 index ab629378e2..0000000000 --- a/src/components/Card/utils.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; - -import type { InternalTheme } from '../../theme/types'; - -type CardMode = 'elevated' | 'outlined' | 'contained'; - -export type CardActionChildProps = { - mode?: string; - style?: StyleProp; -}; - -const getBorderColor = ({ theme }: { theme: InternalTheme }) => { - return theme.colors.outline; -}; - -const getBackgroundColor = ({ - theme, - isMode, -}: { - theme: InternalTheme; - isMode: (mode: CardMode) => boolean; -}) => { - const { colors } = theme; - if (isMode('contained')) { - return colors.surfaceVariant; - } - if (isMode('outlined')) { - return colors.surface; - } - 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 }), - }; -}; 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 6bea220fad..3e43e7800c 100644 --- a/src/components/__tests__/Card/Card.test.tsx +++ b/src/components/__tests__/Card/Card.test.tsx @@ -1,276 +1,1679 @@ -import type { ComponentProps } from 'react'; -import { Platform, StyleSheet, Text } from 'react-native'; +import * as React from 'react'; +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 { cubicBezier, getAnimatedStyle } from 'react-native-reanimated'; -import { render, screen } from '../../../test-utils'; -import { LightTheme } from '../../../theme/schemes'; +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 { getCardColors } from '../../Card/utils'; +import type { Props as CardProps } from '../../Card/Card'; +import type { CardVariant } from '../../Card/tokens'; +import { resolveCardVisuals } from '../../Card/utils'; +import type { CardStateFlags } from '../../Card/utils'; const styles = StyleSheet.create({ - customCoverRadius: { - borderTopLeftRadius: 4, - borderTopRightRadius: 8, - borderBottomLeftRadius: 0, - borderBottomRightRadius: 2, - }, contentStyle: { flexDirection: 'column-reverse', }, + customAction: { + marginRight: 12, + }, }); +const getVariantCard = ( + variant: 'filled' | 'elevated' | 'outlined', + props: Pick = {} +) => { + if (variant === 'elevated') { + return ; + } + if (variant === 'outlined') { + return ; + } + return ; +}; + +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: 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; + + if (!visual?.parent) { + throw new Error('Card visual node not found'); + } + + 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, + // 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) => { + 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. +const expectCardState = ( + variant: CardVariant, + flags: CardStateFlags = {}, + { theme = LightTheme, neutral = false } = {} +) => { + const visuals = resolveCardVisuals({ theme, variant, ...flags }); + const { surface, visual, containerLayer, content, stateLayer, outline } = + getCardLayers({ neutral }); + + 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 }); + 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({ + 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(() => { jest.restoreAllMocks(); }); describe('Card', () => { - it('renders an outlined card', async () => { - const tree = (await render({null})).toJSON(); + it.each(['filled', 'elevated', 'outlined'] as const)( + 'renders the enabled %s appearance', + async (variant) => { + await render(getVariantCard(variant)); + + expect(screen.toJSON()).toMatchSnapshot(); + } + ); + + 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 })); + + expect(getCardLayers({ neutral: true }).container).toHaveStyle({ + backgroundColor: theme.colors[containerRole], + }); + expectCardState(variant, {}, { theme, neutral: true }); - expect(tree).toMatchSnapshot(); + await unmount(); + } + } + ); + + it.each(['filled', 'elevated'] as const)( + 'does not render an outline for the %s variant', + async (variant) => { + await render(getVariantCard(variant)); + + 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( + {}} + theme={{ + colors: { + surfaceContainerHighest: '#111111', + onSurface: '#222222', + }, + }} + /> + ); + + const { surface, container, stateLayer, outline } = getCardLayers(); + + expect(container).toHaveStyle({ backgroundColor: '#111111' }); + expect(stateLayer).toHaveStyle({ backgroundColor: '#222222' }); + expect(outline).toBeUndefined(); + expect(surface).toHaveStyle({ elevation: 0 }); }); - it('renders an outlined card with a custom outline color', async () => { - const { toJSON } = await render( + it('uses custom theme roles for elevated and outlined variants', async () => { + const { unmount } = await render( - {null} - + testID="card" + variant="elevated" + theme={{ colors: { surfaceContainerLow: '#123456' } }} + /> + ); + + expect(getCardLayers({ neutral: true }).container).toHaveStyle({ + backgroundColor: '#123456', + }); + await unmount(); + + await render( + ); - expect(toJSON()).toMatchSnapshot(); + 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 () => { + jest.replaceProperty(Platform, 'OS', 'android'); + + await render(); + + expect(getCardLayers({ neutral: true }).surface).toHaveStyle({ + elevation: androidElevationLevels[5], + }); + }); + + 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(getVariantCard(variant)); + + expect(getCardLayers({ neutral: true }).surface).toHaveStyle({ + elevation: androidElevationLevels[level], + }); }); - it('renders the outline with the color passed to borderColor prop', async () => { - const { toJSON } = await render( - - {null} - + it('applies the medium shape and asymmetric overrides across the shell', async () => { + 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.outline]) { + expect(layer).toHaveStyle({ + borderRadius: LightTheme.shapes.corner.medium, + }); + } + await unmount(); + + const { unmount: unmountOutlined } = await render( + ); - expect(toJSON()).toMatchSnapshot(); + const { surface, visual, outline } = getCardLayers({ neutral: true }); + + 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 with a custom theme background color', async () => { - jest.replaceProperty(Platform, 'OS', 'web'); + it('renders populated slots in deterministic order without rewriting nodes', async () => { + const CustomContent = React.memo(() => ( + + Custom content + + )); await render( - {null} - + media={} + header={} + content={[ + , + null, + , + ]} + actions={ + <> + {null} + + + } + /> ); - expect(screen.getByLabelText('card')).toHaveStyle({ - backgroundColor: '#0000FF', - }); + 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 with a content style', async () => { + it('renders omitted slots as a neutral filled grouping container', async () => { + await render(); + + expectCardState('filled', {}, { neutral: true }); + expect(screen.getByTestId('card')).not.toHaveProp('focusable'); + expect(screen.queryByRole('button')).not.toBeOnTheScreen(); + }); + + it('preserves explicit semantics on a neutral Card shell', async () => { await render( - - Content - + ); - expect(screen.getByText('Content').parent).toHaveStyle(styles.contentStyle); + const shell = screen.getByRole('summary', { name: 'Product summary' }); + + expect(shell).toHaveProp( + 'accessibilityHint', + 'Contains product information' + ); + expect(shell).toHaveProp('focusable', false); + expect(screen.getByTestId('product-card')).not.toHaveProp('role'); }); - it('clips inner content to the card shape', async () => { + 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( - - Content - + ); - expect(screen.getByText('Content').parent).toHaveStyle({ - borderRadius: LightTheme.shapes.corner.medium, - overflow: 'hidden', - }); + 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('does not render a disabled accessibility state', async () => { - await render({null}); + 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} + /> + ); - expect(screen.getByTestId('card')).toBeEnabled(); + const target = screen.getByRole('link', { name: 'Open product' }); + + 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' }, + ]); + // The shell only forwards accessibility semantics to the interaction + // target, so the shell itself should carry none of them. + 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'); + 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('does render a disabled accessibility state', async () => { + + it('keeps the ripple, visual layers, and focus indicator on the Card shape', async () => { + const shape = { + borderTopLeftRadius: 4, + borderTopRightRadius: 8, + borderBottomRightRadius: 16, + borderBottomLeftRadius: 20, + }; + const { unmount } = await render( + {}} /> + ); + + const interaction = screen.getByTestId('product-card'); + const stateLayer = interaction.children + .filter((child): child is Layer => typeof child !== 'string') + .find(isLayer); + + // 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(stateLayer).toHaveStyle(shape); + expect(interaction.parent).toHaveStyle(shape); + 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( - {}} disabled> - {null} - + {}} + /> ); - expect(screen.getByTestId('card')).toBeDisabled(); + expect(shellRef.current).not.toBeNull(); + expect(touchableRef.current).not.toBeNull(); + expect(touchableRef.current).not.toBe(shellRef.current); }); -}); -describe('CardCover', () => { - it('renders with the theme border radius by default', async () => { + it.each(['filled', 'elevated', 'outlined'] as const)( + 'shows and clears the %s hover feedback', + async (variant) => { + jest.replaceProperty(Platform, 'OS', 'android'); + await render(getVariantCard(variant, { onPress: () => {} })); + const target = screen.getByTestId('card'); + + await fireEvent(target, 'hoverIn'); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.08 }); + expectCardState(variant, { hovered: true }); + + await fireEvent(target, 'hoverOut'); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState(variant); + } + ); + + it.each(['filled', 'elevated', 'outlined'] as const)( + 'shows and clears the %s pressed feedback', + async (variant) => { + jest.replaceProperty(Platform, 'OS', 'android'); + await render(getVariantCard(variant, { onPress: () => {} })); + const target = screen.getByTestId('card'); + + await fireEvent(target, 'pressIn'); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState(variant, { pressed: true }); + + await fireEvent(target, 'pressOut'); + await settle(); + + expectCardState(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'); + + await render(getVariantCard(variant, { dragged: true })); + + 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'] as const)( + 'renders the Material disabled treatment for %s Cards', + async (variant) => { + jest.replaceProperty(Platform, 'OS', 'android'); + await render( + getVariantCard(variant, { disabled: true, onPress: () => {} }) + ); + + const { container, content } = getCardLayers(); + + expect(container).toHaveStyle({ opacity: 0.38 }); + expect(content).toHaveStyle({ opacity: 0.38 }); + expectCardState(variant, { disabled: true }); + } + ); + + it('renders the Material disabled treatment for outlined Cards', async () => { + jest.replaceProperty(Platform, 'OS', 'android'); await render( - - - + getVariantCard('outlined', { disabled: true, onPress: () => {} }) ); - expect(screen.getByTestId('card-cover').parent).toHaveStyle({ - borderRadius: LightTheme.shapes.corner.medium, + const { containerLayer, content, outline } = getCardLayers(); + + // 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 }); + }); + + 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 settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.16 }); + expectCardState('outlined', { dragged: true }); + + await rerender(); + await settle(); + + expect(getCardLayers().outline).toHaveStyle({ opacity: 0.12 }); + expectCardState('outlined', { disabled: true }); + }); + + it('updates the controlled dragged presentation in both directions', async () => { + jest.replaceProperty(Platform, 'OS', 'android'); + const props = { variant: 'outlined' as const, onPress: () => {} }; + const { rerender } = await render(); + + await rerender(); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.16 }); + expectCardState('outlined', { dragged: true }); + + await rerender(); + await settle(); + + 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) => { + jest.replaceProperty(Platform, 'OS', 'web'); + await render(getVariantCard(variant, { onPress: () => {} })); + + await fireEvent(screen.getByTestId('card'), 'focus', selfFocus(true)); + 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', + }); + 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 () => { + jest.replaceProperty(Platform, 'OS', 'web'); + await render( {}} />); + const target = screen.getByTestId('card'); + + await fireEvent(target, 'focus', selfFocus(false)); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + expectCardState('outlined'); + + await fireEvent(target, 'focus', selfFocus(true)); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0.1 }); + expectCardState('outlined', { focused: true }); + + await fireEvent(target, 'blur'); + await settle(); + + expect(getCardLayers().stateLayer).toHaveStyle({ opacity: 0 }); + 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('renders with custom border radius', async () => { - await render( - - - + it('clears hover feedback when the Card stops being actionable', async () => { + jest.replaceProperty(Platform, 'OS', 'android'); + const { rerender } = await render( + {}} /> ); - // The border radius is applied to the container which clips the image - expect(screen.getByTestId('card-cover').parent).toHaveStyle( - styles.customCoverRadius + 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'); }); -}); -describe('CardActions', () => { - it('renders button with passed mode', async () => { - const buttonProps = jest.fn(); - const ProbeButton = (props: ComponentProps) => { - buttonProps(props); + it('uses pressed, focused, then hovered precedence and settles at the latest state', async () => { + await render( {}} />); + const target = screen.getByTestId('card'); - return + + } + /> + ); + 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.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'; + 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( + Leading {size}} + trailing={({ size }) => Trailing {size}} + /> ); + + 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('does not inject default button props', async () => { - const buttonProps = jest.fn(); - const ProbeButton = (props: ComponentProps) => { - buttonProps(props); + it('renders with a content style', async () => { + await render( + Content} + contentStyle={styles.contentStyle} + /> + ); + + expect(screen.getByText('Content').parent).toHaveStyle(styles.contentStyle); + }); - return - - - + } + title="Title" + /> ); - expect(screen.getByTestId('card-actions')).toHaveStyle({ + expect(screen.getByTestId('card')).toHaveStyle({ flexDirection: 'row', - justifyContent: 'flex-end', - columnGap: 8, + paddingBottom: 0, }); }); + + 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(); + + 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(target).toBeDisabled(); + await userEvent.press(target); + expect(onPress).not.toHaveBeenCalled(); + }); +}); + +describe('Card types', () => { + it('accepts documented examples and rejects removed or mixed forms', () => { + const variant = 'filled' as 'filled' | 'elevated' | 'outlined'; + const typeCases = ( + <> + + } + actions={} + /> + + } /> + {}} + media={} + title="Weekend trip" + subtitle="Actionable filled Card" + content={ + + View the itinerary. + + } + /> + + Review before saving. + + } + actions={ + + + + + } + /> + } + content={ + + Supply any React node as the header. + + } + /> + } + 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: 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" /> + + {/* @ts-expect-error: Custom and convenience headers are mutually exclusive. */} + } leading={() => } /> + + {/* @ts-expect-error: Cover placement metadata is not public. */} + + + ); + + expect(typeCases).toBeDefined(); + }); }); -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, +describe('CardCover', () => { + it('uses the documented full-width default size', async () => { + await render( + + ); + + expect(screen.getByTestId('card-cover')).toHaveStyle({ + width: '100%', + height: 194, + }); + }); + + it('uses an aspect ratio instead of the default height', async () => { + await render( + + ); + + const cover = screen.getByTestId('responsive-cover'); + + // `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 () => { + 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( + + ); + + expect(screen.getByTestId('styled-cover')).toHaveStyle({ + width: 320, + height: 200, + opacity: 0.8, + borderRadius: 6, }); }); - it('should return correct theme color, for theme version 3, outlined mode', () => { - expect( - getCardColors({ - theme: LightTheme, - mode: 'outlined', - }) - ).toMatchObject({ backgroundColor: LightTheme.colors.surface }); + 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. + expect(screen.getByTestId('edge-cover').parent?.parent).toHaveStyle({ + overflow: 'hidden', + borderTopLeftRadius: 4, + borderTopRightRadius: 8, + borderBottomRightRadius: 16, + borderBottomLeftRadius: 20, + }); + // 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('should return undefined, for theme version 3, elevated mode', () => { - expect( - getCardColors({ - theme: LightTheme, - mode: 'elevated', - }) - ).toMatchObject({ backgroundColor: undefined }); + it('takes its corner rounding from the theme', async () => { + await render( + + ); + + expect(screen.getByTestId('themed-cover')).toHaveStyle({ + borderRadius: 20, + }); }); }); -describe('getCardColors - border color', () => { - it('should return correct theme color, for theme version 3', () => { - expect( - getCardColors({ - theme: LightTheme, - // @ts-expect-error: Verify the runtime fallback when mode is omitted. - mode: undefined, - }) - ).toMatchObject({ borderColor: LightTheme.colors.outline }); +describe('CardTitle', () => { + // Card adds no padding around its slots, so the header pads itself like + // `Card.Content` does. + it('pads its top and sides and spaces its parts by 16dp', async () => { + await render( + + ); + + expect(screen.getByTestId('card-title')).toHaveStyle({ + 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, + }); + }); + + // 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', () => { - it('uses the Card padding when it follows a cover and a title', async () => { + it('pads its top and sides when rendered standalone', async () => { await render( - - - - - Card content - - + + Content + ); - expect(screen.getByTestId('card-content').parent).toHaveStyle({ - padding: 16, - gap: 16, + expect(screen.getByTestId('card-content')).toHaveStyle({ + paddingHorizontal: 16, + paddingTop: 16, + }); + // The Card, not Card.Content, closes the bottom. + expect(screen.getByTestId('card-content')).not.toHaveStyle({ + paddingBottom: 16, + }); + }); + + it('uses fixed padding regardless of neighboring card elements', async () => { + await render( + <> + + + + Content + + + + + + + ); + + expect(screen.getByTestId('card-content')).toHaveStyle({ + paddingHorizontal: 16, + paddingTop: 16, + }); + }); + + it('lets consumer styles override the default padding', async () => { + await render( + + Content + + ); + + expect(screen.getByTestId('card-content')).toHaveStyle({ + paddingHorizontal: 24, + paddingVertical: 12, + }); + }); +}); + +describe('CardActions', () => { + it('lays out heterogeneous nodes with container-owned spacing', async () => { + await render( + + + + Details + + ); + + expect(screen.getByTestId('card-actions')).toHaveStyle({ + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'flex-end', + paddingHorizontal: 16, + paddingTop: 16, + paddingBottom: 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', + paddingHorizontal: 4, + paddingVertical: 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, }); }); }); 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..c6adae37dd --- /dev/null +++ b/src/components/__tests__/Card/Card.tokens.test.ts @@ -0,0 +1,269 @@ +import { describe, expect, it } from '@jest/globals'; + +import { LightTheme } from '../../../theme/schemes'; +import { cardStates, cardVariants } from '../../Card/tokens'; +import type { CardState, CardVariant } from '../../Card/tokens'; +import { resolveCardVisuals } from '../../Card/utils'; + +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' + | 'surface' + | 'onSurface'; + 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: 'onSurface', + 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, + contentOpacity: cardStates[index] === 'disabled' ? 0.38 : 1, + }) + ) + ); + } + ); + + 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()); + }); + + 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; + + expect( + resolveCardVisuals({ theme, variant: 'elevated', elevation: 5 }).elevation + ).toBe(5); + expect( + resolveCardVisuals({ + theme, + variant: 'elevated', + elevation: 5, + hovered: true, + }).elevation + ).toBe(2); + }); +}); diff --git a/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap b/src/components/__tests__/Card/__snapshots__/Card.test.tsx.snap index c746b6a75b..7768733c84 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 renders an outlined card 1`] = ` +exports[`Card renders the enabled elevated appearance 1`] = ` - + > + + `; -exports[`Card renders an outlined card with a custom outline color 1`] = ` +exports[`Card renders the enabled filled appearance 1`] = ` - + > + + `; -exports[`Card renders the outline with the color passed to borderColor prop 1`] = ` +exports[`Card renders the enabled outlined appearance 1`] = ` - + > + + + `; 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..0647ce1821 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,12 +126,19 @@ 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();