diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md
index e577f6be37..a5b7729c0a 100644
--- a/docs/6.x/docs/guides/migration.md
+++ b/docs/6.x/docs/guides/migration.md
@@ -461,7 +461,50 @@ To keep the height of the content row when setting `height` in `style`, add the
```
-In `medium` and `large` mode, `Appbar` now passes its `theme` to `Appbar.BackAction`, `Appbar.Action` and `Appbar.Content`, as the `small` and `center-aligned` modes already did. These children of a medium or large bar with its own `theme` now take their colors, the title's font and their focus rings from that theme, not from the app's. In 5.x, a dark-themed bar in a light app drew dark icons and a dark title on its dark background.
+#### 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 `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.
+
+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.
+
+#### 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` 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 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
+
+- 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. 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
+
+ {}} />
+
+ {}}
+ />
+
+```
+
+#### 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
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 b3107d33bc..85a67eb980 100644
--- a/src/components/Appbar/Appbar.tsx
+++ b/src/components/Appbar/Appbar.tsx
@@ -1,22 +1,31 @@
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 AppbarContent from './AppbarContent';
+import { AppbarContext } from './AppbarContext';
+import type { AppbarContextType } from './AppbarContext';
import {
+ APPBAR_CONTROLS_HEIGHT,
+ APPBAR_CONTROLS_OFFSET,
+ APPBAR_HORIZONTAL_PADDING,
getAppbarBackgroundColor,
+ getCenteringMargins,
+ isFlexibleMode,
+ isLeftRightSwapped,
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 +48,26 @@ 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` - 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?: '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.
+ * @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. An `elevated` Appbar keeps its shadow when it is scrolled. 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 +88,15 @@ 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 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
* ### Top bar
@@ -91,6 +117,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,154 +178,165 @@ const Appbar = ({
style,
mode = 'small',
elevated = false,
+ isScrolled = false,
safeAreaInsets,
theme: themeOverrides,
backgroundColor: customBackground,
+ onLayout,
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);
+ const [barWidth, setBarWidth] = React.useState(0);
+ // 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);
+
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 paddingLeft = insets.left + APPBAR_HORIZONTAL_PADDING;
+ const paddingRight = insets.right + APPBAR_HORIZONTAL_PADDING;
- React.Children.forEach(children, (child) => {
- if (React.isValidElement(child)) {
- const isLeading = child.props.isLeading === true;
+ // 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();
- if (child.type === AppbarContent) {
- hasAppbarContent = true;
- } else if (isLeading || !hasAppbarContent) {
- leftItemsCount++;
- } else {
- rightItemsCount++;
+ // 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 && content && barWidth > 0
+ ? {
+ left: Math.round(
+ content.layout.x -
+ (isSwapped ? paddingRight : paddingLeft) -
+ content.spacers.left
+ ),
+ right: Math.round(
+ barWidth -
+ (isSwapped ? paddingLeft : paddingRight) -
+ (content.layout.x + content.layout.width) -
+ content.spacers.right
+ ),
}
- }
- });
+ : null;
+ const spacers = getCenteringMargins(sides);
- shouldCenterContent =
- hasAppbarContent && leftItemsCount < 2 && rightItemsCount < 3;
- shouldAddLeftSpacing = shouldCenterContent && leftItemsCount === 0;
- shouldAddRightSpacing = shouldCenterContent && rightItemsCount === 0;
- }
+ // The margins as styles
+ const marginLeft = isSwapped ? spacers.right : spacers.left;
+ const marginRight = isSwapped ? spacers.left : spacers.right;
- const spacingStyle = styles.v3Spacing;
+ // The margins the content was last measured with
+ const spacersRef = React.useRef(spacers);
- const insets = {
- paddingBottom: safeAreaInsets?.bottom,
- paddingTop: safeAreaInsets?.top,
- paddingLeft: (safeAreaInsets?.left ?? 0) + APPBAR_HORIZONTAL_PADDING,
- paddingRight: (safeAreaInsets?.right ?? 0) + APPBAR_HORIZONTAL_PADDING,
+ React.useLayoutEffect(() => {
+ 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) => {
+ setContent(layout && { layout, spacers: spacersRef.current });
+ },
+ []
+ );
+
+ const handleLayout = (event: LayoutChangeEvent) => {
+ setBarWidth(event.nativeEvent.layout.width);
+ onLayout?.(event);
+ };
+
+ const appbarContext = React.useMemo(
+ () => ({
+ mode,
+ dark: isDark,
+ insets: {
+ top: insets.top,
+ bottom: insets.bottom,
+ left: insets.left,
+ right: insets.right,
+ },
+ theme: themeOverrides,
+ onContentLayout: handleContentLayout,
+ contentMargins: isCenterAlignedMode
+ ? { left: marginLeft, right: marginRight }
+ : undefined,
+ }),
+ [
+ mode,
+ isDark,
+ insets.top,
+ insets.bottom,
+ insets.left,
+ insets.right,
+ themeOverrides,
+ isCenterAlignedMode,
+ handleContentLayout,
+ marginLeft,
+ marginRight,
+ ]
+ );
+
+ const paddingStyle = {
+ paddingBottom: insets.bottom,
+ 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
- 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_CONTROLS_HEIGHT + (content?.layout.height ?? 0)
+ ) + 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,
- theme,
- renderOnly: ['Appbar.BackAction'],
- mode,
- })}
- {renderAppbarContent({
- children: filterAppbarActions(children, true),
- isDark,
- theme,
- renderOnly: ['Appbar.Action'],
- mode,
- })}
- {/* Right side of row container, can contain other AppbarAction if they are not leading icons */}
-
- {renderAppbarContent({
- children: filterAppbarActions(children),
- isDark,
- theme,
- renderExcept: [
- 'Appbar',
- 'Appbar.BackAction',
- 'Appbar.Content',
- 'Appbar.Header',
- ],
- mode,
- })}
-
-
- {renderAppbarContent({
- children,
- isDark,
- theme,
- renderOnly: ['Appbar.Content'],
- mode,
- })}
-
- )}
- {shouldAddRightSpacing ? : null}
-
+
+
+ {children}
+
+
);
};
@@ -304,27 +345,8 @@ const styles = StyleSheet.create({
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,
- },
- centerAlignedContainer: {
- paddingTop: 0,
+ topAligned: {
+ alignItems: 'flex-start',
},
});
diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx
index bd0296c8a3..7eb9c00b61 100644
--- a/src/components/Appbar/AppbarAction.tsx
+++ b/src/components/Appbar/AppbarAction.tsx
@@ -1,9 +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 { useInternalTheme } from '../../core/theming';
+import { useAppbarContext, useAppbarTheme } from './AppbarContext';
+import { getAppbarColor } from './utils';
import type { ThemeProp } from '../../theme/types';
import type { IconSource } from '../Icon';
import IconButton from '../IconButton/IconButton';
@@ -37,9 +39,31 @@ 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;
+ /**
+ * @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.
+ *
+ * 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';
+ /**
+ * @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 +102,32 @@ 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 = useAppbarTheme(themeOverrides);
const { colors } = theme;
- const actionIconColor = iconColor
- ? iconColor
- : isLeading
- ? colors.onSurface
- : colors.onSurfaceVariant;
+ 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;
+
+ // 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 }
+ : { mode: variantIconButtonModes[variant], selected: selected ?? true };
return (
, 'children'> & {
* Specifies the largest possible scale a title font can reach.
*/
titleMaxFontSizeMultiplier?: number;
- /**
- * @internal
- */
- mode?: 'small' | 'medium' | 'large' | 'center-aligned';
style?: StyleProp;
/**
* @optional
@@ -94,12 +96,13 @@ const AppbarContent = ({
titleStyle,
title,
titleMaxFontSizeMultiplier,
- mode = 'small',
theme: themeOverrides,
testID,
+ onLayout,
...rest
}: Props) => {
- const theme = useInternalTheme(themeOverrides);
+ const appbar = useAppbarContext();
+ const theme = useAppbarTheme(themeOverrides);
const { colors, fonts } = theme;
// With `onPress` the title is a button, so it gets the keyboard focus ring
@@ -110,22 +113,63 @@ const AppbarContent = ({
colors.secondary
);
- const titleTextColor = titleColor ? titleColor : colors.onSurface;
+ const mode = appbar?.mode ?? 'small';
+ const insets = appbar?.insets;
+ const onContentLayout = appbar?.onContentLayout;
+ 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 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,
+ contentMargins && {
+ marginLeft: contentMargins.left,
+ marginRight: contentMargins.right,
+ },
+ ]
+ : styles.container,
+ style,
+ ],
testID,
...rest,
+ // 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 = (
@@ -141,7 +185,7 @@ const AppbarContent = ({
},
titleStyle,
]}
- numberOfLines={1}
+ numberOfLines={isFlexible ? 2 : 1}
accessible
role={onPress ? 'none' : 'heading'}
maxFontSizeMultiplier={titleMaxFontSizeMultiplier}
@@ -154,34 +198,44 @@ const AppbarContent = ({
>
);
- if (onPress) {
+ const wrapper = onPress ? (
+ {
+ focusTarget.onFocus?.(e);
+ rest.onFocus?.(e);
+ }}
+ onBlur={(e) => {
+ focusTarget.onBlur?.();
+ rest.onBlur?.(e);
+ }}
+ {...mergeDataSetProps(rest, focusRing.dataSetProps)}
+ style={[...contentWrapperProps.style, ...focusRing.style]}
+ >
+ {content}
+
+ ) : (
+ {content}
+ );
+
+ if (isBottomAligned) {
return (
- {
- focusTarget.onFocus?.(e);
- rest.onFocus?.(e);
- }}
- onBlur={(e) => {
- focusTarget.onBlur?.();
- rest.onBlur?.(e);
- }}
- {...mergeDataSetProps(rest, focusRing.dataSetProps)}
- style={[...contentWrapperProps.style, ...focusRing.style]}
- >
- {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';
@@ -189,22 +243,27 @@ 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: {
+ 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..e93972f08c
--- /dev/null
+++ b/src/components/Appbar/AppbarContext.tsx
@@ -0,0 +1,63 @@
+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 = {
+ /**
+ * 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;
+ /**
+ * 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.
+ * 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;
+ /**
+ * Margins that center `Appbar.Content` between the actions around it, by
+ * 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 };
+};
+
+export const AppbarContext = React.createContext(
+ null
+);
+
+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 9e9866ee28..2675abba1d 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,22 @@ 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` - 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?: '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;
+ /**
+ * @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. An `elevated` header keeps its shadow when it is scrolled. Overridden by `backgroundColor`.
+ */
+ isScrolled?: boolean;
/**
* @optional
*/
diff --git a/src/components/Appbar/utils.ts b/src/components/Appbar/utils.ts
index f1c4437a2f..aa6a31ea6d 100644
--- a/src/components/Appbar/utils.ts
+++ b/src/components/Appbar/utils.ts
@@ -1,17 +1,32 @@
-import React from 'react';
-import type { ColorValue, StyleProp, ViewStyle } from 'react-native';
-import { StyleSheet } from 'react-native';
+import { I18nManager } 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 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';
export const getAppbarBackgroundColor = (
theme: InternalTheme,
@@ -33,7 +48,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 +63,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 +84,39 @@ 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
+/**
+ * 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
) => {
- return React.Children.toArray(children).filter((child) => {
- if (!React.isValidElement(child)) return false;
- return isLeading ? child.props.isLeading : !child.props.isLeading;
- });
-};
+ if (!sides) {
+ return { left: 0, right: 0 };
+ }
-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 { 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) };
};
-const styles = StyleSheet.create({
- centerAlignedContent: {
- alignItems: 'center',
- },
- v3Spacing: {
- marginLeft: 12,
- },
-});
+/**
+ * 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 49f14e6ec1..f69042930e 100644
--- a/src/components/__tests__/Appbar/Appbar.test.tsx
+++ b/src/components/__tests__/Appbar/Appbar.test.tsx
@@ -1,24 +1,30 @@
-import { describe, expect, it } from '@jest/globals';
+import { I18nManager, Text as NativeText, View } from 'react-native';
+import type { ColorValue } from 'react-native';
+
+import {
+ afterEach,
+ beforeEach,
+ 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 +92,659 @@ 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)}
+ );
- expect(result).toHaveLength(4);
+ it('gives the parts a light color when the Appbar is dark', async () => {
+ await render(
+
+
+
+
+ );
+
+ 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,
- ,
- ],
- 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(screen.getByTestId('icon-color')).toHaveTextContent('purple');
+ expect(screen.getByText('Title')).toHaveStyle({ color: 'purple' });
+ });
+
+ it('applies the Appbar settings to parts wrapped in other components', async () => {
+ await render(
+
+
+
+
+
+
+
+
+ );
+
+ expect(screen.getByTestId('icon-color')).toHaveTextContent('#ffffff');
+ expect(screen.getByText('Title')).toHaveStyle({ color: '#ffffff' });
+ });
+
+ it('applies the theme of the Appbar to its parts', async () => {
+ await render(
+
+
+
+
+ );
+
+ expect(screen.getByTestId('icon-color')).toHaveTextContent('tomato');
+ expect(screen.getByText('Title')).toHaveStyle({ color: 'tomato' });
+ });
+
+ it('prefers the theme of a part over the theme of the Appbar', async () => {
+ await render(
+
+
+
+ );
+
+ 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(
+ <>
+
+ {}} />
+ >
+ );
+
+ expect(screen.getByText('Title')).toBeOnTheScreen();
+ expect(screen.getByRole('button', { name: 'Menu' })).toBeOnTheScreen();
+ });
+
+ 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(result).toHaveLength(3);
+ expect(
+ screen.getByRole('toolbar', { name: 'Navigation' })
+ ).toBeOnTheScreen();
});
+});
- it('should render only children types specified in renderOnly', () => {
- const result = renderAppbarContent({
- children,
- isDark: false,
- renderOnly: ['Appbar.Action'],
+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,
+ // the safe area inset and the space above the controls
+ paddingTop: 20 + 6,
+ });
+ }
+ );
+
+ 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: 64 + 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(
+
+
+
+ );
+
+ expect(screen.getByText('A long title')).toHaveProp('numberOfLines', 1);
+ });
+});
+
+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,
+ });
});
- expect(result).toHaveLength(2);
+ 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 });
+ });
+
+ 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 () => {
+ 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('should render AppbarContent with correct mode', () => {
- const result = renderAppbarContent({
- children,
- isDark: false,
- renderOnly: ['Appbar.Content'],
- mode: 'large',
+ 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();
- // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion.
- expect(result[0].props.mode).toBe('large');
+ 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('should render centered AppbarContent', () => {
- const result = renderAppbarContent({
- children,
- isDark: false,
- renderOnly: ['Appbar.Content'],
- mode: 'center-aligned',
- shouldCenterContent: true,
+ 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();
+ }
+ );
+});
+
+describe('Appbar scroll-aware color', () => {
+ it('uses the surface color by default', async () => {
+ await render(
+
+
+
+ );
+
+ expect(screen.getByTestId('appbar')).toHaveStyle({
+ backgroundColor: LightTheme.colors.surface,
});
+ });
- const centerAlignedContent = {
- alignItems: 'center',
- };
+ it('uses the surface container color when scrolled, without elevation', async () => {
+ await render(
+
+
+
+ );
+
+ expect(screen.getByTestId('appbar')).toHaveStyle({
+ backgroundColor: LightTheme.colors.surfaceContainer,
+ });
+ });
+
+ it('keeps the shadow of an elevated Appbar when it is scrolled', async () => {
+ await render(
+ <>
+
+
+
+
+
+
+ >
+ );
- // 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)])
+ 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(
+
+
+
);
+
+ expect(screen.getByTestId('appbar')).toHaveStyle({
+ backgroundColor: '#FF0000',
+ });
});
- it('should render AppbarContent with correct spacings', () => {
- const renderResult = (withAppbarBackAction = false) =>
- renderAppbarContent({
- children,
- isDark: false,
- renderOnly: [
- 'Appbar.Content',
- withAppbarBackAction && 'Appbar.BackAction',
- ],
- });
+ it('is available on Appbar.Header', async () => {
+ await render(
+
+
+
+
+
+ );
- const v3Spacing = {
- marginLeft: 12,
- };
+ expect(screen.getByTestId('appbar-header')).toHaveStyle({
+ backgroundColor: LightTheme.colors.surfaceContainer,
+ });
+ });
+});
- // 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 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 +760,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 + 6,
});
});
@@ -287,6 +844,136 @@ 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.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',
+ 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(
+
+ (
+ {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 +985,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 3280897b93..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`] = `
-
-
@@ -795,6 +682,7 @@ exports[`Appbar passes additional props to AppbarBackAction, AppbarContent and A
"borderRadius": 20,
"borderWidth": 0,
},
+ false,
undefined,
]
}
@@ -944,6 +832,7 @@ exports[`Appbar passes additional props to AppbarBackAction, AppbarContent and A
exports[`AppbarAction should be rendered with custom color 1`] = `
-
-
-
-