From 653a53a848086fabdd45b695c26130d860e8d152 Mon Sep 17 00:00:00 2001 From: Nikolay Arefyev Date: Thu, 12 Nov 2026 12:36:57 +0200 Subject: [PATCH 1/7] feat(appbar)!: read parts from context and add Expressive props MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Appbar no longer inspects and clones its children. Appbar.BackAction, Appbar.Content and Appbar.Action read dark, theme and mode from context, so they work when wrapped in other components such as Tooltip. Adds Material 3 Expressive support as props on the existing parts: - mode="medium-flexible" and mode="large-flexible" on Appbar and Appbar.Header, which grow with a title that wraps onto a second line - variant and width on Appbar.Action for filled, tonal and wide actions - isScrolled on Appbar and Appbar.Header for the on-scroll color The surface renders in flat mode so an animated style shows on iOS. The bottom bar keeps working and is deprecated until Toolbar lands. BREAKING CHANGE: Appbar renders its children in the order they are given instead of moving Appbar.BackAction and the actions with isLeading to the front. Appbar.Content always has a 12dp margin before its title, and its internal mode prop is removed. In the center-aligned mode, only Appbar.BackAction and actions with isLeading count as leading actions. Based on the work in #5075 by Paweł Kata. Co-Authored-By: Paweł Kata Co-Authored-By: Claude Sonnet 5.5 --- docs/6.x/docs/guides/migration.md | 42 ++ example/src/Examples/AppbarExample.tsx | 37 +- src/components/Appbar/Appbar.tsx | 287 ++++++------ src/components/Appbar/AppbarAction.tsx | 57 ++- src/components/Appbar/AppbarContent.tsx | 125 ++++-- src/components/Appbar/AppbarContext.tsx | 58 +++ src/components/Appbar/AppbarHeader.tsx | 10 +- src/components/Appbar/utils.ts | 133 ++---- .../__tests__/Appbar/Appbar.test.tsx | 407 ++++++++++++++---- .../Appbar/__snapshots__/Appbar.test.tsx.snap | 391 ++--------------- 10 files changed, 795 insertions(+), 752 deletions(-) create mode 100644 src/components/Appbar/AppbarContext.tsx diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index da236a623b..220afd64e5 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -372,6 +372,48 @@ To keep the height of the content row when setting `height` in `style`, add the ``` +#### Parts read from the `Appbar` + +`Appbar` no longer inspects its children and clones them to pass `color`, `theme`, `mode` and `style`. `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action` now read the `dark` and `theme` props and the `mode` of the `Appbar` they are rendered in from context. This means they can be wrapped in other components, for example in a `Tooltip` or a `View`, and still get the colors and the theme of the `Appbar`. A `theme` set on a part takes precedence over the `theme` of the `Appbar`. + +The parts are rendered in the order they are given, so render the leading actions first, then `Appbar.Content`, then the trailing actions. Previously, `Appbar.BackAction` and the actions with `isLeading` were moved before the rest. + +- `Appbar.Content` always has a `12dp` margin before its title. Previously, the margin was only added when the title was the first item after `Appbar.BackAction`. +- The `mode` prop of `Appbar.Content`, which was for internal use, is removed. +- In the `center-aligned` mode, the title is centered between the actions when there is room for it. The actions before the title count as leading actions only when they are `Appbar.BackAction` or have `isLeading`. + +```diff + +- {}} /> ++ {}} /> + + {}} /> + +``` + +#### Material 3 Expressive + +- The `mode` prop of `Appbar` and `Appbar.Header` accepts two new values: `medium-flexible` and `large-flexible`. Their height is the minimum height (`112` and `120`), and they grow when the title wraps onto a second line. +- `Appbar.Action` has new `variant` and `width` props. `variant="filled"` and `variant="tonal"` render the action in a container, and `width="wide"` makes the container wider. +- `Appbar` and `Appbar.Header` have a new `isScrolled` prop. Set it when the content below has scrolled, to switch the container to the `surfaceContainer` color. Unlike `elevated`, it doesn't add elevation. + +```tsx + + {}} /> + + {}} + /> + +``` + +#### Bottom bar + +Using `Appbar` as a bottom bar is deprecated. Material Design 3 moves the bottom bar to toolbars. It continues to work in 6.x, and will be replaced by the `Toolbar` component once it is available. + ### Avatar The `style` prop for `Avatar.Icon`, `Avatar.Image` and `Avatar.Text` no longer configures the background color. Use the `backgroundColor` prop instead. The text or icon color is still derived from the background color unless `color` is specified. diff --git a/example/src/Examples/AppbarExample.tsx b/example/src/Examples/AppbarExample.tsx index 08bbbcbc1b..18097295fa 100644 --- a/example/src/Examples/AppbarExample.tsx +++ b/example/src/Examples/AppbarExample.tsx @@ -17,7 +17,13 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ScreenWrapper from '../ScreenWrapper'; -type AppbarModes = 'small' | 'medium' | 'large' | 'center-aligned'; +type AppbarModes = + | 'small' + | 'medium' + | 'large' + | 'center-aligned' + | 'medium-flexible' + | 'large-flexible'; const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; const MEDIUM_FAB_HEIGHT = 56; @@ -33,6 +39,8 @@ const AppbarExample = () => { const [appbarMode, setAppbarMode] = React.useState('small'); const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); const [showElevated, setShowElevated] = React.useState(false); + const [isScrolled, setIsScrolled] = React.useState(false); + const [showFilledAction, setShowFilledAction] = React.useState(false); const [showSnackbar, setShowSnackbar] = React.useState(false); const theme = useTheme(); @@ -48,6 +56,7 @@ const AppbarExample = () => { backgroundColor={showCustomColor ? Palette.secondary80 : undefined} mode={appbarMode} elevated={showElevated} + isScrolled={isScrolled} > {showLeftIcon && ( navigation.goBack()} /> @@ -61,6 +70,14 @@ const AppbarExample = () => { {showSearchIcon && ( {}} /> )} + {showFilledAction && ( + {}} + /> + )} {showMoreIcon && ( {}} /> )} @@ -78,6 +95,8 @@ const AppbarExample = () => { showCalendarIcon, isCenterAlignedMode, showElevated, + isScrolled, + showFilledAction, ]); const renderFAB = () => { @@ -124,6 +143,14 @@ const AppbarExample = () => { Elevated + + Scrolled + + + + Filled action + + ); @@ -160,6 +187,14 @@ const AppbarExample = () => { Center-aligned + + Medium flexible + + + + Large flexible + + diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index 68156c6327..39e6c168ea 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -2,21 +2,22 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { ColorValue, StyleProp, ViewProps } from 'react-native'; -import AppbarContent from './AppbarContent'; +import { AppbarContext } from './AppbarContext'; +import type { AppbarContextType, AppbarItemKind } from './AppbarContext'; import { + APPBAR_ACTION_WIDTH, + APPBAR_FLEXIBLE_CONTROLS_HEIGHT, + APPBAR_HORIZONTAL_PADDING, getAppbarBackgroundColor, + isFlexibleMode, modeAppbarHeight, - renderAppbarContent, - filterAppbarActions, } from './utils'; -import type { AppbarModes, AppbarChildProps } from './utils'; +import type { AppbarModes } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import Surface from '../Surface'; import type { SurfaceStyle, SurfaceVisualProps } from '../Surface'; -const APPBAR_HORIZONTAL_PADDING = 4; - export type Props = Omit, 'style'> & Omit & { /** @@ -39,15 +40,24 @@ export type Props = Omit, 'style'> & * - `medium` - Appbar with medium height (112). * - `large` - Appbar with large height (152). * - `center-aligned` - Appbar with default height and center-aligned title. + * - `medium-flexible` - Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. + * - `large-flexible` - Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; + mode?: AppbarModes; /** * @supported Available in v5.x with theme version 3 * Whether Appbar background should have the elevation along with primary color pigment. */ elevated?: boolean; /** - * Safe area insets for the Appbar. This can be used to avoid elements like the navigation bar on Android and bottom safe area on iOS. + * Whether the content below the Appbar has scrolled. A scrolled Appbar uses the `surfaceContainer` color for its background, + * without elevation. Overridden by `backgroundColor`. + */ + isScrolled?: boolean; + /** + * Safe area insets for the Appbar. This can be used to avoid elements like the status bar and the camera cutout. + * + * Using `bottom` to build a bottom bar is deprecated. */ safeAreaInsets?: { bottom?: number; @@ -68,9 +78,12 @@ export type Props = Omit, 'style'> & }; /** - * A component to display action items in a bar. It can be placed at the top or bottom. - * The top bar usually contains the screen title, controls such as navigation buttons, menu button etc. - * The bottom bar usually provides access to a drawer and up to four actions. + * A component to display action items in a bar. It is usually placed at the top of the screen + * and contains the screen title and controls such as navigation buttons, menu button etc. + * + * Its parts, `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action`, read what they need from the `Appbar` + * they are rendered in, so they can be wrapped in other components, for example in a `Tooltip` or a `Menu`. + * The parts are laid out in the order they are rendered: render the leading actions first, then the content, then the trailing actions. * * ## Usage * ### Top bar @@ -91,6 +104,10 @@ export type Props = Omit, 'style'> & * ``` * * ### Bottom bar + * + * Using `Appbar` as a bottom bar is deprecated. Material Design 3 moves the bottom bar to toolbars, + * and it will be replaced by the `Toolbar` component once it is available. + * * ```js * import * as React from 'react'; * import { StyleSheet } from 'react-native'; @@ -148,6 +165,7 @@ const Appbar = ({ style, mode = 'small', elevated = false, + isScrolled = false, safeAreaInsets, theme: themeOverrides, backgroundColor: customBackground, @@ -155,172 +173,139 @@ const Appbar = ({ }: Props) => { const theme = useInternalTheme(themeOverrides); + const [items, setItems] = React.useState>({ + leading: 0, + trailing: 0, + content: 0, + }); + const [contentHeight, setContentHeight] = React.useState(0); + const backgroundColor = getAppbarBackgroundColor( theme, - elevated, + elevated || isScrolled, customBackground ); - const isMode = (modeToCompare: AppbarModes) => { - return mode === modeToCompare; - }; - const isDark = typeof dark === 'boolean' ? dark : false; + const isCenterAlignedMode = mode === 'center-aligned'; + const isFlexible = isFlexibleMode(mode); + const isTopAligned = mode === 'medium' || mode === 'large' || isFlexible; - const isCenterAlignedMode = isMode('center-aligned'); + const insets = { + top: safeAreaInsets?.top ?? 0, + bottom: safeAreaInsets?.bottom ?? 0, + left: safeAreaInsets?.left ?? 0, + right: safeAreaInsets?.right ?? 0, + }; - let shouldCenterContent = false; - let shouldAddLeftSpacing = false; - let shouldAddRightSpacing = false; - if (isCenterAlignedMode) { - let hasAppbarContent = false; - let leftItemsCount = 0; - let rightItemsCount = 0; + const registerItem = React.useCallback((kind: AppbarItemKind) => { + setItems((current) => ({ ...current, [kind]: current[kind] + 1 })); - React.Children.forEach(children, (child) => { - if (React.isValidElement(child)) { - const isLeading = child.props.isLeading === true; + return () => + setItems((current) => ({ ...current, [kind]: current[kind] - 1 })); + }, []); - if (child.type === AppbarContent) { - hasAppbarContent = true; - } else if (isLeading || !hasAppbarContent) { - leftItemsCount++; - } else { - rightItemsCount++; - } - } - }); - - shouldCenterContent = - hasAppbarContent && leftItemsCount < 2 && rightItemsCount < 3; - shouldAddLeftSpacing = shouldCenterContent && leftItemsCount === 0; - shouldAddRightSpacing = shouldCenterContent && rightItemsCount === 0; - } + const appbarContext = React.useMemo( + () => ({ + mode, + dark: isDark, + insets: { + top: insets.top, + bottom: insets.bottom, + left: insets.left, + right: insets.right, + }, + theme: themeOverrides, + registerItem: isCenterAlignedMode ? registerItem : undefined, + onContentLayout: isFlexible ? setContentHeight : undefined, + }), + [ + mode, + isDark, + insets.top, + insets.bottom, + insets.left, + insets.right, + themeOverrides, + isCenterAlignedMode, + isFlexible, + registerItem, + ] + ); - const spacingStyle = styles.v3Spacing; + // The title is only centered when there is room for it between the actions + const shouldCenterContent = + isCenterAlignedMode && + items.content > 0 && + items.leading < 2 && + items.trailing < 3; + const shouldAddLeftSpacing = shouldCenterContent && items.leading === 0; + const shouldAddRightSpacing = shouldCenterContent && items.trailing === 0; - const insets = { - paddingBottom: safeAreaInsets?.bottom, - paddingTop: safeAreaInsets?.top, - paddingLeft: (safeAreaInsets?.left ?? 0) + APPBAR_HORIZONTAL_PADDING, - paddingRight: (safeAreaInsets?.right ?? 0) + APPBAR_HORIZONTAL_PADDING, + const paddingStyle = { + paddingBottom: insets.bottom, + paddingTop: insets.top + topOffset[mode], + paddingLeft: insets.left + APPBAR_HORIZONTAL_PADDING, + paddingRight: insets.right + APPBAR_HORIZONTAL_PADDING, }; // The safe area insets are applied as padding, so they need to be included in the height - const height = - modeAppbarHeight[mode] + - (safeAreaInsets?.top ?? 0) + - (safeAreaInsets?.bottom ?? 0); + const verticalInsets = insets.top + insets.bottom; + const heightStyle = isFlexible + ? { + minHeight: + Math.max( + modeAppbarHeight[mode], + APPBAR_FLEXIBLE_CONTROLS_HEIGHT + contentHeight + ) + verticalInsets, + } + : { height: modeAppbarHeight[mode] + verticalInsets }; return ( - - {shouldAddLeftSpacing ? : null} - {(isMode('small') || isMode('center-aligned')) && ( - <> - {/* Render only the back action at first place */} - {renderAppbarContent({ - children, - isDark, - theme, - renderOnly: ['Appbar.BackAction'], - shouldCenterContent: isCenterAlignedMode || shouldCenterContent, - })} - {/* Render the rest of the content except the back action */} - {renderAppbarContent({ - // Filter appbar actions - first leading icons, then trailing icons - children: [ - ...filterAppbarActions(children, true), - ...filterAppbarActions(children), - ], - isDark, - theme, - renderExcept: ['Appbar.BackAction'], - shouldCenterContent: isCenterAlignedMode || shouldCenterContent, - })} - - )} - {(isMode('medium') || isMode('large')) && ( - - {/* Appbar top row with controls */} - - {/* Left side of row container, can contain AppbarBackAction or AppbarAction if it's leading icon */} - {renderAppbarContent({ - children, - isDark, - renderOnly: ['Appbar.BackAction'], - mode, - })} - {renderAppbarContent({ - children: filterAppbarActions(children, true), - isDark, - renderOnly: ['Appbar.Action'], - mode, - })} - {/* Right side of row container, can contain other AppbarAction if they are not leading icons */} - - {renderAppbarContent({ - children: filterAppbarActions(children), - isDark, - renderExcept: [ - 'Appbar', - 'Appbar.BackAction', - 'Appbar.Content', - 'Appbar.Header', - ], - mode, - })} - - - {renderAppbarContent({ - children, - isDark, - renderOnly: ['Appbar.Content'], - mode, - })} - - )} - {shouldAddRightSpacing ? : null} - + + + {shouldAddLeftSpacing ? : null} + {children} + {shouldAddRightSpacing ? : null} + + ); }; +// Offsets the controls of the `medium` and `large` modes so they are vertically centered in the top half of the Appbar +const topOffset = { + small: 0, + 'center-aligned': 0, + 'medium-flexible': 0, + 'large-flexible': 0, + medium: 8, + large: 18, +}; + const styles = StyleSheet.create({ appbar: { flexDirection: 'row', alignItems: 'center', }, - v3Spacing: { - width: 52, - }, - controlsRow: { - flex: 1, - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', - }, - rightActionControls: { - flexDirection: 'row', - flex: 1, - justifyContent: 'flex-end', - }, - columnContainer: { - flexDirection: 'column', - flex: 1, - paddingTop: 8, + topAligned: { + alignItems: 'flex-start', }, - centerAlignedContainer: { - paddingTop: 0, + spacing: { + width: APPBAR_ACTION_WIDTH, }, }); diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx index cf95f9e50e..c31c665b24 100644 --- a/src/components/Appbar/AppbarAction.tsx +++ b/src/components/Appbar/AppbarAction.tsx @@ -1,8 +1,11 @@ import * as React from 'react'; +import { StyleSheet } from 'react-native'; import type { ColorValue, StyleProp, View, ViewStyle } from 'react-native'; import type { AnimatedStyle } from 'react-native-reanimated'; +import { useAppbarContext, useAppbarItem } from './AppbarContext'; +import { getAppbarColor } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import type { IconSource } from '../Icon'; @@ -40,6 +43,23 @@ export type Props = React.PropsWithoutRef & { * Whether it's the leading button. Note: If `Appbar.BackAction` is present, it will be rendered before any `isLeading` icons. */ isLeading?: boolean; + /** + * @supported Available in v6.x + * + * Visual variant of the action. + * - `standard` - Icon without a container. + * - `filled` - Icon in a container with the primary color. + * - `tonal` - Icon in a container with the secondary container color. + */ + variant?: 'standard' | 'filled' | 'tonal'; + /** + * @supported Available in v6.x + * + * Width of the container of a `filled` or `tonal` action. It has no effect on a `standard` action. + * - `default` - Square container. + * - `wide` - Wide container. + */ + width?: 'default' | 'wide'; style?: StyleProp>; ref?: React.Ref>; /** @@ -78,18 +98,28 @@ const AppbarAction = ({ onPress, 'aria-label': ariaLabel, isLeading, + variant = 'standard', + width = 'default', + mode, + selected, + style, theme: themeOverrides, ref, ...rest }: Props) => { - const theme = useInternalTheme(themeOverrides); + const appbar = useAppbarContext(); + const theme = useInternalTheme(themeOverrides ?? appbar?.theme); const { colors } = theme; - const actionIconColor = iconColor - ? iconColor - : isLeading - ? colors.onSurface - : colors.onSurfaceVariant; + useAppbarItem(appbar, isLeading ? 'leading' : 'trailing'); + + const isStandard = variant === 'standard'; + + // The icon of a filled or tonal action takes the color of its container + const actionIconColor = isStandard + ? (getAppbarColor({ color: iconColor, isDark: appbar?.dark ?? false }) ?? + (isLeading ? colors.onSurface : colors.onSurfaceVariant)) + : iconColor; return ( , 'children'> & { * Specifies the largest possible scale a title font can reach. */ titleMaxFontSizeMultiplier?: number; - /** - * @internal - */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; style?: StyleProp; /** * @optional @@ -93,29 +96,61 @@ const AppbarContent = ({ titleStyle, title, titleMaxFontSizeMultiplier, - mode = 'small', theme: themeOverrides, testID, ...rest }: Props) => { - const theme = useInternalTheme(themeOverrides); + const appbar = useAppbarContext(); + const theme = useInternalTheme(themeOverrides ?? appbar?.theme); const { colors, fonts } = theme; - const titleTextColor = titleColor ? titleColor : colors.onSurface; + useAppbarItem(appbar, 'content'); + + const mode = appbar?.mode ?? 'small'; + const insets = appbar?.insets; + const onContentLayout = appbar?.onContentLayout; + const isFlexible = isFlexibleMode(mode); + + React.useEffect(() => () => onContentLayout?.(0), [onContentLayout]); - const modeContainerStyles = { - small: styles.v3DefaultContainer, - medium: styles.v3MediumContainer, - large: styles.v3LargeContainer, - 'center-aligned': styles.v3DefaultContainer, - }; + const titleTextColor = + getAppbarColor({ color: titleColor, isDark: appbar?.dark ?? false }) ?? + colors.onSurface; + + // The `medium` and `large` modes show the title below the actions, and the flexible modes + // grow with the title, so the title is positioned at the bottom of the Appbar + // and the content only takes up the space between the actions. + const isBottomAligned = mode === 'medium' || mode === 'large' || isFlexible; + + const bottomStyle = [ + styles.bottom, + { + left: (insets?.left ?? 0) + APPBAR_HORIZONTAL_PADDING + 12, + right: (insets?.right ?? 0) + APPBAR_HORIZONTAL_PADDING + 12, + bottom: insets?.bottom ?? 0, + }, + mode === 'medium' && styles.mediumBottom, + mode === 'large' && styles.largeBottom, + isFlexible && styles.flexibleBottom, + ]; const variant = modeTextVariant[mode]; const contentWrapperProps = { pointerEvents: 'box-none', - style: [styles.container, modeContainerStyles[mode], style], + style: [ + isBottomAligned + ? bottomStyle + : mode === 'center-aligned' + ? styles.centerAligned + : styles.container, + style, + ], testID, + onLayout: isFlexible + ? (event: LayoutChangeEvent) => + onContentLayout?.(event.nativeEvent.layout.height) + : undefined, ...rest, } satisfies ViewProps; @@ -132,7 +167,7 @@ const AppbarContent = ({ }, titleStyle, ]} - numberOfLines={1} + numberOfLines={isFlexible ? 2 : 1} accessible role={onPress ? 'none' : 'heading'} maxFontSizeMultiplier={titleMaxFontSizeMultiplier} @@ -145,21 +180,31 @@ const AppbarContent = ({ ); - if (onPress) { + const wrapper = onPress ? ( + + {content} + + ) : ( + {content} + ); + + if (isBottomAligned) { return ( - - {content} - + <> + {/* Takes up the space between the actions, so the trailing actions stay at the end */} + + {wrapper} + ); } - return {content}; + return wrapper; }; AppbarContent.displayName = 'Appbar.Content'; @@ -167,22 +212,28 @@ AppbarContent.displayName = 'Appbar.Content'; const styles = StyleSheet.create({ container: { flex: 1, - paddingHorizontal: 12, + marginLeft: 12, + }, + centerAligned: { + flex: 1, + alignItems: 'center', }, - v3DefaultContainer: { - paddingHorizontal: 0, + spacer: { + flex: 1, + }, + bottom: { + position: 'absolute', }, - v3MediumContainer: { - paddingHorizontal: 0, - justifyContent: 'flex-end', + mediumBottom: { paddingBottom: 24, }, - v3LargeContainer: { - paddingHorizontal: 0, - paddingTop: 36, - justifyContent: 'flex-end', + largeBottom: { paddingBottom: 28, }, + flexibleBottom: { + paddingTop: 8, + paddingBottom: 12, + }, }); export default AppbarContent; diff --git a/src/components/Appbar/AppbarContext.tsx b/src/components/Appbar/AppbarContext.tsx new file mode 100644 index 0000000000..0f69b379e2 --- /dev/null +++ b/src/components/Appbar/AppbarContext.tsx @@ -0,0 +1,58 @@ +import * as React from 'react'; + +import type { AppbarModes } from './utils'; +import type { ThemeProp } from '../../theme/types'; + +export type AppbarItemKind = 'leading' | 'trailing' | 'content'; + +export type AppbarContextType = { + /** + * Mode of the surrounding Appbar. + */ + mode: AppbarModes; + /** + * Whether the Appbar background is dark, so its parts render light content. + */ + dark: boolean; + /** + * Safe area insets of the surrounding Appbar. + */ + insets: { top: number; bottom: number; left: number; right: number }; + /** + * Theme override of the surrounding Appbar. + */ + theme?: ThemeProp; + /** + * Registers a part that takes part in the layout of the `center-aligned` + * mode. Returns a function that unregisters it. + * Only available in the `center-aligned` mode. + */ + registerItem?: (kind: AppbarItemKind) => () => void; + /** + * Reports the height of the content area of a flexible Appbar, so the Appbar + * can grow with a title that wraps onto multiple lines. + * Only available in the flexible modes. + */ + onContentLayout?: (height: number) => void; +}; + +export const AppbarContext = React.createContext( + null +); + +AppbarContext.displayName = 'AppbarContext'; + +export const useAppbarContext = () => React.useContext(AppbarContext); + +/** + * Registers a part in the surrounding Appbar when the mode lays out its parts + * based on how many of them there are. + */ +export const useAppbarItem = ( + appbar: AppbarContextType | null, + kind: AppbarItemKind +) => { + const registerItem = appbar?.registerItem; + + React.useLayoutEffect(() => registerItem?.(kind), [registerItem, kind]); +}; diff --git a/src/components/Appbar/AppbarHeader.tsx b/src/components/Appbar/AppbarHeader.tsx index 9e9866ee28..7682ed6245 100644 --- a/src/components/Appbar/AppbarHeader.tsx +++ b/src/components/Appbar/AppbarHeader.tsx @@ -6,6 +6,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { Appbar } from './Appbar'; import type { Props as AppbarProps } from './Appbar'; +import type { AppbarModes } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import type { SurfaceStyle } from '../Surface'; @@ -33,13 +34,20 @@ export type Props = Omit & { * - `medium` - Appbar with medium height (112). * - `large` - Appbar with large height (152). * - `center-aligned` - Appbar with default height and center-aligned title. + * - `medium-flexible` - Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. + * - `large-flexible` - Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; + mode?: AppbarModes; /** * @supported Available in v5.x with theme version 3 * Whether Appbar background should have the elevation along with primary color pigment. */ elevated?: boolean; + /** + * Whether the content below the header has scrolled. A scrolled header uses the `surfaceContainer` color for its background, + * without elevation. Overridden by `backgroundColor`. + */ + isScrolled?: boolean; /** * @optional */ diff --git a/src/components/Appbar/utils.ts b/src/components/Appbar/utils.ts index f1c4437a2f..0fdc8aa40b 100644 --- a/src/components/Appbar/utils.ts +++ b/src/components/Appbar/utils.ts @@ -1,17 +1,26 @@ -import React from 'react'; -import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; -import { StyleSheet } from 'react-native'; +import type { ColorValue } from 'react-native'; import { white } from '../../theme/colors'; -import type { InternalTheme, ThemeProp } from '../../theme/types'; +import type { InternalTheme } from '../../theme/types'; -export type AppbarModes = 'small' | 'medium' | 'large' | 'center-aligned'; +export type AppbarModes = + | 'small' + | 'medium' + | 'large' + | 'center-aligned' + | 'medium-flexible' + | 'large-flexible'; -export type AppbarChildProps = { - isLeading?: boolean; - color: string; - style?: StyleProp; -}; +export const APPBAR_HORIZONTAL_PADDING = 4; + +// Width of an icon button with its margin. +export const APPBAR_ACTION_WIDTH = 52; + +// Height of the row with the controls of a flexible Appbar. +export const APPBAR_FLEXIBLE_CONTROLS_HEIGHT = 56; + +export const isFlexibleMode = (mode: AppbarModes) => + mode === 'medium-flexible' || mode === 'large-flexible'; export const getAppbarBackgroundColor = ( theme: InternalTheme, @@ -33,7 +42,10 @@ export const getAppbarBackgroundColor = ( export const getAppbarColor = ({ color, isDark, -}: BaseProps & { color: string }) => { +}: { + color?: ColorValue; + isDark: boolean; +}) => { if (typeof color !== 'undefined') { return color; } @@ -45,27 +57,20 @@ export const getAppbarColor = ({ return undefined; }; -type BaseProps = { - isDark: boolean; -}; - -type RenderAppbarContentProps = BaseProps & { - children: React.ReactNode; - shouldCenterContent?: boolean; - renderOnly?: (string | boolean)[]; - renderExcept?: string[]; - mode?: AppbarModes; - theme?: ThemeProp; -}; - export const DEFAULT_APPBAR_HEIGHT = 56; const MD3_DEFAULT_APPBAR_HEIGHT = 64; +/** + * Height of the content area of the Appbar, without the safe area insets. + * The flexible modes use it as the minimum height. + */ export const modeAppbarHeight = { small: MD3_DEFAULT_APPBAR_HEIGHT, medium: 112, large: 152, 'center-aligned': MD3_DEFAULT_APPBAR_HEIGHT, + 'medium-flexible': 112, + 'large-flexible': 120, }; export const modeTextVariant = { @@ -73,82 +78,6 @@ export const modeTextVariant = { medium: 'headlineSmall', large: 'headlineMedium', 'center-aligned': 'titleLarge', + 'medium-flexible': 'headlineMedium', + 'large-flexible': 'displaySmall', } as const; - -export const filterAppbarActions = ( - children: React.ReactNode, - isLeading = false -) => { - return React.Children.toArray(children).filter((child) => { - if (!React.isValidElement(child)) return false; - return isLeading ? child.props.isLeading : !child.props.isLeading; - }); -}; - -export const renderAppbarContent = ({ - children, - isDark, - shouldCenterContent = false, - renderOnly, - renderExcept, - mode = 'small', - theme, -}: RenderAppbarContentProps) => { - return React.Children.toArray(children) - .filter((child) => child != null && typeof child !== 'boolean') - .filter((child) => - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - renderExcept ? !renderExcept.includes(child.type.displayName) : child - ) - .filter((child) => - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - renderOnly ? renderOnly.includes(child.type.displayName) : child - ) - .map((child, i) => { - if ( - !React.isValidElement(child) || - ![ - 'Appbar.Content', - 'Appbar.Action', - 'Appbar.BackAction', - 'Tooltip', - ].includes( - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - child.type.displayName - ) - ) { - return child; - } - - const props: { - color?: string; - style?: StyleProp; - mode?: AppbarModes; - theme?: ThemeProp; - } = { - theme, - color: getAppbarColor({ color: child.props.color, isDark }), - }; - - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - if (child.type.displayName === 'Appbar.Content') { - props.mode = mode; - props.style = [ - i === 0 && !shouldCenterContent && styles.v3Spacing, - shouldCenterContent && styles.centerAlignedContent, - child.props.style, - ]; - props.color; - } - return React.cloneElement(child, props); - }); -}; - -const styles = StyleSheet.create({ - centerAlignedContent: { - alignItems: 'center', - }, - v3Spacing: { - marginLeft: 12, - }, -}); diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index 49f14e6ec1..620287877a 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -1,24 +1,23 @@ -import { describe, expect, it } from '@jest/globals'; +import { Text as NativeText, View } from 'react-native'; +import type { ColorValue } from 'react-native'; + +import { describe, expect, it, jest } from '@jest/globals'; +import { + getAnimatedStyle, + useAnimatedStyle, + useSharedValue, +} from 'react-native-reanimated'; import { SafeAreaProvider } from 'react-native-safe-area-context'; -import { render, screen } from '../../../test-utils'; +import { fireEvent, render, screen, userEvent } from '../../../test-utils'; import { DarkTheme, LightTheme } from '../../../theme/schemes'; import { tokens } from '../../../theme/tokens'; import Appbar from '../../Appbar'; -import { - getAppbarBackgroundColor, - modeTextVariant, - renderAppbarContent as utilRenderAppbarContent, -} from '../../Appbar/utils'; -import Menu from '../../Menu/Menu'; +import { getAppbarBackgroundColor, modeTextVariant } from '../../Appbar/utils'; import Searchbar from '../../Searchbar'; +import Tooltip from '../../Tooltip/Tooltip'; import Text from '../../Typography/Text'; -// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -const renderAppbarContent = utilRenderAppbarContent as ( - props: Parameters[0] -) => { props: any }[]; - describe('Appbar', () => { it('does not pass any additional props to Searchbar', async () => { const tree = ( @@ -86,109 +85,279 @@ describe('Appbar', () => { }); }); -describe('renderAppbarContent', () => { - const children = [ - {}} key={0} />, - , - {}} key={2} />, - {}} key={3} />, - ]; - - it('should render all children types if renderOnly is not specified', () => { - const result = renderAppbarContent({ - children, - isDark: false, - }); +describe('Appbar context', () => { + const ColorIcon = ({ color }: { color: ColorValue }) => ( + {String(color)} + ); + + it('gives the parts a light color when the Appbar is dark', async () => { + await render( + + + + + ); - expect(result).toHaveLength(4); + expect(screen.getByTestId('icon-color')).toHaveTextContent('#ffffff'); + expect(screen.getByText('Title')).toHaveStyle({ color: '#ffffff' }); }); - it('should render all children types except specified in renderExcept', () => { - const result = renderAppbarContent({ - children: [ - ...children, - {}} />} - visible={false} - > - {null} - , - ], - isDark: false, - renderExcept: [ - 'Appbar', - 'Appbar.Header', - 'Appbar.BackAction', - 'Appbar.Content', - ], - }); + it('keeps the color of a part over the color of a dark Appbar', async () => { + await render( + + + + + ); - expect(result).toHaveLength(3); + expect(screen.getByTestId('icon-color')).toHaveTextContent('purple'); + expect(screen.getByText('Title')).toHaveStyle({ color: 'purple' }); }); - it('should render only children types specified in renderOnly', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Action'], - }); + it('applies the Appbar settings to parts wrapped in other components', async () => { + await render( + + + + + + + + + ); - expect(result).toHaveLength(2); + expect(screen.getByTestId('icon-color')).toHaveTextContent('#ffffff'); + expect(screen.getByText('Title')).toHaveStyle({ color: '#ffffff' }); }); - it('should render AppbarContent with correct mode', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Content'], - mode: 'large', - }); + it('applies the theme of the Appbar to its parts', async () => { + await render( + + + + + ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(result[0].props.mode).toBe('large'); + expect(screen.getByTestId('icon-color')).toHaveTextContent('tomato'); + expect(screen.getByText('Title')).toHaveStyle({ color: 'tomato' }); }); - it('should render centered AppbarContent', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Content'], - mode: 'center-aligned', - shouldCenterContent: true, - }); + it('prefers the theme of a part over the theme of the Appbar', async () => { + await render( + + + + ); - const centerAlignedContent = { - alignItems: 'center', - }; + expect(screen.getByText('Title')).toHaveStyle({ color: 'navy' }); + }); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(result[0].props.style).toEqual( - expect.arrayContaining([expect.objectContaining(centerAlignedContent)]) + it('renders parts on their own, outside of an Appbar', async () => { + await render( + <> + + + ); + + expect(screen.getByText('Title')).toBeOnTheScreen(); + expect(screen.getByRole('button', { name: 'Menu' })).toBeOnTheScreen(); }); - it('should render AppbarContent with correct spacings', () => { - const renderResult = (withAppbarBackAction = false) => - renderAppbarContent({ - children, - isDark: false, - renderOnly: [ - 'Appbar.Content', - withAppbarBackAction && 'Appbar.BackAction', - ], + it('renders children in the order they are given', async () => { + await render( + + + + + + ); + + const [first, second] = screen.getAllByRole('button'); + + expect(first).toHaveAccessibleName('Menu'); + expect(second).toHaveAccessibleName('Back'); + }); + + it('forwards accessibility props to the container', async () => { + await render( + + + + ); + + expect( + screen.getByRole('toolbar', { name: 'Navigation' }) + ).toBeOnTheScreen(); + }); +}); + +describe('Appbar modes', () => { + it('centers the content in the center-aligned mode', async () => { + await render( + + + + + + ); + + expect(screen.getByTestId('content')).toHaveStyle({ alignItems: 'center' }); + }); + + it.each(['medium-flexible', 'large-flexible'] as const)( + 'uses the %s height as the minimum height and includes the safe area insets', + async (mode) => { + await render( + + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + minHeight: (mode === 'medium-flexible' ? 112 : 120) + 20, + paddingTop: 20, }); + } + ); + + it.each(['medium-flexible', 'large-flexible'] as const)( + 'grows the %s Appbar when the title takes more space', + async (mode) => { + await render( + + + + ); + + await fireEvent(screen.getByTestId('content'), 'layout', { + nativeEvent: { layout: { width: 300, height: 120 } }, + }); + + // the row with the controls and the content + expect(screen.getByTestId('appbar')).toHaveStyle({ minHeight: 56 + 120 }); + } + ); + + it('allows the title of a flexible Appbar to wrap onto two lines', async () => { + await render( + + + + ); + + expect(screen.getByText('A long title that wraps')).toHaveProp( + 'numberOfLines', + 2 + ); + }); + + it('keeps the title of the other modes on a single line', async () => { + await render( + + + + ); - const v3Spacing = { - marginLeft: 12, - }; + expect(screen.getByText('A long title')).toHaveProp('numberOfLines', 1); + }); +}); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(renderResult()[0].props.style).toEqual( - expect.arrayContaining([expect.objectContaining(v3Spacing)]) +describe('Appbar scroll-aware color', () => { + it('uses the surface color by default', async () => { + await render( + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + backgroundColor: LightTheme.colors.surface, + }); }); + it('uses the surface container color when scrolled, without elevation', async () => { + await render( + + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + backgroundColor: LightTheme.colors.surfaceContainer, + }); + }); + + it('prefers the custom background color', async () => { + await render( + + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + backgroundColor: '#FF0000', + }); + }); + + it('is available on Appbar.Header', async () => { + await render( + + + + + + ); + + expect(screen.getByTestId('appbar-header')).toHaveStyle({ + backgroundColor: LightTheme.colors.surfaceContainer, + }); + }); +}); + +describe('Appbar animated style', () => { + const AnimatedAppbar = () => { + const opacity = useSharedValue(0); + const animatedStyle = useAnimatedStyle(() => ({ opacity: opacity.value })); + + return ( + <> + + + + { + opacity.value = 1; + }} + /> + + ); + }; + + it('keeps static styles combined with an animated style', async () => { + await render(); + + const appbar = screen.getByTestId('appbar'); + + expect(appbar).toHaveStyle({ marginHorizontal: 12 }); + expect(getAnimatedStyle(appbar)).toMatchObject({ opacity: 0 }); + + await userEvent.press(screen.getByRole('button', { name: 'Reveal' })); + await jest.runAllTimersAsync(); + + expect(getAnimatedStyle(appbar)).toMatchObject({ opacity: 1 }); + }); +}); + +describe('Appbar.Header', () => { it('includes the status bar height in the header height', async () => { await render( @@ -204,7 +373,8 @@ describe('renderAppbarContent', () => { expect(screen.getByTestId('appbar-header')).toHaveStyle({ height: 112 + 40, - paddingTop: 40, + // the status bar height and the space above the controls + paddingTop: 40 + 8, }); }); @@ -287,6 +457,44 @@ describe('AppbarAction', () => { expect(toJSON()).toMatchSnapshot(); }); + it.each(['filled', 'tonal'] as const)( + 'renders a %s action as a button that handles presses', + async (variant) => { + const onPress = jest.fn<() => void>(); + + await render( + + + + ); + + await userEvent.press(screen.getByRole('button', { name: 'Favorite' })); + + expect(onPress).toHaveBeenCalledTimes(1); + } + ); + + it('does not override the icon color of a filled action by the Appbar', async () => { + await render( + + ( + {String(color)} + )} + variant="filled" + /> + + ); + + expect(screen.getByTestId('icon')).not.toHaveTextContent('#ffffff'); + }); + it('should render AppbarBackAction with custom color', async () => { const { toJSON } = await render( @@ -298,7 +506,16 @@ describe('AppbarAction', () => { }); describe('AppbarContent', () => { - (['small', 'medium', 'large', 'center-aligned'] as const).forEach((mode) => + ( + [ + 'small', + 'medium', + 'large', + 'center-aligned', + 'medium-flexible', + 'large-flexible', + ] as const + ).forEach((mode) => it(`should render text component with appropriate variant for ${mode} mode`, async () => { await render( diff --git a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap index 5ff794c9c0..ef27521cae 100644 --- a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap +++ b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap @@ -13,11 +13,12 @@ exports[`Appbar does not pass any additional props to Searchbar 1`] = ` "alignItems": "center", "flexDirection": "row", }, + false, { - "paddingBottom": undefined, + "paddingBottom": 0, "paddingLeft": 4, "paddingRight": 4, - "paddingTop": undefined, + "paddingTop": 0, }, undefined, {}, @@ -40,65 +41,10 @@ exports[`Appbar does not pass any additional props to Searchbar 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, + false, ] } > - - @@ -817,6 +701,7 @@ exports[`Appbar passes additional props to AppbarBackAction, AppbarContent and A "borderRadius": 20, "borderWidth": 0, }, + false, undefined, ] } @@ -970,11 +855,12 @@ exports[`AppbarAction should be rendered with custom color 1`] = ` "alignItems": "center", "flexDirection": "row", }, + false, { - "paddingBottom": undefined, + "paddingBottom": 0, "paddingLeft": 4, "paddingRight": 4, - "paddingTop": undefined, + "paddingTop": 0, }, undefined, {}, @@ -997,65 +883,10 @@ exports[`AppbarAction should be rendered with custom color 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, + false, ] } > - - - - Date: Thu, 12 Nov 2026 12:36:57 +0200 Subject: [PATCH 2/7] feat(appbar)!: read parts from context and add Expressive props MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Appbar no longer inspects and clones its children. Appbar.BackAction, Appbar.Content and Appbar.Action read dark, theme and mode from context, so they work when wrapped in other components such as Tooltip. Adds Material 3 Expressive support as props on the existing parts: - mode="medium-flexible" and mode="large-flexible" on Appbar and Appbar.Header, which grow with a title that wraps onto a second line - variant and width on Appbar.Action for filled, tonal and wide actions - isScrolled on Appbar and Appbar.Header for the on-scroll color The surface renders in flat mode so an animated style shows on iOS. The bottom bar keeps working and is deprecated until Toolbar lands. BREAKING CHANGE: Appbar renders its children in the order they are given instead of moving Appbar.BackAction and the actions with isLeading to the front. Appbar.Content always has a 12dp margin before its title, and its internal mode prop is removed. In the center-aligned mode, only Appbar.BackAction and actions with isLeading count as leading actions. Based on the work in #5075 by Paweł Kata. Co-Authored-By: Paweł Kata Co-Authored-By: Claude Sonnet 5.5 --- docs/6.x/docs/guides/migration.md | 42 ++ example/src/Examples/AppbarExample.tsx | 37 +- src/components/Appbar/Appbar.tsx | 287 ++++++------ src/components/Appbar/AppbarAction.tsx | 57 ++- src/components/Appbar/AppbarContent.tsx | 125 ++++-- src/components/Appbar/AppbarContext.tsx | 58 +++ src/components/Appbar/AppbarHeader.tsx | 10 +- src/components/Appbar/utils.ts | 133 ++---- .../__tests__/Appbar/Appbar.test.tsx | 407 ++++++++++++++---- .../Appbar/__snapshots__/Appbar.test.tsx.snap | 391 ++--------------- 10 files changed, 795 insertions(+), 752 deletions(-) create mode 100644 src/components/Appbar/AppbarContext.tsx diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index da236a623b..220afd64e5 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -372,6 +372,48 @@ To keep the height of the content row when setting `height` in `style`, add the ``` +#### Parts read from the `Appbar` + +`Appbar` no longer inspects its children and clones them to pass `color`, `theme`, `mode` and `style`. `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action` now read the `dark` and `theme` props and the `mode` of the `Appbar` they are rendered in from context. This means they can be wrapped in other components, for example in a `Tooltip` or a `View`, and still get the colors and the theme of the `Appbar`. A `theme` set on a part takes precedence over the `theme` of the `Appbar`. + +The parts are rendered in the order they are given, so render the leading actions first, then `Appbar.Content`, then the trailing actions. Previously, `Appbar.BackAction` and the actions with `isLeading` were moved before the rest. + +- `Appbar.Content` always has a `12dp` margin before its title. Previously, the margin was only added when the title was the first item after `Appbar.BackAction`. +- The `mode` prop of `Appbar.Content`, which was for internal use, is removed. +- In the `center-aligned` mode, the title is centered between the actions when there is room for it. The actions before the title count as leading actions only when they are `Appbar.BackAction` or have `isLeading`. + +```diff + +- {}} /> ++ {}} /> + + {}} /> + +``` + +#### Material 3 Expressive + +- The `mode` prop of `Appbar` and `Appbar.Header` accepts two new values: `medium-flexible` and `large-flexible`. Their height is the minimum height (`112` and `120`), and they grow when the title wraps onto a second line. +- `Appbar.Action` has new `variant` and `width` props. `variant="filled"` and `variant="tonal"` render the action in a container, and `width="wide"` makes the container wider. +- `Appbar` and `Appbar.Header` have a new `isScrolled` prop. Set it when the content below has scrolled, to switch the container to the `surfaceContainer` color. Unlike `elevated`, it doesn't add elevation. + +```tsx + + {}} /> + + {}} + /> + +``` + +#### Bottom bar + +Using `Appbar` as a bottom bar is deprecated. Material Design 3 moves the bottom bar to toolbars. It continues to work in 6.x, and will be replaced by the `Toolbar` component once it is available. + ### Avatar The `style` prop for `Avatar.Icon`, `Avatar.Image` and `Avatar.Text` no longer configures the background color. Use the `backgroundColor` prop instead. The text or icon color is still derived from the background color unless `color` is specified. diff --git a/example/src/Examples/AppbarExample.tsx b/example/src/Examples/AppbarExample.tsx index 08bbbcbc1b..18097295fa 100644 --- a/example/src/Examples/AppbarExample.tsx +++ b/example/src/Examples/AppbarExample.tsx @@ -17,7 +17,13 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ScreenWrapper from '../ScreenWrapper'; -type AppbarModes = 'small' | 'medium' | 'large' | 'center-aligned'; +type AppbarModes = + | 'small' + | 'medium' + | 'large' + | 'center-aligned' + | 'medium-flexible' + | 'large-flexible'; const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; const MEDIUM_FAB_HEIGHT = 56; @@ -33,6 +39,8 @@ const AppbarExample = () => { const [appbarMode, setAppbarMode] = React.useState('small'); const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); const [showElevated, setShowElevated] = React.useState(false); + const [isScrolled, setIsScrolled] = React.useState(false); + const [showFilledAction, setShowFilledAction] = React.useState(false); const [showSnackbar, setShowSnackbar] = React.useState(false); const theme = useTheme(); @@ -48,6 +56,7 @@ const AppbarExample = () => { backgroundColor={showCustomColor ? Palette.secondary80 : undefined} mode={appbarMode} elevated={showElevated} + isScrolled={isScrolled} > {showLeftIcon && ( navigation.goBack()} /> @@ -61,6 +70,14 @@ const AppbarExample = () => { {showSearchIcon && ( {}} /> )} + {showFilledAction && ( + {}} + /> + )} {showMoreIcon && ( {}} /> )} @@ -78,6 +95,8 @@ const AppbarExample = () => { showCalendarIcon, isCenterAlignedMode, showElevated, + isScrolled, + showFilledAction, ]); const renderFAB = () => { @@ -124,6 +143,14 @@ const AppbarExample = () => { Elevated + + Scrolled + + + + Filled action + + ); @@ -160,6 +187,14 @@ const AppbarExample = () => { Center-aligned + + Medium flexible + + + + Large flexible + + diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index 68156c6327..39e6c168ea 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -2,21 +2,22 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import type { ColorValue, StyleProp, ViewProps } from 'react-native'; -import AppbarContent from './AppbarContent'; +import { AppbarContext } from './AppbarContext'; +import type { AppbarContextType, AppbarItemKind } from './AppbarContext'; import { + APPBAR_ACTION_WIDTH, + APPBAR_FLEXIBLE_CONTROLS_HEIGHT, + APPBAR_HORIZONTAL_PADDING, getAppbarBackgroundColor, + isFlexibleMode, modeAppbarHeight, - renderAppbarContent, - filterAppbarActions, } from './utils'; -import type { AppbarModes, AppbarChildProps } from './utils'; +import type { AppbarModes } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import Surface from '../Surface'; import type { SurfaceStyle, SurfaceVisualProps } from '../Surface'; -const APPBAR_HORIZONTAL_PADDING = 4; - export type Props = Omit, 'style'> & Omit & { /** @@ -39,15 +40,24 @@ export type Props = Omit, 'style'> & * - `medium` - Appbar with medium height (112). * - `large` - Appbar with large height (152). * - `center-aligned` - Appbar with default height and center-aligned title. + * - `medium-flexible` - Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. + * - `large-flexible` - Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; + mode?: AppbarModes; /** * @supported Available in v5.x with theme version 3 * Whether Appbar background should have the elevation along with primary color pigment. */ elevated?: boolean; /** - * Safe area insets for the Appbar. This can be used to avoid elements like the navigation bar on Android and bottom safe area on iOS. + * Whether the content below the Appbar has scrolled. A scrolled Appbar uses the `surfaceContainer` color for its background, + * without elevation. Overridden by `backgroundColor`. + */ + isScrolled?: boolean; + /** + * Safe area insets for the Appbar. This can be used to avoid elements like the status bar and the camera cutout. + * + * Using `bottom` to build a bottom bar is deprecated. */ safeAreaInsets?: { bottom?: number; @@ -68,9 +78,12 @@ export type Props = Omit, 'style'> & }; /** - * A component to display action items in a bar. It can be placed at the top or bottom. - * The top bar usually contains the screen title, controls such as navigation buttons, menu button etc. - * The bottom bar usually provides access to a drawer and up to four actions. + * A component to display action items in a bar. It is usually placed at the top of the screen + * and contains the screen title and controls such as navigation buttons, menu button etc. + * + * Its parts, `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action`, read what they need from the `Appbar` + * they are rendered in, so they can be wrapped in other components, for example in a `Tooltip` or a `Menu`. + * The parts are laid out in the order they are rendered: render the leading actions first, then the content, then the trailing actions. * * ## Usage * ### Top bar @@ -91,6 +104,10 @@ export type Props = Omit, 'style'> & * ``` * * ### Bottom bar + * + * Using `Appbar` as a bottom bar is deprecated. Material Design 3 moves the bottom bar to toolbars, + * and it will be replaced by the `Toolbar` component once it is available. + * * ```js * import * as React from 'react'; * import { StyleSheet } from 'react-native'; @@ -148,6 +165,7 @@ const Appbar = ({ style, mode = 'small', elevated = false, + isScrolled = false, safeAreaInsets, theme: themeOverrides, backgroundColor: customBackground, @@ -155,172 +173,139 @@ const Appbar = ({ }: Props) => { const theme = useInternalTheme(themeOverrides); + const [items, setItems] = React.useState>({ + leading: 0, + trailing: 0, + content: 0, + }); + const [contentHeight, setContentHeight] = React.useState(0); + const backgroundColor = getAppbarBackgroundColor( theme, - elevated, + elevated || isScrolled, customBackground ); - const isMode = (modeToCompare: AppbarModes) => { - return mode === modeToCompare; - }; - const isDark = typeof dark === 'boolean' ? dark : false; + const isCenterAlignedMode = mode === 'center-aligned'; + const isFlexible = isFlexibleMode(mode); + const isTopAligned = mode === 'medium' || mode === 'large' || isFlexible; - const isCenterAlignedMode = isMode('center-aligned'); + const insets = { + top: safeAreaInsets?.top ?? 0, + bottom: safeAreaInsets?.bottom ?? 0, + left: safeAreaInsets?.left ?? 0, + right: safeAreaInsets?.right ?? 0, + }; - let shouldCenterContent = false; - let shouldAddLeftSpacing = false; - let shouldAddRightSpacing = false; - if (isCenterAlignedMode) { - let hasAppbarContent = false; - let leftItemsCount = 0; - let rightItemsCount = 0; + const registerItem = React.useCallback((kind: AppbarItemKind) => { + setItems((current) => ({ ...current, [kind]: current[kind] + 1 })); - React.Children.forEach(children, (child) => { - if (React.isValidElement(child)) { - const isLeading = child.props.isLeading === true; + return () => + setItems((current) => ({ ...current, [kind]: current[kind] - 1 })); + }, []); - if (child.type === AppbarContent) { - hasAppbarContent = true; - } else if (isLeading || !hasAppbarContent) { - leftItemsCount++; - } else { - rightItemsCount++; - } - } - }); - - shouldCenterContent = - hasAppbarContent && leftItemsCount < 2 && rightItemsCount < 3; - shouldAddLeftSpacing = shouldCenterContent && leftItemsCount === 0; - shouldAddRightSpacing = shouldCenterContent && rightItemsCount === 0; - } + const appbarContext = React.useMemo( + () => ({ + mode, + dark: isDark, + insets: { + top: insets.top, + bottom: insets.bottom, + left: insets.left, + right: insets.right, + }, + theme: themeOverrides, + registerItem: isCenterAlignedMode ? registerItem : undefined, + onContentLayout: isFlexible ? setContentHeight : undefined, + }), + [ + mode, + isDark, + insets.top, + insets.bottom, + insets.left, + insets.right, + themeOverrides, + isCenterAlignedMode, + isFlexible, + registerItem, + ] + ); - const spacingStyle = styles.v3Spacing; + // The title is only centered when there is room for it between the actions + const shouldCenterContent = + isCenterAlignedMode && + items.content > 0 && + items.leading < 2 && + items.trailing < 3; + const shouldAddLeftSpacing = shouldCenterContent && items.leading === 0; + const shouldAddRightSpacing = shouldCenterContent && items.trailing === 0; - const insets = { - paddingBottom: safeAreaInsets?.bottom, - paddingTop: safeAreaInsets?.top, - paddingLeft: (safeAreaInsets?.left ?? 0) + APPBAR_HORIZONTAL_PADDING, - paddingRight: (safeAreaInsets?.right ?? 0) + APPBAR_HORIZONTAL_PADDING, + const paddingStyle = { + paddingBottom: insets.bottom, + paddingTop: insets.top + topOffset[mode], + paddingLeft: insets.left + APPBAR_HORIZONTAL_PADDING, + paddingRight: insets.right + APPBAR_HORIZONTAL_PADDING, }; // The safe area insets are applied as padding, so they need to be included in the height - const height = - modeAppbarHeight[mode] + - (safeAreaInsets?.top ?? 0) + - (safeAreaInsets?.bottom ?? 0); + const verticalInsets = insets.top + insets.bottom; + const heightStyle = isFlexible + ? { + minHeight: + Math.max( + modeAppbarHeight[mode], + APPBAR_FLEXIBLE_CONTROLS_HEIGHT + contentHeight + ) + verticalInsets, + } + : { height: modeAppbarHeight[mode] + verticalInsets }; return ( - - {shouldAddLeftSpacing ? : null} - {(isMode('small') || isMode('center-aligned')) && ( - <> - {/* Render only the back action at first place */} - {renderAppbarContent({ - children, - isDark, - theme, - renderOnly: ['Appbar.BackAction'], - shouldCenterContent: isCenterAlignedMode || shouldCenterContent, - })} - {/* Render the rest of the content except the back action */} - {renderAppbarContent({ - // Filter appbar actions - first leading icons, then trailing icons - children: [ - ...filterAppbarActions(children, true), - ...filterAppbarActions(children), - ], - isDark, - theme, - renderExcept: ['Appbar.BackAction'], - shouldCenterContent: isCenterAlignedMode || shouldCenterContent, - })} - - )} - {(isMode('medium') || isMode('large')) && ( - - {/* Appbar top row with controls */} - - {/* Left side of row container, can contain AppbarBackAction or AppbarAction if it's leading icon */} - {renderAppbarContent({ - children, - isDark, - renderOnly: ['Appbar.BackAction'], - mode, - })} - {renderAppbarContent({ - children: filterAppbarActions(children, true), - isDark, - renderOnly: ['Appbar.Action'], - mode, - })} - {/* Right side of row container, can contain other AppbarAction if they are not leading icons */} - - {renderAppbarContent({ - children: filterAppbarActions(children), - isDark, - renderExcept: [ - 'Appbar', - 'Appbar.BackAction', - 'Appbar.Content', - 'Appbar.Header', - ], - mode, - })} - - - {renderAppbarContent({ - children, - isDark, - renderOnly: ['Appbar.Content'], - mode, - })} - - )} - {shouldAddRightSpacing ? : null} - + + + {shouldAddLeftSpacing ? : null} + {children} + {shouldAddRightSpacing ? : null} + + ); }; +// Offsets the controls of the `medium` and `large` modes so they are vertically centered in the top half of the Appbar +const topOffset = { + small: 0, + 'center-aligned': 0, + 'medium-flexible': 0, + 'large-flexible': 0, + medium: 8, + large: 18, +}; + const styles = StyleSheet.create({ appbar: { flexDirection: 'row', alignItems: 'center', }, - v3Spacing: { - width: 52, - }, - controlsRow: { - flex: 1, - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', - }, - rightActionControls: { - flexDirection: 'row', - flex: 1, - justifyContent: 'flex-end', - }, - columnContainer: { - flexDirection: 'column', - flex: 1, - paddingTop: 8, + topAligned: { + alignItems: 'flex-start', }, - centerAlignedContainer: { - paddingTop: 0, + spacing: { + width: APPBAR_ACTION_WIDTH, }, }); diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx index cf95f9e50e..c31c665b24 100644 --- a/src/components/Appbar/AppbarAction.tsx +++ b/src/components/Appbar/AppbarAction.tsx @@ -1,8 +1,11 @@ import * as React from 'react'; +import { StyleSheet } from 'react-native'; import type { ColorValue, StyleProp, View, ViewStyle } from 'react-native'; import type { AnimatedStyle } from 'react-native-reanimated'; +import { useAppbarContext, useAppbarItem } from './AppbarContext'; +import { getAppbarColor } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import type { IconSource } from '../Icon'; @@ -40,6 +43,23 @@ export type Props = React.PropsWithoutRef & { * Whether it's the leading button. Note: If `Appbar.BackAction` is present, it will be rendered before any `isLeading` icons. */ isLeading?: boolean; + /** + * @supported Available in v6.x + * + * Visual variant of the action. + * - `standard` - Icon without a container. + * - `filled` - Icon in a container with the primary color. + * - `tonal` - Icon in a container with the secondary container color. + */ + variant?: 'standard' | 'filled' | 'tonal'; + /** + * @supported Available in v6.x + * + * Width of the container of a `filled` or `tonal` action. It has no effect on a `standard` action. + * - `default` - Square container. + * - `wide` - Wide container. + */ + width?: 'default' | 'wide'; style?: StyleProp>; ref?: React.Ref>; /** @@ -78,18 +98,28 @@ const AppbarAction = ({ onPress, 'aria-label': ariaLabel, isLeading, + variant = 'standard', + width = 'default', + mode, + selected, + style, theme: themeOverrides, ref, ...rest }: Props) => { - const theme = useInternalTheme(themeOverrides); + const appbar = useAppbarContext(); + const theme = useInternalTheme(themeOverrides ?? appbar?.theme); const { colors } = theme; - const actionIconColor = iconColor - ? iconColor - : isLeading - ? colors.onSurface - : colors.onSurfaceVariant; + useAppbarItem(appbar, isLeading ? 'leading' : 'trailing'); + + const isStandard = variant === 'standard'; + + // The icon of a filled or tonal action takes the color of its container + const actionIconColor = isStandard + ? (getAppbarColor({ color: iconColor, isDark: appbar?.dark ?? false }) ?? + (isLeading ? colors.onSurface : colors.onSurfaceVariant)) + : iconColor; return ( , 'children'> & { * Specifies the largest possible scale a title font can reach. */ titleMaxFontSizeMultiplier?: number; - /** - * @internal - */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; style?: StyleProp; /** * @optional @@ -93,29 +96,61 @@ const AppbarContent = ({ titleStyle, title, titleMaxFontSizeMultiplier, - mode = 'small', theme: themeOverrides, testID, ...rest }: Props) => { - const theme = useInternalTheme(themeOverrides); + const appbar = useAppbarContext(); + const theme = useInternalTheme(themeOverrides ?? appbar?.theme); const { colors, fonts } = theme; - const titleTextColor = titleColor ? titleColor : colors.onSurface; + useAppbarItem(appbar, 'content'); + + const mode = appbar?.mode ?? 'small'; + const insets = appbar?.insets; + const onContentLayout = appbar?.onContentLayout; + const isFlexible = isFlexibleMode(mode); + + React.useEffect(() => () => onContentLayout?.(0), [onContentLayout]); - const modeContainerStyles = { - small: styles.v3DefaultContainer, - medium: styles.v3MediumContainer, - large: styles.v3LargeContainer, - 'center-aligned': styles.v3DefaultContainer, - }; + const titleTextColor = + getAppbarColor({ color: titleColor, isDark: appbar?.dark ?? false }) ?? + colors.onSurface; + + // The `medium` and `large` modes show the title below the actions, and the flexible modes + // grow with the title, so the title is positioned at the bottom of the Appbar + // and the content only takes up the space between the actions. + const isBottomAligned = mode === 'medium' || mode === 'large' || isFlexible; + + const bottomStyle = [ + styles.bottom, + { + left: (insets?.left ?? 0) + APPBAR_HORIZONTAL_PADDING + 12, + right: (insets?.right ?? 0) + APPBAR_HORIZONTAL_PADDING + 12, + bottom: insets?.bottom ?? 0, + }, + mode === 'medium' && styles.mediumBottom, + mode === 'large' && styles.largeBottom, + isFlexible && styles.flexibleBottom, + ]; const variant = modeTextVariant[mode]; const contentWrapperProps = { pointerEvents: 'box-none', - style: [styles.container, modeContainerStyles[mode], style], + style: [ + isBottomAligned + ? bottomStyle + : mode === 'center-aligned' + ? styles.centerAligned + : styles.container, + style, + ], testID, + onLayout: isFlexible + ? (event: LayoutChangeEvent) => + onContentLayout?.(event.nativeEvent.layout.height) + : undefined, ...rest, } satisfies ViewProps; @@ -132,7 +167,7 @@ const AppbarContent = ({ }, titleStyle, ]} - numberOfLines={1} + numberOfLines={isFlexible ? 2 : 1} accessible role={onPress ? 'none' : 'heading'} maxFontSizeMultiplier={titleMaxFontSizeMultiplier} @@ -145,21 +180,31 @@ const AppbarContent = ({ ); - if (onPress) { + const wrapper = onPress ? ( + + {content} + + ) : ( + {content} + ); + + if (isBottomAligned) { return ( - - {content} - + <> + {/* Takes up the space between the actions, so the trailing actions stay at the end */} + + {wrapper} + ); } - return {content}; + return wrapper; }; AppbarContent.displayName = 'Appbar.Content'; @@ -167,22 +212,28 @@ AppbarContent.displayName = 'Appbar.Content'; const styles = StyleSheet.create({ container: { flex: 1, - paddingHorizontal: 12, + marginLeft: 12, + }, + centerAligned: { + flex: 1, + alignItems: 'center', }, - v3DefaultContainer: { - paddingHorizontal: 0, + spacer: { + flex: 1, + }, + bottom: { + position: 'absolute', }, - v3MediumContainer: { - paddingHorizontal: 0, - justifyContent: 'flex-end', + mediumBottom: { paddingBottom: 24, }, - v3LargeContainer: { - paddingHorizontal: 0, - paddingTop: 36, - justifyContent: 'flex-end', + largeBottom: { paddingBottom: 28, }, + flexibleBottom: { + paddingTop: 8, + paddingBottom: 12, + }, }); export default AppbarContent; diff --git a/src/components/Appbar/AppbarContext.tsx b/src/components/Appbar/AppbarContext.tsx new file mode 100644 index 0000000000..0f69b379e2 --- /dev/null +++ b/src/components/Appbar/AppbarContext.tsx @@ -0,0 +1,58 @@ +import * as React from 'react'; + +import type { AppbarModes } from './utils'; +import type { ThemeProp } from '../../theme/types'; + +export type AppbarItemKind = 'leading' | 'trailing' | 'content'; + +export type AppbarContextType = { + /** + * Mode of the surrounding Appbar. + */ + mode: AppbarModes; + /** + * Whether the Appbar background is dark, so its parts render light content. + */ + dark: boolean; + /** + * Safe area insets of the surrounding Appbar. + */ + insets: { top: number; bottom: number; left: number; right: number }; + /** + * Theme override of the surrounding Appbar. + */ + theme?: ThemeProp; + /** + * Registers a part that takes part in the layout of the `center-aligned` + * mode. Returns a function that unregisters it. + * Only available in the `center-aligned` mode. + */ + registerItem?: (kind: AppbarItemKind) => () => void; + /** + * Reports the height of the content area of a flexible Appbar, so the Appbar + * can grow with a title that wraps onto multiple lines. + * Only available in the flexible modes. + */ + onContentLayout?: (height: number) => void; +}; + +export const AppbarContext = React.createContext( + null +); + +AppbarContext.displayName = 'AppbarContext'; + +export const useAppbarContext = () => React.useContext(AppbarContext); + +/** + * Registers a part in the surrounding Appbar when the mode lays out its parts + * based on how many of them there are. + */ +export const useAppbarItem = ( + appbar: AppbarContextType | null, + kind: AppbarItemKind +) => { + const registerItem = appbar?.registerItem; + + React.useLayoutEffect(() => registerItem?.(kind), [registerItem, kind]); +}; diff --git a/src/components/Appbar/AppbarHeader.tsx b/src/components/Appbar/AppbarHeader.tsx index 9e9866ee28..7682ed6245 100644 --- a/src/components/Appbar/AppbarHeader.tsx +++ b/src/components/Appbar/AppbarHeader.tsx @@ -6,6 +6,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { Appbar } from './Appbar'; import type { Props as AppbarProps } from './Appbar'; +import type { AppbarModes } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import type { SurfaceStyle } from '../Surface'; @@ -33,13 +34,20 @@ export type Props = Omit & { * - `medium` - Appbar with medium height (112). * - `large` - Appbar with large height (152). * - `center-aligned` - Appbar with default height and center-aligned title. + * - `medium-flexible` - Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. + * - `large-flexible` - Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; + mode?: AppbarModes; /** * @supported Available in v5.x with theme version 3 * Whether Appbar background should have the elevation along with primary color pigment. */ elevated?: boolean; + /** + * Whether the content below the header has scrolled. A scrolled header uses the `surfaceContainer` color for its background, + * without elevation. Overridden by `backgroundColor`. + */ + isScrolled?: boolean; /** * @optional */ diff --git a/src/components/Appbar/utils.ts b/src/components/Appbar/utils.ts index f1c4437a2f..00585d5bf7 100644 --- a/src/components/Appbar/utils.ts +++ b/src/components/Appbar/utils.ts @@ -1,17 +1,26 @@ -import React from 'react'; -import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; -import { StyleSheet } from 'react-native'; +import type { ColorValue } from 'react-native'; import { white } from '../../theme/colors'; -import type { InternalTheme, ThemeProp } from '../../theme/types'; +import type { InternalTheme } from '../../theme/types'; -export type AppbarModes = 'small' | 'medium' | 'large' | 'center-aligned'; +export type AppbarModes = + | 'small' + | 'medium' + | 'large' + | 'center-aligned' + | 'medium-flexible' + | 'large-flexible'; -export type AppbarChildProps = { - isLeading?: boolean; - color: string; - style?: StyleProp; -}; +export const APPBAR_HORIZONTAL_PADDING = 4; + +// Width of an icon button with its margin. +export const APPBAR_ACTION_WIDTH = 52; + +// Height of the row with the controls of a flexible Appbar. +export const APPBAR_FLEXIBLE_CONTROLS_HEIGHT = 56; + +export const isFlexibleMode = (mode: AppbarModes) => + mode === 'medium-flexible' || mode === 'large-flexible'; export const getAppbarBackgroundColor = ( theme: InternalTheme, @@ -33,7 +42,10 @@ export const getAppbarBackgroundColor = ( export const getAppbarColor = ({ color, isDark, -}: BaseProps & { color: string }) => { +}: { + color?: ColorValue; + isDark: boolean; +}): ColorValue | undefined => { if (typeof color !== 'undefined') { return color; } @@ -45,27 +57,20 @@ export const getAppbarColor = ({ return undefined; }; -type BaseProps = { - isDark: boolean; -}; - -type RenderAppbarContentProps = BaseProps & { - children: React.ReactNode; - shouldCenterContent?: boolean; - renderOnly?: (string | boolean)[]; - renderExcept?: string[]; - mode?: AppbarModes; - theme?: ThemeProp; -}; - export const DEFAULT_APPBAR_HEIGHT = 56; const MD3_DEFAULT_APPBAR_HEIGHT = 64; +/** + * Height of the content area of the Appbar, without the safe area insets. + * The flexible modes use it as the minimum height. + */ export const modeAppbarHeight = { small: MD3_DEFAULT_APPBAR_HEIGHT, medium: 112, large: 152, 'center-aligned': MD3_DEFAULT_APPBAR_HEIGHT, + 'medium-flexible': 112, + 'large-flexible': 120, }; export const modeTextVariant = { @@ -73,82 +78,6 @@ export const modeTextVariant = { medium: 'headlineSmall', large: 'headlineMedium', 'center-aligned': 'titleLarge', + 'medium-flexible': 'headlineMedium', + 'large-flexible': 'displaySmall', } as const; - -export const filterAppbarActions = ( - children: React.ReactNode, - isLeading = false -) => { - return React.Children.toArray(children).filter((child) => { - if (!React.isValidElement(child)) return false; - return isLeading ? child.props.isLeading : !child.props.isLeading; - }); -}; - -export const renderAppbarContent = ({ - children, - isDark, - shouldCenterContent = false, - renderOnly, - renderExcept, - mode = 'small', - theme, -}: RenderAppbarContentProps) => { - return React.Children.toArray(children) - .filter((child) => child != null && typeof child !== 'boolean') - .filter((child) => - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - renderExcept ? !renderExcept.includes(child.type.displayName) : child - ) - .filter((child) => - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - renderOnly ? renderOnly.includes(child.type.displayName) : child - ) - .map((child, i) => { - if ( - !React.isValidElement(child) || - ![ - 'Appbar.Content', - 'Appbar.Action', - 'Appbar.BackAction', - 'Tooltip', - ].includes( - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - child.type.displayName - ) - ) { - return child; - } - - const props: { - color?: string; - style?: StyleProp; - mode?: AppbarModes; - theme?: ThemeProp; - } = { - theme, - color: getAppbarColor({ color: child.props.color, isDark }), - }; - - // @ts-expect-error: TypeScript complains about the type of type but it doesn't matter - if (child.type.displayName === 'Appbar.Content') { - props.mode = mode; - props.style = [ - i === 0 && !shouldCenterContent && styles.v3Spacing, - shouldCenterContent && styles.centerAlignedContent, - child.props.style, - ]; - props.color; - } - return React.cloneElement(child, props); - }); -}; - -const styles = StyleSheet.create({ - centerAlignedContent: { - alignItems: 'center', - }, - v3Spacing: { - marginLeft: 12, - }, -}); diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index 49f14e6ec1..620287877a 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -1,24 +1,23 @@ -import { describe, expect, it } from '@jest/globals'; +import { Text as NativeText, View } from 'react-native'; +import type { ColorValue } from 'react-native'; + +import { describe, expect, it, jest } from '@jest/globals'; +import { + getAnimatedStyle, + useAnimatedStyle, + useSharedValue, +} from 'react-native-reanimated'; import { SafeAreaProvider } from 'react-native-safe-area-context'; -import { render, screen } from '../../../test-utils'; +import { fireEvent, render, screen, userEvent } from '../../../test-utils'; import { DarkTheme, LightTheme } from '../../../theme/schemes'; import { tokens } from '../../../theme/tokens'; import Appbar from '../../Appbar'; -import { - getAppbarBackgroundColor, - modeTextVariant, - renderAppbarContent as utilRenderAppbarContent, -} from '../../Appbar/utils'; -import Menu from '../../Menu/Menu'; +import { getAppbarBackgroundColor, modeTextVariant } from '../../Appbar/utils'; import Searchbar from '../../Searchbar'; +import Tooltip from '../../Tooltip/Tooltip'; import Text from '../../Typography/Text'; -// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -const renderAppbarContent = utilRenderAppbarContent as ( - props: Parameters[0] -) => { props: any }[]; - describe('Appbar', () => { it('does not pass any additional props to Searchbar', async () => { const tree = ( @@ -86,109 +85,279 @@ describe('Appbar', () => { }); }); -describe('renderAppbarContent', () => { - const children = [ - {}} key={0} />, - , - {}} key={2} />, - {}} key={3} />, - ]; - - it('should render all children types if renderOnly is not specified', () => { - const result = renderAppbarContent({ - children, - isDark: false, - }); +describe('Appbar context', () => { + const ColorIcon = ({ color }: { color: ColorValue }) => ( + {String(color)} + ); + + it('gives the parts a light color when the Appbar is dark', async () => { + await render( + + + + + ); - expect(result).toHaveLength(4); + expect(screen.getByTestId('icon-color')).toHaveTextContent('#ffffff'); + expect(screen.getByText('Title')).toHaveStyle({ color: '#ffffff' }); }); - it('should render all children types except specified in renderExcept', () => { - const result = renderAppbarContent({ - children: [ - ...children, - {}} />} - visible={false} - > - {null} - , - ], - isDark: false, - renderExcept: [ - 'Appbar', - 'Appbar.Header', - 'Appbar.BackAction', - 'Appbar.Content', - ], - }); + it('keeps the color of a part over the color of a dark Appbar', async () => { + await render( + + + + + ); - expect(result).toHaveLength(3); + expect(screen.getByTestId('icon-color')).toHaveTextContent('purple'); + expect(screen.getByText('Title')).toHaveStyle({ color: 'purple' }); }); - it('should render only children types specified in renderOnly', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Action'], - }); + it('applies the Appbar settings to parts wrapped in other components', async () => { + await render( + + + + + + + + + ); - expect(result).toHaveLength(2); + expect(screen.getByTestId('icon-color')).toHaveTextContent('#ffffff'); + expect(screen.getByText('Title')).toHaveStyle({ color: '#ffffff' }); }); - it('should render AppbarContent with correct mode', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Content'], - mode: 'large', - }); + it('applies the theme of the Appbar to its parts', async () => { + await render( + + + + + ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(result[0].props.mode).toBe('large'); + expect(screen.getByTestId('icon-color')).toHaveTextContent('tomato'); + expect(screen.getByText('Title')).toHaveStyle({ color: 'tomato' }); }); - it('should render centered AppbarContent', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Content'], - mode: 'center-aligned', - shouldCenterContent: true, - }); + it('prefers the theme of a part over the theme of the Appbar', async () => { + await render( + + + + ); - const centerAlignedContent = { - alignItems: 'center', - }; + expect(screen.getByText('Title')).toHaveStyle({ color: 'navy' }); + }); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(result[0].props.style).toEqual( - expect.arrayContaining([expect.objectContaining(centerAlignedContent)]) + it('renders parts on their own, outside of an Appbar', async () => { + await render( + <> + + + ); + + expect(screen.getByText('Title')).toBeOnTheScreen(); + expect(screen.getByRole('button', { name: 'Menu' })).toBeOnTheScreen(); }); - it('should render AppbarContent with correct spacings', () => { - const renderResult = (withAppbarBackAction = false) => - renderAppbarContent({ - children, - isDark: false, - renderOnly: [ - 'Appbar.Content', - withAppbarBackAction && 'Appbar.BackAction', - ], + it('renders children in the order they are given', async () => { + await render( + + + + + + ); + + const [first, second] = screen.getAllByRole('button'); + + expect(first).toHaveAccessibleName('Menu'); + expect(second).toHaveAccessibleName('Back'); + }); + + it('forwards accessibility props to the container', async () => { + await render( + + + + ); + + expect( + screen.getByRole('toolbar', { name: 'Navigation' }) + ).toBeOnTheScreen(); + }); +}); + +describe('Appbar modes', () => { + it('centers the content in the center-aligned mode', async () => { + await render( + + + + + + ); + + expect(screen.getByTestId('content')).toHaveStyle({ alignItems: 'center' }); + }); + + it.each(['medium-flexible', 'large-flexible'] as const)( + 'uses the %s height as the minimum height and includes the safe area insets', + async (mode) => { + await render( + + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + minHeight: (mode === 'medium-flexible' ? 112 : 120) + 20, + paddingTop: 20, }); + } + ); + + it.each(['medium-flexible', 'large-flexible'] as const)( + 'grows the %s Appbar when the title takes more space', + async (mode) => { + await render( + + + + ); + + await fireEvent(screen.getByTestId('content'), 'layout', { + nativeEvent: { layout: { width: 300, height: 120 } }, + }); + + // the row with the controls and the content + expect(screen.getByTestId('appbar')).toHaveStyle({ minHeight: 56 + 120 }); + } + ); + + it('allows the title of a flexible Appbar to wrap onto two lines', async () => { + await render( + + + + ); + + expect(screen.getByText('A long title that wraps')).toHaveProp( + 'numberOfLines', + 2 + ); + }); + + it('keeps the title of the other modes on a single line', async () => { + await render( + + + + ); - const v3Spacing = { - marginLeft: 12, - }; + expect(screen.getByText('A long title')).toHaveProp('numberOfLines', 1); + }); +}); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(renderResult()[0].props.style).toEqual( - expect.arrayContaining([expect.objectContaining(v3Spacing)]) +describe('Appbar scroll-aware color', () => { + it('uses the surface color by default', async () => { + await render( + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + backgroundColor: LightTheme.colors.surface, + }); }); + it('uses the surface container color when scrolled, without elevation', async () => { + await render( + + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + backgroundColor: LightTheme.colors.surfaceContainer, + }); + }); + + it('prefers the custom background color', async () => { + await render( + + + + ); + + expect(screen.getByTestId('appbar')).toHaveStyle({ + backgroundColor: '#FF0000', + }); + }); + + it('is available on Appbar.Header', async () => { + await render( + + + + + + ); + + expect(screen.getByTestId('appbar-header')).toHaveStyle({ + backgroundColor: LightTheme.colors.surfaceContainer, + }); + }); +}); + +describe('Appbar animated style', () => { + const AnimatedAppbar = () => { + const opacity = useSharedValue(0); + const animatedStyle = useAnimatedStyle(() => ({ opacity: opacity.value })); + + return ( + <> + + + + { + opacity.value = 1; + }} + /> + + ); + }; + + it('keeps static styles combined with an animated style', async () => { + await render(); + + const appbar = screen.getByTestId('appbar'); + + expect(appbar).toHaveStyle({ marginHorizontal: 12 }); + expect(getAnimatedStyle(appbar)).toMatchObject({ opacity: 0 }); + + await userEvent.press(screen.getByRole('button', { name: 'Reveal' })); + await jest.runAllTimersAsync(); + + expect(getAnimatedStyle(appbar)).toMatchObject({ opacity: 1 }); + }); +}); + +describe('Appbar.Header', () => { it('includes the status bar height in the header height', async () => { await render( @@ -204,7 +373,8 @@ describe('renderAppbarContent', () => { expect(screen.getByTestId('appbar-header')).toHaveStyle({ height: 112 + 40, - paddingTop: 40, + // the status bar height and the space above the controls + paddingTop: 40 + 8, }); }); @@ -287,6 +457,44 @@ describe('AppbarAction', () => { expect(toJSON()).toMatchSnapshot(); }); + it.each(['filled', 'tonal'] as const)( + 'renders a %s action as a button that handles presses', + async (variant) => { + const onPress = jest.fn<() => void>(); + + await render( + + + + ); + + await userEvent.press(screen.getByRole('button', { name: 'Favorite' })); + + expect(onPress).toHaveBeenCalledTimes(1); + } + ); + + it('does not override the icon color of a filled action by the Appbar', async () => { + await render( + + ( + {String(color)} + )} + variant="filled" + /> + + ); + + expect(screen.getByTestId('icon')).not.toHaveTextContent('#ffffff'); + }); + it('should render AppbarBackAction with custom color', async () => { const { toJSON } = await render( @@ -298,7 +506,16 @@ describe('AppbarAction', () => { }); describe('AppbarContent', () => { - (['small', 'medium', 'large', 'center-aligned'] as const).forEach((mode) => + ( + [ + 'small', + 'medium', + 'large', + 'center-aligned', + 'medium-flexible', + 'large-flexible', + ] as const + ).forEach((mode) => it(`should render text component with appropriate variant for ${mode} mode`, async () => { await render( diff --git a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap index 5ff794c9c0..ef27521cae 100644 --- a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap +++ b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap @@ -13,11 +13,12 @@ exports[`Appbar does not pass any additional props to Searchbar 1`] = ` "alignItems": "center", "flexDirection": "row", }, + false, { - "paddingBottom": undefined, + "paddingBottom": 0, "paddingLeft": 4, "paddingRight": 4, - "paddingTop": undefined, + "paddingTop": 0, }, undefined, {}, @@ -40,65 +41,10 @@ exports[`Appbar does not pass any additional props to Searchbar 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, + false, ] } > - - @@ -817,6 +701,7 @@ exports[`Appbar passes additional props to AppbarBackAction, AppbarContent and A "borderRadius": 20, "borderWidth": 0, }, + false, undefined, ] } @@ -970,11 +855,12 @@ exports[`AppbarAction should be rendered with custom color 1`] = ` "alignItems": "center", "flexDirection": "row", }, + false, { - "paddingBottom": undefined, + "paddingBottom": 0, "paddingLeft": 4, "paddingRight": 4, - "paddingTop": undefined, + "paddingTop": 0, }, undefined, {}, @@ -997,65 +883,10 @@ exports[`AppbarAction should be rendered with custom color 1`] = ` "borderTopRightRadius": undefined, "borderTopStartRadius": undefined, }, - { - "shadowColor": "rgba(0, 0, 0, 1)", - "shadowOffset": { - "height": 0, - "width": 0, - }, - "shadowOpacity": 0, - "shadowRadius": 0, - }, + false, ] } > - - - - Date: Tue, 17 Nov 2026 16:46:32 +0200 Subject: [PATCH 3/7] fix(appbar): address review feedback on layout and docs - Center the title of the center-aligned mode from the measured width of the items around it, so actions without isLeading and custom children are counted, and no spacer pushes the actions - Call the onLayout of Appbar.Content and Appbar along with the Appbar's - Center the controls of every mode at the same height as small - Replace nested ternaries in Appbar.Action with a lookup - Say Appbar.Content has to be a direct child, add tests for wrapped actions, and document the layout, theme and center-aligned changes Co-Authored-By: Claude Sonnet 5.5 --- docs/6.x/docs/guides/migration.md | 23 +- src/components/Appbar/Appbar.tsx | 132 ++++++---- src/components/Appbar/AppbarAction.tsx | 27 +- src/components/Appbar/AppbarContent.tsx | 28 ++- src/components/Appbar/AppbarContext.tsx | 34 +-- src/components/Appbar/utils.ts | 31 ++- .../__tests__/Appbar/Appbar.test.tsx | 238 +++++++++++++++++- 7 files changed, 404 insertions(+), 109 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 3f5eafa853..784e3a8c64 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -435,22 +435,23 @@ To keep the height of the content row when setting `height` in `style`, add the #### Parts read from the `Appbar` -`Appbar` no longer inspects its children and clones them to pass `color`, `theme`, `mode` and `style`. `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action` now read the `dark` and `theme` props and the `mode` of the `Appbar` they are rendered in from context. This means they can be wrapped in other components, for example in a `Tooltip` or a `View`, and still get the colors and the theme of the `Appbar`. A `theme` set on a part takes precedence over the `theme` of the `Appbar`. +`Appbar` no longer inspects its children and clones them to pass `color`, `theme`, `mode` and `style`. `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action` now read the `dark` and `theme` props and the `mode` of the `Appbar` they are rendered in from context. This means `Appbar.Action` and `Appbar.BackAction` can be wrapped in other components, for example in a `Tooltip` or a `View`, and still get the colors and the theme of the `Appbar`. `Appbar.Content` positions the title in the `Appbar`, so render it directly in the `Appbar`, not in a wrapper. The parts are rendered in the order they are given, so render the leading actions first, then `Appbar.Content`, then the trailing actions. Previously, `Appbar.BackAction` and the actions with `isLeading` were moved before the rest. - `Appbar.Content` always has a `12dp` margin before its title. Previously, the margin was only added when the title was the first item after `Appbar.BackAction`. - The `mode` prop of `Appbar.Content`, which was for internal use, is removed. -- In the `center-aligned` mode, the title is centered between the actions when there is room for it. The actions before the title count as leading actions only when they are `Appbar.BackAction` or have `isLeading`. -```diff - -- {}} /> -+ {}} /> - - {}} /> - -``` +#### Layout of the modes + +- In the `medium` and `large` modes, `Appbar` now lays out the actions in a single row and `Appbar.Content` places the title below them, instead of the `Appbar` rendering a row for the actions and a row for the title. The actions of all modes are centered vertically in a `64dp` row, so those of `medium` and `large` moved up by `2dp` and `12dp`. +- In the `center-aligned` mode, the title is centered by measuring the width of the items on each side of it, so any actions, in any order, and custom children are taken into account. Previously, the actions before the title only counted as leading when they were `Appbar.BackAction` or had `isLeading`, and custom children were not counted. The title is centered when each side is at most two actions wide, as before. + +#### Theme + +`Appbar` now passes its `theme` to its parts in every mode. In 5.x, the `medium` and `large` modes didn't, so a bar with its own `theme` drew the icons, the title and the focus rings of these parts with the theme of the app. For example, a dark-themed bar in a light app drew dark icons and a dark title on its dark background. + +A `theme` set on a part takes precedence over the `theme` of the `Appbar`. In 5.x, the `theme` of the `Appbar` overrode it. #### Material 3 Expressive @@ -475,8 +476,6 @@ The parts are rendered in the order they are given, so render the leading action Using `Appbar` as a bottom bar is deprecated. Material Design 3 moves the bottom bar to toolbars. It continues to work in 6.x, and will be replaced by the `Toolbar` component once it is available. -In every mode, `Appbar` now passes its `theme` to `Appbar.BackAction`, `Appbar.Action` and `Appbar.Content`. In 5.x, the `medium` and `large` modes didn't, so a bar with its own `theme` drew the icons, the title and the focus rings of these parts with the theme of the app. For example, a dark-themed bar in a light app drew dark icons and a dark title on its dark background. - ### Avatar The `style` prop for `Avatar.Icon`, `Avatar.Image` and `Avatar.Text` no longer configures the background color. Use the `backgroundColor` prop instead. The text or icon color is still derived from the background color unless `color` is specified. diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index 39e6c168ea..99da03acc0 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -1,14 +1,21 @@ import * as React from 'react'; -import { StyleSheet, View } from 'react-native'; -import type { ColorValue, StyleProp, ViewProps } from 'react-native'; +import { StyleSheet } from 'react-native'; +import type { + ColorValue, + LayoutChangeEvent, + LayoutRectangle, + StyleProp, + ViewProps, +} from 'react-native'; import { AppbarContext } from './AppbarContext'; -import type { AppbarContextType, AppbarItemKind } from './AppbarContext'; +import type { AppbarContextType } from './AppbarContext'; import { - APPBAR_ACTION_WIDTH, - APPBAR_FLEXIBLE_CONTROLS_HEIGHT, + APPBAR_CONTROLS_HEIGHT, + APPBAR_CONTROLS_OFFSET, APPBAR_HORIZONTAL_PADDING, getAppbarBackgroundColor, + getCenteringMargins, isFlexibleMode, modeAppbarHeight, } from './utils'; @@ -81,8 +88,9 @@ export type Props = Omit, 'style'> & * A component to display action items in a bar. It is usually placed at the top of the screen * and contains the screen title and controls such as navigation buttons, menu button etc. * - * Its parts, `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action`, read what they need from the `Appbar` - * they are rendered in, so they can be wrapped in other components, for example in a `Tooltip` or a `Menu`. + * Its parts, `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action`, read the colors and the theme from the `Appbar` + * they are rendered in. `Appbar.Action` and `Appbar.BackAction` can be wrapped in other components, for example in a `Tooltip` or a `Menu`. + * `Appbar.Content` positions the title in the `Appbar`, so render it directly in the `Appbar`, not in a wrapper. * The parts are laid out in the order they are rendered: render the leading actions first, then the content, then the trailing actions. * * ## Usage @@ -169,16 +177,18 @@ const Appbar = ({ safeAreaInsets, theme: themeOverrides, backgroundColor: customBackground, + onLayout, ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); - const [items, setItems] = React.useState>({ - leading: 0, - trailing: 0, - content: 0, - }); const [contentHeight, setContentHeight] = React.useState(0); + const [barWidth, setBarWidth] = React.useState(0); + const [centeredContent, setCenteredContent] = React.useState<{ + x: number; + width: number; + spacers: { left: number; right: number }; + } | null>(null); const backgroundColor = getAppbarBackgroundColor( theme, @@ -198,12 +208,56 @@ const Appbar = ({ right: safeAreaInsets?.right ?? 0, }; - const registerItem = React.useCallback((kind: AppbarItemKind) => { - setItems((current) => ({ ...current, [kind]: current[kind] + 1 })); + const paddingLeft = insets.left + APPBAR_HORIZONTAL_PADDING; + const paddingRight = insets.right + APPBAR_HORIZONTAL_PADDING; + + // The title is centered by adding a margin to it on the side with less actions. + // The width of the actions on each side is what is left of the bar around the + // content, after taking the margins it was measured with out. + const sides = + isCenterAlignedMode && centeredContent && barWidth > 0 + ? { + left: Math.round( + centeredContent.x - paddingLeft - centeredContent.spacers.left + ), + right: Math.round( + barWidth - + paddingRight - + (centeredContent.x + centeredContent.width) - + centeredContent.spacers.right + ), + } + : null; + const spacers = getCenteringMargins(sides); - return () => - setItems((current) => ({ ...current, [kind]: current[kind] - 1 })); - }, []); + // The margins the content was last measured with + const spacersRef = React.useRef(spacers); + + React.useLayoutEffect(() => { + spacersRef.current = spacers; + }); + + const handleContentLayout = React.useCallback( + (layout: LayoutRectangle | null) => { + if (isFlexible) { + setContentHeight(layout?.height ?? 0); + } else { + setCenteredContent( + layout && { + x: layout.x, + width: layout.width, + spacers: spacersRef.current, + } + ); + } + }, + [isFlexible] + ); + + const handleLayout = (event: LayoutChangeEvent) => { + setBarWidth(event.nativeEvent.layout.width); + onLayout?.(event); + }; const appbarContext = React.useMemo( () => ({ @@ -216,8 +270,11 @@ const Appbar = ({ right: insets.right, }, theme: themeOverrides, - registerItem: isCenterAlignedMode ? registerItem : undefined, - onContentLayout: isFlexible ? setContentHeight : undefined, + onContentLayout: + isCenterAlignedMode || isFlexible ? handleContentLayout : undefined, + contentMargins: isCenterAlignedMode + ? { left: spacers.left, right: spacers.right } + : undefined, }), [ mode, @@ -229,24 +286,17 @@ const Appbar = ({ themeOverrides, isCenterAlignedMode, isFlexible, - registerItem, + handleContentLayout, + spacers.left, + spacers.right, ] ); - // The title is only centered when there is room for it between the actions - const shouldCenterContent = - isCenterAlignedMode && - items.content > 0 && - items.leading < 2 && - items.trailing < 3; - const shouldAddLeftSpacing = shouldCenterContent && items.leading === 0; - const shouldAddRightSpacing = shouldCenterContent && items.trailing === 0; - const paddingStyle = { paddingBottom: insets.bottom, - paddingTop: insets.top + topOffset[mode], - paddingLeft: insets.left + APPBAR_HORIZONTAL_PADDING, - paddingRight: insets.right + APPBAR_HORIZONTAL_PADDING, + paddingTop: insets.top + (isTopAligned ? APPBAR_CONTROLS_OFFSET : 0), + paddingLeft, + paddingRight, }; // The safe area insets are applied as padding, so they need to be included in the height @@ -256,7 +306,7 @@ const Appbar = ({ minHeight: Math.max( modeAppbarHeight[mode], - APPBAR_FLEXIBLE_CONTROLS_HEIGHT + contentHeight + APPBAR_CONTROLS_HEIGHT + contentHeight ) + verticalInsets, } : { height: modeAppbarHeight[mode] + verticalInsets }; @@ -276,26 +326,15 @@ const Appbar = ({ // The flat mode renders a single view, so an animated `style` is visible on iOS mode={elevated ? 'elevated' : 'flat'} {...rest} + onLayout={isCenterAlignedMode ? handleLayout : onLayout} theme={theme} > - {shouldAddLeftSpacing ? : null} {children} - {shouldAddRightSpacing ? : null} ); }; -// Offsets the controls of the `medium` and `large` modes so they are vertically centered in the top half of the Appbar -const topOffset = { - small: 0, - 'center-aligned': 0, - 'medium-flexible': 0, - 'large-flexible': 0, - medium: 8, - large: 18, -}; - const styles = StyleSheet.create({ appbar: { flexDirection: 'row', @@ -304,9 +343,6 @@ const styles = StyleSheet.create({ topAligned: { alignItems: 'flex-start', }, - spacing: { - width: APPBAR_ACTION_WIDTH, - }, }); export default Appbar; diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx index 2ab8de7b3e..e79d75ccdb 100644 --- a/src/components/Appbar/AppbarAction.tsx +++ b/src/components/Appbar/AppbarAction.tsx @@ -4,7 +4,7 @@ import type { ColorValue, StyleProp, View, ViewStyle } from 'react-native'; import type { AnimatedStyle } from 'react-native-reanimated'; -import { useAppbarContext, useAppbarItem } from './AppbarContext'; +import { useAppbarContext } from './AppbarContext'; import { getAppbarColor } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; @@ -50,6 +50,8 @@ export type Props = React.PropsWithoutRef & { * - `standard` - Icon without a container. * - `filled` - Icon in a container with the primary color. * - `tonal` - Icon in a container with the secondary container color. + * + * The `filled` and `tonal` variants set the `mode` and `selected` props of the icon button, which are ignored. */ variant?: 'standard' | 'filled' | 'tonal'; /** @@ -111,8 +113,6 @@ const AppbarAction = ({ const theme = useInternalTheme(themeOverrides ?? appbar?.theme); const { colors } = theme; - useAppbarItem(appbar, isLeading ? 'leading' : 'trailing'); - const isStandard = variant === 'standard'; // The icon of a filled or tonal action takes the color of its container @@ -121,6 +121,12 @@ const AppbarAction = ({ (isLeading ? colors.onSurface : colors.onSurfaceVariant)) : iconColor; + // A filled or tonal action is a selected icon button in the matching mode, + // so `variant` takes over the `mode` and `selected` props for these + const variantProps = isStandard + ? { mode, selected } + : variantIconButtonProps[variant]; + return ( { const appbar = useAppbarContext(); const theme = useInternalTheme(themeOverrides ?? appbar?.theme); const { colors, fonts } = theme; - useAppbarItem(appbar, 'content'); - // With `onPress` the title is a button, so it gets the keyboard focus ring // (MD3: interactive elements in an app bar have focus rings). It is a plain // `Pressable`, so it calls the hook directly. Outward, the default. @@ -118,9 +117,10 @@ const AppbarContent = ({ const mode = appbar?.mode ?? 'small'; const insets = appbar?.insets; const onContentLayout = appbar?.onContentLayout; + const contentMargins = appbar?.contentMargins; const isFlexible = isFlexibleMode(mode); - React.useEffect(() => () => onContentLayout?.(0), [onContentLayout]); + React.useEffect(() => () => onContentLayout?.(null), [onContentLayout]); const titleTextColor = getAppbarColor({ color: titleColor, isDark: appbar?.dark ?? false }) ?? @@ -151,16 +151,25 @@ const AppbarContent = ({ isBottomAligned ? bottomStyle : mode === 'center-aligned' - ? styles.centerAligned + ? [ + styles.centerAligned, + contentMargins && { + marginLeft: contentMargins.left, + marginRight: contentMargins.right, + }, + ] : styles.container, style, ], testID, - onLayout: isFlexible - ? (event: LayoutChangeEvent) => - onContentLayout?.(event.nativeEvent.layout.height) - : undefined, ...rest, + // The Appbar grows with the title, or centers it, based on its layout + onLayout: onContentLayout + ? (event: LayoutChangeEvent) => { + onContentLayout(event.nativeEvent.layout); + onLayout?.(event); + } + : onLayout, } satisfies ViewProps; const content = ( @@ -253,7 +262,6 @@ const styles = StyleSheet.create({ paddingBottom: 28, }, flexibleBottom: { - paddingTop: 8, paddingBottom: 12, }, }); diff --git a/src/components/Appbar/AppbarContext.tsx b/src/components/Appbar/AppbarContext.tsx index 0f69b379e2..8ca29f9ce5 100644 --- a/src/components/Appbar/AppbarContext.tsx +++ b/src/components/Appbar/AppbarContext.tsx @@ -1,10 +1,9 @@ import * as React from 'react'; +import type { LayoutRectangle } from 'react-native'; import type { AppbarModes } from './utils'; import type { ThemeProp } from '../../theme/types'; -export type AppbarItemKind = 'leading' | 'trailing' | 'content'; - export type AppbarContextType = { /** * Mode of the surrounding Appbar. @@ -23,17 +22,19 @@ export type AppbarContextType = { */ theme?: ThemeProp; /** - * Registers a part that takes part in the layout of the `center-aligned` - * mode. Returns a function that unregisters it. - * Only available in the `center-aligned` mode. + * Reports the layout of `Appbar.Content`, or `null` when it unmounts. The + * flexible modes use its height to grow with a title that wraps onto + * multiple lines, and the `center-aligned` mode uses its position to center + * the title. + * Only available in these modes. */ - registerItem?: (kind: AppbarItemKind) => () => void; + onContentLayout?: (layout: LayoutRectangle | null) => void; /** - * Reports the height of the content area of a flexible Appbar, so the Appbar - * can grow with a title that wraps onto multiple lines. - * Only available in the flexible modes. + * Margins that center `Appbar.Content` between the actions around it, by + * making up for the side with less width. + * Only available in the `center-aligned` mode. */ - onContentLayout?: (height: number) => void; + contentMargins?: { left: number; right: number }; }; export const AppbarContext = React.createContext( @@ -43,16 +44,3 @@ export const AppbarContext = React.createContext( AppbarContext.displayName = 'AppbarContext'; export const useAppbarContext = () => React.useContext(AppbarContext); - -/** - * Registers a part in the surrounding Appbar when the mode lays out its parts - * based on how many of them there are. - */ -export const useAppbarItem = ( - appbar: AppbarContextType | null, - kind: AppbarItemKind -) => { - const registerItem = appbar?.registerItem; - - React.useLayoutEffect(() => registerItem?.(kind), [registerItem, kind]); -}; diff --git a/src/components/Appbar/utils.ts b/src/components/Appbar/utils.ts index 00585d5bf7..0232b3b24d 100644 --- a/src/components/Appbar/utils.ts +++ b/src/components/Appbar/utils.ts @@ -16,8 +16,13 @@ export const APPBAR_HORIZONTAL_PADDING = 4; // Width of an icon button with its margin. export const APPBAR_ACTION_WIDTH = 52; -// Height of the row with the controls of a flexible Appbar. -export const APPBAR_FLEXIBLE_CONTROLS_HEIGHT = 56; +// Height of the row with the controls of the `medium`, `large` and flexible modes. +export const APPBAR_CONTROLS_HEIGHT = 64; + +// Space above the controls of these modes, which centers them in the row, +// at the same height as in the `small` mode. +export const APPBAR_CONTROLS_OFFSET = + (APPBAR_CONTROLS_HEIGHT - APPBAR_ACTION_WIDTH) / 2; export const isFlexibleMode = (mode: AppbarModes) => mode === 'medium-flexible' || mode === 'large-flexible'; @@ -81,3 +86,25 @@ export const modeTextVariant = { 'medium-flexible': 'headlineMedium', 'large-flexible': 'displaySmall', } as const; + +/** + * Margins that center the title of the `center-aligned` Appbar, + * from the width of the actions on each side of it. Wider actions on one side + * than room for two actions leave the title off-center, as there is not + * enough space to center it. + */ +export const getCenteringMargins = ( + sides: { left: number; right: number } | null +) => { + if (!sides) { + return { left: 0, right: 0 }; + } + + const { left, right } = sides; + + if (Math.max(left, right) > 2 * APPBAR_ACTION_WIDTH) { + return { left: 0, right: 0 }; + } + + return { left: Math.max(0, right - left), right: Math.max(0, left - right) }; +}; diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index ede4fbef0d..8eef4eaf1b 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -224,7 +224,8 @@ describe('Appbar modes', () => { expect(screen.getByTestId('appbar')).toHaveStyle({ minHeight: (mode === 'medium-flexible' ? 112 : 120) + 20, - paddingTop: 20, + // the safe area inset and the space above the controls + paddingTop: 20 + 6, }); } ); @@ -243,7 +244,7 @@ describe('Appbar modes', () => { }); // the row with the controls and the content - expect(screen.getByTestId('appbar')).toHaveStyle({ minHeight: 56 + 120 }); + expect(screen.getByTestId('appbar')).toHaveStyle({ minHeight: 64 + 120 }); } ); @@ -271,6 +272,237 @@ describe('Appbar modes', () => { }); }); +describe('Appbar layout', () => { + const layout = (x: number, width: number) => ({ + nativeEvent: { layout: { x, y: 0, width, height: 64 } }, + }); + + it.each([ + { mode: 'small', offset: 0 }, + { mode: 'center-aligned', offset: 0 }, + { mode: 'medium', offset: 6 }, + { mode: 'large', offset: 6 }, + { mode: 'medium-flexible', offset: 6 }, + { mode: 'large-flexible', offset: 6 }, + ] as const)( + 'places the controls of the $mode mode at the same height', + async ({ mode, offset }) => { + await render( + + + + ); + + // The controls are 64 high, and their buttons are 52 high with margins + expect(screen.getByTestId('appbar')).toHaveStyle({ paddingTop: offset }); + } + ); + + describe('in the center-aligned mode', () => { + const renderAppbar = async (children: React.ReactNode) => { + await render( + + {children} + + ); + }; + + // The bar is 420 wide with 4 of padding on each side + const measure = async (contentX: number, contentWidth: number) => { + await fireEvent(screen.getByTestId('appbar'), 'layout', layout(0, 420)); + await fireEvent( + screen.getByTestId('content'), + 'layout', + layout(contentX, contentWidth) + ); + }; + + it('adds a margin to the title on the side with less width', async () => { + await renderAppbar( + <> + {}} /> + + + ); + + expect(screen.getByTestId('content')).toHaveStyle({ + marginLeft: 0, + marginRight: 0, + }); + + // 52 wide actions on the left, nothing on the right + await measure(56, 360); + + expect(screen.getByTestId('content')).toHaveStyle({ + marginLeft: 0, + marginRight: 52, + }); + }); + + it('does not add a margin when an action before the title is not leading', async () => { + await renderAppbar( + <> + {}} /> + + {}} /> + + ); + + // 52 wide actions on both sides + await measure(56, 308); + + expect(screen.getByTestId('content')).toHaveStyle({ + marginLeft: 0, + marginRight: 0, + }); + }); + + it('takes custom children into account', async () => { + await renderAppbar( + <> + {}} /> + + + + ); + + // 52 wide actions on the left, and a 40 wide custom child on the right + await measure(56, 320); + + expect(screen.getByTestId('content')).toHaveStyle({ + marginLeft: 0, + marginRight: 12, + }); + }); + + it('balances an asymmetric number of actions', async () => { + await renderAppbar( + <> + {}} /> + + {}} /> + {}} /> + + ); + + // 52 wide actions on the left, and two on the right + await measure(56, 256); + + expect(screen.getByTestId('content')).toHaveStyle({ + marginLeft: 52, + marginRight: 0, + }); + }); + + it('does not center the title when there are more than two actions on a side', async () => { + await renderAppbar( + <> + {}} /> + + {}} /> + {}} /> + {}} /> + + ); + + // 52 wide actions on the left, and three on the right + await measure(56, 208); + + expect(screen.getByTestId('content')).toHaveStyle({ + marginLeft: 0, + marginRight: 0, + }); + }); + + it('measures the bar again after it was resized', async () => { + await renderAppbar( + <> + {}} /> + + + ); + + await measure(56, 360); + expect(screen.getByTestId('content')).toHaveStyle({ marginRight: 52 }); + + // The content shrinks by its margin, which must not count as an action + await fireEvent(screen.getByTestId('content'), 'layout', layout(56, 308)); + + expect(screen.getByTestId('content')).toHaveStyle({ marginRight: 52 }); + }); + }); + + it('keeps the onLayout of Appbar.Content when the Appbar uses its layout', async () => { + const onLayout = jest.fn(); + + await render( + + + + ); + + await fireEvent(screen.getByTestId('content'), 'layout', layout(0, 300)); + + expect(onLayout).toHaveBeenCalledTimes(1); + // the Appbar still grows + expect(screen.getByTestId('appbar')).toHaveStyle({ + minHeight: 64 + 64, + }); + }); + + it('keeps the onLayout of the Appbar in the center-aligned mode', async () => { + const onLayout = jest.fn(); + + await render( + + + + ); + + await fireEvent(screen.getByTestId('appbar'), 'layout', layout(0, 420)); + + expect(onLayout).toHaveBeenCalledTimes(1); + }); + + it.each(['medium', 'large', 'medium-flexible', 'large-flexible'] as const)( + 'passes the Appbar settings to an action in a wrapper in the %s mode', + async (mode) => { + await render( + + + + + ( + {String(color)} + )} + aria-label="Menu" + onPress={() => {}} + /> + + + + ); + + expect(screen.getByTestId('icon-color')).toHaveTextContent('#ffffff'); + expect(screen.getByRole('button', { name: 'Menu' })).toBeOnTheScreen(); + } + ); + + it('gives a theme set on a part priority over the theme of the Appbar', async () => { + await render( + + + + ); + + expect(screen.getByText('Title')).toHaveStyle({ color: 'navy' }); + }); +}); + describe('Appbar scroll-aware color', () => { it('uses the surface color by default', async () => { await render( @@ -379,7 +611,7 @@ describe('Appbar.Header', () => { expect(screen.getByTestId('appbar-header')).toHaveStyle({ height: 112 + 40, // the status bar height and the space above the controls - paddingTop: 40 + 8, + paddingTop: 40 + 6, }); }); From 2a651e8cecd19e3a20fcaa9e1b9d6b86dde06e4d Mon Sep 17 00:00:00 2001 From: Nikolay Arefyev Date: Wed, 18 Nov 2026 09:13:42 +0200 Subject: [PATCH 4/7] fix(appbar): respect an explicit selected on filled and tonal actions A filled or tonal Appbar.Action is selected by default, but an explicitly passed selected was ignored, so a toggle could never show its off state. Default selected to true instead, document it, and cover both variants. Co-Authored-By: Claude Sonnet 5.5 --- docs/6.x/docs/guides/migration.md | 2 +- src/components/Appbar/AppbarAction.tsx | 16 +++-- .../__tests__/Appbar/Appbar.test.tsx | 66 +++++++++++++++++++ 3 files changed, 76 insertions(+), 8 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 784e3a8c64..5af1712326 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -456,7 +456,7 @@ A `theme` set on a part takes precedence over the `theme` of the `Appbar`. In 5. #### Material 3 Expressive - The `mode` prop of `Appbar` and `Appbar.Header` accepts two new values: `medium-flexible` and `large-flexible`. Their height is the minimum height (`112` and `120`), and they grow when the title wraps onto a second line. -- `Appbar.Action` has new `variant` and `width` props. `variant="filled"` and `variant="tonal"` render the action in a container, and `width="wide"` makes the container wider. +- `Appbar.Action` has new `variant` and `width` props. `variant="filled"` and `variant="tonal"` render the action in a container, and `width="wide"` makes the container wider. A filled or tonal action is selected by default, and passing `selected={false}` shows the unselected container. - `Appbar` and `Appbar.Header` have a new `isScrolled` prop. Set it when the content below has scrolled, to switch the container to the `surfaceContainer` color. Unlike `elevated`, it doesn't add elevation. ```tsx diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx index e79d75ccdb..6ec46818a8 100644 --- a/src/components/Appbar/AppbarAction.tsx +++ b/src/components/Appbar/AppbarAction.tsx @@ -51,7 +51,9 @@ export type Props = React.PropsWithoutRef & { * - `filled` - Icon in a container with the primary color. * - `tonal` - Icon in a container with the secondary container color. * - * The `filled` and `tonal` variants set the `mode` and `selected` props of the icon button, which are ignored. + * The `filled` and `tonal` variants set the `mode` of the icon button, so its `mode` prop is ignored. + * They are selected by default, with the primary or the secondary container color. Pass `selected={false}` to + * show the unselected container, for example to toggle the action. */ variant?: 'standard' | 'filled' | 'tonal'; /** @@ -121,11 +123,11 @@ const AppbarAction = ({ (isLeading ? colors.onSurface : colors.onSurfaceVariant)) : iconColor; - // A filled or tonal action is a selected icon button in the matching mode, - // so `variant` takes over the `mode` and `selected` props for these + // A filled or tonal action is an icon button in the matching mode, which is + // selected unless `selected` is passed, so `variant` takes over `mode` const variantProps = isStandard ? { mode, selected } - : variantIconButtonProps[variant]; + : { mode: variantIconButtonModes[variant], selected: selected ?? true }; return ( { } ); + describe.each([ + { + variant: 'filled', + selected: { container: 'primary', icon: 'onPrimary' }, + unselected: { container: 'surfaceVariant', icon: 'primary' }, + }, + { + variant: 'tonal', + selected: { + container: 'secondaryContainer', + icon: 'onSecondaryContainer', + }, + unselected: { container: 'surfaceVariant', icon: 'onSurfaceVariant' }, + }, + ] as const)('a $variant action', ({ variant, selected, unselected }) => { + const renderAction = async (props: { selected?: boolean }) => { + await render( + + ( + {String(color)} + )} + aria-label="Favorite" + variant={variant} + onPress={() => {}} + {...props} + /> + + ); + }; + + // The container is the view around the button + const container = () => + screen.getByRole('button', { name: 'Favorite' }).parent; + + it('is selected when selected is not passed', async () => { + await renderAction({}); + + expect(container()).toHaveStyle({ + backgroundColor: LightTheme.colors[selected.container], + }); + expect(screen.getByTestId('icon-color')).toHaveTextContent( + String(LightTheme.colors[selected.icon]) + ); + }); + + it('is selected when selected is true', async () => { + await renderAction({ selected: true }); + + expect(container()).toHaveStyle({ + backgroundColor: LightTheme.colors[selected.container], + }); + }); + + it('shows the unselected container when selected is false', async () => { + await renderAction({ selected: false }); + + expect(container()).toHaveStyle({ + backgroundColor: LightTheme.colors[unselected.container], + }); + expect(screen.getByTestId('icon-color')).toHaveTextContent( + String(LightTheme.colors[unselected.icon]) + ); + }); + }); + it('does not override the icon color of a filled action by the Appbar', async () => { await render( From 7ba7098e108d9efab8da17f8946b8f1afe6e4315 Mon Sep 17 00:00:00 2001 From: Nikolay Arefyev Date: Wed, 18 Nov 2026 09:34:00 +0200 Subject: [PATCH 5/7] docs(appbar): note isLeading and custom children, test unmount - isLeading only selects the icon color now, say so in its doc and the migration guide - Say that only Appbar.BackAction, Appbar.Content and Appbar.Action read the colors and the theme of the Appbar, and that a Tooltip no longer gets its theme - Test that the Appbar forgets the layout of an Appbar.Content that unmounts in the flexible and center-aligned modes Co-Authored-By: Claude Sonnet 5.5 --- docs/6.x/docs/guides/migration.md | 4 +- src/components/Appbar/Appbar.tsx | 2 + src/components/Appbar/AppbarAction.tsx | 3 +- src/components/Appbar/AppbarContent.tsx | 2 + .../__tests__/Appbar/Appbar.test.tsx | 51 +++++++++++++++++++ 5 files changed, 60 insertions(+), 2 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 5af1712326..ea9e17607f 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -437,7 +437,9 @@ To keep the height of the content row when setting `height` in `style`, add the `Appbar` no longer inspects its children and clones them to pass `color`, `theme`, `mode` and `style`. `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action` now read the `dark` and `theme` props and the `mode` of the `Appbar` they are rendered in from context. This means `Appbar.Action` and `Appbar.BackAction` can be wrapped in other components, for example in a `Tooltip` or a `View`, and still get the colors and the theme of the `Appbar`. `Appbar.Content` positions the title in the `Appbar`, so render it directly in the `Appbar`, not in a wrapper. -The parts are rendered in the order they are given, so render the leading actions first, then `Appbar.Content`, then the trailing actions. Previously, `Appbar.BackAction` and the actions with `isLeading` were moved before the rest. +Only these three parts read the colors and the theme of the `Appbar`. Other children, such as a custom icon or an inline SVG, never got them, and they still need an explicit `color` or `theme`. A `Tooltip` was the exception: the `Appbar` passed it its `theme`, and now it doesn't, so pass `theme` to a `Tooltip` that needs the theme of the `Appbar`. + +The parts are rendered in the order they are given, so render the leading actions first, then `Appbar.Content`, then the trailing actions. Previously, `Appbar.BackAction` and the actions with `isLeading` were moved before the rest. The `isLeading` prop now only selects the icon color of the action (`onSurface` instead of `onSurfaceVariant`). - `Appbar.Content` always has a `12dp` margin before its title. Previously, the margin was only added when the title was the first item after `Appbar.BackAction`. - The `mode` prop of `Appbar.Content`, which was for internal use, is removed. diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index 99da03acc0..fcdb3d7136 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -91,6 +91,8 @@ export type Props = Omit, 'style'> & * Its parts, `Appbar.BackAction`, `Appbar.Content` and `Appbar.Action`, read the colors and the theme from the `Appbar` * they are rendered in. `Appbar.Action` and `Appbar.BackAction` can be wrapped in other components, for example in a `Tooltip` or a `Menu`. * `Appbar.Content` positions the title in the `Appbar`, so render it directly in the `Appbar`, not in a wrapper. + * Only these parts read the colors and the theme of the `Appbar`. A custom child, such as an icon or a `Tooltip`, doesn't get them, + * so pass it the `color` or the `theme` it needs. * The parts are laid out in the order they are rendered: render the leading actions first, then the content, then the trailing actions. * * ## Usage diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx index 6ec46818a8..dab1140da9 100644 --- a/src/components/Appbar/AppbarAction.tsx +++ b/src/components/Appbar/AppbarAction.tsx @@ -40,7 +40,8 @@ export type Props = React.PropsWithoutRef & { /** * @supported Available in v5.x with theme version 3 * - * Whether it's the leading button. Note: If `Appbar.BackAction` is present, it will be rendered before any `isLeading` icons. + * Whether it's the leading button: it takes the `onSurface` icon color instead of `onSurfaceVariant`. + * It does not reorder the action, the parts are laid out in the order they are rendered. */ isLeading?: boolean; /** diff --git a/src/components/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx index ffd47c0296..d4d2b374d5 100644 --- a/src/components/Appbar/AppbarContent.tsx +++ b/src/components/Appbar/AppbarContent.tsx @@ -120,6 +120,8 @@ const AppbarContent = ({ const contentMargins = appbar?.contentMargins; const isFlexible = isFlexibleMode(mode); + // The cleanup of the effect runs when the content unmounts, and when the + // callback changes, so the Appbar forgets the layout of a content that is gone React.useEffect(() => () => onContentLayout?.(null), [onContentLayout]); const titleTextColor = diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index c05d9d534b..a951a41bc5 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -432,6 +432,57 @@ describe('Appbar layout', () => { }); }); + it('resets the height of a flexible Appbar when the content unmounts', async () => { + const { rerender } = await render( + + + + ); + + await fireEvent(screen.getByTestId('content'), 'layout', layout(0, 300)); + expect(screen.getByTestId('appbar')).toHaveStyle({ minHeight: 64 + 64 }); + + await rerender( + + {null} + + ); + + // back to the minimum height, which is larger than the controls and content + expect(screen.getByTestId('appbar')).toHaveStyle({ minHeight: 120 }); + }); + + it('forgets the measured content of a center-aligned Appbar when it unmounts', async () => { + const { rerender } = await render( + + {}} /> + + + ); + + await fireEvent(screen.getByTestId('appbar'), 'layout', layout(0, 420)); + await fireEvent(screen.getByTestId('content'), 'layout', layout(56, 360)); + expect(screen.getByTestId('content')).toHaveStyle({ marginRight: 52 }); + + await rerender( + + {}} /> + + ); + await rerender( + + {}} /> + + + ); + + // A new content starts without the margin of the removed one + expect(screen.getByTestId('content')).toHaveStyle({ + marginLeft: 0, + marginRight: 0, + }); + }); + it('keeps the onLayout of Appbar.Content when the Appbar uses its layout', async () => { const onLayout = jest.fn(); From 079b70fb45c2923090b4dba947b125c18492c179 Mon Sep 17 00:00:00 2001 From: Nikolay Arefyev Date: Thu, 19 Nov 2026 10:05:26 +0200 Subject: [PATCH 6/7] fix(appbar): center title in RTL and after a mode change - Measure the center-aligned title in RTL with the margins React Native swaps, so it settles instead of jumping. - Set the layout handlers in every mode, as the web only observes elements that have onLayout when they mount. - Merge the theme of a part over the theme of the Appbar. - Make the wide action 52 wide, as in Material 3. - Fix the icon offsets in the migration guide, mark the v6 props. Co-Authored-By: Claude Sonnet 5.5 --- docs/6.x/docs/guides/migration.md | 4 +- src/components/Appbar/Appbar.tsx | 65 +++++---- src/components/Appbar/AppbarAction.tsx | 7 +- src/components/Appbar/AppbarContent.tsx | 18 ++- src/components/Appbar/AppbarContext.tsx | 23 ++- src/components/Appbar/AppbarHeader.tsx | 6 +- src/components/Appbar/utils.ts | 12 ++ .../__tests__/Appbar/Appbar.test.tsx | 134 ++++++++++++++++-- .../Appbar/__snapshots__/Appbar.test.tsx.snap | 7 + 9 files changed, 209 insertions(+), 67 deletions(-) diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 4636738fae..a5b7729c0a 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -474,14 +474,14 @@ The parts are rendered in the order they are given, so render the leading action #### Layout of the modes -- In the `medium` and `large` modes, `Appbar` now lays out the actions in a single row and `Appbar.Content` places the title below them, instead of the `Appbar` rendering a row for the actions and a row for the title. The actions of all modes are centered vertically in a `64dp` row, so those of `medium` and `large` moved up by `2dp` and `12dp`. +- In the `medium` and `large` modes, `Appbar` now lays out the actions in a single row and `Appbar.Content` places the title below them, instead of the `Appbar` rendering a row for the actions and a row for the title. The actions of all modes are centered vertically in a `64dp` row, so those of `medium` moved down by `4dp` and those of `large` moved up by `6dp`. - In the `center-aligned` mode, the title is centered by measuring the width of the items on each side of it, so any actions, in any order, and custom children are taken into account. Previously, the actions before the title only counted as leading when they were `Appbar.BackAction` or had `isLeading`, and custom children were not counted. The title is centered when each side is at most two actions wide, as before. #### Theme `Appbar` now passes its `theme` to its parts in every mode. In 5.x, the `medium` and `large` modes didn't, so a bar with its own `theme` drew the icons, the title and the focus rings of these parts with the theme of the app. For example, a dark-themed bar in a light app drew dark icons and a dark title on its dark background. -A `theme` set on a part takes precedence over the `theme` of the `Appbar`. In 5.x, the `theme` of the `Appbar` overrode it. +A `theme` set on a part is merged over the `theme` of the `Appbar`, so it takes precedence for the values it sets and the rest comes from the `Appbar`. In 5.x, the `theme` of the `Appbar` overrode it. #### Material 3 Expressive diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index fcdb3d7136..ab4a3f3676 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -17,6 +17,7 @@ import { getAppbarBackgroundColor, getCenteringMargins, isFlexibleMode, + isLeftRightSwapped, modeAppbarHeight, } from './utils'; import type { AppbarModes } from './utils'; @@ -47,8 +48,8 @@ export type Props = Omit, 'style'> & * - `medium` - Appbar with medium height (112). * - `large` - Appbar with large height (152). * - `center-aligned` - Appbar with default height and center-aligned title. - * - `medium-flexible` - Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. - * - `large-flexible` - Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. + * - `medium-flexible` - Available in v6.x. Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. + * - `large-flexible` - Available in v6.x. Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. */ mode?: AppbarModes; /** @@ -57,6 +58,8 @@ export type Props = Omit, 'style'> & */ elevated?: boolean; /** + * @supported Available in v6.x + * * Whether the content below the Appbar has scrolled. A scrolled Appbar uses the `surfaceContainer` color for its background, * without elevation. Overridden by `backgroundColor`. */ @@ -184,11 +187,11 @@ const Appbar = ({ }: Props) => { const theme = useInternalTheme(themeOverrides); - const [contentHeight, setContentHeight] = React.useState(0); const [barWidth, setBarWidth] = React.useState(0); - const [centeredContent, setCenteredContent] = React.useState<{ - x: number; - width: number; + // The layout of `Appbar.Content`, with the margins it was measured with. + // It is recorded in every mode, so the Appbar can use it when the mode changes. + const [content, setContent] = React.useState<{ + layout: LayoutRectangle; spacers: { left: number; right: number }; } | null>(null); @@ -213,25 +216,35 @@ const Appbar = ({ const paddingLeft = insets.left + APPBAR_HORIZONTAL_PADDING; const paddingRight = insets.right + APPBAR_HORIZONTAL_PADDING; + // In RTL, React Native applies the left of a style to the right, and the other way round. + // The layout it reports and the sides below are not swapped, so the styles are mapped to them. + const isSwapped = isLeftRightSwapped(); + // The title is centered by adding a margin to it on the side with less actions. // The width of the actions on each side is what is left of the bar around the // content, after taking the margins it was measured with out. const sides = - isCenterAlignedMode && centeredContent && barWidth > 0 + isCenterAlignedMode && content && barWidth > 0 ? { left: Math.round( - centeredContent.x - paddingLeft - centeredContent.spacers.left + content.layout.x - + (isSwapped ? paddingRight : paddingLeft) - + content.spacers.left ), right: Math.round( barWidth - - paddingRight - - (centeredContent.x + centeredContent.width) - - centeredContent.spacers.right + (isSwapped ? paddingLeft : paddingRight) - + (content.layout.x + content.layout.width) - + content.spacers.right ), } : null; const spacers = getCenteringMargins(sides); + // The margins as styles + const marginLeft = isSwapped ? spacers.right : spacers.left; + const marginRight = isSwapped ? spacers.left : spacers.right; + // The margins the content was last measured with const spacersRef = React.useRef(spacers); @@ -239,21 +252,13 @@ const Appbar = ({ spacersRef.current = spacers; }); + // The layout handlers are passed in every mode: on the web, an element is only + // observed if it has `onLayout` when it mounts, so one added when the mode changes would never be called const handleContentLayout = React.useCallback( (layout: LayoutRectangle | null) => { - if (isFlexible) { - setContentHeight(layout?.height ?? 0); - } else { - setCenteredContent( - layout && { - x: layout.x, - width: layout.width, - spacers: spacersRef.current, - } - ); - } + setContent(layout && { layout, spacers: spacersRef.current }); }, - [isFlexible] + [] ); const handleLayout = (event: LayoutChangeEvent) => { @@ -272,10 +277,9 @@ const Appbar = ({ right: insets.right, }, theme: themeOverrides, - onContentLayout: - isCenterAlignedMode || isFlexible ? handleContentLayout : undefined, + onContentLayout: handleContentLayout, contentMargins: isCenterAlignedMode - ? { left: spacers.left, right: spacers.right } + ? { left: marginLeft, right: marginRight } : undefined, }), [ @@ -287,10 +291,9 @@ const Appbar = ({ insets.right, themeOverrides, isCenterAlignedMode, - isFlexible, handleContentLayout, - spacers.left, - spacers.right, + marginLeft, + marginRight, ] ); @@ -308,7 +311,7 @@ const Appbar = ({ minHeight: Math.max( modeAppbarHeight[mode], - APPBAR_CONTROLS_HEIGHT + contentHeight + APPBAR_CONTROLS_HEIGHT + (content?.layout.height ?? 0) ) + verticalInsets, } : { height: modeAppbarHeight[mode] + verticalInsets }; @@ -328,7 +331,7 @@ const Appbar = ({ // The flat mode renders a single view, so an animated `style` is visible on iOS mode={elevated ? 'elevated' : 'flat'} {...rest} - onLayout={isCenterAlignedMode ? handleLayout : onLayout} + onLayout={handleLayout} theme={theme} > {children} diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx index dab1140da9..7eb9c00b61 100644 --- a/src/components/Appbar/AppbarAction.tsx +++ b/src/components/Appbar/AppbarAction.tsx @@ -4,9 +4,8 @@ import type { ColorValue, StyleProp, View, ViewStyle } from 'react-native'; import type { AnimatedStyle } from 'react-native-reanimated'; -import { useAppbarContext } from './AppbarContext'; +import { useAppbarContext, useAppbarTheme } from './AppbarContext'; import { getAppbarColor } from './utils'; -import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import type { IconSource } from '../Icon'; import IconButton from '../IconButton/IconButton'; @@ -113,7 +112,7 @@ const AppbarAction = ({ ...rest }: Props) => { const appbar = useAppbarContext(); - const theme = useInternalTheme(themeOverrides ?? appbar?.theme); + const theme = useAppbarTheme(themeOverrides); const { colors } = theme; const isStandard = variant === 'standard'; @@ -156,7 +155,7 @@ const variantIconButtonModes = { const styles = StyleSheet.create({ wide: { - width: 56, + width: 52, }, }); diff --git a/src/components/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx index d4d2b374d5..92fae42e7d 100644 --- a/src/components/Appbar/AppbarContent.tsx +++ b/src/components/Appbar/AppbarContent.tsx @@ -9,14 +9,13 @@ import type { ViewProps, } from 'react-native'; -import { useAppbarContext } from './AppbarContext'; +import { useAppbarContext, useAppbarTheme } from './AppbarContext'; import { APPBAR_HORIZONTAL_PADDING, getAppbarColor, isFlexibleMode, modeTextVariant, } from './utils'; -import { useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; import { mergeDataSetProps, useFocusRing } from '../../utils/useFocusRing'; import Text from '../Typography/Text'; @@ -103,7 +102,7 @@ const AppbarContent = ({ ...rest }: Props) => { const appbar = useAppbarContext(); - const theme = useInternalTheme(themeOverrides ?? appbar?.theme); + const theme = useAppbarTheme(themeOverrides); const { colors, fonts } = theme; // With `onPress` the title is a button, so it gets the keyboard focus ring @@ -165,13 +164,12 @@ const AppbarContent = ({ ], testID, ...rest, - // The Appbar grows with the title, or centers it, based on its layout - onLayout: onContentLayout - ? (event: LayoutChangeEvent) => { - onContentLayout(event.nativeEvent.layout); - onLayout?.(event); - } - : onLayout, + // The Appbar grows with the title, or centers it, based on its layout. The + // handler is always set, as on the web it is only called if it is set when the content mounts. + onLayout: (event: LayoutChangeEvent) => { + onContentLayout?.(event.nativeEvent.layout); + onLayout?.(event); + }, } satisfies ViewProps; const content = ( diff --git a/src/components/Appbar/AppbarContext.tsx b/src/components/Appbar/AppbarContext.tsx index 8ca29f9ce5..e93972f08c 100644 --- a/src/components/Appbar/AppbarContext.tsx +++ b/src/components/Appbar/AppbarContext.tsx @@ -2,6 +2,7 @@ import * as React from 'react'; import type { LayoutRectangle } from 'react-native'; import type { AppbarModes } from './utils'; +import { safeMerge, useInternalTheme } from '../../core/theming'; import type { ThemeProp } from '../../theme/types'; export type AppbarContextType = { @@ -26,12 +27,14 @@ export type AppbarContextType = { * flexible modes use its height to grow with a title that wraps onto * multiple lines, and the `center-aligned` mode uses its position to center * the title. - * Only available in these modes. + * It is available in every mode, since on the web an element is only + * observed if it has `onLayout` when it mounts. */ - onContentLayout?: (layout: LayoutRectangle | null) => void; + onContentLayout: (layout: LayoutRectangle | null) => void; /** * Margins that center `Appbar.Content` between the actions around it, by - * making up for the side with less width. + * making up for the side with less width. They are style values, so React Native + * applies them to the right and the left in RTL. * Only available in the `center-aligned` mode. */ contentMargins?: { left: number; right: number }; @@ -44,3 +47,17 @@ export const AppbarContext = React.createContext( AppbarContext.displayName = 'AppbarContext'; export const useAppbarContext = () => React.useContext(AppbarContext); + +/** + * Theme of a part of the `Appbar`: the theme of the app, with the `theme` of the + * `Appbar` and then the `theme` of the part merged over it. + */ +export const useAppbarTheme = (themeOverrides?: ThemeProp) => { + const appbarTheme = useAppbarContext()?.theme; + + return useInternalTheme( + appbarTheme && themeOverrides + ? safeMerge(appbarTheme, themeOverrides) + : (themeOverrides ?? appbarTheme) + ); +}; diff --git a/src/components/Appbar/AppbarHeader.tsx b/src/components/Appbar/AppbarHeader.tsx index 7682ed6245..e32f053c56 100644 --- a/src/components/Appbar/AppbarHeader.tsx +++ b/src/components/Appbar/AppbarHeader.tsx @@ -34,8 +34,8 @@ export type Props = Omit & { * - `medium` - Appbar with medium height (112). * - `large` - Appbar with large height (152). * - `center-aligned` - Appbar with default height and center-aligned title. - * - `medium-flexible` - Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. - * - `large-flexible` - Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. + * - `medium-flexible` - Available in v6.x. Material 3 Expressive Appbar with a larger title and a minimum height of 112. It grows when the title wraps onto a second line. + * - `large-flexible` - Available in v6.x. Material 3 Expressive Appbar with a prominent title and a minimum height of 120. It grows when the title wraps onto a second line. */ mode?: AppbarModes; /** @@ -44,6 +44,8 @@ export type Props = Omit & { */ elevated?: boolean; /** + * @supported Available in v6.x + * * Whether the content below the header has scrolled. A scrolled header uses the `surfaceContainer` color for its background, * without elevation. Overridden by `backgroundColor`. */ diff --git a/src/components/Appbar/utils.ts b/src/components/Appbar/utils.ts index 0232b3b24d..aa6a31ea6d 100644 --- a/src/components/Appbar/utils.ts +++ b/src/components/Appbar/utils.ts @@ -1,3 +1,4 @@ +import { I18nManager } from 'react-native'; import type { ColorValue } from 'react-native'; import { white } from '../../theme/colors'; @@ -108,3 +109,14 @@ export const getCenteringMargins = ( return { left: Math.max(0, right - left), right: Math.max(0, left - right) }; }; + +/** + * Whether React Native swaps the left and right of the styles, which it does in RTL, + * so they apply to the right and the left of the screen. The layout it reports + * is not swapped. + */ +export const isLeftRightSwapped = () => { + const constants = I18nManager.getConstants?.(); + + return !!constants?.isRTL && !!constants.doLeftAndRightSwapInRTL; +}; diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index a951a41bc5..39ae573d9d 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -1,7 +1,14 @@ -import { Text as NativeText, View } from 'react-native'; +import { I18nManager, Text as NativeText, View } from 'react-native'; import type { ColorValue } from 'react-native'; -import { describe, expect, it, jest } from '@jest/globals'; +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest, +} from '@jest/globals'; import { getAnimatedStyle, useAnimatedStyle, @@ -155,6 +162,23 @@ describe('Appbar context', () => { expect(screen.getByText('Title')).toHaveStyle({ color: 'navy' }); }); + it('merges the theme of a part over the theme of the Appbar', async () => { + await render( + + + + + ); + + // A part that sets other values still gets the rest from the Appbar + expect(screen.getByTestId('icon-color')).toHaveTextContent('tomato'); + expect(screen.getByText('Title')).toHaveStyle({ color: 'tomato' }); + }); + it('renders parts on their own, outside of an Appbar', async () => { await render( <> @@ -430,6 +454,73 @@ describe('Appbar layout', () => { expect(screen.getByTestId('content')).toHaveStyle({ marginRight: 52 }); }); + + describe.each([ + // React Native applies the left of a style to the right in RTL + { swapped: true, margin: { marginLeft: 52, marginRight: 0 } }, + { swapped: false, margin: { marginLeft: 0, marginRight: 52 } }, + ])('in RTL, with the sides swapped: $swapped', ({ swapped, margin }) => { + beforeEach(() => { + jest.spyOn(I18nManager, 'getConstants').mockReturnValue({ + isRTL: true, + doLeftAndRightSwapInRTL: swapped, + localeIdentifier: 'ar', + }); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('adds the margin on the side with less width and settles', async () => { + await renderAppbar( + <> + {}} /> + + {}} /> + {}} /> + + ); + + // The back action is on the right, and two actions are on the left + await measure(108, 256); + + // The margin is on the right, where there is less width + expect(screen.getByTestId('content')).toHaveStyle(margin); + + // The content shrinks by its margin on the right, and the margin must settle + await fireEvent( + screen.getByTestId('content'), + 'layout', + layout(108, 204) + ); + + expect(screen.getByTestId('content')).toHaveStyle(margin); + }); + }); + + // The web only observes an element that has `onLayout` when it mounts, so + // the handlers are set in every mode + it('uses the layout measured before the mode changed to center-aligned', async () => { + const { rerender } = await render( + + {}} /> + + + ); + + // The bar and the content are measured in the small mode + await measure(56, 360); + + await rerender( + + {}} /> + + + ); + + expect(screen.getByTestId('content')).toHaveStyle({ marginRight: 52 }); + }); }); it('resets the height of a flexible Appbar when the content unmounts', async () => { @@ -539,19 +630,6 @@ describe('Appbar layout', () => { expect(screen.getByRole('button', { name: 'Menu' })).toBeOnTheScreen(); } ); - - it('gives a theme set on a part priority over the theme of the Appbar', async () => { - await render( - - - - ); - - expect(screen.getByText('Title')).toHaveStyle({ color: 'navy' }); - }); }); describe('Appbar scroll-aware color', () => { @@ -768,6 +846,32 @@ describe('AppbarAction', () => { } ); + it.each([ + { variant: 'filled', width: 'wide', expected: 52 }, + { variant: 'tonal', width: 'wide', expected: 52 }, + { variant: 'filled', width: 'default', expected: 40 }, + ] as const)( + 'makes a $variant action with $width width $expected wide', + async ({ variant, width, expected }) => { + await render( + + {}} + /> + + ); + + // The container of the button is the one with the width + expect( + screen.getByRole('button', { name: 'Favorite' }).parent + ).toHaveStyle({ width: expected }); + } + ); + describe.each([ { variant: 'filled', diff --git a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap index 73db9b23a2..7a8b69936e 100644 --- a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap +++ b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap @@ -3,6 +3,7 @@ exports[`Appbar does not pass any additional props to Searchbar 1`] = ` Date: Thu, 19 Nov 2026 11:21:15 +0200 Subject: [PATCH 7/7] docs(appbar): note that elevated keeps its shadow when scrolled Pin it with a test: elevated with isScrolled keeps the shadow and uses the surfaceContainer color, isScrolled alone has no shadow. Co-Authored-By: Claude Sonnet 5.5 --- src/components/Appbar/Appbar.tsx | 2 +- src/components/Appbar/AppbarHeader.tsx | 2 +- .../__tests__/Appbar/Appbar.test.tsx | 21 +++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index ab4a3f3676..85a67eb980 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -61,7 +61,7 @@ export type Props = Omit, 'style'> & * @supported Available in v6.x * * Whether the content below the Appbar has scrolled. A scrolled Appbar uses the `surfaceContainer` color for its background, - * without elevation. Overridden by `backgroundColor`. + * without elevation. An `elevated` Appbar keeps its shadow when it is scrolled. Overridden by `backgroundColor`. */ isScrolled?: boolean; /** diff --git a/src/components/Appbar/AppbarHeader.tsx b/src/components/Appbar/AppbarHeader.tsx index e32f053c56..2675abba1d 100644 --- a/src/components/Appbar/AppbarHeader.tsx +++ b/src/components/Appbar/AppbarHeader.tsx @@ -47,7 +47,7 @@ export type Props = Omit & { * @supported Available in v6.x * * Whether the content below the header has scrolled. A scrolled header uses the `surfaceContainer` color for its background, - * without elevation. Overridden by `backgroundColor`. + * without elevation. An `elevated` header keeps its shadow when it is scrolled. Overridden by `backgroundColor`. */ isScrolled?: boolean; /** diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index 39ae573d9d..f69042930e 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -657,6 +657,27 @@ describe('Appbar scroll-aware color', () => { }); }); + it('keeps the shadow of an elevated Appbar when it is scrolled', async () => { + await render( + <> + + + + + + + + ); + + expect(screen.getByTestId('both')).toHaveStyle({ + backgroundColor: LightTheme.colors.surfaceContainer, + shadowOpacity: 0.19, + }); + expect(screen.getByTestId('scrolled')).not.toHaveStyle({ + shadowOpacity: 0.19, + }); + }); + it('prefers the custom background color', async () => { await render(